-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagentParser.js
More file actions
243 lines (207 loc) · 7.48 KB
/
agentParser.js
File metadata and controls
243 lines (207 loc) · 7.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
const fs = require('fs');
const path = require('path');
const parseAgentFileByName = (name) => {
// if the name ends with "agent, or "Agent", replace ageent with empty string
if (name.endsWith("agent") || name.endsWith("Agent")) {
name = name.replace("agent", "").replace("Agent", "");
}
// always lowercase the first letter of the name
name = name.charAt(0).toLowerCase() + name.slice(1);
const agentFile = fs.readFileSync(`agents/${dasherize(name)}.xml`, 'utf8');
const agent = parse(agentFile);
return agent;
}
const parse = (file) => {
const json = xmlParse(file);
return json;
}
// this function will parse the xml file into a javascript object
const xmlParse = (fileText) => {
const tokens = tokenize(fileText);
const json = parseTokens(tokens);
return json;
}
const tokenize = (fileText) => {
const tokens = [];
let i = 0;
while (i < fileText.length) {
if (fileText[i] === '<') {
if (fileText[i+1] === '/') {
// Closing tag
const end = fileText.indexOf('>', i);
tokens.push({
type: 'closeTag',
value: fileText.substring(i, end + 1)
});
i = end + 1;
} else {
// Opening tag or self-closing tag
const end = fileText.indexOf('>', i);
const tagContent = fileText.substring(i, end + 1);
// Check if it's a self-closing tag
if (tagContent.endsWith('/>')) {
tokens.push({
type: 'selfClosingTag',
value: tagContent
});
} else {
tokens.push({
type: 'openTag',
value: tagContent
});
}
i = end + 1;
}
} else {
// Text content
const end = fileText.indexOf('<', i);
if (end === -1) break;
const text = fileText.substring(i, end).trim();
if (text) {
tokens.push({
type: 'text',
value: text
});
}
i = end;
}
}
return tokens;
}
const parseTagAttributes = (tagString) => {
// Remove < > brackets and split by first space
const content = tagString.slice(1, -1).trim();
const firstSpace = content.indexOf(' ');
if (firstSpace === -1) {
// No attributes
return { name: content, attributes: {} };
}
const name = content.slice(0, firstSpace);
const attributesString = content.slice(firstSpace + 1);
const attributes = {};
// Parse attributes using regex
const attrRegex = /([\w-]+)(?:="([^"]*)"|='([^']*)'|=(\S+))?/g;
let match;
while ((match = attrRegex.exec(attributesString)) !== null) {
const key = match[1];
const value = match[2] || match[3] || match[4] || true;
attributes[key] = value;
}
return { name, attributes };
}
const loadToolMetadata = (toolName) => {
try {
// Remove 'Tool' suffix if present to get the actual tool name
const actualToolName = toolName.endsWith('Tool') ? toolName.slice(0, -4) : toolName;
const actualToolNameWithLowerCaseFirstLetter = actualToolName.charAt(0).toLowerCase() + actualToolName.slice(1);
// let's take a pascal case tool name and convert it to snake case
// first letter needs to be made lowercase just prior to the conversion
const snakeCaseToolName = actualToolNameWithLowerCaseFirstLetter.replace(/([A-Z])/g, '_$1').toLowerCase();
console.log("snakeCaseToolName:", snakeCaseToolName)
const toolPath = path.join(__dirname, 'tools', `${snakeCaseToolName}.js`);
console.log("toolPath:", toolPath)
if (fs.existsSync(toolPath)) {
console.log("toolPath2:", toolPath)
// Require the tool module
const toolModule = require(toolPath);
console.log("toolModule:", toolModule)
const toolFunction = toolModule[actualToolNameWithLowerCaseFirstLetter];
// Get description and input_schema if available
return {
description: toolFunction.description || '',
input_schema: toolFunction.input_schema || {}
};
}
} catch (error) {
console.error(`Error loading metadata for tool ${toolName}:`, error);
}
return { description: '', input_schema: {} };
};
const loadAgentMetadata = (agentName, tag, isRoot = false) => {
console.log("here:", {agentName, tag, isRoot})
// Don't load metadata for the root agent since we're already parsing its file
if (isRoot) {
return {
description: tag.attributes.description || '',
input_schema: {}
};
}
const agentMetadata = {
tag: tag.name,
attributes: tag.attributes,
children: [],
isTool: false,
isAgent: true,
description: tag.attributes.description || '',
input_schema: {
type: "object",
properties: {
prompt: { type: "string" }
}
}
};
return agentMetadata;
}
const parseTokens = (tokens) => {
const rootNode = { children: [] };
const stack = [rootNode];
let currentNode = rootNode;
let isRoot = true; // Track if we're parsing the root agent
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (token.type === 'openTag' || token.type === 'selfClosingTag') {
// Parse tag name and attributes
const tag = parseTagAttributes(token.value);
const isTool = tag.name.endsWith('Tool');
const isAgent = tag.name.endsWith('Agent');
let metadata = {};
// If it's a tool, load its metadata
if (isTool) {
metadata = loadToolMetadata(tag.name);
}
if (isAgent) {
metadata = loadAgentMetadata(tag.name, tag, isRoot);
}
const newNode = {
tag: tag.name,
attributes: tag.attributes,
children: [],
isTool,
isAgent,
description: metadata.description || '',
input_schema: metadata.input_schema || {}
};
currentNode.children.push(newNode);
// Only push to stack and update currentNode if it's not a self-closing tag
if (token.type === 'openTag') {
stack.push(newNode);
currentNode = newNode;
}
isRoot = false; // After first tag, we're no longer at root
}
else if (token.type === 'closeTag') {
stack.pop();
currentNode = stack[stack.length - 1];
}
else if (token.type === 'text') {
currentNode.children.push({
type: 'text',
value: token.value
});
}
}
return rootNode.children[0] || {};
}
const dasherize = (name) => {
return name.replace(/([A-Z])/g, '-$1').toLowerCase();
}
// Export functions for testing
module.exports = {
xmlParse,
parse,
parseAgentFileByName,
tokenize,
parseTokens,
parseTagAttributes,
loadToolMetadata
};