@agiflowai/scaffold-mcp 1.0.14 → 1.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/ListScaffoldingMethodsTool-RfVCiYIl.mjs +1016 -0
  2. package/dist/ListScaffoldingMethodsTool-dP6UGYi-.cjs +1104 -0
  3. package/dist/cli.cjs +11 -16
  4. package/dist/cli.mjs +5 -9
  5. package/dist/index.cjs +7 -11
  6. package/dist/index.mjs +2 -6
  7. package/dist/{stdio-AbTm52SJ.mjs → stdio-C0MGNdE2.mjs} +15 -18
  8. package/dist/{stdio-baUp7xGL.cjs → stdio-CMrGIHf9.cjs} +24 -28
  9. package/dist/{useScaffoldMethod-CcrpFEPv.cjs → useScaffoldMethod-CYcSFnmq.cjs} +1 -3
  10. package/dist/{useScaffoldMethod-DOvwnNOJ.cjs → useScaffoldMethod-CazDraH-.cjs} +10 -9
  11. package/dist/{useScaffoldMethod-CPgJIBHx.mjs → useScaffoldMethod-D5xkoGJE.mjs} +1 -2
  12. package/dist/{useScaffoldMethod-BMWhFebp.mjs → useScaffoldMethod-D_Bu4nj2.mjs} +7 -5
  13. package/package.json +4 -4
  14. package/dist/ListScaffoldingMethodsTool-B49G_iLj.mjs +0 -350
  15. package/dist/ListScaffoldingMethodsTool-DuYGFDwJ.cjs +0 -376
  16. package/dist/ScaffoldConfigLoader-8YI7v2GJ.mjs +0 -142
  17. package/dist/ScaffoldConfigLoader-BWpNpMx-.cjs +0 -150
  18. package/dist/ScaffoldConfigLoader-DKJtnrWT.mjs +0 -3
  19. package/dist/ScaffoldConfigLoader-HutEtfaH.cjs +0 -3
  20. package/dist/ScaffoldService-DSQBnAHm.cjs +0 -308
  21. package/dist/ScaffoldService-DcsGLMuD.mjs +0 -295
  22. package/dist/ScaffoldService-DfXjmrNT.cjs +0 -3
  23. package/dist/ScaffoldService-dL74anIv.mjs +0 -3
  24. package/dist/TemplateService-7QcWREot.cjs +0 -85
  25. package/dist/TemplateService-B1bd6iHw.mjs +0 -3
  26. package/dist/TemplateService-CVDL2uqt.mjs +0 -79
  27. package/dist/TemplateService-DUbdBOFs.cjs +0 -3
  28. package/dist/VariableReplacementService-B9RA8D0a.mjs +0 -66
  29. package/dist/VariableReplacementService-BO-UYgcf.mjs +0 -3
  30. package/dist/VariableReplacementService-DNYx0Dym.cjs +0 -73
  31. package/dist/VariableReplacementService-wuYKgeui.cjs +0 -3
  32. package/dist/chunk-CbDLau6x.cjs +0 -34
@@ -0,0 +1,1104 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+ let node_path = require("node:path");
29
+ node_path = __toESM(node_path);
30
+ let __agiflowai_aicode_utils = require("@agiflowai/aicode-utils");
31
+ let js_yaml = require("js-yaml");
32
+ js_yaml = __toESM(js_yaml);
33
+ let __composio_json_schema_to_zod = require("@composio/json-schema-to-zod");
34
+ let zod = require("zod");
35
+ let node_url = require("node:url");
36
+ let liquidjs = require("liquidjs");
37
+
38
+ //#region src/utils/pagination.ts
39
+ var PaginationHelper = class PaginationHelper {
40
+ /**
41
+ * Default page size for pagination
42
+ */
43
+ static DEFAULT_PAGE_SIZE = 10;
44
+ /**
45
+ * Decodes a cursor string to extract the start index
46
+ * @param cursor - String representing the start index (e.g., "10")
47
+ * @returns Start index or 0 if invalid/undefined
48
+ */
49
+ static decodeCursor(cursor) {
50
+ if (!cursor) return 0;
51
+ const index = Number.parseInt(cursor, 10);
52
+ if (Number.isNaN(index) || index < 0) return 0;
53
+ return index;
54
+ }
55
+ /**
56
+ * Encodes an index into a cursor string
57
+ * @param index - Start index to encode
58
+ * @returns Cursor string (e.g., "10")
59
+ */
60
+ static encodeCursor(index) {
61
+ return index.toString();
62
+ }
63
+ /**
64
+ * Paginates an array of items
65
+ * @param items - All items to paginate
66
+ * @param cursor - Optional cursor representing the start index
67
+ * @param pageSize - Number of items per page (default: 10)
68
+ * @param includeMeta - Whether to include metadata in response (default: true)
69
+ * @returns Paginated result with items and optional nextCursor
70
+ */
71
+ static paginate(items, cursor, pageSize = PaginationHelper.DEFAULT_PAGE_SIZE, includeMeta = true) {
72
+ const startIndex = PaginationHelper.decodeCursor(cursor);
73
+ const endIndex = startIndex + pageSize;
74
+ const result = {
75
+ items: items.slice(startIndex, endIndex),
76
+ nextCursor: endIndex < items.length ? PaginationHelper.encodeCursor(endIndex) : void 0
77
+ };
78
+ if (includeMeta) result._meta = {
79
+ total: items.length,
80
+ offset: startIndex,
81
+ limit: pageSize
82
+ };
83
+ return result;
84
+ }
85
+ };
86
+
87
+ //#endregion
88
+ //#region src/services/FileSystemService.ts
89
+ var FileSystemService = class {
90
+ async pathExists(path$5) {
91
+ return (0, __agiflowai_aicode_utils.pathExists)(path$5);
92
+ }
93
+ async readFile(path$5, encoding = "utf8") {
94
+ return (0, __agiflowai_aicode_utils.readFile)(path$5, encoding);
95
+ }
96
+ async readJson(path$5) {
97
+ return (0, __agiflowai_aicode_utils.readJson)(path$5);
98
+ }
99
+ async writeFile(path$5, content, encoding = "utf8") {
100
+ return (0, __agiflowai_aicode_utils.writeFile)(path$5, content, encoding);
101
+ }
102
+ async ensureDir(path$5) {
103
+ return (0, __agiflowai_aicode_utils.ensureDir)(path$5);
104
+ }
105
+ async copy(src, dest) {
106
+ return (0, __agiflowai_aicode_utils.copy)(src, dest);
107
+ }
108
+ async readdir(path$5) {
109
+ return (0, __agiflowai_aicode_utils.readdir)(path$5);
110
+ }
111
+ async stat(path$5) {
112
+ return (0, __agiflowai_aicode_utils.stat)(path$5);
113
+ }
114
+ };
115
+
116
+ //#endregion
117
+ //#region src/services/ScaffoldConfigLoader.ts
118
+ const VariablesSchemaSchema = zod.z.object({
119
+ type: zod.z.literal("object"),
120
+ properties: zod.z.record(zod.z.any()),
121
+ required: zod.z.array(zod.z.string()),
122
+ additionalProperties: zod.z.boolean()
123
+ });
124
+ const ScaffoldConfigEntrySchema = zod.z.object({
125
+ name: zod.z.string(),
126
+ description: zod.z.string().optional(),
127
+ instruction: zod.z.string().optional(),
128
+ targetFolder: zod.z.string().optional(),
129
+ variables_schema: VariablesSchemaSchema,
130
+ includes: zod.z.array(zod.z.string()),
131
+ generator: zod.z.string().optional(),
132
+ patterns: zod.z.array(zod.z.string()).optional()
133
+ });
134
+ const ScaffoldYamlSchema = zod.z.object({
135
+ boilerplate: zod.z.union([ScaffoldConfigEntrySchema, zod.z.array(ScaffoldConfigEntrySchema)]).optional(),
136
+ features: zod.z.union([ScaffoldConfigEntrySchema, zod.z.array(ScaffoldConfigEntrySchema)]).optional()
137
+ }).catchall(zod.z.union([ScaffoldConfigEntrySchema, zod.z.array(ScaffoldConfigEntrySchema)]));
138
+ var ScaffoldConfigLoader = class {
139
+ constructor(fileSystem, templateService) {
140
+ this.fileSystem = fileSystem;
141
+ this.templateService = templateService;
142
+ }
143
+ async parseArchitectConfig(templatePath) {
144
+ const architectPath = node_path.default.join(templatePath, "scaffold.yaml");
145
+ if (!await this.fileSystem.pathExists(architectPath)) return null;
146
+ try {
147
+ const content = await this.fileSystem.readFile(architectPath, "utf8");
148
+ const rawConfig = js_yaml.default.load(content);
149
+ return ScaffoldYamlSchema.parse(rawConfig);
150
+ } catch (error) {
151
+ if (error instanceof zod.z.ZodError) {
152
+ const errorMessages = error.errors.map((err) => `${err.path.join(".")}: ${err.message}`).join("; ");
153
+ throw new Error(`scaffold.yaml validation failed: ${errorMessages}`);
154
+ }
155
+ throw new Error(`Failed to parse scaffold.yaml: ${error instanceof Error ? error.message : String(error)}`);
156
+ }
157
+ }
158
+ parseIncludeEntry(includeEntry, variables) {
159
+ const [pathPart, conditionsPart] = includeEntry.split("?");
160
+ const conditions = {};
161
+ if (conditionsPart) {
162
+ const conditionPairs = conditionsPart.split("&");
163
+ for (const pair of conditionPairs) {
164
+ const [key, value] = pair.split("=");
165
+ if (key && value) conditions[key.trim()] = value.trim();
166
+ }
167
+ }
168
+ if (pathPart.includes("->")) {
169
+ const [sourcePath, targetPath] = pathPart.split("->").map((p) => p.trim());
170
+ return {
171
+ sourcePath,
172
+ targetPath: this.replaceVariablesInPath(targetPath, variables),
173
+ conditions
174
+ };
175
+ }
176
+ const processedPath = this.replaceVariablesInPath(pathPart.trim(), variables);
177
+ return {
178
+ sourcePath: pathPart.trim(),
179
+ targetPath: processedPath,
180
+ conditions
181
+ };
182
+ }
183
+ replaceVariablesInPath(pathStr, variables) {
184
+ return this.templateService.renderString(pathStr, variables);
185
+ }
186
+ shouldIncludeFile(conditions, variables) {
187
+ if (!conditions || Object.keys(conditions).length === 0) return true;
188
+ for (const [conditionKey, conditionValue] of Object.entries(conditions)) {
189
+ const variableValue = variables[conditionKey];
190
+ if (conditionValue === "true" || conditionValue === "false") {
191
+ const expectedBoolean = conditionValue === "true";
192
+ let actualBoolean;
193
+ if (typeof variableValue === "string") actualBoolean = variableValue.toLowerCase() === "true";
194
+ else actualBoolean = Boolean(variableValue);
195
+ if (actualBoolean !== expectedBoolean) return false;
196
+ } else if (String(variableValue) !== conditionValue) return false;
197
+ }
198
+ return true;
199
+ }
200
+ async validateTemplate(templatePath, scaffoldType) {
201
+ const errors = [];
202
+ const missingFiles = [];
203
+ if (!await this.fileSystem.pathExists(templatePath)) {
204
+ errors.push(`Template directory ${templatePath} does not exist`);
205
+ return {
206
+ isValid: false,
207
+ errors,
208
+ missingFiles
209
+ };
210
+ }
211
+ let architectConfig;
212
+ try {
213
+ architectConfig = await this.parseArchitectConfig(templatePath);
214
+ } catch (error) {
215
+ errors.push(`Failed to parse scaffold.yaml: ${error instanceof Error ? error.message : String(error)}`);
216
+ return {
217
+ isValid: false,
218
+ errors,
219
+ missingFiles
220
+ };
221
+ }
222
+ if (!architectConfig) {
223
+ errors.push("scaffold.yaml not found in template directory");
224
+ return {
225
+ isValid: false,
226
+ errors,
227
+ missingFiles
228
+ };
229
+ }
230
+ if (!architectConfig[scaffoldType]) {
231
+ const availableTypes = Object.keys(architectConfig).join(", ");
232
+ errors.push(`Scaffold type '${scaffoldType}' not found in scaffold.yaml. Available types: ${availableTypes}`);
233
+ return {
234
+ isValid: false,
235
+ errors,
236
+ missingFiles
237
+ };
238
+ }
239
+ const config = architectConfig[scaffoldType];
240
+ if (config.includes && Array.isArray(config.includes)) for (const includeFile of config.includes) {
241
+ const parsed = this.parseIncludeEntry(includeFile, {});
242
+ const sourcePath = node_path.default.join(templatePath, parsed.sourcePath);
243
+ const liquidSourcePath = `${sourcePath}.liquid`;
244
+ const sourceExists = await this.fileSystem.pathExists(sourcePath);
245
+ const liquidExists = await this.fileSystem.pathExists(liquidSourcePath);
246
+ if (!sourceExists && !liquidExists) missingFiles.push(includeFile);
247
+ }
248
+ return {
249
+ isValid: errors.length === 0 && missingFiles.length === 0,
250
+ errors,
251
+ missingFiles
252
+ };
253
+ }
254
+ };
255
+
256
+ //#endregion
257
+ //#region src/utils/schemaDefaults.ts
258
+ /**
259
+ * Applies schema defaults to variables without strict validation.
260
+ * This is useful when you want to fill in defaults but not fail on extra properties.
261
+ *
262
+ * @param schema - JSON Schema with properties and defaults
263
+ * @param variables - User-provided variables
264
+ * @returns Variables with defaults applied for missing properties
265
+ */
266
+ function applySchemaDefaults(schema, variables) {
267
+ const result = { ...variables };
268
+ if (!schema.properties) return result;
269
+ for (const [key, propSchema] of Object.entries(schema.properties)) if (result[key] === void 0 && propSchema.default !== void 0) result[key] = propSchema.default;
270
+ return result;
271
+ }
272
+
273
+ //#endregion
274
+ //#region src/services/ScaffoldProcessingService.ts
275
+ /**
276
+ * Shared service for common scaffolding operations like processing templates and tracking files
277
+ */
278
+ var ScaffoldProcessingService = class {
279
+ constructor(fileSystem, variableReplacer) {
280
+ this.fileSystem = fileSystem;
281
+ this.variableReplacer = variableReplacer;
282
+ }
283
+ /**
284
+ * Process a target path for variable replacement, handling both files and directories
285
+ */
286
+ async processTargetForVariableReplacement(targetPath, variables) {
287
+ if ((await this.fileSystem.stat(targetPath)).isDirectory()) await this.variableReplacer.processFilesForVariableReplacement(targetPath, variables);
288
+ else await this.variableReplacer.replaceVariablesInFile(targetPath, variables);
289
+ }
290
+ /**
291
+ * Track all created files, handling both single files and directories
292
+ */
293
+ async trackCreatedFiles(targetPath, createdFiles) {
294
+ if ((await this.fileSystem.stat(targetPath)).isDirectory()) await this.trackCreatedFilesRecursive(targetPath, createdFiles);
295
+ else createdFiles.push(targetPath);
296
+ }
297
+ /**
298
+ * Track all existing files, handling both single files and directories
299
+ */
300
+ async trackExistingFiles(targetPath, existingFiles) {
301
+ if ((await this.fileSystem.stat(targetPath)).isDirectory()) await this.trackExistingFilesRecursive(targetPath, existingFiles);
302
+ else existingFiles.push(targetPath);
303
+ }
304
+ /**
305
+ * Copy source to target, then process templates and track files
306
+ * Now supports tracking existing files separately from created files
307
+ * Automatically handles .liquid template files by stripping the extension
308
+ */
309
+ async copyAndProcess(sourcePath, targetPath, variables, createdFiles, existingFiles) {
310
+ await this.fileSystem.ensureDir(node_path.default.dirname(targetPath));
311
+ if (await this.fileSystem.pathExists(targetPath) && existingFiles) {
312
+ await this.trackExistingFiles(targetPath, existingFiles);
313
+ return;
314
+ }
315
+ let actualSourcePath = sourcePath;
316
+ if (!await this.fileSystem.pathExists(sourcePath)) {
317
+ const liquidSourcePath = `${sourcePath}.liquid`;
318
+ if (await this.fileSystem.pathExists(liquidSourcePath)) actualSourcePath = liquidSourcePath;
319
+ else throw new Error(`Source file not found: ${sourcePath} (also tried ${liquidSourcePath})`);
320
+ }
321
+ await this.fileSystem.copy(actualSourcePath, targetPath);
322
+ await this.processTargetForVariableReplacement(targetPath, variables);
323
+ await this.trackCreatedFiles(targetPath, createdFiles);
324
+ }
325
+ /**
326
+ * Recursively collect all file paths in a directory for created files
327
+ */
328
+ async trackCreatedFilesRecursive(dirPath, createdFiles) {
329
+ let items = [];
330
+ try {
331
+ items = await this.fileSystem.readdir(dirPath);
332
+ } catch (error) {
333
+ __agiflowai_aicode_utils.log.warn(`Cannot read directory ${dirPath}: ${error}`);
334
+ return;
335
+ }
336
+ const itemPaths = items.filter((item) => item).map((item) => node_path.default.join(dirPath, item));
337
+ const statResults = await Promise.all(itemPaths.map(async (itemPath) => {
338
+ try {
339
+ return {
340
+ itemPath,
341
+ stat: await this.fileSystem.stat(itemPath),
342
+ error: null
343
+ };
344
+ } catch (error) {
345
+ __agiflowai_aicode_utils.log.warn(`Cannot stat ${itemPath}: ${error}`);
346
+ return {
347
+ itemPath,
348
+ stat: null,
349
+ error
350
+ };
351
+ }
352
+ }));
353
+ const directories = [];
354
+ for (const { itemPath, stat } of statResults) {
355
+ if (!stat) continue;
356
+ if (stat.isDirectory()) directories.push(itemPath);
357
+ else if (stat.isFile()) createdFiles.push(itemPath);
358
+ }
359
+ await Promise.all(directories.map((dir) => this.trackCreatedFilesRecursive(dir, createdFiles)));
360
+ }
361
+ /**
362
+ * Recursively collect all file paths in a directory for existing files
363
+ */
364
+ async trackExistingFilesRecursive(dirPath, existingFiles) {
365
+ let items = [];
366
+ try {
367
+ items = await this.fileSystem.readdir(dirPath);
368
+ } catch (error) {
369
+ __agiflowai_aicode_utils.log.warn(`Cannot read directory ${dirPath}: ${error}`);
370
+ return;
371
+ }
372
+ const itemPaths = items.filter((item) => item).map((item) => node_path.default.join(dirPath, item));
373
+ const statResults = await Promise.all(itemPaths.map(async (itemPath) => {
374
+ try {
375
+ return {
376
+ itemPath,
377
+ stat: await this.fileSystem.stat(itemPath),
378
+ error: null
379
+ };
380
+ } catch (error) {
381
+ __agiflowai_aicode_utils.log.warn(`Cannot stat ${itemPath}: ${error}`);
382
+ return {
383
+ itemPath,
384
+ stat: null,
385
+ error
386
+ };
387
+ }
388
+ }));
389
+ const directories = [];
390
+ for (const { itemPath, stat } of statResults) {
391
+ if (!stat) continue;
392
+ if (stat.isDirectory()) directories.push(itemPath);
393
+ else if (stat.isFile()) existingFiles.push(itemPath);
394
+ }
395
+ await Promise.all(directories.map((dir) => this.trackExistingFilesRecursive(dir, existingFiles)));
396
+ }
397
+ };
398
+
399
+ //#endregion
400
+ //#region src/services/ScaffoldService.ts
401
+ var ScaffoldService = class {
402
+ templatesRootPath;
403
+ processingService;
404
+ constructor(fileSystem, scaffoldConfigLoader, variableReplacer, templatesRootPath) {
405
+ this.fileSystem = fileSystem;
406
+ this.scaffoldConfigLoader = scaffoldConfigLoader;
407
+ this.variableReplacer = variableReplacer;
408
+ const resolvedPath = templatesRootPath || __agiflowai_aicode_utils.TemplatesManagerService.findTemplatesPathSync();
409
+ if (!resolvedPath) throw new Error("Templates folder not found. Please create a \"templates\" folder in your workspace root, or specify \"templatesPath\" in toolkit.yaml to point to your templates directory.");
410
+ this.templatesRootPath = resolvedPath;
411
+ this.processingService = new ScaffoldProcessingService(fileSystem, variableReplacer);
412
+ }
413
+ /**
414
+ * Scaffold a new project from a boilerplate template
415
+ */
416
+ async useBoilerplate(options) {
417
+ try {
418
+ const { projectName, packageName, targetFolder, templateFolder, boilerplateName, variables = {} } = options;
419
+ const targetPath = node_path.default.isAbsolute(targetFolder) ? projectName ? node_path.default.join(targetFolder, projectName) : targetFolder : projectName ? node_path.default.join(process.cwd(), targetFolder, projectName) : node_path.default.join(process.cwd(), targetFolder);
420
+ const templatePath = node_path.default.join(this.templatesRootPath, templateFolder);
421
+ const validationResult = await this.scaffoldConfigLoader.validateTemplate(templatePath, "boilerplate");
422
+ if (!validationResult.isValid) return {
423
+ success: false,
424
+ message: `Template validation failed: ${[...validationResult.errors, ...validationResult.missingFiles.map((f) => `Template file not found: ${f}`)].join("; ")}`
425
+ };
426
+ if (projectName) {
427
+ if (await this.fileSystem.pathExists(targetPath)) return {
428
+ success: false,
429
+ message: `Directory ${targetPath} already exists`
430
+ };
431
+ }
432
+ const architectConfig = await this.scaffoldConfigLoader.parseArchitectConfig(templatePath);
433
+ if (!architectConfig || !architectConfig.boilerplate) return {
434
+ success: false,
435
+ message: `Invalid architect configuration: missing 'boilerplate' section in scaffold.yaml`
436
+ };
437
+ const boilerplateArray = architectConfig.boilerplate;
438
+ let config;
439
+ if (Array.isArray(boilerplateArray)) {
440
+ config = boilerplateArray.find((b) => b.name === boilerplateName);
441
+ if (!config) return {
442
+ success: false,
443
+ message: `Boilerplate '${boilerplateName}' not found in scaffold configuration`
444
+ };
445
+ } else config = architectConfig.boilerplate;
446
+ const effectiveProjectName = projectName || (packageName.includes("/") ? packageName.split("/")[1] : packageName);
447
+ const allVariables = {
448
+ ...variables,
449
+ projectName: effectiveProjectName,
450
+ packageName
451
+ };
452
+ return await this.processScaffold({
453
+ config,
454
+ targetPath,
455
+ templatePath,
456
+ allVariables,
457
+ scaffoldType: "boilerplate"
458
+ });
459
+ } catch (error) {
460
+ return {
461
+ success: false,
462
+ message: `Error scaffolding boilerplate: ${error instanceof Error ? error.message : String(error)}`
463
+ };
464
+ }
465
+ }
466
+ /**
467
+ * Scaffold a new feature into an existing project
468
+ */
469
+ async useFeature(options) {
470
+ try {
471
+ const { projectPath, templateFolder, featureName, variables = {} } = options;
472
+ const targetPath = node_path.default.resolve(projectPath);
473
+ const templatePath = node_path.default.join(this.templatesRootPath, templateFolder);
474
+ const projectName = node_path.default.basename(targetPath);
475
+ const validationResult = await this.scaffoldConfigLoader.validateTemplate(templatePath, "features");
476
+ if (!validationResult.isValid) return {
477
+ success: false,
478
+ message: `Template validation failed: ${[...validationResult.errors, ...validationResult.missingFiles.map((f) => `Template file not found: ${f}`)].join("; ")}`
479
+ };
480
+ if (!await this.fileSystem.pathExists(targetPath)) return {
481
+ success: false,
482
+ message: `Target directory ${targetPath} does not exist. Please create the parent directory first.`
483
+ };
484
+ const architectConfig = await this.scaffoldConfigLoader.parseArchitectConfig(templatePath);
485
+ if (!architectConfig || !architectConfig.features) return {
486
+ success: false,
487
+ message: `Invalid architect configuration: missing 'features' section in scaffold.yaml`
488
+ };
489
+ const featureArray = architectConfig.features;
490
+ let config;
491
+ if (Array.isArray(featureArray)) {
492
+ config = featureArray.find((f) => f.name === featureName);
493
+ if (!config) return {
494
+ success: false,
495
+ message: `Feature '${featureName}' not found in scaffold configuration`
496
+ };
497
+ } else config = architectConfig.features;
498
+ const allVariables = {
499
+ ...variables,
500
+ projectName,
501
+ appPath: targetPath,
502
+ appName: projectName
503
+ };
504
+ return await this.processScaffold({
505
+ config,
506
+ targetPath,
507
+ templatePath,
508
+ allVariables,
509
+ scaffoldType: "feature"
510
+ });
511
+ } catch (error) {
512
+ return {
513
+ success: false,
514
+ message: `Error scaffolding feature: ${error instanceof Error ? error.message : String(error)}`
515
+ };
516
+ }
517
+ }
518
+ /**
519
+ * Common scaffolding processing logic shared by both useBoilerplate and useFeature
520
+ */
521
+ async processScaffold(params) {
522
+ const { config, targetPath, templatePath, allVariables, scaffoldType } = params;
523
+ __agiflowai_aicode_utils.log.debug("Config generator:", config.generator);
524
+ __agiflowai_aicode_utils.log.debug("Config:", JSON.stringify(config, null, 2));
525
+ if (config.generator) {
526
+ __agiflowai_aicode_utils.log.info("Using custom generator:", config.generator);
527
+ try {
528
+ const generator = (await import(node_path.default.join(templatePath, "generators", config.generator))).default;
529
+ if (typeof generator !== "function") return {
530
+ success: false,
531
+ message: `Invalid generator: ${config.generator} does not export a default function`
532
+ };
533
+ return await generator({
534
+ variables: allVariables,
535
+ config,
536
+ targetPath,
537
+ templatePath,
538
+ fileSystem: this.fileSystem,
539
+ scaffoldConfigLoader: this.scaffoldConfigLoader,
540
+ variableReplacer: this.variableReplacer,
541
+ ScaffoldProcessingService: this.processingService.constructor,
542
+ getRootPath: () => {
543
+ const __dirname$1 = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
544
+ return node_path.default.join(__dirname$1, "../../../../..");
545
+ },
546
+ getProjectPath: (projectPath) => {
547
+ const __dirname$1 = node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
548
+ const rootPath = node_path.default.join(__dirname$1, "../../../../..");
549
+ return projectPath.replace(rootPath, "").replace("/", "");
550
+ }
551
+ });
552
+ } catch (error) {
553
+ return {
554
+ success: false,
555
+ message: `Error loading or executing generator ${config.generator}: ${error instanceof Error ? error.message : String(error)}`
556
+ };
557
+ }
558
+ }
559
+ const parsedIncludes = [];
560
+ const warnings = [];
561
+ const variablesWithDefaults = config.variables_schema ? applySchemaDefaults(config.variables_schema, allVariables) : allVariables;
562
+ if (config.includes && Array.isArray(config.includes)) {
563
+ const filteredIncludes = config.includes.map((includeEntry) => this.scaffoldConfigLoader.parseIncludeEntry(includeEntry, variablesWithDefaults)).filter((parsed) => this.scaffoldConfigLoader.shouldIncludeFile(parsed.conditions, variablesWithDefaults));
564
+ const existsResults = await Promise.all(filteredIncludes.map(async (parsed) => {
565
+ const targetFilePath = node_path.default.join(targetPath, parsed.targetPath);
566
+ return {
567
+ parsed,
568
+ exists: await this.fileSystem.pathExists(targetFilePath)
569
+ };
570
+ }));
571
+ for (const { parsed, exists } of existsResults) {
572
+ parsedIncludes.push(parsed);
573
+ if (exists) warnings.push(`File/folder ${parsed.targetPath} already exists and will be preserved`);
574
+ }
575
+ }
576
+ await this.fileSystem.ensureDir(targetPath);
577
+ const createdFiles = [];
578
+ const existingFiles = [];
579
+ await Promise.all(parsedIncludes.map(async (parsed) => {
580
+ const sourcePath = node_path.default.join(templatePath, parsed.sourcePath);
581
+ const targetFilePath = node_path.default.join(targetPath, parsed.targetPath);
582
+ await this.processingService.copyAndProcess(sourcePath, targetFilePath, variablesWithDefaults, createdFiles, existingFiles);
583
+ }));
584
+ let message = `Successfully scaffolded ${scaffoldType} at ${targetPath}`;
585
+ if (existingFiles.length > 0) message += `. ${existingFiles.length} existing file(s) were preserved`;
586
+ message += ". Run 'pnpm install' to install dependencies.";
587
+ return {
588
+ success: true,
589
+ message,
590
+ warnings: warnings.length > 0 ? warnings : void 0,
591
+ createdFiles: createdFiles.length > 0 ? createdFiles : void 0,
592
+ existingFiles: existingFiles.length > 0 ? existingFiles : void 0
593
+ };
594
+ }
595
+ };
596
+
597
+ //#endregion
598
+ //#region src/services/TemplateService.ts
599
+ var TemplateService = class {
600
+ liquid;
601
+ constructor() {
602
+ this.liquid = new liquidjs.Liquid({
603
+ strictFilters: false,
604
+ strictVariables: false
605
+ });
606
+ this.setupCustomFilters();
607
+ __agiflowai_aicode_utils.log.info("TemplateService initialized");
608
+ }
609
+ toPascalCase(str) {
610
+ const camelCase = str.replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "");
611
+ return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
612
+ }
613
+ setupCustomFilters() {
614
+ this.liquid.registerFilter("camelCase", (str) => {
615
+ return str.replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "");
616
+ });
617
+ this.liquid.registerFilter("pascalCase", (str) => {
618
+ return this.toPascalCase(str);
619
+ });
620
+ this.liquid.registerFilter("titleCase", (str) => {
621
+ return this.toPascalCase(str);
622
+ });
623
+ this.liquid.registerFilter("kebabCase", (str) => {
624
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
625
+ });
626
+ this.liquid.registerFilter("snakeCase", (str) => {
627
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toLowerCase();
628
+ });
629
+ this.liquid.registerFilter("upperCase", (str) => {
630
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toUpperCase();
631
+ });
632
+ this.liquid.registerFilter("lower", (str) => str.toLowerCase());
633
+ this.liquid.registerFilter("upper", (str) => str.toUpperCase());
634
+ this.liquid.registerFilter("pluralize", (str) => {
635
+ if (str.endsWith("y")) return `${str.slice(0, -1)}ies`;
636
+ else if (str.endsWith("s") || str.endsWith("sh") || str.endsWith("ch") || str.endsWith("x") || str.endsWith("z")) return `${str}es`;
637
+ else return `${str}s`;
638
+ });
639
+ this.liquid.registerFilter("singularize", (str) => {
640
+ if (str.endsWith("ies")) return `${str.slice(0, -3)}y`;
641
+ else if (str.endsWith("es")) return str.slice(0, -2);
642
+ else if (str.endsWith("s") && !str.endsWith("ss")) return str.slice(0, -1);
643
+ else return str;
644
+ });
645
+ this.liquid.registerFilter("strip", (str) => {
646
+ return str.trim();
647
+ });
648
+ }
649
+ renderString(template, variables) {
650
+ try {
651
+ __agiflowai_aicode_utils.log.debug("Rendering template", {
652
+ variables,
653
+ templatePreview: template.substring(0, 100)
654
+ });
655
+ const result = this.liquid.parseAndRenderSync(template, variables);
656
+ __agiflowai_aicode_utils.log.debug("Rendered template", { resultPreview: result.substring(0, 100) });
657
+ return result;
658
+ } catch (error) {
659
+ __agiflowai_aicode_utils.log.error("LiquidJS rendering error", {
660
+ error: error instanceof Error ? error.message : String(error),
661
+ templatePreview: template.substring(0, 200),
662
+ variables
663
+ });
664
+ return template;
665
+ }
666
+ }
667
+ containsTemplateVariables(content) {
668
+ return [/\{\{.*?\}\}/, /\{%.*?%\}/].some((pattern) => pattern.test(content));
669
+ }
670
+ };
671
+
672
+ //#endregion
673
+ //#region src/services/VariableReplacementService.ts
674
+ var VariableReplacementService = class {
675
+ binaryExtensions = [
676
+ ".png",
677
+ ".jpg",
678
+ ".jpeg",
679
+ ".gif",
680
+ ".ico",
681
+ ".woff",
682
+ ".woff2",
683
+ ".ttf",
684
+ ".eot",
685
+ ".pdf",
686
+ ".zip",
687
+ ".tar",
688
+ ".gz",
689
+ ".exe",
690
+ ".dll",
691
+ ".so",
692
+ ".dylib"
693
+ ];
694
+ constructor(fileSystem, templateService) {
695
+ this.fileSystem = fileSystem;
696
+ this.templateService = templateService;
697
+ }
698
+ async processFilesForVariableReplacement(dirPath, variables) {
699
+ let items = [];
700
+ try {
701
+ items = await this.fileSystem.readdir(dirPath);
702
+ } catch (error) {
703
+ __agiflowai_aicode_utils.log.warn(`Skipping directory ${dirPath}: ${error}`);
704
+ return;
705
+ }
706
+ const itemPaths = items.filter((item) => item).map((item) => node_path.default.join(dirPath, item));
707
+ const statResults = await Promise.all(itemPaths.map(async (itemPath) => {
708
+ try {
709
+ return {
710
+ itemPath,
711
+ stat: await this.fileSystem.stat(itemPath),
712
+ error: null
713
+ };
714
+ } catch (error) {
715
+ __agiflowai_aicode_utils.log.warn(`Skipping item ${itemPath}: ${error}`);
716
+ return {
717
+ itemPath,
718
+ stat: null,
719
+ error
720
+ };
721
+ }
722
+ }));
723
+ const directories = [];
724
+ const files = [];
725
+ for (const { itemPath, stat } of statResults) {
726
+ if (!stat) continue;
727
+ if (stat.isDirectory()) directories.push(itemPath);
728
+ else if (stat.isFile()) files.push(itemPath);
729
+ }
730
+ await Promise.all([...files.map((file) => this.replaceVariablesInFile(file, variables)), ...directories.map((dir) => this.processFilesForVariableReplacement(dir, variables))]);
731
+ }
732
+ async replaceVariablesInFile(filePath, variables) {
733
+ try {
734
+ if (this.isBinaryFile(filePath)) return;
735
+ const content = await this.fileSystem.readFile(filePath, "utf8");
736
+ const renderedContent = this.templateService.renderString(content, variables);
737
+ await this.fileSystem.writeFile(filePath, renderedContent, "utf8");
738
+ } catch (error) {
739
+ __agiflowai_aicode_utils.log.warn(`Skipping file ${filePath}: ${error}`);
740
+ }
741
+ }
742
+ isBinaryFile(filePath) {
743
+ const ext = node_path.default.extname(filePath).toLowerCase();
744
+ return this.binaryExtensions.includes(ext);
745
+ }
746
+ };
747
+
748
+ //#endregion
749
+ //#region src/services/ScaffoldingMethodsService.ts
750
+ var ScaffoldingMethodsService = class {
751
+ templateService;
752
+ constructor(fileSystem, templatesRootPath) {
753
+ this.fileSystem = fileSystem;
754
+ this.templatesRootPath = templatesRootPath;
755
+ this.templateService = new TemplateService();
756
+ }
757
+ async listScaffoldingMethods(projectPath, cursor) {
758
+ const absoluteProjectPath = node_path.default.resolve(projectPath);
759
+ const sourceTemplate = (await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(absoluteProjectPath)).sourceTemplate;
760
+ return this.listScaffoldingMethodsByTemplate(sourceTemplate, cursor);
761
+ }
762
+ async listScaffoldingMethodsByTemplate(templateName, cursor) {
763
+ const templatePath = await this.findTemplatePath(templateName);
764
+ if (!templatePath) throw new Error(`Template not found for sourceTemplate: ${templateName}`);
765
+ const fullTemplatePath = node_path.default.join(this.templatesRootPath, templatePath);
766
+ const scaffoldYamlPath = node_path.default.join(fullTemplatePath, "scaffold.yaml");
767
+ if (!await this.fileSystem.pathExists(scaffoldYamlPath)) throw new Error(`scaffold.yaml not found at ${scaffoldYamlPath}`);
768
+ const scaffoldContent = await this.fileSystem.readFile(scaffoldYamlPath, "utf8");
769
+ const architectConfig = js_yaml.default.load(scaffoldContent);
770
+ const methods = [];
771
+ if (architectConfig.features && Array.isArray(architectConfig.features)) architectConfig.features.forEach((feature) => {
772
+ const featureName = feature.name || `scaffold-${templateName}`;
773
+ methods.push({
774
+ name: featureName,
775
+ description: feature.description || "",
776
+ instruction: feature.instruction || "",
777
+ variables_schema: feature.variables_schema || {
778
+ type: "object",
779
+ properties: {},
780
+ required: [],
781
+ additionalProperties: false
782
+ },
783
+ generator: feature.generator
784
+ });
785
+ });
786
+ const paginatedResult = PaginationHelper.paginate(methods, cursor);
787
+ return {
788
+ sourceTemplate: templateName,
789
+ templatePath,
790
+ methods: paginatedResult.items,
791
+ nextCursor: paginatedResult.nextCursor,
792
+ _meta: paginatedResult._meta
793
+ };
794
+ }
795
+ /**
796
+ * Gets scaffolding methods with instructions rendered using provided variables
797
+ */
798
+ async listScaffoldingMethodsWithVariables(projectPath, variables, cursor) {
799
+ const result = await this.listScaffoldingMethods(projectPath, cursor);
800
+ const processedMethods = result.methods.map((method) => ({
801
+ ...method,
802
+ instruction: method.instruction ? this.processScaffoldInstruction(method.instruction, variables) : void 0
803
+ }));
804
+ return {
805
+ ...result,
806
+ methods: processedMethods
807
+ };
808
+ }
809
+ /**
810
+ * Processes scaffold instruction with template service
811
+ */
812
+ processScaffoldInstruction(instruction, variables) {
813
+ if (this.templateService.containsTemplateVariables(instruction)) return this.templateService.renderString(instruction, variables);
814
+ return instruction;
815
+ }
816
+ async findTemplatePath(sourceTemplate) {
817
+ const templateDirs = await this.discoverTemplateDirs();
818
+ if (templateDirs.includes(sourceTemplate)) return sourceTemplate;
819
+ for (const templateDir of templateDirs) {
820
+ const templatePath = node_path.default.join(this.templatesRootPath, templateDir);
821
+ const scaffoldYamlPath = node_path.default.join(templatePath, "scaffold.yaml");
822
+ if (await this.fileSystem.pathExists(scaffoldYamlPath)) try {
823
+ const scaffoldContent = await this.fileSystem.readFile(scaffoldYamlPath, "utf8");
824
+ const architectConfig = js_yaml.default.load(scaffoldContent);
825
+ if (architectConfig.boilerplate && Array.isArray(architectConfig.boilerplate)) {
826
+ for (const boilerplate of architectConfig.boilerplate) if (boilerplate.name?.includes(sourceTemplate)) return templateDir;
827
+ }
828
+ } catch (error) {
829
+ __agiflowai_aicode_utils.log.warn(`Failed to read scaffold.yaml at ${scaffoldYamlPath}:`, error);
830
+ }
831
+ }
832
+ return null;
833
+ }
834
+ /**
835
+ * Resolves the project path, handling both monorepo and monolith cases
836
+ * Uses ProjectConfigResolver to find the correct workspace/project root
837
+ */
838
+ async resolveProjectPath(projectPath) {
839
+ const absolutePath = node_path.default.resolve(projectPath);
840
+ return (await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(absolutePath)).workspaceRoot || absolutePath;
841
+ }
842
+ /**
843
+ * Dynamically discovers all template directories
844
+ * Supports both flat structure (templates/nextjs-15) and nested structure (templates/apps/nextjs-15)
845
+ **/
846
+ async discoverTemplateDirs() {
847
+ const templateDirs = [];
848
+ try {
849
+ const itemPaths = (await this.fileSystem.readdir(this.templatesRootPath)).map((item) => ({
850
+ item,
851
+ itemPath: node_path.default.join(this.templatesRootPath, item)
852
+ }));
853
+ const itemResults = await Promise.all(itemPaths.map(async ({ item, itemPath }) => {
854
+ try {
855
+ if (!(await this.fileSystem.stat(itemPath)).isDirectory()) return {
856
+ item,
857
+ itemPath,
858
+ isDir: false,
859
+ hasScaffold: false
860
+ };
861
+ const scaffoldYamlPath = node_path.default.join(itemPath, "scaffold.yaml");
862
+ return {
863
+ item,
864
+ itemPath,
865
+ isDir: true,
866
+ hasScaffold: await this.fileSystem.pathExists(scaffoldYamlPath)
867
+ };
868
+ } catch {
869
+ return {
870
+ item,
871
+ itemPath,
872
+ isDir: false,
873
+ hasScaffold: false
874
+ };
875
+ }
876
+ }));
877
+ const categoryDirs = [];
878
+ for (const result of itemResults) {
879
+ if (!result.isDir) continue;
880
+ if (result.hasScaffold) templateDirs.push(result.item);
881
+ else categoryDirs.push({
882
+ item: result.item,
883
+ itemPath: result.itemPath
884
+ });
885
+ }
886
+ const nestedResults = await Promise.all(categoryDirs.map(async ({ item, itemPath }) => {
887
+ const found = [];
888
+ try {
889
+ const subItems = await this.fileSystem.readdir(itemPath);
890
+ const subResults = await Promise.all(subItems.map(async (subItem) => {
891
+ const subItemPath = node_path.default.join(itemPath, subItem);
892
+ try {
893
+ if (!(await this.fileSystem.stat(subItemPath)).isDirectory()) return null;
894
+ const subScaffoldYamlPath = node_path.default.join(subItemPath, "scaffold.yaml");
895
+ if (await this.fileSystem.pathExists(subScaffoldYamlPath)) return node_path.default.join(item, subItem);
896
+ } catch {
897
+ return null;
898
+ }
899
+ return null;
900
+ }));
901
+ for (const relativePath of subResults) if (relativePath) found.push(relativePath);
902
+ } catch (error) {
903
+ __agiflowai_aicode_utils.log.warn(`Failed to read subdirectories in ${itemPath}:`, error);
904
+ }
905
+ return found;
906
+ }));
907
+ for (const dirs of nestedResults) templateDirs.push(...dirs);
908
+ } catch (error) {
909
+ __agiflowai_aicode_utils.log.warn(`Failed to read templates root directory ${this.templatesRootPath}:`, error);
910
+ }
911
+ return templateDirs;
912
+ }
913
+ async useScaffoldMethod(request) {
914
+ const { projectPath, scaffold_feature_name, variables, sessionId } = request;
915
+ const absoluteProjectPath = await this.resolveProjectPath(projectPath);
916
+ const scaffoldingMethods = await this.listScaffoldingMethods(absoluteProjectPath);
917
+ const method = scaffoldingMethods.methods.find((m) => m.name === scaffold_feature_name);
918
+ if (!method) {
919
+ const availableMethods = scaffoldingMethods.methods.map((m) => m.name).join(", ");
920
+ throw new Error(`Scaffold method '${scaffold_feature_name}' not found. Available methods: ${availableMethods}`);
921
+ }
922
+ const templateService = new TemplateService();
923
+ const scaffoldConfigLoader = new ScaffoldConfigLoader(this.fileSystem, templateService);
924
+ const variableReplacer = new VariableReplacementService(this.fileSystem, templateService);
925
+ const scaffoldService = new ScaffoldService(this.fileSystem, scaffoldConfigLoader, variableReplacer, this.templatesRootPath);
926
+ const projectName = node_path.default.basename(absoluteProjectPath);
927
+ const result = await scaffoldService.useFeature({
928
+ projectPath: absoluteProjectPath,
929
+ templateFolder: scaffoldingMethods.templatePath,
930
+ featureName: scaffold_feature_name,
931
+ variables: {
932
+ ...variables,
933
+ appPath: absoluteProjectPath,
934
+ appName: projectName
935
+ }
936
+ });
937
+ if (!result.success) throw new Error(result.message);
938
+ if (sessionId && result.createdFiles && result.createdFiles.length > 0) try {
939
+ const { ExecutionLogService, DECISION_ALLOW } = await import("@agiflowai/hooks-adapter");
940
+ await new ExecutionLogService(sessionId).logExecution({
941
+ filePath: absoluteProjectPath,
942
+ operation: "scaffold",
943
+ decision: DECISION_ALLOW,
944
+ generatedFiles: result.createdFiles
945
+ });
946
+ } catch (error) {
947
+ __agiflowai_aicode_utils.log.warn("Failed to log scaffold execution:", error);
948
+ }
949
+ return {
950
+ success: true,
951
+ message: `
952
+ Successfully scaffolded ${scaffold_feature_name} in ${projectPath}.
953
+ Please follow this **instruction**: \n ${method.instruction ? this.processScaffoldInstruction(method.instruction, variables) : ""}.
954
+ -> Create or update the plan based on the instruction.
955
+ `,
956
+ warnings: result.warnings,
957
+ createdFiles: result.createdFiles,
958
+ existingFiles: result.existingFiles
959
+ };
960
+ }
961
+ };
962
+
963
+ //#endregion
964
+ //#region src/instructions/tools/list-scaffolding-methods/description.md?raw
965
+ var description_default = "Lists all available scaffolding methods (features) that can be added to an existing project{% if not isMonolith %} or for a specific template{% endif %}.\n\nThis tool:\n{% if isMonolith %}\n- Reads your project's sourceTemplate from toolkit.yaml at workspace root\n{% else %}\n- Reads the project's sourceTemplate from project.json (monorepo) or toolkit.yaml (monolith), OR\n- Directly uses the provided templateName to list available features\n{% endif %}\n- Returns available features for that template type\n- Provides variable schemas for each scaffolding method\n- Shows descriptions of what each method creates\n\nUse this FIRST when adding features to understand:\n- What scaffolding methods are available\n- What variables each method requires\n- What files/features will be generated\n\nExample methods might include:\n- Adding new React routes (for React apps)\n- Creating API endpoints (for backend projects)\n- Adding new components (for frontend projects)\n- Setting up database models (for API projects)\n";
966
+
967
+ //#endregion
968
+ //#region src/tools/ListScaffoldingMethodsTool.ts
969
+ var ListScaffoldingMethodsTool = class ListScaffoldingMethodsTool {
970
+ static TOOL_NAME = "list-scaffolding-methods";
971
+ fileSystemService;
972
+ scaffoldingMethodsService;
973
+ templateService;
974
+ isMonolith;
975
+ constructor(templatesPath, isMonolith = false) {
976
+ this.fileSystemService = new FileSystemService();
977
+ this.scaffoldingMethodsService = new ScaffoldingMethodsService(this.fileSystemService, templatesPath);
978
+ this.templateService = new TemplateService();
979
+ this.isMonolith = isMonolith;
980
+ }
981
+ /**
982
+ * Get the tool definition for MCP
983
+ */
984
+ getDefinition() {
985
+ const description = this.templateService.renderString(description_default, { isMonolith: this.isMonolith });
986
+ const properties = { cursor: {
987
+ type: "string",
988
+ description: "Optional pagination cursor to fetch the next page of results. Omit to fetch the first page."
989
+ } };
990
+ if (!this.isMonolith) {
991
+ properties.projectPath = {
992
+ type: "string",
993
+ description: "Absolute path to the project directory (for monorepo: containing project.json; for monolith: workspace root with toolkit.yaml). Either projectPath or templateName is required."
994
+ };
995
+ properties.templateName = {
996
+ type: "string",
997
+ description: "Name of the template to list scaffolding methods for (e.g., \"nextjs-15\", \"typescript-mcp-package\"). Either projectPath or templateName is required."
998
+ };
999
+ }
1000
+ return {
1001
+ name: ListScaffoldingMethodsTool.TOOL_NAME,
1002
+ description: description.trim(),
1003
+ inputSchema: {
1004
+ type: "object",
1005
+ properties,
1006
+ additionalProperties: false
1007
+ }
1008
+ };
1009
+ }
1010
+ /**
1011
+ * Execute the tool
1012
+ */
1013
+ async execute(args) {
1014
+ try {
1015
+ const { projectPath, templateName, cursor } = args;
1016
+ let result;
1017
+ if (this.isMonolith) try {
1018
+ const resolvedTemplateName = (await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(process.cwd())).sourceTemplate;
1019
+ result = await this.scaffoldingMethodsService.listScaffoldingMethodsByTemplate(resolvedTemplateName, cursor);
1020
+ } catch (error) {
1021
+ throw new Error(`Failed to read template name from configuration: ${error instanceof Error ? error.message : String(error)}`);
1022
+ }
1023
+ else {
1024
+ if (!projectPath && !templateName) throw new Error("Either projectPath or templateName must be provided");
1025
+ if (projectPath) result = await this.scaffoldingMethodsService.listScaffoldingMethods(projectPath, cursor);
1026
+ else result = await this.scaffoldingMethodsService.listScaffoldingMethodsByTemplate(templateName, cursor);
1027
+ }
1028
+ return { content: [{
1029
+ type: "text",
1030
+ text: JSON.stringify(result, null, 2)
1031
+ }] };
1032
+ } catch (error) {
1033
+ return {
1034
+ content: [{
1035
+ type: "text",
1036
+ text: `Error listing scaffolding methods: ${error instanceof Error ? error.message : String(error)}`
1037
+ }],
1038
+ isError: true
1039
+ };
1040
+ }
1041
+ }
1042
+ };
1043
+
1044
+ //#endregion
1045
+ Object.defineProperty(exports, 'FileSystemService', {
1046
+ enumerable: true,
1047
+ get: function () {
1048
+ return FileSystemService;
1049
+ }
1050
+ });
1051
+ Object.defineProperty(exports, 'ListScaffoldingMethodsTool', {
1052
+ enumerable: true,
1053
+ get: function () {
1054
+ return ListScaffoldingMethodsTool;
1055
+ }
1056
+ });
1057
+ Object.defineProperty(exports, 'PaginationHelper', {
1058
+ enumerable: true,
1059
+ get: function () {
1060
+ return PaginationHelper;
1061
+ }
1062
+ });
1063
+ Object.defineProperty(exports, 'ScaffoldConfigLoader', {
1064
+ enumerable: true,
1065
+ get: function () {
1066
+ return ScaffoldConfigLoader;
1067
+ }
1068
+ });
1069
+ Object.defineProperty(exports, 'ScaffoldProcessingService', {
1070
+ enumerable: true,
1071
+ get: function () {
1072
+ return ScaffoldProcessingService;
1073
+ }
1074
+ });
1075
+ Object.defineProperty(exports, 'ScaffoldService', {
1076
+ enumerable: true,
1077
+ get: function () {
1078
+ return ScaffoldService;
1079
+ }
1080
+ });
1081
+ Object.defineProperty(exports, 'ScaffoldingMethodsService', {
1082
+ enumerable: true,
1083
+ get: function () {
1084
+ return ScaffoldingMethodsService;
1085
+ }
1086
+ });
1087
+ Object.defineProperty(exports, 'TemplateService', {
1088
+ enumerable: true,
1089
+ get: function () {
1090
+ return TemplateService;
1091
+ }
1092
+ });
1093
+ Object.defineProperty(exports, 'VariableReplacementService', {
1094
+ enumerable: true,
1095
+ get: function () {
1096
+ return VariableReplacementService;
1097
+ }
1098
+ });
1099
+ Object.defineProperty(exports, '__toESM', {
1100
+ enumerable: true,
1101
+ get: function () {
1102
+ return __toESM;
1103
+ }
1104
+ });