-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathyaml-parser.mjs
More file actions
326 lines (289 loc) · 9.63 KB
/
Copy pathyaml-parser.mjs
File metadata and controls
326 lines (289 loc) · 9.63 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// YAML parser for frontmatter parsing using vfile-matter
import fs from "fs";
import * as yaml from "js-yaml";
import path from "path";
import { VFile } from "vfile";
import { matter } from "vfile-matter";
function safeFileOperation(operation, filePath, defaultValue = null) {
try {
return operation();
} catch (error) {
console.error(`Error processing file ${filePath}: ${error.message}`);
return defaultValue;
}
}
/**
* Parse frontmatter from a markdown file using vfile-matter
* Works with any markdown file that has YAML frontmatter (agents, prompts, instructions)
* @param {string} filePath - Path to the markdown file
* @returns {object|null} Parsed frontmatter object or null on error
*/
function parseFrontmatter(filePath) {
return safeFileOperation(
() => {
const content = fs.readFileSync(filePath, "utf8");
const file = new VFile({ path: filePath, value: content });
// Parse the frontmatter using vfile-matter
matter(file);
// The frontmatter is now available in file.data.matter
const frontmatter = file.data.matter;
// Normalize string fields that can accumulate trailing newlines/spaces
if (frontmatter) {
if (typeof frontmatter.name === "string") {
frontmatter.name = frontmatter.name.replace(/[\r\n]+$/g, "").trim();
}
if (typeof frontmatter.title === "string") {
frontmatter.title = frontmatter.title.replace(/[\r\n]+$/g, "").trim();
}
if (typeof frontmatter.description === "string") {
// Remove only trailing whitespace/newlines; preserve internal formatting
frontmatter.description = frontmatter.description.replace(
/[\s\r\n]+$/g,
""
);
}
}
return frontmatter;
},
filePath,
null
);
}
/**
* Extract agent metadata including MCP server information
* @param {string} filePath - Path to the agent file
* @returns {object|null} Agent metadata object with name, description, tools, and mcp-servers
*/
function extractAgentMetadata(filePath) {
const frontmatter = parseFrontmatter(filePath);
if (!frontmatter) {
return null;
}
return {
name: typeof frontmatter.name === "string" ? frontmatter.name : null,
description:
typeof frontmatter.description === "string"
? frontmatter.description
: null,
tools: frontmatter.tools || [],
mcpServers: frontmatter["mcp-servers"] || {},
};
}
/**
* Extract MCP server names from an agent file
* @param {string} filePath - Path to the agent file
* @returns {string[]} Array of MCP server names
*/
function extractMcpServers(filePath) {
const metadata = extractAgentMetadata(filePath);
if (!metadata || !metadata.mcpServers) {
return [];
}
return Object.keys(metadata.mcpServers);
}
/**
* Extract full MCP server configs from an agent file
* @param {string} filePath - Path to the agent file
* @returns {Array<{name:string,type?:string,command?:string,args?:string[],url?:string,headers?:object}>}
*/
function extractMcpServerConfigs(filePath) {
const metadata = extractAgentMetadata(filePath);
if (!metadata || !metadata.mcpServers) return [];
return Object.entries(metadata.mcpServers).map(([name, cfg]) => {
// Ensure we don't mutate original cfg
const copy = { ...cfg };
return {
name,
type: typeof copy.type === "string" ? copy.type : undefined,
command: typeof copy.command === "string" ? copy.command : undefined,
args: Array.isArray(copy.args) ? copy.args : undefined,
url: typeof copy.url === "string" ? copy.url : undefined,
headers:
typeof copy.headers === "object" && copy.headers !== null
? copy.headers
: undefined,
};
});
}
/**
* Parse SKILL.md frontmatter and list bundled assets in a skill folder
* @param {string} skillPath - Path to skill folder
* @returns {object|null} Skill metadata with name, description, and assets array
*/
function parseSkillMetadata(skillPath) {
return safeFileOperation(
() => {
const skillFile = path.join(skillPath, "SKILL.md");
if (!fs.existsSync(skillFile)) {
return null;
}
const frontmatter = parseFrontmatter(skillFile);
// Validate required fields
if (!frontmatter?.name || !frontmatter?.description) {
console.warn(
`Invalid skill at ${skillPath}: missing name or description in frontmatter`
);
return null;
}
// List bundled assets (all files except SKILL.md), recursing through subdirectories
const getAllFiles = (dirPath, arrayOfFiles = []) => {
const files = fs.readdirSync(dirPath);
const assetPaths = ['references', 'assets', 'scripts'];
files.forEach((file) => {
const filePath = path.join(dirPath, file);
if (fs.statSync(filePath).isDirectory() && assetPaths.includes(file)) {
arrayOfFiles = getAllFiles(filePath, arrayOfFiles);
} else {
const relativePath = path.relative(skillPath, filePath);
if (relativePath !== "SKILL.md") {
// Normalize path separators to forward slashes for cross-platform consistency
arrayOfFiles.push(relativePath.replace(/\\/g, "/"));
}
}
});
return arrayOfFiles;
};
const assets = getAllFiles(skillPath).sort();
return {
name: frontmatter.name,
description: frontmatter.description,
assets,
path: skillPath,
};
},
skillPath,
null
);
}
/**
* Parse hook metadata from a hook folder (similar to skills)
* @param {string} hookPath - Path to the hook folder
* @returns {object|null} Hook metadata or null on error
*/
function parseHookMetadata(hookPath) {
return safeFileOperation(
() => {
const readmeFile = path.join(hookPath, "README.md");
if (!fs.existsSync(readmeFile)) {
return null;
}
const frontmatter = parseFrontmatter(readmeFile);
// Validate required fields
if (!frontmatter?.name || !frontmatter?.description) {
console.warn(
`Invalid hook at ${hookPath}: missing name or description in frontmatter`
);
return null;
}
// Extract hook events from hooks.json if it exists
let hookEvents = [];
const hooksJsonPath = path.join(hookPath, "hooks.json");
if (fs.existsSync(hooksJsonPath)) {
try {
const hooksJsonContent = fs.readFileSync(hooksJsonPath, "utf8");
const hooksConfig = JSON.parse(hooksJsonContent);
// Extract all hook event names from the hooks object
if (hooksConfig.hooks && typeof hooksConfig.hooks === "object") {
hookEvents = Object.keys(hooksConfig.hooks);
}
} catch (error) {
console.warn(
`Failed to parse hooks.json at ${hookPath}: ${error.message}`
);
}
}
// List bundled assets (all files except README.md), recursing through subdirectories
const getAllFiles = (dirPath, arrayOfFiles = []) => {
const files = fs.readdirSync(dirPath);
files.forEach((file) => {
const filePath = path.join(dirPath, file);
if (fs.statSync(filePath).isDirectory()) {
arrayOfFiles = getAllFiles(filePath, arrayOfFiles);
} else {
const relativePath = path.relative(hookPath, filePath);
if (relativePath !== "README.md") {
// Normalize path separators to forward slashes for cross-platform consistency
arrayOfFiles.push(relativePath.replace(/\\/g, "/"));
}
}
});
return arrayOfFiles;
};
const assets = getAllFiles(hookPath).sort();
return {
name: frontmatter.name,
description: frontmatter.description,
hooks: hookEvents,
tags: frontmatter.tags || [],
assets,
path: hookPath,
};
},
hookPath,
null
);
}
/**
* Parse workflow metadata from a standalone .md workflow file
* @param {string} filePath - Path to the workflow .md file
* @returns {object|null} Workflow metadata or null on error
*/
function parseWorkflowMetadata(filePath) {
return safeFileOperation(
() => {
if (!fs.existsSync(filePath)) {
return null;
}
const frontmatter = parseFrontmatter(filePath);
// Validate required fields
if (!frontmatter?.name || !frontmatter?.description) {
console.warn(
`Invalid workflow at ${filePath}: missing name or description in frontmatter`
);
return null;
}
// Extract triggers from the 'on' field (top-level keys)
const onField = frontmatter.on;
const triggers = [];
if (onField && typeof onField === "object") {
triggers.push(...Object.keys(onField));
} else if (typeof onField === "string") {
triggers.push(onField);
}
return {
name: frontmatter.name,
description: frontmatter.description,
triggers,
path: filePath,
};
},
filePath,
null
);
}
/**
* Parse a generic YAML file (used for tools.yml and other config files)
* @param {string} filePath - Path to the YAML file
* @returns {object|null} Parsed YAML object or null on error
*/
function parseYamlFile(filePath) {
return safeFileOperation(
() => {
const content = fs.readFileSync(filePath, "utf8");
return yaml.load(content, { schema: yaml.JSON_SCHEMA });
},
filePath,
null
);
}
export {
extractAgentMetadata,
extractMcpServerConfigs,
extractMcpServers,
parseFrontmatter,
parseSkillMetadata,
parseHookMetadata,
parseWorkflowMetadata,
parseYamlFile,
safeFileOperation,
};