@inkeep/agents-cli 0.59.3 → 0.60.0

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 (88) hide show
  1. package/dist/agents-cli/package.js +1 -1
  2. package/dist/commands/pull-v4/collector-common.js +128 -0
  3. package/dist/commands/pull-v4/collector-common.js.map +1 -0
  4. package/dist/commands/pull-v4/collector-reference-helpers.js +323 -0
  5. package/dist/commands/pull-v4/collector-reference-helpers.js.map +1 -0
  6. package/dist/commands/pull-v4/component-parser.js +2 -1
  7. package/dist/commands/pull-v4/component-parser.js.map +1 -1
  8. package/dist/commands/pull-v4/file-scope.js +43 -0
  9. package/dist/commands/pull-v4/file-scope.js.map +1 -0
  10. package/dist/commands/pull-v4/generation-resolver.js +305 -0
  11. package/dist/commands/pull-v4/generation-resolver.js.map +1 -0
  12. package/dist/commands/pull-v4/generation-types.js +56 -0
  13. package/dist/commands/pull-v4/generation-types.js.map +1 -0
  14. package/dist/commands/pull-v4/generators/agent-generator.helpers.js +4 -10
  15. package/dist/commands/pull-v4/generators/agent-generator.helpers.js.map +1 -1
  16. package/dist/commands/pull-v4/generators/agent-generator.js +154 -81
  17. package/dist/commands/pull-v4/generators/agent-generator.js.map +1 -1
  18. package/dist/commands/pull-v4/generators/artifact-component-generator.js +48 -27
  19. package/dist/commands/pull-v4/generators/artifact-component-generator.js.map +1 -1
  20. package/dist/commands/pull-v4/generators/context-config-generator.js +147 -129
  21. package/dist/commands/pull-v4/generators/context-config-generator.js.map +1 -1
  22. package/dist/commands/pull-v4/generators/credential-generator.js +36 -14
  23. package/dist/commands/pull-v4/generators/credential-generator.js.map +1 -1
  24. package/dist/commands/pull-v4/generators/data-component-generator.js +55 -19
  25. package/dist/commands/pull-v4/generators/data-component-generator.js.map +1 -1
  26. package/dist/commands/pull-v4/generators/environment-generator.js +29 -33
  27. package/dist/commands/pull-v4/generators/environment-generator.js.map +1 -1
  28. package/dist/commands/pull-v4/generators/environment-settings-generator.js +57 -0
  29. package/dist/commands/pull-v4/generators/environment-settings-generator.js.map +1 -0
  30. package/dist/commands/pull-v4/generators/external-agent-generator.js +51 -23
  31. package/dist/commands/pull-v4/generators/external-agent-generator.js.map +1 -1
  32. package/dist/commands/pull-v4/generators/function-tool-generator.js +50 -14
  33. package/dist/commands/pull-v4/generators/function-tool-generator.js.map +1 -1
  34. package/dist/commands/pull-v4/generators/helpers/agent.js +129 -0
  35. package/dist/commands/pull-v4/generators/helpers/agent.js.map +1 -0
  36. package/dist/commands/pull-v4/generators/helpers/sub-agent.js +65 -0
  37. package/dist/commands/pull-v4/generators/helpers/sub-agent.js.map +1 -0
  38. package/dist/commands/pull-v4/generators/index.js +38 -0
  39. package/dist/commands/pull-v4/generators/index.js.map +1 -0
  40. package/dist/commands/pull-v4/generators/mcp-tool-generator.js +48 -27
  41. package/dist/commands/pull-v4/generators/mcp-tool-generator.js.map +1 -1
  42. package/dist/commands/pull-v4/generators/project-generator.js +144 -110
  43. package/dist/commands/pull-v4/generators/project-generator.js.map +1 -1
  44. package/dist/commands/pull-v4/generators/scheduled-trigger-generator.js +66 -0
  45. package/dist/commands/pull-v4/generators/scheduled-trigger-generator.js.map +1 -0
  46. package/dist/commands/pull-v4/generators/status-component-generator.js +55 -20
  47. package/dist/commands/pull-v4/generators/status-component-generator.js.map +1 -1
  48. package/dist/commands/pull-v4/generators/sub-agent-generator.helpers.js +4 -1
  49. package/dist/commands/pull-v4/generators/sub-agent-generator.helpers.js.map +1 -1
  50. package/dist/commands/pull-v4/generators/sub-agent-generator.js +282 -166
  51. package/dist/commands/pull-v4/generators/sub-agent-generator.js.map +1 -1
  52. package/dist/commands/pull-v4/generators/trigger-generator.js +62 -27
  53. package/dist/commands/pull-v4/generators/trigger-generator.js.map +1 -1
  54. package/dist/commands/pull-v4/import-plan.js +40 -0
  55. package/dist/commands/pull-v4/import-plan.js.map +1 -0
  56. package/dist/commands/pull-v4/introspect/index.js +11 -7
  57. package/dist/commands/pull-v4/introspect/index.js.map +1 -1
  58. package/dist/commands/pull-v4/introspect-generator.js +15 -1218
  59. package/dist/commands/pull-v4/introspect-generator.js.map +1 -1
  60. package/dist/commands/pull-v4/module-merge.js +14 -5
  61. package/dist/commands/pull-v4/module-merge.js.map +1 -1
  62. package/dist/commands/pull-v4/reference-resolution.js +111 -0
  63. package/dist/commands/pull-v4/reference-resolution.js.map +1 -0
  64. package/dist/commands/pull-v4/simple-factory-generator.js +54 -0
  65. package/dist/commands/pull-v4/simple-factory-generator.js.map +1 -0
  66. package/dist/commands/pull-v4/{generators/skill-generator.js → skill.js} +18 -6
  67. package/dist/commands/pull-v4/skill.js.map +1 -0
  68. package/dist/commands/pull-v4/typescript-file-writer.js +78 -0
  69. package/dist/commands/pull-v4/typescript-file-writer.js.map +1 -0
  70. package/dist/commands/pull-v4/utils/code-values.js +64 -0
  71. package/dist/commands/pull-v4/utils/code-values.js.map +1 -0
  72. package/dist/commands/pull-v4/utils/factory-writer.js +128 -0
  73. package/dist/commands/pull-v4/utils/factory-writer.js.map +1 -0
  74. package/dist/commands/pull-v4/utils/index.js +8 -0
  75. package/dist/commands/pull-v4/utils/naming.js +74 -0
  76. package/dist/commands/pull-v4/utils/naming.js.map +1 -0
  77. package/dist/commands/pull-v4/utils/schema-rendering.js +20 -0
  78. package/dist/commands/pull-v4/utils/schema-rendering.js.map +1 -0
  79. package/dist/commands/pull-v4/utils/shared.js +18 -0
  80. package/dist/commands/pull-v4/utils/shared.js.map +1 -0
  81. package/dist/commands/pull-v4/utils/templates.js +58 -0
  82. package/dist/commands/pull-v4/utils/templates.js.map +1 -0
  83. package/package.json +4 -4
  84. package/dist/commands/pull-v4/generators/skill-generator.js.map +0 -1
  85. package/dist/commands/pull-v4/scheduled-trigger-generator.js +0 -38
  86. package/dist/commands/pull-v4/scheduled-trigger-generator.js.map +0 -1
  87. package/dist/commands/pull-v4/utils.js +0 -320
  88. package/dist/commands/pull-v4/utils.js.map +0 -1
@@ -1,38 +1,29 @@
1
- import { buildComponentFileName, collectTemplateVariableNames, createInMemoryProject, isHumanReadableId, isPlainObject, toCamelCase, toCredentialReferenceName, toKebabCase, toToolReferenceName } from "./utils.js";
2
1
  import { buildComponentRegistryFromParsing } from "./component-parser.js";
3
- import { generateAgentDefinition } from "./generators/agent-generator.js";
4
- import { generateArtifactComponentDefinition } from "./generators/artifact-component-generator.js";
5
- import { generateContextConfigDefinition } from "./generators/context-config-generator.js";
6
- import { generateCredentialDefinition } from "./generators/credential-generator.js";
7
- import { generateDataComponentDefinition } from "./generators/data-component-generator.js";
8
- import { generateEnvironmentIndexDefinition, generateEnvironmentSettingsDefinition } from "./generators/environment-generator.js";
9
- import { generateExternalAgentDefinition } from "./generators/external-agent-generator.js";
10
- import { generateFunctionToolDefinition } from "./generators/function-tool-generator.js";
11
- import { generateMcpToolDefinition } from "./generators/mcp-tool-generator.js";
12
- import { generateProjectDefinition } from "./generators/project-generator.js";
13
- import { generateStatusComponentDefinition } from "./generators/status-component-generator.js";
14
- import { resolveSubAgentVariableName } from "./generators/sub-agent-generator.helpers.js";
15
- import { generateSubAgentDefinition } from "./generators/sub-agent-generator.js";
16
- import { generateTriggerDefinition } from "./generators/trigger-generator.js";
17
- import { mergeGeneratedModule } from "./module-merge.js";
18
- import { generateScheduledTriggerDefinition } from "./scheduled-trigger-generator.js";
19
- import { basename, dirname, join } from "node:path";
20
- import { Node, SyntaxKind } from "ts-morph";
21
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { GenerationResolver } from "./generation-resolver.js";
3
+ import { collectCompleteAgentIds, validateProject } from "./generation-types.js";
4
+ import { generationTasks } from "./generators/index.js";
5
+ import { writeTypeScriptFile } from "./typescript-file-writer.js";
22
6
 
23
7
  //#region src/commands/pull-v4/introspect-generator.ts
24
8
  async function introspectGenerate({ project, paths, writeMode = "merge", debug = false }) {
25
9
  validateProject(project);
26
10
  const skippedAgents = [];
11
+ const completeAgentIds = collectCompleteAgentIds(project, skippedAgents);
12
+ const existingComponentRegistry = writeMode === "merge" ? buildComponentRegistryFromParsing(paths.projectRoot, debug) : void 0;
27
13
  const context = {
28
14
  project,
29
15
  paths,
30
- completeAgentIds: collectCompleteAgentIds(project, skippedAgents),
31
- existingComponentRegistry: writeMode === "merge" ? buildComponentRegistryFromParsing(paths.projectRoot, debug) : void 0
16
+ completeAgentIds,
17
+ existingComponentRegistry,
18
+ resolver: new GenerationResolver({
19
+ project,
20
+ projectRoot: paths.projectRoot,
21
+ completeAgentIds,
22
+ existingComponentRegistry
23
+ })
32
24
  };
33
- const tasks = createGenerationTasks();
34
25
  const generatedFiles = [];
35
- for (const task of tasks) {
26
+ for (const task of Object.values(generationTasks)) {
36
27
  const records = task.collect(context);
37
28
  for (const record of records) {
38
29
  const sourceFile = task.generate(record.payload);
@@ -45,1200 +36,6 @@ async function introspectGenerate({ project, paths, writeMode = "merge", debug =
45
36
  if (skippedAgents.length) console.log(`Skipped ${skippedAgents.length} agent(s): ${skippedAgents.map((agent) => `${agent.id} (${agent.reason})`).join(", ")}`);
46
37
  }
47
38
  }
48
- function createGenerationTasks() {
49
- return [
50
- {
51
- type: "credential",
52
- collect: collectCredentialRecords,
53
- generate: generateCredentialDefinition
54
- },
55
- {
56
- type: "environment-settings",
57
- collect: collectEnvironmentSettingsRecords,
58
- generate: generateEnvironmentSettingsRecord
59
- },
60
- {
61
- type: "environment-index",
62
- collect: collectEnvironmentIndexRecords,
63
- generate: generateEnvironmentIndexDefinition
64
- },
65
- {
66
- type: "artifact-component",
67
- collect: collectArtifactComponentRecords,
68
- generate: generateArtifactComponentDefinition
69
- },
70
- {
71
- type: "data-component",
72
- collect: collectDataComponentRecords,
73
- generate: generateDataComponentDefinition
74
- },
75
- {
76
- type: "function-tool",
77
- collect: collectFunctionToolRecords,
78
- generate: generateFunctionToolDefinition
79
- },
80
- {
81
- type: "tool",
82
- collect: collectToolRecords,
83
- generate: generateMcpToolDefinition
84
- },
85
- {
86
- type: "external-agent",
87
- collect: collectExternalAgentRecords,
88
- generate: generateExternalAgentDefinition
89
- },
90
- {
91
- type: "context-config",
92
- collect: collectContextConfigRecords,
93
- generate: generateContextConfigDefinition
94
- },
95
- {
96
- type: "trigger",
97
- collect: collectTriggerRecords,
98
- generate: generateTriggerDefinition
99
- },
100
- {
101
- type: "scheduled-trigger",
102
- collect: collectScheduledTriggerRecords,
103
- generate: generateScheduledTriggerDefinition
104
- },
105
- {
106
- type: "sub-agent",
107
- collect: collectSubAgentRecords,
108
- generate: generateSubAgentDefinition
109
- },
110
- {
111
- type: "status-component",
112
- collect: collectStatusComponentRecords,
113
- generate: generateStatusComponentDefinition
114
- },
115
- {
116
- type: "agent",
117
- collect: collectAgentRecords,
118
- generate: generateAgentDefinition
119
- },
120
- {
121
- type: "project",
122
- collect: collectProjectRecord,
123
- generate: generateProjectDefinition
124
- }
125
- ];
126
- }
127
- function collectCredentialRecords(context) {
128
- if (!context.project.credentialReferences) return [];
129
- const credentialEntries = Object.entries(context.project.credentialReferences);
130
- const fileNamesByCredentialId = buildSequentialNameFileNames(credentialEntries);
131
- return credentialEntries.map(([credentialId, credentialData]) => ({
132
- id: credentialId,
133
- filePath: resolveRecordFilePath(context, "credentials", credentialId, join(context.paths.credentialsDir, fileNamesByCredentialId[credentialId])),
134
- payload: {
135
- credentialId,
136
- ...credentialData
137
- }
138
- }));
139
- }
140
- function collectEnvironmentSettingsRecords(context) {
141
- const credentialReferenceIds = collectEnvironmentCredentialReferenceIds(context.project);
142
- if (credentialReferenceIds.length === 0) return [];
143
- const credentialsById = {};
144
- for (const credentialReferenceId of credentialReferenceIds) {
145
- const credentialData = context.project.credentialReferences?.[credentialReferenceId];
146
- if (isPlainObject(credentialData)) {
147
- credentialsById[credentialReferenceId] = {
148
- ...credentialData,
149
- id: credentialReferenceId
150
- };
151
- continue;
152
- }
153
- credentialsById[credentialReferenceId] = { id: credentialReferenceId };
154
- }
155
- return [{
156
- id: "development",
157
- filePath: resolveRecordFilePath(context, "environments", "development", join(context.paths.environmentsDir, "development.env.ts")),
158
- payload: { credentials: credentialsById }
159
- }];
160
- }
161
- function collectEnvironmentIndexRecords(context) {
162
- if (collectEnvironmentCredentialReferenceIds(context.project).length === 0) return [];
163
- return [{
164
- id: "index",
165
- filePath: resolveRecordFilePath(context, "environments", "index", join(context.paths.environmentsDir, "index.ts")),
166
- payload: ["development"]
167
- }];
168
- }
169
- function generateEnvironmentSettingsRecord(payload) {
170
- return generateEnvironmentSettingsDefinition("development", payload);
171
- }
172
- function collectArtifactComponentRecords(context) {
173
- if (!context.project.artifactComponents) return [];
174
- return Object.entries(context.project.artifactComponents).map(([artifactComponentId, artifactComponentData]) => ({
175
- id: artifactComponentId,
176
- filePath: resolveRecordFilePath(context, "artifactComponents", artifactComponentId, join(context.paths.artifactComponentsDir, buildComponentFileName(artifactComponentId, artifactComponentData.name ?? void 0))),
177
- payload: {
178
- artifactComponentId,
179
- ...artifactComponentData
180
- }
181
- }));
182
- }
183
- function collectDataComponentRecords(context) {
184
- const recordsByDataComponentId = /* @__PURE__ */ new Map();
185
- for (const [dataComponentId, dataComponent] of Object.entries(context.project.dataComponents ?? {})) recordsByDataComponentId.set(dataComponentId, {
186
- id: dataComponentId,
187
- filePath: resolveRecordFilePath(context, "dataComponents", dataComponentId, join(context.paths.dataComponentsDir, buildComponentFileName(dataComponentId, dataComponent.name ?? void 0))),
188
- payload: {
189
- dataComponentId,
190
- ...dataComponent
191
- }
192
- });
193
- for (const dataComponentId of collectReferencedSubAgentComponentIds(context, "dataComponents")) {
194
- if (recordsByDataComponentId.has(dataComponentId)) continue;
195
- recordsByDataComponentId.set(dataComponentId, {
196
- id: dataComponentId,
197
- filePath: resolveRecordFilePath(context, "dataComponents", dataComponentId, join(context.paths.dataComponentsDir, `${dataComponentId}.ts`)),
198
- payload: {
199
- dataComponentId,
200
- name: dataComponentId,
201
- props: {
202
- type: "object",
203
- properties: {}
204
- }
205
- }
206
- });
207
- }
208
- return [...recordsByDataComponentId.values()];
209
- }
210
- function collectReferencedSubAgentComponentIds(context, componentProperty) {
211
- const componentIds = /* @__PURE__ */ new Set();
212
- for (const agentId of context.completeAgentIds) {
213
- const agentData = context.project.agents?.[agentId];
214
- const subAgents = asRecord(agentData?.subAgents);
215
- if (!subAgents) continue;
216
- for (const subAgentData of Object.values(subAgents)) {
217
- const subAgentRecord = asRecord(subAgentData);
218
- if (!subAgentRecord) continue;
219
- for (const componentId of extractReferenceIds(subAgentRecord[componentProperty])) componentIds.add(componentId);
220
- }
221
- }
222
- return [...componentIds];
223
- }
224
- function collectContextConfigRecords(context) {
225
- if (!context.project.agents) return [];
226
- const contextConfigRecordsById = /* @__PURE__ */ new Map();
227
- for (const agentId of context.completeAgentIds) {
228
- const agentData = context.project.agents[agentId];
229
- const contextConfig = agentData ? asRecord(agentData.contextConfig) : void 0;
230
- if (!agentData || !contextConfig) continue;
231
- const normalizedContextConfig = applyPromptHeaderTemplateSchema(contextConfig, collectHeaderTemplateVariablesFromAgentPrompts(agentData));
232
- const contextConfigId = typeof normalizedContextConfig.id === "string" ? normalizedContextConfig.id : "";
233
- if (!contextConfigId) continue;
234
- if (!contextConfigRecordsById.has(contextConfigId)) {
235
- const contextConfigFilePath = resolveRecordFilePath(context, "contextConfigs", contextConfigId, join(context.paths.contextConfigsDir, `${contextConfigId}.ts`));
236
- const credentialReferenceOverrides = collectContextConfigCredentialReferenceOverrides(context, normalizedContextConfig);
237
- const credentialReferencePathOverrides = collectContextConfigCredentialReferencePathOverrides(context, normalizedContextConfig);
238
- const headersReferenceOverride = collectContextConfigHeadersReferenceOverride(context, contextConfigId, contextConfigFilePath);
239
- contextConfigRecordsById.set(contextConfigId, {
240
- id: contextConfigId,
241
- filePath: contextConfigFilePath,
242
- payload: {
243
- contextConfigId,
244
- ...normalizedContextConfig,
245
- ...headersReferenceOverride && { headersReference: headersReferenceOverride },
246
- ...credentialReferenceOverrides && { referenceOverrides: { credentialReferences: credentialReferenceOverrides } },
247
- ...credentialReferencePathOverrides && { referencePathOverrides: { credentialReferences: credentialReferencePathOverrides } }
248
- }
249
- });
250
- }
251
- }
252
- return [...contextConfigRecordsById.values()];
253
- }
254
- function collectFunctionToolRecords(context) {
255
- const functionToolEntries = collectFunctionToolEntries(context.project);
256
- if (!functionToolEntries.length) return [];
257
- const fileNamesByFunctionToolId = buildSequentialNameFileNames(functionToolEntries.map(({ functionToolId, fileName }) => [functionToolId, { name: fileName }]));
258
- return functionToolEntries.map(({ functionToolId, functionToolData, functionData }) => {
259
- const modulePath = stripExtension(fileNamesByFunctionToolId[functionToolId]);
260
- const functionToolName = typeof functionToolData.name === "string" && functionToolData.name.length > 0 ? functionToolData.name : typeof functionData.name === "string" && functionData.name.length > 0 ? functionData.name : void 0;
261
- const functionToolDescription = typeof functionToolData.description === "string" ? functionToolData.description : typeof functionData.description === "string" ? functionData.description : void 0;
262
- return {
263
- id: functionToolId,
264
- filePath: resolveRecordFilePath(context, "functionTools", functionToolId, join(context.paths.toolsDir, `${modulePath}.ts`)),
265
- payload: {
266
- functionToolId,
267
- ...functionToolName && { name: functionToolName },
268
- ...functionToolDescription !== void 0 && { description: functionToolDescription },
269
- ...functionData.inputSchema !== void 0 && { inputSchema: functionData.inputSchema },
270
- ...functionData.schema !== void 0 && { schema: functionData.schema },
271
- ...functionData.executeCode !== void 0 && { executeCode: functionData.executeCode },
272
- ...functionData.dependencies !== void 0 && { dependencies: functionData.dependencies }
273
- }
274
- };
275
- });
276
- }
277
- function collectFunctionToolEntries(project) {
278
- const functionToolsById = collectFunctionToolsById(project);
279
- const functionsById = collectFunctionsById(project);
280
- const entries = [];
281
- for (const [functionToolId, functionToolData] of Object.entries(functionToolsById)) {
282
- const functionId = typeof functionToolData.functionId === "string" && functionToolData.functionId.length > 0 ? functionToolData.functionId : functionToolId;
283
- const functionData = functionsById[functionId] ?? {};
284
- const functionToolName = typeof functionToolData.name === "string" && functionToolData.name.length > 0 ? functionToolData.name : void 0;
285
- const functionName = typeof functionData.name === "string" && functionData.name.length > 0 ? functionData.name : void 0;
286
- const fallbackName = functionToolName ?? functionName ?? functionToolId;
287
- entries.push({
288
- functionToolId,
289
- functionId,
290
- functionToolData,
291
- functionData,
292
- exportName: fallbackName,
293
- fileName: fallbackName
294
- });
295
- }
296
- return entries;
297
- }
298
- function collectFunctionToolsById(project) {
299
- const functionToolsById = {};
300
- for (const [functionToolId, functionToolData] of Object.entries(project.functionTools ?? {})) {
301
- const functionToolRecord = asRecord(functionToolData);
302
- if (!functionToolRecord) continue;
303
- functionToolsById[functionToolId] = { ...functionToolRecord };
304
- }
305
- for (const agentData of Object.values(project.agents ?? {})) {
306
- const agentFunctionTools = asRecord(asRecord(agentData)?.functionTools);
307
- if (!agentFunctionTools) continue;
308
- for (const [functionToolId, functionToolData] of Object.entries(agentFunctionTools)) {
309
- const functionToolRecord = asRecord(functionToolData);
310
- if (!functionToolRecord) continue;
311
- const existingFunctionTool = functionToolsById[functionToolId] ?? {};
312
- functionToolsById[functionToolId] = {
313
- ...functionToolRecord,
314
- ...existingFunctionTool
315
- };
316
- }
317
- }
318
- return functionToolsById;
319
- }
320
- function collectFunctionsById(project) {
321
- const functionsById = {};
322
- for (const [functionId, functionData] of Object.entries(project.functions ?? {})) {
323
- const functionRecord = asRecord(functionData);
324
- if (!functionRecord) continue;
325
- functionsById[functionId] = { ...functionRecord };
326
- }
327
- for (const agentData of Object.values(project.agents ?? {})) {
328
- const agentFunctions = asRecord(asRecord(agentData)?.functions);
329
- if (!agentFunctions) continue;
330
- for (const [functionId, functionData] of Object.entries(agentFunctions)) {
331
- const functionRecord = asRecord(functionData);
332
- if (!functionRecord) continue;
333
- const existingFunction = functionsById[functionId] ?? {};
334
- functionsById[functionId] = {
335
- ...functionRecord,
336
- ...existingFunction
337
- };
338
- }
339
- }
340
- return functionsById;
341
- }
342
- function collectToolRecords(context) {
343
- const toolEntries = Object.entries(context.project.tools ?? {});
344
- const fileNamesByToolId = buildSequentialNameFileNames(toolEntries);
345
- return toolEntries.map(([toolId, toolData]) => ({
346
- id: toolId,
347
- filePath: resolveRecordFilePath(context, "tools", toolId, join(context.paths.toolsDir, fileNamesByToolId[toolId])),
348
- payload: {
349
- mcpToolId: toolId,
350
- ...toolData
351
- }
352
- }));
353
- }
354
- function collectExternalAgentRecords(context) {
355
- const externalAgentEntries = Object.entries(context.project.externalAgents ?? {});
356
- const fileNamesByExternalAgentId = buildSequentialNameFileNames(externalAgentEntries.map(([externalAgentId, externalAgentData]) => [externalAgentId, { name: resolveExternalAgentNamingSeed(externalAgentId, externalAgentData) }]));
357
- const referenceNamesByExternalAgentId = buildExternalAgentReferenceNamesById(context.project);
358
- return externalAgentEntries.map(([externalAgentId, externalAgentData]) => {
359
- const externalAgentRecord = asRecord(externalAgentData) ?? {};
360
- return {
361
- id: externalAgentId,
362
- filePath: resolveRecordFilePath(context, "externalAgents", externalAgentId, join(context.paths.externalAgentsDir, fileNamesByExternalAgentId[externalAgentId])),
363
- payload: {
364
- externalAgentId,
365
- externalAgentReferenceName: referenceNamesByExternalAgentId[externalAgentId],
366
- ...externalAgentRecord
367
- }
368
- };
369
- });
370
- }
371
- function collectContextConfigCredentialReferenceOverrides(context, contextConfigData) {
372
- const contextVariables = asRecord(contextConfigData.contextVariables);
373
- if (!contextVariables) return;
374
- const credentialReferenceNamesById = buildCredentialReferenceNamesById(context.project);
375
- const registry = context.existingComponentRegistry;
376
- const overrides = {};
377
- for (const contextVariable of Object.values(contextVariables)) {
378
- const contextVariableRecord = asRecord(contextVariable);
379
- const credentialReferenceId = contextVariableRecord && typeof contextVariableRecord.credentialReferenceId === "string" ? contextVariableRecord.credentialReferenceId : void 0;
380
- if (!credentialReferenceId) continue;
381
- const credentialReferenceName = credentialReferenceNamesById[credentialReferenceId];
382
- if (credentialReferenceName) overrides[credentialReferenceId] = credentialReferenceName;
383
- const existingCredential = registry?.get(credentialReferenceId, "credentials");
384
- if (existingCredential?.name) overrides[credentialReferenceId] = existingCredential.name;
385
- }
386
- return Object.keys(overrides).length ? overrides : void 0;
387
- }
388
- function collectContextConfigCredentialReferencePathOverrides(context, contextConfigData) {
389
- const contextVariables = asRecord(contextConfigData.contextVariables);
390
- if (!contextVariables) return;
391
- const credentialReferencePathById = buildCredentialReferencePathById(context.project);
392
- const registry = context.existingComponentRegistry;
393
- const overrides = {};
394
- for (const contextVariable of Object.values(contextVariables)) {
395
- const contextVariableRecord = asRecord(contextVariable);
396
- const credentialReferenceId = contextVariableRecord && typeof contextVariableRecord.credentialReferenceId === "string" ? contextVariableRecord.credentialReferenceId : void 0;
397
- if (!credentialReferenceId) continue;
398
- const credentialReferencePath = credentialReferencePathById[credentialReferenceId];
399
- if (credentialReferencePath) overrides[credentialReferenceId] = credentialReferencePath;
400
- const existingCredential = registry?.get(credentialReferenceId, "credentials");
401
- if (existingCredential?.filePath) overrides[credentialReferenceId] = stripExtension(basename(existingCredential.filePath));
402
- }
403
- return Object.keys(overrides).length ? overrides : void 0;
404
- }
405
- function collectContextConfigHeadersReferenceOverride(context, contextConfigId, filePath) {
406
- if (!context.existingComponentRegistry || !existsSync(filePath)) return;
407
- const sourceFile = createInMemoryProject().createSourceFile("existing-context-config.ts", readFileSync(filePath, "utf8"), { overwrite: true });
408
- for (const declaration of sourceFile.getVariableDeclarations()) {
409
- const initializer = declaration.getInitializer();
410
- if (!initializer || !Node.isCallExpression(initializer)) continue;
411
- const expression = initializer.getExpression();
412
- if (!Node.isIdentifier(expression) || expression.getText() !== "contextConfig") continue;
413
- const [configArg] = initializer.getArguments();
414
- if (!configArg || !Node.isObjectLiteralExpression(configArg)) continue;
415
- const idProperty = configArg.getProperty("id");
416
- if (!idProperty || !Node.isPropertyAssignment(idProperty)) continue;
417
- const idInitializer = idProperty.getInitializer();
418
- if (!idInitializer || !Node.isStringLiteral(idInitializer)) continue;
419
- if (idInitializer.getLiteralValue() !== contextConfigId) continue;
420
- const headersProperty = configArg.getProperty("headers");
421
- if (!headersProperty) return;
422
- if (Node.isShorthandPropertyAssignment(headersProperty)) return headersProperty.getName();
423
- if (!Node.isPropertyAssignment(headersProperty)) return;
424
- const headersInitializer = headersProperty.getInitializer();
425
- if (!headersInitializer) return;
426
- if (Node.isIdentifier(headersInitializer)) return headersInitializer.getText();
427
- if (Node.isAsExpression(headersInitializer)) {
428
- const valueExpression = headersInitializer.getExpression();
429
- if (Node.isIdentifier(valueExpression)) return valueExpression.getText();
430
- }
431
- return;
432
- }
433
- }
434
- function collectTriggerRecords(context) {
435
- if (!context.project.agents) return [];
436
- const credentialReferenceNamesById = buildCredentialReferenceNamesById(context.project);
437
- const credentialReferencePathsById = buildCredentialReferencePathById(context.project);
438
- const records = [];
439
- for (const agentId of context.completeAgentIds) {
440
- const agentData = context.project.agents[agentId];
441
- if (!agentData?.triggers) continue;
442
- const triggerEntries = Object.entries(agentData.triggers);
443
- const fileNamesByTriggerId = buildSequentialNameFileNames(triggerEntries);
444
- for (const [triggerId, triggerData] of triggerEntries) {
445
- const triggerRecord = asRecord(triggerData);
446
- const signingSecretCredentialReferenceId = typeof triggerRecord?.signingSecretCredentialReferenceId === "string" ? triggerRecord.signingSecretCredentialReferenceId : void 0;
447
- let signingSecretCredentialReferenceName = signingSecretCredentialReferenceId ? credentialReferenceNamesById[signingSecretCredentialReferenceId] : void 0;
448
- let signingSecretCredentialReferencePath = signingSecretCredentialReferenceId ? credentialReferencePathsById[signingSecretCredentialReferenceId] : void 0;
449
- if (signingSecretCredentialReferenceId && context.existingComponentRegistry) {
450
- const existingCredential = context.existingComponentRegistry.get(signingSecretCredentialReferenceId, "credentials");
451
- if (existingCredential?.name) signingSecretCredentialReferenceName = existingCredential.name;
452
- if (existingCredential?.filePath) signingSecretCredentialReferencePath = stripExtension(basename(existingCredential.filePath));
453
- }
454
- records.push({
455
- id: triggerId,
456
- filePath: resolveRecordFilePath(context, "triggers", triggerId, join(context.paths.agentsDir, "triggers", fileNamesByTriggerId[triggerId])),
457
- payload: {
458
- triggerId,
459
- ...triggerData,
460
- ...signingSecretCredentialReferenceName && { signingSecretCredentialReferenceName },
461
- ...signingSecretCredentialReferencePath && { signingSecretCredentialReferencePath }
462
- }
463
- });
464
- }
465
- }
466
- return records;
467
- }
468
- function collectScheduledTriggerRecords(context) {
469
- if (!context.project.agents) return [];
470
- const records = [];
471
- for (const agentId of context.completeAgentIds) {
472
- const agentData = context.project.agents[agentId];
473
- if (!agentData?.scheduledTriggers) continue;
474
- const fileNamesByScheduledTriggerId = buildSequentialNameFileNames(Object.entries(agentData.scheduledTriggers));
475
- for (const [scheduledTriggerId, scheduledTriggerData] of Object.entries(agentData.scheduledTriggers)) records.push({
476
- id: scheduledTriggerId,
477
- filePath: resolveRecordFilePath(context, "scheduledTriggers", scheduledTriggerId, join(context.paths.agentsDir, "scheduled-triggers", fileNamesByScheduledTriggerId[scheduledTriggerId])),
478
- payload: {
479
- scheduledTriggerId,
480
- ...scheduledTriggerData
481
- }
482
- });
483
- }
484
- return records;
485
- }
486
- function collectAgentRecords(context) {
487
- if (!context.project.agents) return [];
488
- const records = [];
489
- for (const agentId of context.completeAgentIds) {
490
- const agentData = context.project.agents[agentId];
491
- if (!agentData) continue;
492
- const agentName = typeof agentData.name === "string" ? agentData.name : void 0;
493
- const agentFilePath = resolveRecordFilePath(context, "agents", agentId, join(context.paths.agentsDir, buildComponentFileName(agentId, agentName)));
494
- const existingAgent = context.existingComponentRegistry?.get(agentId, "agents");
495
- const subAgentReferences = collectSubAgentReferenceOverrides(context, agentData, agentFilePath);
496
- const subAgentReferencePathOverrides = collectSubAgentReferencePathOverrides(context, agentData);
497
- const statusUpdates = asRecord(agentData.statusUpdates);
498
- const contextTemplateReferences = collectContextTemplateReferences(context, agentData, agentFilePath, [typeof agentData.prompt === "string" ? agentData.prompt : void 0, typeof statusUpdates?.prompt === "string" ? statusUpdates.prompt : void 0]);
499
- records.push({
500
- id: agentId,
501
- filePath: agentFilePath,
502
- payload: {
503
- agentId,
504
- ...agentData,
505
- ...existingAgent?.name?.length && { agentVariableName: existingAgent.name },
506
- ...Object.keys(subAgentReferences).length && { subAgentReferences },
507
- ...Object.keys(subAgentReferencePathOverrides).length && { subAgentReferencePathOverrides },
508
- ...contextTemplateReferences && { contextConfigReference: contextTemplateReferences.contextConfigReference },
509
- ...contextTemplateReferences?.contextConfigHeadersReference && { contextConfigHeadersReference: contextTemplateReferences.contextConfigHeadersReference }
510
- }
511
- });
512
- }
513
- return records;
514
- }
515
- function collectSubAgentReferencePathOverrides(context, agentData) {
516
- const generatedSubAgentReferencePathById = buildSubAgentReferencePathById(context.project, context.completeAgentIds);
517
- const subAgentIds = new Set(extractReferenceIds(agentData.subAgents));
518
- if (typeof agentData.defaultSubAgentId === "string" && agentData.defaultSubAgentId.length > 0) subAgentIds.add(agentData.defaultSubAgentId);
519
- if (!subAgentIds.size) return {};
520
- const subAgents = asRecord(agentData.subAgents);
521
- const overrides = {};
522
- for (const subAgentId of subAgentIds) {
523
- const fallbackReferencePath = generatedSubAgentReferencePathById[subAgentId];
524
- const subAgentData = asRecord(subAgents?.[subAgentId]);
525
- const subAgentName = typeof subAgentData?.name === "string" ? subAgentData.name : void 0;
526
- overrides[subAgentId] = stripExtension(basename(resolveRecordFilePath(context, "subAgents", subAgentId, join(context.paths.agentsDir, "sub-agents", fallbackReferencePath ? `${fallbackReferencePath}.ts` : buildComponentFileName(subAgentId, subAgentName)))));
527
- }
528
- return overrides;
529
- }
530
- function collectSubAgentRecords(context) {
531
- if (!context.project.agents) return [];
532
- const recordsBySubAgentId = /* @__PURE__ */ new Map();
533
- for (const agentId of context.completeAgentIds) {
534
- const agentData = context.project.agents[agentId];
535
- const subAgents = asRecord(agentData?.subAgents);
536
- if (!subAgents) continue;
537
- for (const [subAgentId, subAgentData] of Object.entries(subAgents)) {
538
- const payload = asRecord(subAgentData);
539
- if (!payload) continue;
540
- const dependencyReferences = collectSubAgentDependencyReferenceOverrides(context, payload);
541
- const subAgentName = typeof payload.name === "string" ? payload.name : void 0;
542
- const subAgentFilePath = resolveRecordFilePath(context, "subAgents", subAgentId, join(context.paths.agentsDir, "sub-agents", buildComponentFileName(subAgentId, subAgentName)));
543
- const contextTemplateReferences = collectContextTemplateReferences(context, agentData, subAgentFilePath, [typeof payload.prompt === "string" ? payload.prompt : void 0]);
544
- recordsBySubAgentId.set(subAgentId, {
545
- id: subAgentId,
546
- filePath: subAgentFilePath,
547
- payload: {
548
- subAgentId,
549
- ...payload,
550
- ...dependencyReferences?.referenceOverrides && { referenceOverrides: dependencyReferences.referenceOverrides },
551
- ...dependencyReferences?.referencePathOverrides && { referencePathOverrides: dependencyReferences.referencePathOverrides },
552
- ...contextTemplateReferences && {
553
- contextConfigId: contextTemplateReferences.contextConfigId,
554
- contextConfigReference: contextTemplateReferences.contextConfigReference
555
- },
556
- ...contextTemplateReferences?.contextConfigHeadersReference && { contextConfigHeadersReference: contextTemplateReferences.contextConfigHeadersReference }
557
- }
558
- });
559
- }
560
- }
561
- return [...recordsBySubAgentId.values()];
562
- }
563
- function collectStatusComponentRecords(context) {
564
- if (!context.project.agents) return [];
565
- const statusComponentRecordsById = /* @__PURE__ */ new Map();
566
- for (const agentId of context.completeAgentIds) {
567
- const agentData = context.project.agents[agentId];
568
- const statusUpdates = asRecord(agentData?.statusUpdates);
569
- const statusComponents = Array.isArray(statusUpdates?.statusComponents) ? statusUpdates.statusComponents : [];
570
- for (const statusComponentData of statusComponents) {
571
- const payload = asRecord(statusComponentData);
572
- if (!payload) continue;
573
- const statusComponentId = resolveStatusComponentId(payload);
574
- if (!statusComponentId || statusComponentRecordsById.has(statusComponentId)) continue;
575
- const statusComponentName = typeof payload.name === "string" ? payload.name : void 0;
576
- statusComponentRecordsById.set(statusComponentId, {
577
- id: statusComponentId,
578
- filePath: resolveRecordFilePath(context, "statusComponents", statusComponentId, join(context.paths.statusComponentsDir, buildComponentFileName(statusComponentId, statusComponentName))),
579
- payload: {
580
- statusComponentId,
581
- ...payload
582
- }
583
- });
584
- }
585
- }
586
- return [...statusComponentRecordsById.values()];
587
- }
588
- function collectProjectRecord(context) {
589
- const referenceOverrides = collectProjectReferenceOverrides(context);
590
- const referencePathOverrides = collectProjectReferencePathOverrides(context);
591
- return [{
592
- id: context.project.id,
593
- filePath: resolveRecordFilePath(context, "project", context.project.id, join(context.paths.projectRoot, "index.ts")),
594
- payload: {
595
- projectId: context.project.id,
596
- name: context.project.name,
597
- description: context.project.description,
598
- models: context.project.models,
599
- stopWhen: context.project.stopWhen,
600
- skills: getObjectKeys(context.project.skills),
601
- agents: [...context.completeAgentIds],
602
- tools: getObjectKeys(context.project.tools),
603
- externalAgents: getObjectKeys(context.project.externalAgents),
604
- dataComponents: getObjectKeys(context.project.dataComponents),
605
- artifactComponents: getObjectKeys(context.project.artifactComponents),
606
- credentialReferences: getObjectKeys(context.project.credentialReferences),
607
- ...referenceOverrides && { referenceOverrides },
608
- ...referencePathOverrides && { referencePathOverrides }
609
- }
610
- }];
611
- }
612
- function validateProject(project) {
613
- if (!project || typeof project !== "object") throw new Error("Project data is required");
614
- if (!project.id) throw new Error("Project id is required");
615
- if (!project.name) throw new Error("Project name is required");
616
- }
617
- function collectCompleteAgentIds(project, skippedAgents) {
618
- const completeAgentIds = /* @__PURE__ */ new Set();
619
- for (const [agentId, agentData] of Object.entries(project.agents ?? {})) {
620
- const completeness = isAgentComplete(agentData);
621
- if (!completeness.complete) {
622
- skippedAgents.push({
623
- id: agentId,
624
- reason: completeness.reason ?? "incomplete"
625
- });
626
- continue;
627
- }
628
- completeAgentIds.add(agentId);
629
- }
630
- return completeAgentIds;
631
- }
632
- function isAgentComplete(agentData) {
633
- const data = asRecord(agentData);
634
- if (!data) return {
635
- complete: false,
636
- reason: "invalid agent object"
637
- };
638
- if (!data.name || typeof data.name !== "string") return {
639
- complete: false,
640
- reason: "missing name"
641
- };
642
- if (!data.defaultSubAgentId || typeof data.defaultSubAgentId !== "string") return {
643
- complete: false,
644
- reason: "missing defaultSubAgentId"
645
- };
646
- if (!asRecord(data.subAgents) || !Object.keys(data.subAgents).length) return {
647
- complete: false,
648
- reason: "no sub-agents defined"
649
- };
650
- return { complete: true };
651
- }
652
- function collectEnvironmentCredentialReferenceIds(project) {
653
- const credentialReferenceIds = /* @__PURE__ */ new Set();
654
- for (const toolData of Object.values(project.tools ?? {})) {
655
- const toolRecord = asRecord(toolData);
656
- const credentialReferenceId = toolRecord && typeof toolRecord.credentialReferenceId === "string" ? toolRecord.credentialReferenceId : void 0;
657
- const hasInlineCredential = toolRecord?.credential !== void 0 && toolRecord?.credential !== null;
658
- if (credentialReferenceId && !hasInlineCredential) credentialReferenceIds.add(credentialReferenceId);
659
- }
660
- return [...credentialReferenceIds];
661
- }
662
- function getObjectKeys(value) {
663
- const record = asRecord(value);
664
- if (!record) return [];
665
- return Object.keys(record);
666
- }
667
- function resolveStatusComponentId(statusComponentData) {
668
- if (typeof statusComponentData.id === "string") return statusComponentData.id;
669
- if (typeof statusComponentData.type === "string") return statusComponentData.type;
670
- if (typeof statusComponentData.name === "string") return statusComponentData.name;
671
- }
672
- function asRecord(value) {
673
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
674
- return value;
675
- }
676
- function collectSubAgentReferenceOverrides(context, agentData, agentFilePath) {
677
- const generatedSubAgentReferenceNamesById = buildSubAgentReferenceNamesById(context.project, context.completeAgentIds);
678
- const subAgentIds = new Set(extractReferenceIds(agentData.subAgents));
679
- if (typeof agentData.defaultSubAgentId === "string" && agentData.defaultSubAgentId.length > 0) subAgentIds.add(agentData.defaultSubAgentId);
680
- if (!subAgentIds.size) return {};
681
- const subAgents = asRecord(agentData.subAgents);
682
- const overrides = {};
683
- for (const subAgentId of subAgentIds) {
684
- const subAgentData = asRecord(subAgents?.[subAgentId]);
685
- const subAgentName = typeof subAgentData?.name === "string" ? subAgentData.name : void 0;
686
- overrides[subAgentId] = { name: generatedSubAgentReferenceNamesById[subAgentId] ?? resolveSubAgentVariableName(subAgentId, subAgentName) };
687
- const existingSubAgent = context.existingComponentRegistry?.get(subAgentId, "subAgents");
688
- if (!existingSubAgent?.name) continue;
689
- overrides[subAgentId] = normalizeFilePath(resolveProjectFilePath(context.paths.projectRoot, existingSubAgent.filePath)) === normalizeFilePath(agentFilePath) ? {
690
- name: existingSubAgent.name,
691
- local: true
692
- } : { name: existingSubAgent.name };
693
- }
694
- return overrides;
695
- }
696
- function collectAgentContextConfigReferenceOverride(context, agentData, agentFilePath) {
697
- const contextConfigId = extractContextConfigData(agentData)?.id;
698
- if (!contextConfigId) return;
699
- const existingContextConfig = context.existingComponentRegistry?.get(contextConfigId, "contextConfigs");
700
- if (!existingContextConfig?.name) return;
701
- return normalizeFilePath(resolveProjectFilePath(context.paths.projectRoot, existingContextConfig.filePath)) === normalizeFilePath(agentFilePath) ? {
702
- name: existingContextConfig.name,
703
- local: true
704
- } : { name: existingContextConfig.name };
705
- }
706
- function collectContextTemplateReferences(context, agentData, targetFilePath, promptValues) {
707
- const contextConfig = extractContextConfigData(agentData);
708
- const contextConfigId = contextConfig?.id;
709
- if (!contextConfigId) return;
710
- const contextConfigFilePath = resolveRecordFilePath(context, "contextConfigs", contextConfigId, join(context.paths.contextConfigsDir, `${contextConfigId}.ts`));
711
- const isLocal = normalizeFilePath(contextConfigFilePath) === normalizeFilePath(targetFilePath);
712
- const contextConfigReference = collectAgentContextConfigReferenceOverride(context, agentData, targetFilePath) ?? (isLocal ? {
713
- name: toCamelCase(contextConfigId),
714
- local: true
715
- } : { name: toCamelCase(contextConfigId) });
716
- const hasHeadersTemplateVariables = collectTemplateVariablesFromValues(promptValues).some((variableName) => variableName.startsWith("headers."));
717
- let headersReferenceName = collectContextConfigHeadersReferenceOverride(context, contextConfigId, contextConfigFilePath) ?? inferHeadersReferenceFromContextConfig(contextConfig, contextConfigId);
718
- if (!headersReferenceName && hasHeadersTemplateVariables) headersReferenceName = `${toCamelCase(contextConfigId)}Headers`;
719
- return {
720
- contextConfigId,
721
- contextConfigReference,
722
- ...headersReferenceName && { contextConfigHeadersReference: isLocal ? {
723
- name: headersReferenceName,
724
- local: true
725
- } : { name: headersReferenceName } }
726
- };
727
- }
728
- function extractContextConfigData(agentData) {
729
- const contextConfig = typeof agentData.contextConfig === "string" ? { id: agentData.contextConfig } : asRecord(agentData.contextConfig);
730
- const contextConfigId = contextConfig && typeof contextConfig.id === "string" ? contextConfig.id : void 0;
731
- if (!contextConfigId || !contextConfig) return;
732
- return {
733
- id: contextConfigId,
734
- value: contextConfig
735
- };
736
- }
737
- function inferHeadersReferenceFromContextConfig(contextConfig, contextConfigId) {
738
- const headers = contextConfig.value.headers;
739
- if (typeof headers === "string" && headers.length > 0) return toCamelCase(headers);
740
- const headersRecord = asRecord(headers);
741
- if (headersRecord) {
742
- if (typeof headersRecord.id === "string" && headersRecord.id) return toCamelCase(headersRecord.id);
743
- if (typeof headersRecord.name === "string" && headersRecord.name) return toCamelCase(headersRecord.name);
744
- }
745
- if (isPlainObject(contextConfig.value.headersSchema)) return `${toCamelCase(contextConfigId)}Headers`;
746
- }
747
- function collectTemplateVariablesFromValues(values) {
748
- const variables = [];
749
- for (const value of values) {
750
- if (typeof value !== "string") continue;
751
- variables.push(...collectTemplateVariableNames(value));
752
- }
753
- return variables;
754
- }
755
- function collectHeaderTemplateVariablesFromAgentPrompts(agentData) {
756
- const variables = /* @__PURE__ */ new Set();
757
- addHeaderTemplateVariablesFromString(typeof agentData.prompt === "string" ? agentData.prompt : void 0, variables);
758
- const statusUpdates = asRecord(agentData.statusUpdates);
759
- addHeaderTemplateVariablesFromString(typeof statusUpdates?.prompt === "string" ? statusUpdates.prompt : void 0, variables);
760
- const subAgents = asRecord(agentData.subAgents);
761
- if (!subAgents) return variables;
762
- for (const subAgentData of Object.values(subAgents)) {
763
- const subAgent = asRecord(subAgentData);
764
- addHeaderTemplateVariablesFromString(typeof subAgent?.prompt === "string" ? subAgent.prompt : void 0, variables);
765
- }
766
- return variables;
767
- }
768
- function addHeaderTemplateVariablesFromString(value, variables) {
769
- if (typeof value !== "string") return;
770
- for (const variableName of collectTemplateVariableNames(value)) {
771
- if (!variableName.startsWith("headers.")) continue;
772
- const headerPath = variableName.slice(8);
773
- if (headerPath) variables.add(headerPath);
774
- }
775
- }
776
- function applyPromptHeaderTemplateSchema(contextConfig, headerTemplateVariables) {
777
- if (!headerTemplateVariables.size) return contextConfig;
778
- if (typeof contextConfig.headers === "string" || isPlainObject(contextConfig.headers) || isPlainObject(contextConfig.headersSchema)) return contextConfig;
779
- const variableNames = [...headerTemplateVariables].sort();
780
- const properties = Object.fromEntries(variableNames.map((variableName) => [variableName, { type: "string" }]));
781
- return {
782
- ...contextConfig,
783
- headersSchema: {
784
- type: "object",
785
- properties,
786
- required: variableNames,
787
- additionalProperties: false
788
- }
789
- };
790
- }
791
- function collectSubAgentDependencyReferenceOverrides(context, subAgentData) {
792
- const registry = context.existingComponentRegistry;
793
- const referenceOverrides = {};
794
- const referencePathOverrides = {};
795
- const toolReferenceNamesById = buildToolReferenceNamesById(context.project);
796
- const toolReferencePathsById = buildToolReferencePathById(context.project);
797
- const subAgentReferenceNamesById = buildSubAgentReferenceNamesById(context.project, context.completeAgentIds);
798
- const subAgentReferencePathsById = buildSubAgentReferencePathById(context.project, context.completeAgentIds);
799
- const agentReferenceNamesById = buildAgentReferenceNamesById(context.project);
800
- const agentReferencePathsById = buildAgentReferencePathById(context.project);
801
- const externalAgentReferenceNamesById = buildExternalAgentReferenceNamesById(context.project);
802
- const externalAgentReferencePathsById = buildExternalAgentReferencePathById(context.project);
803
- const assignSubAgentReferenceOverrides = (subAgentId) => {
804
- const subAgentReferenceName = subAgentReferenceNamesById[subAgentId];
805
- if (subAgentReferenceName) assignReferenceOverride(referenceOverrides, "subAgents", subAgentId, subAgentReferenceName);
806
- const subAgentReferencePath = subAgentReferencePathsById[subAgentId];
807
- if (subAgentReferencePath) assignReferencePathOverride(referencePathOverrides, "subAgents", subAgentId, subAgentReferencePath);
808
- };
809
- const assignAgentReferenceOverrides = (agentId) => {
810
- const agentReferenceName = agentReferenceNamesById[agentId];
811
- if (agentReferenceName) assignReferenceOverride(referenceOverrides, "agents", agentId, agentReferenceName);
812
- const agentReferencePath = agentReferencePathsById[agentId];
813
- if (agentReferencePath) assignReferencePathOverride(referencePathOverrides, "agents", agentId, agentReferencePath);
814
- };
815
- const assignExternalAgentReferenceOverrides = (externalAgentId) => {
816
- const externalAgentReferenceName = externalAgentReferenceNamesById[externalAgentId];
817
- if (externalAgentReferenceName) assignReferenceOverride(referenceOverrides, "externalAgents", externalAgentId, externalAgentReferenceName);
818
- const externalAgentReferencePath = externalAgentReferencePathsById[externalAgentId];
819
- if (externalAgentReferencePath) assignReferencePathOverride(referencePathOverrides, "externalAgents", externalAgentId, externalAgentReferencePath);
820
- };
821
- const canUse = Array.isArray(subAgentData.canUse) ? subAgentData.canUse : [];
822
- for (const item of canUse) {
823
- const canUseRecord = asRecord(item);
824
- const toolId = typeof item === "string" ? item : canUseRecord && typeof canUseRecord.toolId === "string" ? canUseRecord.toolId : void 0;
825
- if (!toolId) continue;
826
- assignReferenceOverride(referenceOverrides, "tools", toolId, toolReferenceNamesById[toolId] ?? toToolReferenceName(toolId));
827
- assignReferencePathOverride(referencePathOverrides, "tools", toolId, toolReferencePathsById[toolId] ?? toKebabCase(toolId));
828
- if (registry) {
829
- assignComponentReferenceOverride(registry, referenceOverrides, "tools", toolId, "tools");
830
- assignComponentReferenceOverride(registry, referenceOverrides, "tools", toolId, "functionTools");
831
- const toolComponent = registry.get(toolId, "functionTools") ?? registry.get(toolId, "tools");
832
- if (toolComponent?.filePath) assignReferencePathOverride(referencePathOverrides, "tools", toolId, resolveToolModulePath(toolComponent.filePath));
833
- }
834
- }
835
- const canDelegateTo = Array.isArray(subAgentData.canDelegateTo) ? subAgentData.canDelegateTo : [];
836
- for (const item of canDelegateTo) {
837
- if (typeof item === "string") {
838
- assignSubAgentReferenceOverrides(item);
839
- assignAgentReferenceOverrides(item);
840
- assignExternalAgentReferenceOverrides(item);
841
- continue;
842
- }
843
- const canDelegateRecord = asRecord(item);
844
- if (typeof canDelegateRecord?.subAgentId === "string") assignSubAgentReferenceOverrides(canDelegateRecord.subAgentId);
845
- if (typeof canDelegateRecord?.agentId === "string") assignAgentReferenceOverrides(canDelegateRecord.agentId);
846
- if (typeof canDelegateRecord?.externalAgentId === "string") assignExternalAgentReferenceOverrides(canDelegateRecord.externalAgentId);
847
- }
848
- const canTransferTo = extractReferenceIds(subAgentData.canTransferTo);
849
- for (const transferTargetId of canTransferTo) {
850
- assignSubAgentReferenceOverrides(transferTargetId);
851
- assignAgentReferenceOverrides(transferTargetId);
852
- assignExternalAgentReferenceOverrides(transferTargetId);
853
- }
854
- if (registry) {
855
- for (const item of canDelegateTo) {
856
- if (typeof item === "string") {
857
- assignFirstMatchingComponentReferenceOverride(registry, referenceOverrides, item, [
858
- ["subAgents", "subAgents"],
859
- ["agents", "agents"],
860
- ["externalAgents", "externalAgents"]
861
- ]);
862
- assignComponentReferencePathOverride(registry, referencePathOverrides, "subAgents", item, "subAgents");
863
- assignComponentReferencePathOverride(registry, referencePathOverrides, "agents", item, "agents");
864
- assignComponentReferencePathOverride(registry, referencePathOverrides, "externalAgents", item, "externalAgents");
865
- continue;
866
- }
867
- const canDelegateRecord = asRecord(item);
868
- if (!canDelegateRecord) continue;
869
- if (typeof canDelegateRecord.subAgentId === "string") {
870
- assignComponentReferenceOverride(registry, referenceOverrides, "subAgents", canDelegateRecord.subAgentId, "subAgents");
871
- assignComponentReferencePathOverride(registry, referencePathOverrides, "subAgents", canDelegateRecord.subAgentId, "subAgents");
872
- continue;
873
- }
874
- if (typeof canDelegateRecord.agentId === "string") {
875
- assignComponentReferenceOverride(registry, referenceOverrides, "agents", canDelegateRecord.agentId, "agents");
876
- assignComponentReferencePathOverride(registry, referencePathOverrides, "agents", canDelegateRecord.agentId, "agents");
877
- continue;
878
- }
879
- if (typeof canDelegateRecord.externalAgentId === "string") {
880
- assignComponentReferenceOverride(registry, referenceOverrides, "externalAgents", canDelegateRecord.externalAgentId, "externalAgents");
881
- assignComponentReferencePathOverride(registry, referencePathOverrides, "externalAgents", canDelegateRecord.externalAgentId, "externalAgents");
882
- }
883
- }
884
- for (const transferTargetId of canTransferTo) {
885
- assignFirstMatchingComponentReferenceOverride(registry, referenceOverrides, transferTargetId, [
886
- ["subAgents", "subAgents"],
887
- ["agents", "agents"],
888
- ["externalAgents", "externalAgents"]
889
- ]);
890
- assignComponentReferencePathOverride(registry, referencePathOverrides, "subAgents", transferTargetId, "subAgents");
891
- assignComponentReferencePathOverride(registry, referencePathOverrides, "agents", transferTargetId, "agents");
892
- assignComponentReferencePathOverride(registry, referencePathOverrides, "externalAgents", transferTargetId, "externalAgents");
893
- }
894
- const dataComponentIds = extractReferenceIds(subAgentData.dataComponents);
895
- for (const dataComponentId of dataComponentIds) assignComponentReferenceOverride(registry, referenceOverrides, "dataComponents", dataComponentId, "dataComponents");
896
- const artifactComponentIds = extractReferenceIds(subAgentData.artifactComponents);
897
- for (const artifactComponentId of artifactComponentIds) assignComponentReferenceOverride(registry, referenceOverrides, "artifactComponents", artifactComponentId, "artifactComponents");
898
- }
899
- return Object.keys(referenceOverrides).length > 0 || Object.keys(referencePathOverrides).length > 0 ? {
900
- ...Object.keys(referenceOverrides).length > 0 && { referenceOverrides },
901
- ...Object.keys(referencePathOverrides).length > 0 && { referencePathOverrides }
902
- } : void 0;
903
- }
904
- function assignFirstMatchingComponentReferenceOverride(registry, overrides, componentId, candidates) {
905
- for (const [overrideType, componentType] of candidates) {
906
- const component = registry.get(componentId, componentType);
907
- if (!component?.name) continue;
908
- assignReferenceOverride(overrides, overrideType, componentId, component.name);
909
- return;
910
- }
911
- }
912
- function assignComponentReferenceOverride(registry, overrides, overrideType, componentId, componentType) {
913
- const component = registry.get(componentId, componentType);
914
- if (!component?.name) return;
915
- assignReferenceOverride(overrides, overrideType, componentId, component.name);
916
- }
917
- function assignComponentReferencePathOverride(registry, overrides, overrideType, componentId, componentType) {
918
- const component = registry.get(componentId, componentType);
919
- if (!component?.filePath) return;
920
- assignReferencePathOverride(overrides, overrideType, componentId, componentType === "tools" || componentType === "functionTools" ? resolveToolModulePath(component.filePath) : stripExtension(basename(component.filePath)));
921
- }
922
- function assignReferenceOverride(overrides, overrideType, componentId, referenceName) {
923
- const overrideMap = overrides[overrideType] ?? {};
924
- overrideMap[componentId] = referenceName;
925
- overrides[overrideType] = overrideMap;
926
- }
927
- function assignReferencePathOverride(overrides, overrideType, componentId, referencePath) {
928
- const overrideMap = overrides[overrideType] ?? {};
929
- overrideMap[componentId] = referencePath;
930
- overrides[overrideType] = overrideMap;
931
- }
932
- function buildToolReferenceNamesById(project) {
933
- const toolReferenceNamesById = {};
934
- for (const [toolId, toolData] of Object.entries(project.tools ?? {})) {
935
- const toolName = asRecord(toolData)?.name;
936
- toolReferenceNamesById[toolId] = typeof toolName === "string" && toolName.length > 0 ? toToolReferenceName(toolName) : toToolReferenceName(toolId);
937
- }
938
- for (const functionToolEntry of collectFunctionToolEntries(project)) toolReferenceNamesById[functionToolEntry.functionToolId] = toToolReferenceName(functionToolEntry.exportName);
939
- return toolReferenceNamesById;
940
- }
941
- function buildToolReferencePathById(project) {
942
- const toolEntries = Object.entries(project.tools ?? {});
943
- const toolFileNamesById = buildSequentialNameFileNames(toolEntries);
944
- const toolReferencePathById = {};
945
- for (const [toolId] of toolEntries) toolReferencePathById[toolId] = stripExtension(toolFileNamesById[toolId]);
946
- const functionToolEntries = collectFunctionToolEntries(project);
947
- const functionToolFileNamesById = buildSequentialNameFileNames(functionToolEntries.map(({ functionToolId, fileName }) => [functionToolId, { name: fileName }]));
948
- for (const { functionToolId } of functionToolEntries) toolReferencePathById[functionToolId] = stripExtension(functionToolFileNamesById[functionToolId]);
949
- return toolReferencePathById;
950
- }
951
- function buildCredentialReferenceNamesById(project) {
952
- const credentialReferenceNamesById = {};
953
- const countsByReferenceName = /* @__PURE__ */ new Map();
954
- for (const [credentialId, credentialData] of Object.entries(project.credentialReferences ?? {})) {
955
- const credentialName = asRecord(credentialData)?.name;
956
- const baseReferenceName = typeof credentialName === "string" && credentialName.length > 0 ? toCredentialReferenceName(credentialName) : toCredentialReferenceName(credentialId);
957
- const occurrence = countsByReferenceName.get(baseReferenceName) ?? 0;
958
- countsByReferenceName.set(baseReferenceName, occurrence + 1);
959
- credentialReferenceNamesById[credentialId] = occurrence === 0 ? baseReferenceName : `${baseReferenceName}${occurrence}`;
960
- }
961
- return credentialReferenceNamesById;
962
- }
963
- function buildCredentialReferencePathById(project) {
964
- const credentialEntries = Object.entries(project.credentialReferences ?? {});
965
- const credentialFileNamesById = buildSequentialNameFileNames(credentialEntries);
966
- const credentialReferencePathById = {};
967
- for (const [credentialId] of credentialEntries) credentialReferencePathById[credentialId] = stripExtension(credentialFileNamesById[credentialId]);
968
- return credentialReferencePathById;
969
- }
970
- function buildExternalAgentReferenceNamesById(project) {
971
- const externalAgentReferenceNamesById = {};
972
- const countsByReferenceName = /* @__PURE__ */ new Map();
973
- for (const [externalAgentId, externalAgentData] of Object.entries(project.externalAgents ?? {})) {
974
- const baseReferenceName = toExternalAgentReferenceName(resolveExternalAgentNamingSeed(externalAgentId, externalAgentData));
975
- const occurrence = countsByReferenceName.get(baseReferenceName) ?? 0;
976
- countsByReferenceName.set(baseReferenceName, occurrence + 1);
977
- externalAgentReferenceNamesById[externalAgentId] = occurrence === 0 ? baseReferenceName : `${baseReferenceName}${occurrence}`;
978
- }
979
- return externalAgentReferenceNamesById;
980
- }
981
- function buildExternalAgentReferencePathById(project) {
982
- const externalAgentEntries = Object.entries(project.externalAgents ?? {}).map(([externalAgentId, externalAgentData]) => [externalAgentId, { name: resolveExternalAgentNamingSeed(externalAgentId, externalAgentData) }]);
983
- const externalAgentFileNamesById = buildSequentialNameFileNames(externalAgentEntries);
984
- const externalAgentReferencePathById = {};
985
- for (const [externalAgentId] of externalAgentEntries) externalAgentReferencePathById[externalAgentId] = stripExtension(externalAgentFileNamesById[externalAgentId]);
986
- return externalAgentReferencePathById;
987
- }
988
- function buildSubAgentReferenceNamesById(project, agentIds) {
989
- const subAgentReferenceNamesById = {};
990
- const candidateAgentIds = agentIds !== void 0 ? [...agentIds] : Object.keys(project.agents ?? {});
991
- for (const agentId of candidateAgentIds) {
992
- const agentData = project.agents?.[agentId];
993
- const subAgents = asRecord(agentData?.subAgents);
994
- if (!subAgents) continue;
995
- for (const [subAgentId, subAgentData] of Object.entries(subAgents)) {
996
- const subAgentName = asRecord(subAgentData)?.name;
997
- subAgentReferenceNamesById[subAgentId] = resolveSubAgentVariableName(subAgentId, typeof subAgentName === "string" ? subAgentName : void 0);
998
- }
999
- }
1000
- return subAgentReferenceNamesById;
1001
- }
1002
- function buildSubAgentReferencePathById(project, agentIds) {
1003
- const subAgentReferencePathById = {};
1004
- const candidateAgentIds = agentIds !== void 0 ? [...agentIds] : Object.keys(project.agents ?? {});
1005
- for (const agentId of candidateAgentIds) {
1006
- const agentData = project.agents?.[agentId];
1007
- const subAgents = asRecord(agentData?.subAgents);
1008
- if (!subAgents) continue;
1009
- for (const [subAgentId, subAgentData] of Object.entries(subAgents)) {
1010
- const subAgentName = asRecord(subAgentData)?.name;
1011
- subAgentReferencePathById[subAgentId] = stripExtension(buildComponentFileName(subAgentId, typeof subAgentName === "string" ? subAgentName : void 0));
1012
- }
1013
- }
1014
- return subAgentReferencePathById;
1015
- }
1016
- function buildAgentReferenceNamesById(project) {
1017
- const agentReferenceNamesById = {};
1018
- for (const agentId of Object.keys(project.agents ?? {})) agentReferenceNamesById[agentId] = toCamelCase(agentId);
1019
- return agentReferenceNamesById;
1020
- }
1021
- function buildAgentReferencePathById(project) {
1022
- const agentReferencePathById = {};
1023
- for (const [agentId, agentData] of Object.entries(project.agents ?? {})) {
1024
- const agentName = asRecord(agentData)?.name;
1025
- agentReferencePathById[agentId] = stripExtension(buildComponentFileName(agentId, typeof agentName === "string" ? agentName : void 0));
1026
- }
1027
- return agentReferencePathById;
1028
- }
1029
- function collectProjectReferenceOverrides(context) {
1030
- const overrides = {};
1031
- addProjectNameBasedReferenceOverrides(context.project, overrides);
1032
- const registry = context.existingComponentRegistry;
1033
- if (!registry) return Object.keys(overrides).length > 0 ? overrides : void 0;
1034
- for (const agentId of context.completeAgentIds) assignComponentReferenceOverrideForProject(registry, overrides, "agents", agentId, "agents");
1035
- const toolIds = getObjectKeys(context.project.tools);
1036
- for (const toolId of toolIds) {
1037
- if (assignComponentReferenceOverrideForProject(registry, overrides, "tools", toolId, "functionTools")) continue;
1038
- assignComponentReferenceOverrideForProject(registry, overrides, "tools", toolId, "tools");
1039
- }
1040
- const externalAgentIds = getObjectKeys(context.project.externalAgents);
1041
- for (const externalAgentId of externalAgentIds) assignComponentReferenceOverrideForProject(registry, overrides, "externalAgents", externalAgentId, "externalAgents");
1042
- const dataComponentIds = getObjectKeys(context.project.dataComponents);
1043
- for (const dataComponentId of dataComponentIds) assignComponentReferenceOverrideForProject(registry, overrides, "dataComponents", dataComponentId, "dataComponents");
1044
- const artifactComponentIds = getObjectKeys(context.project.artifactComponents);
1045
- for (const artifactComponentId of artifactComponentIds) assignComponentReferenceOverrideForProject(registry, overrides, "artifactComponents", artifactComponentId, "artifactComponents");
1046
- const credentialIds = getObjectKeys(context.project.credentialReferences);
1047
- for (const credentialId of credentialIds) assignComponentReferenceOverrideForProject(registry, overrides, "credentialReferences", credentialId, "credentials");
1048
- return Object.keys(overrides).length > 0 ? overrides : void 0;
1049
- }
1050
- function addProjectNameBasedReferenceOverrides(project, overrides) {
1051
- for (const [toolId, toolData] of Object.entries(project.tools ?? {})) {
1052
- const toolName = asRecord(toolData)?.name;
1053
- assignProjectReferenceOverride(overrides, "tools", toolId, typeof toolName === "string" && toolName.length > 0 ? toToolReferenceName(toolName) : toToolReferenceName(toolId));
1054
- }
1055
- for (const [credentialId, credentialData] of Object.entries(project.credentialReferences ?? {})) {
1056
- const credentialName = asRecord(credentialData)?.name;
1057
- assignProjectReferenceOverride(overrides, "credentialReferences", credentialId, typeof credentialName === "string" && credentialName.length > 0 ? toCredentialReferenceName(credentialName) : toCredentialReferenceName(credentialId));
1058
- }
1059
- const externalAgentReferenceNamesById = buildExternalAgentReferenceNamesById(project);
1060
- for (const [externalAgentId, referenceName] of Object.entries(externalAgentReferenceNamesById)) assignProjectReferenceOverride(overrides, "externalAgents", externalAgentId, referenceName);
1061
- }
1062
- function collectProjectReferencePathOverrides(context) {
1063
- const overrides = {};
1064
- if (context.project.agents) for (const agentId of context.completeAgentIds) {
1065
- const agentData = asRecord(context.project.agents[agentId]);
1066
- assignProjectReferenceOverride(overrides, "agents", agentId, stripExtension(buildComponentFileName(agentId, typeof agentData?.name === "string" ? agentData.name : void 0)));
1067
- }
1068
- const toolEntries = Object.entries(context.project.tools ?? {});
1069
- const toolFileNamesById = buildSequentialNameFileNames(toolEntries);
1070
- for (const [toolId] of toolEntries) assignProjectReferenceOverride(overrides, "tools", toolId, stripExtension(toolFileNamesById[toolId]));
1071
- const credentialEntries = Object.entries(context.project.credentialReferences ?? {});
1072
- const credentialFileNamesById = buildSequentialNameFileNames(credentialEntries);
1073
- for (const [credentialId] of credentialEntries) assignProjectReferenceOverride(overrides, "credentialReferences", credentialId, stripExtension(credentialFileNamesById[credentialId]));
1074
- const externalAgentReferencePathsById = buildExternalAgentReferencePathById(context.project);
1075
- for (const [externalAgentId, referencePath] of Object.entries(externalAgentReferencePathsById)) assignProjectReferenceOverride(overrides, "externalAgents", externalAgentId, referencePath);
1076
- const registry = context.existingComponentRegistry;
1077
- if (registry) {
1078
- for (const agentId of context.completeAgentIds) {
1079
- const agentComponent = registry.get(agentId, "agents");
1080
- if (agentComponent?.filePath) assignProjectReferenceOverride(overrides, "agents", agentId, stripExtension(basename(agentComponent.filePath)));
1081
- }
1082
- for (const toolId of getObjectKeys(context.project.tools)) {
1083
- const toolComponent = registry.get(toolId, "functionTools") ?? registry.get(toolId, "tools");
1084
- if (toolComponent?.filePath) assignProjectReferenceOverride(overrides, "tools", toolId, resolveToolModulePath(toolComponent.filePath));
1085
- }
1086
- for (const credentialId of getObjectKeys(context.project.credentialReferences)) {
1087
- const credentialComponent = registry.get(credentialId, "credentials");
1088
- if (credentialComponent?.filePath) assignProjectReferenceOverride(overrides, "credentialReferences", credentialId, stripExtension(basename(credentialComponent.filePath)));
1089
- }
1090
- for (const externalAgentId of getObjectKeys(context.project.externalAgents)) {
1091
- const externalAgentComponent = registry.get(externalAgentId, "externalAgents");
1092
- if (externalAgentComponent?.filePath) assignProjectReferenceOverride(overrides, "externalAgents", externalAgentId, stripExtension(basename(externalAgentComponent.filePath)));
1093
- }
1094
- }
1095
- return Object.keys(overrides).length > 0 ? overrides : void 0;
1096
- }
1097
- function assignProjectReferenceOverride(overrides, overrideType, componentId, referenceName) {
1098
- const overrideMap = overrides[overrideType] ?? {};
1099
- overrideMap[componentId] = referenceName;
1100
- overrides[overrideType] = overrideMap;
1101
- }
1102
- function stripExtension(fileName) {
1103
- return fileName.replace(/\.[^.]+$/, "");
1104
- }
1105
- function resolveToolModulePath(filePath) {
1106
- const normalizedFilePath = normalizeFilePath(filePath);
1107
- const toolsIndex = normalizedFilePath.lastIndexOf("/tools/");
1108
- if (toolsIndex >= 0) {
1109
- let modulePath = stripExtension(normalizedFilePath.slice(toolsIndex + 7));
1110
- if (modulePath.endsWith("/index")) modulePath = modulePath.slice(0, -6);
1111
- if (modulePath.length > 0) return modulePath;
1112
- }
1113
- const baseModulePath = stripExtension(basename(normalizedFilePath));
1114
- if (baseModulePath === "index") return stripExtension(basename(dirname(normalizedFilePath)));
1115
- return baseModulePath;
1116
- }
1117
- function resolveExternalAgentNamingSeed(externalAgentId, externalAgentData) {
1118
- if (isHumanReadableId(externalAgentId)) return externalAgentId;
1119
- const externalAgentName = asRecord(externalAgentData)?.name;
1120
- if (typeof externalAgentName === "string" && externalAgentName.length > 0) return externalAgentName;
1121
- return externalAgentId;
1122
- }
1123
- function toExternalAgentReferenceName(input) {
1124
- const base = toCamelCase(input);
1125
- return base.endsWith("Agent") ? base : `${base}Agent`;
1126
- }
1127
- function buildSequentialNameFileNames(entries) {
1128
- const countsByStem = /* @__PURE__ */ new Map();
1129
- const fileNamesById = {};
1130
- for (const [componentId, componentData] of entries) {
1131
- const name = asRecord(componentData)?.name;
1132
- const baseStem = resolveNameFileStem(componentId, typeof name === "string" ? name : void 0);
1133
- const occurrence = countsByStem.get(baseStem) ?? 0;
1134
- countsByStem.set(baseStem, occurrence + 1);
1135
- fileNamesById[componentId] = `${occurrence === 0 ? baseStem : `${baseStem}-${occurrence}`}.ts`;
1136
- }
1137
- return fileNamesById;
1138
- }
1139
- function resolveNameFileStem(componentId, name) {
1140
- const nameStem = name ? toKebabCase(name) : "";
1141
- if (nameStem.length > 0) return nameStem;
1142
- const idStem = toKebabCase(componentId);
1143
- if (idStem.length > 0) return idStem;
1144
- return componentId;
1145
- }
1146
- function assignComponentReferenceOverrideForProject(registry, overrides, overrideType, componentId, componentType) {
1147
- const component = registry.get(componentId, componentType);
1148
- if (!component?.name) return false;
1149
- const overrideMap = overrides[overrideType] ?? {};
1150
- overrideMap[componentId] = component.name;
1151
- overrides[overrideType] = overrideMap;
1152
- return true;
1153
- }
1154
- function extractReferenceIds(value) {
1155
- if (Array.isArray(value)) return value.map((item) => {
1156
- if (typeof item === "string") return item;
1157
- const record$1 = asRecord(item);
1158
- if (record$1 && typeof record$1.id === "string") return record$1.id;
1159
- }).filter((id) => !!id);
1160
- const record = asRecord(value);
1161
- if (!record) return [];
1162
- return Object.keys(record);
1163
- }
1164
- function resolveRecordFilePath(context, componentType, componentId, fallbackFilePath) {
1165
- const existingComponent = context.existingComponentRegistry?.get(componentId, componentType);
1166
- if (!existingComponent?.filePath) return fallbackFilePath;
1167
- return resolveProjectFilePath(context.paths.projectRoot, existingComponent.filePath);
1168
- }
1169
- function resolveProjectFilePath(projectRoot, filePath) {
1170
- if (filePath.startsWith("/")) return filePath;
1171
- return join(projectRoot, filePath);
1172
- }
1173
- function normalizeFilePath(filePath) {
1174
- return filePath.replaceAll("\\", "/");
1175
- }
1176
- function writeTypeScriptFile(filePath, content, writeMode) {
1177
- mkdirSync(dirname(filePath), { recursive: true });
1178
- const processedContent = writeMode === "merge" && existsSync(filePath) ? mergeSafely(readFileSync(filePath, "utf8"), content) : content;
1179
- const sourceFile = createInMemoryProject().createSourceFile("generated.ts", processedContent, { overwrite: true });
1180
- const normalizedSourceFile = moveVariableDeclarationsBeforeUsage(applyObjectShorthand(sourceFile));
1181
- sourceFile.formatText();
1182
- writeFileSync(filePath, `${normalizedSourceFile.getFullText().trimEnd()}\n`);
1183
- }
1184
- function mergeSafely(existingContent, generatedContent) {
1185
- try {
1186
- return mergeGeneratedModule(existingContent, generatedContent);
1187
- } catch (error) {
1188
- console.warn(`Warning: Failed to merge file, using generated content. Manual changes may be lost. Reason: ${error instanceof Error ? error.message : String(error)}`);
1189
- return generatedContent;
1190
- }
1191
- }
1192
- function applyObjectShorthand(sourceFile) {
1193
- for (const objectLiteral of sourceFile.getDescendantsOfKind(SyntaxKind.ObjectLiteralExpression)) for (const property of objectLiteral.getProperties()) {
1194
- if (!Node.isPropertyAssignment(property)) continue;
1195
- const nameNode = property.getNameNode();
1196
- const initializer = property.getInitializer();
1197
- if (!Node.isIdentifier(nameNode) || !initializer || !Node.isIdentifier(initializer)) continue;
1198
- if (nameNode.getText() !== initializer.getText()) continue;
1199
- property.replaceWithText(nameNode.getText());
1200
- }
1201
- return sourceFile;
1202
- }
1203
- function moveVariableDeclarationsBeforeUsage(sourceFile) {
1204
- let moved = true;
1205
- while (moved) {
1206
- moved = false;
1207
- const variableStatements = sourceFile.getVariableStatements();
1208
- for (const variableStatement of variableStatements) {
1209
- const statementStart = variableStatement.getStart();
1210
- const sourceStatements = sourceFile.getStatements();
1211
- const statementIndex = sourceStatements.indexOf(variableStatement);
1212
- if (statementIndex <= 0) continue;
1213
- let targetIndex;
1214
- for (const declaration of variableStatement.getDeclarations()) for (const referenceNode of declaration.findReferencesAsNodes()) {
1215
- if (referenceNode.getSourceFile() !== sourceFile) continue;
1216
- if (referenceNode.getParent() === declaration) continue;
1217
- if (referenceNode.getStart() >= statementStart) continue;
1218
- if (isReferenceInsideFunctionLike(referenceNode)) continue;
1219
- const topLevelStatement = referenceNode.getFirstAncestor((ancestor) => {
1220
- return Node.isStatement(ancestor) && ancestor.getParentIfKind(SyntaxKind.SourceFile);
1221
- });
1222
- if (!topLevelStatement) continue;
1223
- const topLevelStatementIndex = sourceStatements.indexOf(topLevelStatement);
1224
- if (topLevelStatementIndex === -1 || topLevelStatementIndex >= statementIndex) continue;
1225
- targetIndex = targetIndex === void 0 ? topLevelStatementIndex : Math.min(targetIndex, topLevelStatementIndex);
1226
- }
1227
- if (targetIndex === void 0) continue;
1228
- const statementText = variableStatement.getText();
1229
- variableStatement.remove();
1230
- sourceFile.insertStatements(targetIndex, [statementText]);
1231
- moved = true;
1232
- break;
1233
- }
1234
- }
1235
- return sourceFile;
1236
- }
1237
- function isReferenceInsideFunctionLike(referenceNode) {
1238
- return Boolean(referenceNode.getFirstAncestor((ancestor) => {
1239
- return Node.isArrowFunction(ancestor) || Node.isFunctionDeclaration(ancestor) || Node.isFunctionExpression(ancestor) || Node.isMethodDeclaration(ancestor) || Node.isGetAccessorDeclaration(ancestor) || Node.isSetAccessorDeclaration(ancestor);
1240
- }));
1241
- }
1242
39
 
1243
40
  //#endregion
1244
41
  export { introspectGenerate };