@inkeep/agents-cli 0.0.0-dev-20251105013355 → 0.0.0-dev-20251105034049

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 (2) hide show
  1. package/dist/index.js +2002 -2002
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -5033,8 +5033,8 @@ var init_contextConfigs = __esm({
5033
5033
  "../packages/agents-core/src/data-access/contextConfigs.ts"() {
5034
5034
  "use strict";
5035
5035
  init_esm_shims();
5036
- init_conversations();
5037
5036
  init_schema();
5037
+ init_conversations();
5038
5038
  }
5039
5039
  });
5040
5040
 
@@ -218118,8 +218118,8 @@ var init_functionTools = __esm({
218118
218118
  "../packages/agents-core/src/data-access/functionTools.ts"() {
218119
218119
  "use strict";
218120
218120
  init_esm_shims();
218121
- init_conversations();
218122
218121
  init_schema();
218122
+ init_conversations();
218123
218123
  init_logger();
218124
218124
  logger4 = getLogger("functionTools");
218125
218125
  }
@@ -218184,8 +218184,8 @@ var init_apiKeys = __esm({
218184
218184
  "use strict";
218185
218185
  init_esm_shims();
218186
218186
  init_nanoid();
218187
- init_logger();
218188
218187
  init_conversations();
218188
+ init_logger();
218189
218189
  scryptAsync = promisify(scrypt);
218190
218190
  logger5 = getLogger("api-key");
218191
218191
  PUBLIC_ID_LENGTH = 12;
@@ -233614,8 +233614,8 @@ var init_artifactComponents = __esm({
233614
233614
  "../packages/agents-core/src/data-access/artifactComponents.ts"() {
233615
233615
  "use strict";
233616
233616
  init_esm_shims();
233617
- init_conversations();
233618
233617
  init_schema();
233618
+ init_conversations();
233619
233619
  init_props_validation();
233620
233620
  }
233621
233621
  });
@@ -233681,8 +233681,8 @@ var init_contextCache = __esm({
233681
233681
  "../packages/agents-core/src/data-access/contextCache.ts"() {
233682
233682
  "use strict";
233683
233683
  init_esm_shims();
233684
- init_conversations();
233685
233684
  init_schema();
233685
+ init_conversations();
233686
233686
  }
233687
233687
  });
233688
233688
 
@@ -233703,8 +233703,8 @@ var init_ledgerArtifacts = __esm({
233703
233703
  "../packages/agents-core/src/data-access/ledgerArtifacts.ts"() {
233704
233704
  "use strict";
233705
233705
  init_esm_shims();
233706
- init_conversations();
233707
233706
  init_schema();
233707
+ init_conversations();
233708
233708
  }
233709
233709
  });
233710
233710
 
@@ -233735,6 +233735,7 @@ var init_projectFull = __esm({
233735
233735
  "../packages/agents-core/src/data-access/projectFull.ts"() {
233736
233736
  "use strict";
233737
233737
  init_esm_shims();
233738
+ init_schema();
233738
233739
  init_logger();
233739
233740
  init_agentFull2();
233740
233741
  init_agents();
@@ -233745,7 +233746,6 @@ var init_projectFull = __esm({
233745
233746
  init_functions();
233746
233747
  init_projects();
233747
233748
  init_tools();
233748
- init_schema();
233749
233749
  defaultLogger = getLogger("projectFull");
233750
233750
  }
233751
233751
  });
@@ -234634,403 +234634,6 @@ var init_background_version_check = __esm({
234634
234634
  }
234635
234635
  });
234636
234636
 
234637
- // src/commands/pull-v3/utils/component-registry.ts
234638
- function registerAllComponents(project, registry2) {
234639
- registry2.register(project.id, "project", "index.ts");
234640
- if (project.credentialReferences) {
234641
- for (const credId of Object.keys(project.credentialReferences)) {
234642
- registry2.register(credId, "credential", `credentials/${credId}.ts`);
234643
- }
234644
- }
234645
- if (project.tools) {
234646
- for (const toolId of Object.keys(project.tools)) {
234647
- registry2.register(toolId, "tool", `tools/${toolId}.ts`);
234648
- }
234649
- }
234650
- const processedFunctionIds = /* @__PURE__ */ new Set();
234651
- if (project.functions) {
234652
- for (const funcId of Object.keys(project.functions)) {
234653
- registry2.register(funcId, "functionTool", `tools/functions/${funcId}.ts`);
234654
- processedFunctionIds.add(funcId);
234655
- }
234656
- }
234657
- if (project.functionTools) {
234658
- for (const funcToolId of Object.keys(project.functionTools)) {
234659
- if (!processedFunctionIds.has(funcToolId)) {
234660
- registry2.register(funcToolId, "functionTool", `tools/functions/${funcToolId}.ts`);
234661
- }
234662
- }
234663
- }
234664
- if (project.dataComponents) {
234665
- for (const componentId of Object.keys(project.dataComponents)) {
234666
- registry2.register(componentId, "dataComponent", `data-components/${componentId}.ts`);
234667
- }
234668
- }
234669
- if (project.artifactComponents) {
234670
- for (const componentId of Object.keys(project.artifactComponents)) {
234671
- registry2.register(componentId, "artifactComponent", `artifact-components/${componentId}.ts`);
234672
- }
234673
- }
234674
- if (project.externalAgents) {
234675
- for (const extAgentId of Object.keys(project.externalAgents)) {
234676
- registry2.register(extAgentId, "externalAgent", `external-agents/${extAgentId}.ts`);
234677
- }
234678
- }
234679
- const statusComponents = extractStatusComponents(project);
234680
- for (const statusId of Object.keys(statusComponents)) {
234681
- registry2.register(statusId, "statusComponent", `status-components/${statusId}.ts`);
234682
- }
234683
- if (project.agents) {
234684
- for (const agentId of Object.keys(project.agents)) {
234685
- registry2.register(agentId, "agent", `agents/${agentId}.ts`);
234686
- }
234687
- }
234688
- const subAgents2 = extractSubAgents(project);
234689
- for (const subAgentId of Object.keys(subAgents2)) {
234690
- registry2.register(subAgentId, "subAgent", `agents/sub-agents/${subAgentId}.ts`);
234691
- }
234692
- const contextConfigs2 = extractContextConfigs(project);
234693
- for (const contextId of Object.keys(contextConfigs2)) {
234694
- registry2.register(contextId, "contextConfig", `context-configs/${contextId}.ts`);
234695
- }
234696
- }
234697
- function extractStatusComponents(project) {
234698
- const statusComponents = {};
234699
- if (project.agents) {
234700
- for (const [agentId, agentData] of Object.entries(project.agents)) {
234701
- if (agentData.statusUpdates && agentData.statusUpdates.statusComponents) {
234702
- for (const statusComp of agentData.statusUpdates.statusComponents) {
234703
- let statusId;
234704
- if (typeof statusComp === "string") {
234705
- statusId = statusComp;
234706
- } else if (typeof statusComp === "object" && statusComp) {
234707
- statusId = statusComp.type;
234708
- } else {
234709
- continue;
234710
- }
234711
- if (statusId && !statusComponents[statusId]) {
234712
- statusComponents[statusId] = {
234713
- // Include any other properties from the actual data first
234714
- ...statusComp,
234715
- id: statusId,
234716
- type: statusComp.type || statusId,
234717
- description: statusComp.description || `Status component for ${statusId}`,
234718
- detailsSchema: statusComp.detailsSchema
234719
- };
234720
- }
234721
- }
234722
- }
234723
- }
234724
- }
234725
- return statusComponents;
234726
- }
234727
- function extractSubAgents(project) {
234728
- const subAgents2 = {};
234729
- if (project.agents) {
234730
- for (const [agentId, agentData] of Object.entries(project.agents)) {
234731
- if (agentData.subAgents) {
234732
- for (const [subAgentId, subAgentData] of Object.entries(agentData.subAgents)) {
234733
- subAgents2[subAgentId] = subAgentData;
234734
- }
234735
- }
234736
- }
234737
- }
234738
- return subAgents2;
234739
- }
234740
- function extractContextConfigs(project) {
234741
- const contextConfigs2 = {};
234742
- if (project.agents) {
234743
- for (const [agentId, agentData] of Object.entries(project.agents)) {
234744
- if (agentData.contextConfig) {
234745
- const contextConfigId = agentData.contextConfig.id;
234746
- if (contextConfigId) {
234747
- contextConfigs2[contextConfigId] = agentData.contextConfig;
234748
- } else {
234749
- console.warn(`contextConfig for agent ${agentId} is missing required 'id' field`);
234750
- }
234751
- }
234752
- }
234753
- }
234754
- return contextConfigs2;
234755
- }
234756
- function findSubAgentWithParent(project, subAgentId) {
234757
- if (project.agents) {
234758
- for (const [agentId, agentData] of Object.entries(project.agents)) {
234759
- if (agentData.subAgents && agentData.subAgents[subAgentId]) {
234760
- const contextConfigData = agentData.contextConfig?.id ? agentData.contextConfig : void 0;
234761
- return {
234762
- subAgentData: agentData.subAgents[subAgentId],
234763
- parentAgentId: agentId,
234764
- contextConfigData
234765
- };
234766
- }
234767
- }
234768
- }
234769
- return void 0;
234770
- }
234771
- var ComponentRegistry;
234772
- var init_component_registry = __esm({
234773
- "src/commands/pull-v3/utils/component-registry.ts"() {
234774
- "use strict";
234775
- init_esm_shims();
234776
- ComponentRegistry = class {
234777
- components = /* @__PURE__ */ new Map();
234778
- componentsByTypeAndId = /* @__PURE__ */ new Map();
234779
- // Type-aware lookup
234780
- usedNames = /* @__PURE__ */ new Set();
234781
- // Global name registry for uniqueness
234782
- /**
234783
- * Register a component with both unique name and file path
234784
- */
234785
- register(id, type, filePath, exportName, isInline = false) {
234786
- const typeKey = `${type}:${id}`;
234787
- const existing = this.componentsByTypeAndId.get(typeKey);
234788
- if (existing) {
234789
- return existing;
234790
- }
234791
- let name;
234792
- let actualExportName;
234793
- if (exportName) {
234794
- name = exportName;
234795
- actualExportName = exportName;
234796
- } else {
234797
- const baseName = this.toCamelCase(id);
234798
- const uniqueName = this.ensureUniqueName(baseName, type);
234799
- name = uniqueName;
234800
- actualExportName = uniqueName;
234801
- }
234802
- const info = {
234803
- id,
234804
- name,
234805
- type,
234806
- filePath,
234807
- exportName: actualExportName,
234808
- isInline
234809
- };
234810
- this.components.set(id, info);
234811
- this.componentsByTypeAndId.set(typeKey, info);
234812
- this.usedNames.add(name);
234813
- if (actualExportName && actualExportName !== name) {
234814
- this.usedNames.add(actualExportName);
234815
- }
234816
- return info;
234817
- }
234818
- /**
234819
- * Get component info by ID and type
234820
- */
234821
- get(id, type) {
234822
- const typeKey = `${type}:${id}`;
234823
- return this.componentsByTypeAndId.get(typeKey);
234824
- }
234825
- /**
234826
- * Get component info by variable name (since variable names are globally unique)
234827
- */
234828
- getByVariableName(variableName) {
234829
- for (const component of this.componentsByTypeAndId.values()) {
234830
- if (component.name === variableName) {
234831
- return component;
234832
- }
234833
- }
234834
- return void 0;
234835
- }
234836
- /**
234837
- * Get unique variable name for a component by ID and type
234838
- */
234839
- getVariableName(id, type) {
234840
- const typeKey = `${type}:${id}`;
234841
- const result = this.componentsByTypeAndId.get(typeKey)?.name;
234842
- return result;
234843
- }
234844
- /**
234845
- * Get import statement for a component
234846
- */
234847
- getImportStatement(fromFilePath, componentId, componentType) {
234848
- const component = this.get(componentId, componentType);
234849
- if (!component) return void 0;
234850
- const relativePath = this.calculateRelativeImport(fromFilePath, component.filePath);
234851
- const importStmt = `import { ${component.exportName} } from '${relativePath}';`;
234852
- return importStmt;
234853
- }
234854
- /**
234855
- * Format an array of references for code generation
234856
- */
234857
- formatReferencesForCode(references, componentType, style, indentLevel) {
234858
- if (!Array.isArray(references) || references.length === 0) {
234859
- return "[]";
234860
- }
234861
- const variableNames = [];
234862
- for (const ref of references) {
234863
- const id = this.extractIdFromReference(ref);
234864
- if (id) {
234865
- const component = this.get(id, componentType);
234866
- if (component) {
234867
- variableNames.push(component.name);
234868
- } else {
234869
- console.warn(`ComponentRegistry: Component not found: ${id} (type: ${componentType})`);
234870
- variableNames.push(this.toCamelCase(id));
234871
- }
234872
- }
234873
- }
234874
- if (variableNames.length === 0) {
234875
- return "[]";
234876
- }
234877
- if (variableNames.length === 1) {
234878
- return `[${variableNames[0]}]`;
234879
- }
234880
- const { indentation } = style;
234881
- const indent = indentation.repeat(indentLevel);
234882
- const lines = ["["];
234883
- for (let i = 0; i < variableNames.length; i++) {
234884
- const isLast = i === variableNames.length - 1;
234885
- lines.push(`${indent}${variableNames[i]}${isLast ? "" : ","}`);
234886
- }
234887
- lines.push(`${indentation.repeat(indentLevel - 1)}]`);
234888
- return lines.join("\n");
234889
- }
234890
- /**
234891
- * Get all import statements needed for a file
234892
- */
234893
- getImportsForFile(fromFilePath, referencedComponents) {
234894
- const imports = [];
234895
- const seenImports = /* @__PURE__ */ new Set();
234896
- for (const { id, type } of referencedComponents) {
234897
- const importStatement = this.getImportStatement(fromFilePath, id, type);
234898
- if (importStatement && !seenImports.has(importStatement)) {
234899
- imports.push(importStatement);
234900
- seenImports.add(importStatement);
234901
- }
234902
- }
234903
- return imports;
234904
- }
234905
- /**
234906
- * Get all component IDs referenced in arrays for import generation
234907
- */
234908
- getReferencedComponentIds(referenceArrays) {
234909
- const componentIds = [];
234910
- for (const refArray of referenceArrays) {
234911
- if (Array.isArray(refArray)) {
234912
- for (const ref of refArray) {
234913
- const id = this.extractIdFromReference(ref);
234914
- if (id) {
234915
- componentIds.push(id);
234916
- }
234917
- }
234918
- }
234919
- }
234920
- return componentIds;
234921
- }
234922
- /**
234923
- * Extract ID from a reference (string or object) based on component type
234924
- */
234925
- extractIdFromReference(ref) {
234926
- if (typeof ref === "string") {
234927
- return ref;
234928
- } else if (typeof ref === "object" && ref) {
234929
- if (ref.toolId) return ref.toolId;
234930
- if (ref.agentId) return ref.agentId;
234931
- if (ref.externalAgentId) return ref.externalAgentId;
234932
- if (ref.credentialStoreId) return ref.credentialStoreId;
234933
- if (ref.type && !ref.agentId && !ref.toolId && !ref.externalAgentId) return ref.type;
234934
- if (ref.id) return ref.id;
234935
- if (ref.name) return ref.name;
234936
- console.warn("ComponentRegistry: Reference without recognized ID field:", ref);
234937
- return null;
234938
- }
234939
- return null;
234940
- }
234941
- /**
234942
- * Convert string to camelCase and ensure it's a valid JavaScript identifier
234943
- */
234944
- toCamelCase(str) {
234945
- return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
234946
- }
234947
- /**
234948
- * Ensure a name is unique by adding prefixes/suffixes if needed
234949
- */
234950
- ensureUniqueName(baseName, type) {
234951
- let uniqueName = baseName;
234952
- let counter = 1;
234953
- while (this.usedNames.has(uniqueName)) {
234954
- if (counter === 1) {
234955
- const typePrefix = this.getTypePrefix(type);
234956
- uniqueName = `${typePrefix}${baseName.charAt(0).toUpperCase() + baseName.slice(1)}`;
234957
- } else {
234958
- uniqueName = `${baseName}${counter}`;
234959
- }
234960
- counter++;
234961
- if (counter > 100) {
234962
- uniqueName = `${baseName}_${Date.now()}`;
234963
- break;
234964
- }
234965
- }
234966
- return uniqueName;
234967
- }
234968
- /**
234969
- * Get type prefix for uniqueness resolution
234970
- */
234971
- getTypePrefix(type) {
234972
- switch (type) {
234973
- case "agent":
234974
- return "agent";
234975
- case "subAgent":
234976
- return "sub";
234977
- case "externalAgent":
234978
- return "ext";
234979
- case "tool":
234980
- return "tool";
234981
- case "functionTool":
234982
- return "func";
234983
- case "dataComponent":
234984
- return "data";
234985
- case "artifactComponent":
234986
- return "artifact";
234987
- case "credential":
234988
- return "cred";
234989
- case "statusComponent":
234990
- return "status";
234991
- case "contextConfig":
234992
- return "context";
234993
- case "project":
234994
- return "project";
234995
- default:
234996
- return "comp";
234997
- }
234998
- }
234999
- /**
235000
- * Calculate relative import path between files
235001
- */
235002
- calculateRelativeImport(fromPath, toPath) {
235003
- const fromParts = fromPath.replace(".ts", "").split("/");
235004
- const toParts = toPath.replace(".ts", "").split("/");
235005
- fromParts.pop();
235006
- let relativePath = "";
235007
- for (let i = 0; i < fromParts.length; i++) {
235008
- relativePath += "../";
235009
- }
235010
- relativePath += toParts.join("/");
235011
- if (relativePath.startsWith("../")) {
235012
- return relativePath;
235013
- } else {
235014
- return "./" + relativePath;
235015
- }
235016
- }
235017
- /**
235018
- * Get all components for debugging
235019
- */
235020
- getAllComponents() {
235021
- return Array.from(this.components.values());
235022
- }
235023
- /**
235024
- * Clear all components (for testing)
235025
- */
235026
- clear() {
235027
- this.components.clear();
235028
- this.usedNames.clear();
235029
- }
235030
- };
235031
- }
235032
- });
235033
-
235034
234637
  // src/commands/pull-v3/utils/generator-utils.ts
235035
234638
  function toCamelCase(str) {
235036
234639
  const result = str.replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
@@ -235147,195 +234750,6 @@ var init_generator_utils = __esm({
235147
234750
  }
235148
234751
  });
235149
234752
 
235150
- // src/commands/pull-v3/components/project-generator.ts
235151
- function generateProjectDefinition(projectId, projectData, style = DEFAULT_STYLE, registry2) {
235152
- if (!projectId || typeof projectId !== "string") {
235153
- throw new Error("projectId is required and must be a string");
235154
- }
235155
- if (!projectData || typeof projectData !== "object") {
235156
- throw new Error(`projectData is required for project '${projectId}'`);
235157
- }
235158
- const requiredFields = ["name", "models"];
235159
- const missingFields = requiredFields.filter(
235160
- (field) => !projectData[field] || projectData[field] === null || projectData[field] === void 0
235161
- );
235162
- if (!projectData.models?.base) {
235163
- missingFields.push("models.base");
235164
- }
235165
- if (missingFields.length > 0) {
235166
- throw new Error(
235167
- `Missing required fields for project '${projectId}': ${missingFields.join(", ")}`
235168
- );
235169
- }
235170
- const { quotes, semicolons, indentation } = style;
235171
- const q = quotes === "single" ? "'" : '"';
235172
- const semi = semicolons ? ";" : "";
235173
- const projectVarName = toCamelCase(projectId);
235174
- const lines = [];
235175
- lines.push(`export const ${projectVarName} = project({`);
235176
- lines.push(`${indentation}id: ${formatString(projectId, q)},`);
235177
- lines.push(`${indentation}name: ${formatString(projectData.name, q)},`);
235178
- if (shouldInclude(projectData.description)) {
235179
- lines.push(`${indentation}description: ${formatString(projectData.description, q, true)},`);
235180
- }
235181
- if (shouldInclude(projectData.models)) {
235182
- lines.push(`${indentation}models: ${formatObject(projectData.models, style, 2)},`);
235183
- }
235184
- if (shouldInclude(projectData.stopWhen)) {
235185
- lines.push(`${indentation}stopWhen: {`);
235186
- if (projectData.stopWhen.transferCountIs !== void 0) {
235187
- lines.push(
235188
- `${indentation}${indentation}transferCountIs: ${projectData.stopWhen.transferCountIs}, // Max transfers for agents`
235189
- );
235190
- }
235191
- if (projectData.stopWhen.stepCountIs !== void 0) {
235192
- lines.push(
235193
- `${indentation}${indentation}stepCountIs: ${projectData.stopWhen.stepCountIs} // Max steps for sub-agents`
235194
- );
235195
- }
235196
- if (lines.length > 1) {
235197
- const lastLine = lines[lines.length - 1];
235198
- if (lastLine.includes(",") && (lastLine.includes("//") || lastLine.endsWith(","))) {
235199
- if (lastLine.includes("//")) {
235200
- lines[lines.length - 1] = lastLine.replace(", //", " //");
235201
- } else {
235202
- lines[lines.length - 1] = lastLine.slice(0, -1);
235203
- }
235204
- }
235205
- }
235206
- lines.push(`${indentation}},`);
235207
- }
235208
- if (shouldInclude(projectData.agents)) {
235209
- const agentsArray = registry2 ? registry2.formatReferencesForCode(projectData.agents, "agent", style, 2) : "[]";
235210
- lines.push(`${indentation}agents: () => ${agentsArray},`);
235211
- }
235212
- if (shouldInclude(projectData.tools)) {
235213
- const toolsArray = registry2 ? registry2.formatReferencesForCode(projectData.tools, "tool", style, 2) : "[]";
235214
- lines.push(`${indentation}tools: () => ${toolsArray},`);
235215
- }
235216
- if (shouldInclude(projectData.externalAgents)) {
235217
- const externalAgentsArray = registry2 ? registry2.formatReferencesForCode(projectData.externalAgents, "externalAgent", style, 2) : "[]";
235218
- lines.push(`${indentation}externalAgents: () => ${externalAgentsArray},`);
235219
- }
235220
- if (shouldInclude(projectData.dataComponents)) {
235221
- const dataComponentsArray = registry2 ? registry2.formatReferencesForCode(projectData.dataComponents, "dataComponent", style, 2) : "[]";
235222
- lines.push(`${indentation}dataComponents: () => ${dataComponentsArray},`);
235223
- }
235224
- if (shouldInclude(projectData.artifactComponents)) {
235225
- const artifactComponentsArray = registry2 ? registry2.formatReferencesForCode(
235226
- projectData.artifactComponents,
235227
- "artifactComponent",
235228
- style,
235229
- 2
235230
- ) : "[]";
235231
- lines.push(`${indentation}artifactComponents: () => ${artifactComponentsArray},`);
235232
- }
235233
- if (shouldInclude(projectData.credentialReferences)) {
235234
- const credentialReferencesArray = registry2 ? registry2.formatReferencesForCode(projectData.credentialReferences, "credential", style, 2) : "[]";
235235
- lines.push(`${indentation}credentialReferences: () => ${credentialReferencesArray},`);
235236
- }
235237
- removeTrailingComma(lines);
235238
- lines.push(`})${semi}`);
235239
- return lines.join("\n");
235240
- }
235241
- function generateProjectImports(projectId, projectData, style = DEFAULT_STYLE, registry2) {
235242
- const imports = [];
235243
- imports.push(generateImport(["project"], "@inkeep/agents-sdk", style));
235244
- if (registry2) {
235245
- const currentFilePath = "index.ts";
235246
- const referencedComponents = [];
235247
- if (projectData.agents) {
235248
- let agentIds = [];
235249
- if (Array.isArray(projectData.agents)) {
235250
- agentIds = projectData.agents;
235251
- } else if (typeof projectData.agents === "object") {
235252
- agentIds = Object.keys(projectData.agents);
235253
- }
235254
- for (const agentId of agentIds) {
235255
- referencedComponents.push({ id: agentId, type: "agent" });
235256
- }
235257
- }
235258
- if (projectData.tools) {
235259
- let toolIds = [];
235260
- if (Array.isArray(projectData.tools)) {
235261
- toolIds = projectData.tools;
235262
- } else if (typeof projectData.tools === "object") {
235263
- toolIds = Object.keys(projectData.tools);
235264
- }
235265
- for (const toolId of toolIds) {
235266
- let componentType = "tool";
235267
- if (registry2 && registry2.get(toolId, "functionTool")) {
235268
- componentType = "functionTool";
235269
- } else if (registry2 && registry2.get(toolId, "tool")) {
235270
- componentType = "tool";
235271
- }
235272
- referencedComponents.push({ id: toolId, type: componentType });
235273
- }
235274
- }
235275
- if (projectData.externalAgents) {
235276
- let extAgentIds = [];
235277
- if (Array.isArray(projectData.externalAgents)) {
235278
- extAgentIds = projectData.externalAgents;
235279
- } else if (typeof projectData.externalAgents === "object") {
235280
- extAgentIds = Object.keys(projectData.externalAgents);
235281
- }
235282
- for (const extAgentId of extAgentIds) {
235283
- referencedComponents.push({ id: extAgentId, type: "externalAgent" });
235284
- }
235285
- }
235286
- if (projectData.dataComponents) {
235287
- let dataCompIds = [];
235288
- if (Array.isArray(projectData.dataComponents)) {
235289
- dataCompIds = projectData.dataComponents;
235290
- } else if (typeof projectData.dataComponents === "object") {
235291
- dataCompIds = Object.keys(projectData.dataComponents);
235292
- }
235293
- for (const dataCompId of dataCompIds) {
235294
- referencedComponents.push({ id: dataCompId, type: "dataComponent" });
235295
- }
235296
- }
235297
- if (projectData.artifactComponents) {
235298
- let artifactCompIds = [];
235299
- if (Array.isArray(projectData.artifactComponents)) {
235300
- artifactCompIds = projectData.artifactComponents;
235301
- } else if (typeof projectData.artifactComponents === "object") {
235302
- artifactCompIds = Object.keys(projectData.artifactComponents);
235303
- }
235304
- for (const artifactCompId of artifactCompIds) {
235305
- referencedComponents.push({ id: artifactCompId, type: "artifactComponent" });
235306
- }
235307
- }
235308
- if (projectData.credentialReferences) {
235309
- let credIds = [];
235310
- if (Array.isArray(projectData.credentialReferences)) {
235311
- credIds = projectData.credentialReferences;
235312
- } else if (typeof projectData.credentialReferences === "object") {
235313
- credIds = Object.keys(projectData.credentialReferences);
235314
- }
235315
- for (const credId of credIds) {
235316
- referencedComponents.push({ id: credId, type: "credential" });
235317
- }
235318
- }
235319
- if (referencedComponents.length > 0) {
235320
- const componentImports = registry2.getImportsForFile(currentFilePath, referencedComponents);
235321
- imports.push(...componentImports);
235322
- }
235323
- }
235324
- return imports;
235325
- }
235326
- function generateProjectFile(projectId, projectData, style = DEFAULT_STYLE, registry2) {
235327
- const imports = generateProjectImports(projectId, projectData, style, registry2);
235328
- const definition = generateProjectDefinition(projectId, projectData, style, registry2);
235329
- return generateFileContent(imports, [definition]);
235330
- }
235331
- var init_project_generator = __esm({
235332
- "src/commands/pull-v3/components/project-generator.ts"() {
235333
- "use strict";
235334
- init_esm_shims();
235335
- init_generator_utils();
235336
- }
235337
- });
235338
-
235339
234753
  // src/commands/pull-v3/components/agent-generator.ts
235340
234754
  function formatStatusUpdates(statusUpdatesConfig, style, indentLevel, registry2, contextConfigData, agentId) {
235341
234755
  if (!statusUpdatesConfig) {
@@ -235635,546 +235049,514 @@ var init_agent_generator = __esm({
235635
235049
  }
235636
235050
  });
235637
235051
 
235638
- // src/commands/pull-v3/components/sub-agent-generator.ts
235639
- function hasDistinctModels2(subAgentModels, parentModels) {
235640
- if (!subAgentModels) return false;
235641
- if (!parentModels) return !!subAgentModels;
235642
- const modelTypes = ["base", "structuredOutput", "summarizer"];
235643
- for (const type of modelTypes) {
235644
- const subAgentModel = subAgentModels[type]?.model;
235645
- const parentModel = parentModels[type]?.model;
235646
- if (subAgentModel !== parentModel) {
235052
+ // src/commands/pull-v3/components/artifact-component-generator.ts
235053
+ import { jsonSchemaToZod } from "json-schema-to-zod";
235054
+ function toCamelCase2(str) {
235055
+ return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
235056
+ }
235057
+ function formatString2(str, quote = "'", multiline = false) {
235058
+ if (!str) return `${quote}${quote}`;
235059
+ if (multiline && (str.includes("\n") || str.length > 80)) {
235060
+ return `\`${str.replace(/`/g, "\\`")}\``;
235061
+ }
235062
+ return `${quote}${str.replace(new RegExp(quote, "g"), "\\" + quote)}${quote}`;
235063
+ }
235064
+ function hasInPreviewFields(schema) {
235065
+ if (!schema || typeof schema !== "object" || schema.type !== "object" || !schema.properties) {
235066
+ return false;
235067
+ }
235068
+ for (const prop of Object.values(schema.properties)) {
235069
+ if (prop.inPreview === true) {
235647
235070
  return true;
235648
235071
  }
235649
- if (subAgentModel && parentModel) {
235650
- const subAgentOptions = subAgentModels[type]?.providerOptions;
235651
- const parentOptions = parentModels[type]?.providerOptions;
235652
- if (subAgentOptions !== parentOptions) {
235653
- if (!subAgentOptions && !parentOptions) {
235654
- continue;
235655
- }
235656
- if (!subAgentOptions || !parentOptions) {
235657
- return true;
235658
- }
235659
- if (JSON.stringify(subAgentOptions) !== JSON.stringify(parentOptions)) {
235660
- return true;
235661
- }
235662
- }
235663
- }
235664
235072
  }
235665
235073
  return false;
235666
235074
  }
235667
- function generateSubAgentDefinition(agentId, agentData, style = DEFAULT_STYLE, registry2, parentAgentId, contextConfigData, parentModels) {
235668
- if (!agentId || typeof agentId !== "string") {
235669
- throw new Error("agentId is required and must be a string");
235075
+ function formatArtifactSchema(schema, style) {
235076
+ if (!schema || typeof schema !== "object") {
235077
+ return "z.any()";
235670
235078
  }
235671
- if (!agentData || typeof agentData !== "object") {
235672
- throw new Error(`agentData is required for sub-agent '${agentId}'`);
235079
+ if (schema.type === "object" && schema.properties) {
235080
+ const { indentation } = style;
235081
+ const lines = ["z.object({"];
235082
+ for (const [key, prop] of Object.entries(schema.properties)) {
235083
+ const propCopy = { ...prop };
235084
+ delete propCopy.inPreview;
235085
+ const baseZodType = convertJsonSchemaToZod(propCopy);
235086
+ const finalZodType = prop.inPreview === true ? `preview(${baseZodType})` : baseZodType;
235087
+ lines.push(`${indentation}${key}: ${finalZodType},`);
235088
+ }
235089
+ lines.push("})");
235090
+ if (schema.description) {
235091
+ return lines.join("\n") + `.describe(\`${schema.description}\`)`;
235092
+ }
235093
+ return lines.join("\n");
235673
235094
  }
235674
- const requiredFields = ["name", "description", "prompt"];
235095
+ return convertJsonSchemaToZod(schema);
235096
+ }
235097
+ function convertJsonSchemaToZod(schema) {
235098
+ if (!schema || typeof schema !== "object") {
235099
+ return "z.any()";
235100
+ }
235101
+ try {
235102
+ return jsonSchemaToZod(schema);
235103
+ } catch (error) {
235104
+ console.warn("Failed to convert JSON schema to Zod:", error);
235105
+ return "z.any()";
235106
+ }
235107
+ }
235108
+ function generateArtifactComponentDefinition(componentId, componentData, style = DEFAULT_STYLE2) {
235109
+ if (!componentId || typeof componentId !== "string") {
235110
+ throw new Error("componentId is required and must be a string");
235111
+ }
235112
+ if (!componentData || typeof componentData !== "object") {
235113
+ throw new Error(`componentData is required for artifact component '${componentId}'`);
235114
+ }
235115
+ const requiredFields = ["name", "description", "props"];
235675
235116
  const missingFields = requiredFields.filter(
235676
- (field) => !agentData[field] || agentData[field] === null || agentData[field] === void 0
235117
+ (field) => !componentData[field] || componentData[field] === null || componentData[field] === void 0
235677
235118
  );
235678
235119
  if (missingFields.length > 0) {
235679
235120
  throw new Error(
235680
- `Missing required fields for sub-agent '${agentId}': ${missingFields.join(", ")}`
235121
+ `Missing required fields for artifact component '${componentId}': ${missingFields.join(", ")}`
235681
235122
  );
235682
235123
  }
235683
235124
  const { quotes, semicolons, indentation } = style;
235684
235125
  const q = quotes === "single" ? "'" : '"';
235685
235126
  const semi = semicolons ? ";" : "";
235686
- let agentVarName = toCamelCase(agentId);
235687
- if (registry2) {
235688
- const registryVarName = registry2.getVariableName(agentId, "subAgent");
235689
- if (registryVarName) {
235690
- agentVarName = registryVarName;
235691
- }
235692
- }
235127
+ const componentVarName = toCamelCase2(componentId);
235693
235128
  const lines = [];
235694
- lines.push(`export const ${agentVarName} = subAgent({`);
235695
- lines.push(`${indentation}id: ${formatString(agentId, q)},`);
235696
- lines.push(`${indentation}name: ${formatString(agentData.name, q)},`);
235697
- lines.push(`${indentation}description: ${formatString(agentData.description, q, true)},`);
235698
- if (agentData.prompt !== void 0 && agentData.prompt !== null) {
235699
- if (hasTemplateVariables(agentData.prompt) && parentAgentId && registry2 && contextConfigData) {
235700
- const contextVarName = registry2.getVariableName(contextConfigData.id, "contextConfig");
235701
- if (!contextVarName) {
235702
- throw new Error(
235703
- `Failed to resolve context config variable name for: ${contextConfigData.id}`
235704
- );
235705
- }
235706
- const headersVarName = "headersSchema";
235707
- lines.push(
235708
- `${indentation}prompt: ${formatPromptWithContext(agentData.prompt, contextVarName, headersVarName, contextConfigData, q, true)},`
235709
- );
235129
+ lines.push(`export const ${componentVarName} = artifactComponent({`);
235130
+ lines.push(`${indentation}id: ${formatString2(componentId, q)},`);
235131
+ lines.push(`${indentation}name: ${formatString2(componentData.name, q)},`);
235132
+ lines.push(`${indentation}description: ${formatString2(componentData.description, q, true)},`);
235133
+ const schema = componentData.props || componentData.schema;
235134
+ if (schema) {
235135
+ const zodSchema = formatArtifactSchema(schema, style);
235136
+ if (zodSchema.includes("\n")) {
235137
+ const schemaLines = zodSchema.split("\n");
235138
+ lines.push(`${indentation}props: ${schemaLines[0]}`);
235139
+ schemaLines.slice(1, -1).forEach((line) => {
235140
+ lines[lines.length - 1] += "\n" + indentation + line;
235141
+ });
235142
+ lines[lines.length - 1] += "\n" + indentation + schemaLines[schemaLines.length - 1] + ",";
235710
235143
  } else {
235711
- lines.push(`${indentation}prompt: ${formatString(agentData.prompt, q, true)},`);
235144
+ lines.push(`${indentation}props: ${zodSchema},`);
235712
235145
  }
235713
235146
  }
235714
- if (agentData.models && hasDistinctModels2(agentData.models, parentModels)) {
235715
- lines.push(`${indentation}models: {`);
235716
- if (agentData.models.base?.model) {
235717
- lines.push(`${indentation}${indentation}base: {`);
235718
- lines.push(
235719
- `${indentation}${indentation}${indentation}model: ${formatString(agentData.models.base.model, q)}`
235720
- );
235721
- if (agentData.models.base.providerOptions) {
235722
- lines.push(`${indentation}${indentation}${indentation},`);
235723
- lines.push(
235724
- `${indentation}${indentation}${indentation}providerOptions: ${JSON.stringify(agentData.models.base.providerOptions)}`
235725
- );
235726
- }
235727
- lines.push(`${indentation}${indentation}},`);
235728
- }
235729
- if (agentData.models.structuredOutput?.model) {
235730
- lines.push(`${indentation}${indentation}structuredOutput: {`);
235731
- lines.push(
235732
- `${indentation}${indentation}${indentation}model: ${formatString(agentData.models.structuredOutput.model, q)}`
235733
- );
235734
- if (agentData.models.structuredOutput.providerOptions) {
235735
- lines.push(`${indentation}${indentation}${indentation},`);
235736
- lines.push(
235737
- `${indentation}${indentation}${indentation}providerOptions: ${JSON.stringify(agentData.models.structuredOutput.providerOptions)}`
235738
- );
235739
- }
235740
- lines.push(`${indentation}${indentation}},`);
235741
- }
235742
- if (agentData.models.summarizer?.model) {
235743
- lines.push(`${indentation}${indentation}summarizer: {`);
235744
- lines.push(
235745
- `${indentation}${indentation}${indentation}model: ${formatString(agentData.models.summarizer.model, q)}`
235746
- );
235747
- if (agentData.models.summarizer.providerOptions) {
235748
- lines.push(`${indentation}${indentation}${indentation},`);
235749
- lines.push(
235750
- `${indentation}${indentation}${indentation}providerOptions: ${JSON.stringify(agentData.models.summarizer.providerOptions)}`
235751
- );
235752
- }
235753
- lines.push(`${indentation}${indentation}},`);
235754
- }
235755
- removeTrailingComma(lines);
235756
- lines.push(`${indentation}},`);
235147
+ if (componentData.template) {
235148
+ lines.push(`${indentation}template: ${formatString2(componentData.template, q, true)},`);
235757
235149
  }
235758
- if (agentData.canUse && Array.isArray(agentData.canUse) && agentData.canUse.length > 0) {
235759
- const toolReferences = [];
235760
- if (!registry2) {
235761
- throw new Error("Registry is required for canUse generation");
235762
- }
235763
- for (const toolRelation of agentData.canUse) {
235764
- const toolId = toolRelation.toolId;
235765
- let toolVarName = registry2.getVariableName(toolId, "tool");
235766
- if (!toolVarName) {
235767
- toolVarName = registry2.getVariableName(toolId, "functionTool");
235768
- }
235769
- if (!toolVarName) {
235770
- throw new Error(
235771
- `Failed to resolve variable name for tool: ${toolId} (tried both 'tool' and 'functionTool' types)`
235772
- );
235773
- }
235774
- const hasToolSelection = toolRelation.toolSelection && toolRelation.toolSelection.length > 0;
235775
- const hasHeaders = toolRelation.headers && Object.keys(toolRelation.headers).length > 0;
235776
- if (hasToolSelection || hasHeaders) {
235777
- const configLines = [];
235778
- if (hasToolSelection) {
235779
- const selectedToolsStr = JSON.stringify(toolRelation.toolSelection);
235780
- configLines.push(`selectedTools: ${selectedToolsStr}`);
235781
- }
235782
- if (hasHeaders) {
235783
- const headersStr = JSON.stringify(toolRelation.headers);
235784
- configLines.push(`headers: ${headersStr}`);
235785
- }
235786
- const configStr = configLines.join(", ");
235787
- const finalRef = `${toolVarName}.with({ ${configStr} })`;
235788
- toolReferences.push(finalRef);
235789
- } else {
235790
- toolReferences.push(toolVarName);
235791
- }
235792
- }
235793
- const { indentation: indent } = style;
235794
- const nestedIndent = indent.repeat(2);
235795
- if (toolReferences.length === 1) {
235796
- lines.push(`${indentation}canUse: () => [${toolReferences[0]}],`);
235797
- } else {
235798
- lines.push(`${indentation}canUse: () => [`);
235799
- toolReferences.forEach((ref, index2) => {
235800
- const isLast = index2 === toolReferences.length - 1;
235801
- lines.push(`${indentation}${nestedIndent}${ref}${isLast ? "" : ","}`);
235802
- });
235803
- lines.push(`${indentation}],`);
235804
- }
235150
+ if (componentData.contentType) {
235151
+ lines.push(`${indentation}contentType: ${formatString2(componentData.contentType, q)},`);
235805
235152
  }
235806
- if (agentData.canDelegateTo && Array.isArray(agentData.canDelegateTo) && agentData.canDelegateTo.length > 0) {
235807
- if (!registry2) {
235808
- throw new Error("Registry is required for canDelegateTo generation");
235809
- }
235810
- const delegateReferences = [];
235811
- for (const delegateRelation of agentData.canDelegateTo) {
235812
- let targetAgentId;
235813
- let targetType;
235814
- let hasHeaders = false;
235815
- if (typeof delegateRelation === "string") {
235816
- targetAgentId = delegateRelation;
235817
- targetType = "subAgent";
235818
- hasHeaders = false;
235819
- } else if (delegateRelation && typeof delegateRelation === "object") {
235820
- hasHeaders = delegateRelation.headers && Object.keys(delegateRelation.headers).length > 0;
235821
- if (delegateRelation.externalAgentId) {
235822
- targetAgentId = delegateRelation.externalAgentId;
235823
- targetType = "externalAgent";
235824
- } else if (delegateRelation.agentId) {
235825
- targetAgentId = delegateRelation.agentId;
235826
- targetType = "agent";
235827
- } else if (delegateRelation.subAgentId) {
235828
- targetAgentId = delegateRelation.subAgentId;
235829
- targetType = "subAgent";
235830
- } else {
235831
- throw new Error(
235832
- `Delegate relation missing agentId, subAgentId, or externalAgentId: ${JSON.stringify(delegateRelation)}`
235833
- );
235834
- }
235835
- } else {
235836
- throw new Error(`Invalid delegate relation format: ${JSON.stringify(delegateRelation)}`);
235837
- }
235838
- if (!targetAgentId) {
235839
- throw new Error(
235840
- `Failed to extract target agent ID from delegate relation: ${JSON.stringify(delegateRelation)}`
235841
- );
235842
- }
235843
- const agentVarName2 = registry2.getVariableName(targetAgentId, targetType);
235844
- if (!agentVarName2) {
235845
- throw new Error(
235846
- `Failed to resolve variable name for delegate ${targetType}: ${targetAgentId}`
235153
+ if (lines.length > 0 && lines[lines.length - 1].endsWith(",")) {
235154
+ lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
235155
+ }
235156
+ lines.push(`})${semi}`);
235157
+ return lines.join("\n");
235158
+ }
235159
+ function generateArtifactComponentImports(componentId, componentData, style = DEFAULT_STYLE2) {
235160
+ const { quotes, semicolons } = style;
235161
+ const q = quotes === "single" ? "'" : '"';
235162
+ const semi = semicolons ? ";" : "";
235163
+ const imports = [];
235164
+ const schema = componentData.props || componentData.schema;
235165
+ const needsPreviewImport = hasInPreviewFields(schema);
235166
+ if (needsPreviewImport) {
235167
+ imports.push(`import { preview } from ${q}@inkeep/agents-core${q}${semi}`);
235168
+ }
235169
+ imports.push(`import { artifactComponent } from ${q}@inkeep/agents-sdk${q}${semi}`);
235170
+ if (schema) {
235171
+ imports.push(`import { z } from ${q}zod${q}${semi}`);
235172
+ }
235173
+ return imports;
235174
+ }
235175
+ function generateArtifactComponentFile(componentId, componentData, style = DEFAULT_STYLE2) {
235176
+ const imports = generateArtifactComponentImports(componentId, componentData, style);
235177
+ const definition = generateArtifactComponentDefinition(componentId, componentData, style);
235178
+ return imports.join("\n") + "\n\n" + definition + "\n";
235179
+ }
235180
+ var DEFAULT_STYLE2;
235181
+ var init_artifact_component_generator = __esm({
235182
+ "src/commands/pull-v3/components/artifact-component-generator.ts"() {
235183
+ "use strict";
235184
+ init_esm_shims();
235185
+ DEFAULT_STYLE2 = {
235186
+ quotes: "single",
235187
+ semicolons: true,
235188
+ indentation: " "
235189
+ };
235190
+ }
235191
+ });
235192
+
235193
+ // src/commands/pull-v3/components/context-config-generator.ts
235194
+ import { jsonSchemaToZod as jsonSchemaToZod2 } from "json-schema-to-zod";
235195
+ function processFetchConfigTemplates(fetchConfig, headersVarName) {
235196
+ const processValue = (value) => {
235197
+ if (typeof value === "string") {
235198
+ if (hasTemplateVariables(value)) {
235199
+ const convertedStr = value.replace(
235200
+ /\{\{headers\.([^}]+)\}\}/g,
235201
+ `\${${headersVarName}.toTemplate("$1")}`
235847
235202
  );
235848
- }
235849
- if (hasHeaders) {
235850
- const headersStr = JSON.stringify(delegateRelation.headers);
235851
- const finalRef = `${agentVarName2}.with({ headers: ${headersStr} })`;
235852
- delegateReferences.push(finalRef);
235203
+ return `\`${convertedStr.replace(/`/g, "\\`")}\``;
235853
235204
  } else {
235854
- delegateReferences.push(agentVarName2);
235205
+ return `'${value.replace(/'/g, "\\'")}'`;
235855
235206
  }
235856
- }
235857
- const { indentation: indent } = style;
235858
- const nestedIndent = indent.repeat(2);
235859
- if (delegateReferences.length === 1) {
235860
- lines.push(`${indentation}canDelegateTo: () => [${delegateReferences[0]}],`);
235207
+ } else if (typeof value === "object" && value !== null) {
235208
+ return processObject(value);
235861
235209
  } else {
235862
- lines.push(`${indentation}canDelegateTo: () => [`);
235863
- delegateReferences.forEach((ref, index2) => {
235864
- const isLast = index2 === delegateReferences.length - 1;
235865
- lines.push(`${indentation}${nestedIndent}${ref}${isLast ? "" : ","}`);
235866
- });
235867
- lines.push(`${indentation}],`);
235210
+ return JSON.stringify(value);
235868
235211
  }
235869
- }
235870
- if (agentData.canTransferTo && Array.isArray(agentData.canTransferTo) && agentData.canTransferTo.length > 0) {
235871
- if (!registry2) {
235872
- throw new Error("Registry is required for canTransferTo generation");
235212
+ };
235213
+ const processObject = (obj) => {
235214
+ if (Array.isArray(obj)) {
235215
+ const items = obj.map((item) => processValue(item)).join(", ");
235216
+ return `[${items}]`;
235873
235217
  }
235874
- const transferArray = registry2.formatReferencesForCode(
235875
- agentData.canTransferTo,
235876
- "subAgent",
235877
- style,
235878
- 2
235218
+ const entries = Object.entries(obj).map(([key, val]) => {
235219
+ const processedKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : `'${key}'`;
235220
+ return `${processedKey}: ${processValue(val)}`;
235221
+ });
235222
+ return `{
235223
+ ${entries.join(",\n ")}
235224
+ }`;
235225
+ };
235226
+ return processObject(fetchConfig);
235227
+ }
235228
+ function generateHeadersDefinition(headersId, headersData, style = DEFAULT_STYLE) {
235229
+ const { quotes, semicolons, indentation } = style;
235230
+ const q = quotes === "single" ? "'" : '"';
235231
+ const semi = semicolons ? ";" : "";
235232
+ const headersVarName = toCamelCase(headersId);
235233
+ const lines = [];
235234
+ lines.push(`const ${headersVarName} = headers({`);
235235
+ if (headersData.schema) {
235236
+ const zodSchema = jsonSchemaToZod2(headersData.schema, { module: "none" });
235237
+ lines.push(`${indentation}schema: ${zodSchema},`);
235238
+ }
235239
+ removeTrailingComma(lines);
235240
+ lines.push(`})${semi}`);
235241
+ return lines.join("\n");
235242
+ }
235243
+ function generateFetchDefinitionDefinition(fetchId, fetchData, style = DEFAULT_STYLE, headersVarName) {
235244
+ const { quotes, semicolons, indentation } = style;
235245
+ const q = quotes === "single" ? "'" : '"';
235246
+ const semi = semicolons ? ";" : "";
235247
+ const fetchVarName = toCamelCase(fetchId);
235248
+ const lines = [];
235249
+ lines.push(`const ${fetchVarName} = fetchDefinition({`);
235250
+ lines.push(`${indentation}id: ${formatString(fetchData.id || fetchId, q)},`);
235251
+ if (fetchData.name) {
235252
+ lines.push(`${indentation}name: ${formatString(fetchData.name, q)},`);
235253
+ }
235254
+ if (fetchData.trigger) {
235255
+ lines.push(`${indentation}trigger: ${formatString(fetchData.trigger, q)},`);
235256
+ }
235257
+ if (fetchData.fetchConfig) {
235258
+ const processedFetchConfig = processFetchConfigTemplates(
235259
+ fetchData.fetchConfig,
235260
+ headersVarName || "headers"
235879
235261
  );
235880
- if (!transferArray) {
235881
- throw new Error(
235882
- `Failed to resolve variable names for canTransferTo agents: ${agentData.canTransferTo.join(", ")}`
235883
- );
235262
+ lines.push(`${indentation}fetchConfig: ${processedFetchConfig},`);
235263
+ }
235264
+ if (fetchData.responseSchema) {
235265
+ const zodSchema = jsonSchemaToZod2(fetchData.responseSchema, { module: "none" });
235266
+ lines.push(`${indentation}responseSchema: ${zodSchema},`);
235267
+ }
235268
+ if (fetchData.defaultValue) {
235269
+ if (typeof fetchData.defaultValue === "string") {
235270
+ lines.push(`${indentation}defaultValue: ${formatString(fetchData.defaultValue, q)},`);
235271
+ } else {
235272
+ lines.push(`${indentation}defaultValue: ${JSON.stringify(fetchData.defaultValue)},`);
235884
235273
  }
235885
- lines.push(`${indentation}canTransferTo: () => ${transferArray},`);
235886
235274
  }
235887
- if (agentData.dataComponents && Array.isArray(agentData.dataComponents) && agentData.dataComponents.length > 0) {
235275
+ removeTrailingComma(lines);
235276
+ lines.push(`})${semi}`);
235277
+ return lines.join("\n");
235278
+ }
235279
+ function generateContextConfigDefinition(contextId, contextData, style = DEFAULT_STYLE, registry2, agentId, headersVarName) {
235280
+ if (!contextId || typeof contextId !== "string") {
235281
+ throw new Error("contextId is required and must be a string");
235282
+ }
235283
+ if (!contextData || typeof contextData !== "object") {
235284
+ throw new Error(`contextData is required for context config '${contextId}'`);
235285
+ }
235286
+ const { quotes, semicolons, indentation } = style;
235287
+ const q = quotes === "single" ? "'" : '"';
235288
+ const semi = semicolons ? ";" : "";
235289
+ const contextVarName = (() => {
235888
235290
  if (!registry2) {
235889
- throw new Error("Registry is required for dataComponents generation");
235291
+ throw new Error("Registry is required for context config variable name generation");
235890
235292
  }
235891
- const dataComponentsArray = registry2.formatReferencesForCode(
235892
- agentData.dataComponents,
235893
- "dataComponent",
235894
- style,
235895
- 2
235896
- );
235897
- if (!dataComponentsArray) {
235898
- throw new Error(
235899
- `Failed to resolve variable names for data components: ${agentData.dataComponents.join(", ")}`
235900
- );
235293
+ const varName = registry2.getVariableName(contextId, "contextConfig");
235294
+ if (!varName) {
235295
+ throw new Error(`Failed to resolve variable name for context config: ${contextId}`);
235901
235296
  }
235902
- lines.push(`${indentation}dataComponents: () => ${dataComponentsArray},`);
235297
+ return varName;
235298
+ })();
235299
+ const lines = [];
235300
+ lines.push(`const ${contextVarName} = contextConfig({`);
235301
+ if (contextData.id) {
235302
+ lines.push(`${indentation}id: ${formatString(contextData.id, q)},`);
235903
235303
  }
235904
- if (agentData.artifactComponents && Array.isArray(agentData.artifactComponents) && agentData.artifactComponents.length > 0) {
235905
- if (!registry2) {
235906
- throw new Error("Registry is required for artifactComponents generation");
235304
+ if (headersVarName) {
235305
+ lines.push(`${indentation}headers: ${headersVarName},`);
235306
+ } else if (contextData.headers) {
235307
+ lines.push(`${indentation}headers: ${contextData.headers},`);
235308
+ }
235309
+ if (contextData.contextVariables) {
235310
+ const contextVarLines = [`${indentation}contextVariables: {`];
235311
+ for (const [varName, varData] of Object.entries(contextData.contextVariables)) {
235312
+ if (typeof varData === "string") {
235313
+ contextVarLines.push(`${indentation} ${varName}: ${varData},`);
235314
+ } else if (varData && typeof varData === "object" && (varData.fetchConfig || varData.responseSchema)) {
235315
+ contextVarLines.push(`${indentation} ${varName},`);
235316
+ }
235907
235317
  }
235908
- const artifactComponentsArray = registry2.formatReferencesForCode(
235909
- agentData.artifactComponents,
235910
- "artifactComponent",
235911
- style,
235912
- 2
235913
- );
235914
- if (!artifactComponentsArray) {
235915
- throw new Error(
235916
- `Failed to resolve variable names for artifact components: ${agentData.artifactComponents.join(", ")}`
235917
- );
235318
+ if (contextVarLines[contextVarLines.length - 1].endsWith(",")) {
235319
+ contextVarLines[contextVarLines.length - 1] = contextVarLines[contextVarLines.length - 1].slice(0, -1);
235918
235320
  }
235919
- lines.push(`${indentation}artifactComponents: () => ${artifactComponentsArray},`);
235920
- }
235921
- if (agentData.stopWhen && agentData.stopWhen.stepCountIs !== void 0) {
235922
- lines.push(`${indentation}stopWhen: {`);
235923
- lines.push(
235924
- `${indentation}${indentation}stepCountIs: ${agentData.stopWhen.stepCountIs} // Max tool calls + LLM responses`
235925
- );
235926
- lines.push(`${indentation}},`);
235321
+ contextVarLines.push(`${indentation}},`);
235322
+ lines.push(...contextVarLines);
235927
235323
  }
235928
235324
  removeTrailingComma(lines);
235929
235325
  lines.push(`})${semi}`);
235930
235326
  return lines.join("\n");
235931
235327
  }
235932
- function generateSubAgentImports(agentId, agentData, style = DEFAULT_STYLE, registry2, parentAgentId, contextConfigData) {
235328
+ function generateContextConfigImports(contextId, contextData, style = DEFAULT_STYLE) {
235933
235329
  const imports = [];
235934
- imports.push(generateImport(["subAgent"], "@inkeep/agents-sdk", style));
235935
- if (hasTemplateVariables(agentData.prompt) && parentAgentId && registry2 && contextConfigData) {
235936
- const contextConfigId = contextConfigData.id;
235937
- const currentFilePath = `agents/sub-agents/${agentId}.ts`;
235938
- const importStatement = registry2.getImportStatement(
235939
- currentFilePath,
235940
- contextConfigId,
235941
- "contextConfig"
235942
- );
235943
- if (importStatement) {
235944
- imports.push(importStatement);
235945
- }
235330
+ const coreImports = [];
235331
+ if (contextData.headers || hasHeadersInData(contextData)) {
235332
+ coreImports.push("headers");
235946
235333
  }
235947
- if (registry2) {
235948
- const currentFilePath = `agents/sub-agents/${agentId}.ts`;
235949
- const referencedComponents = [];
235950
- if (Array.isArray(agentData.canUse)) {
235951
- for (const toolRelation of agentData.canUse) {
235952
- const toolId = toolRelation.toolId;
235953
- if (toolId) {
235954
- let componentType = "tool";
235955
- if (registry2.get(toolId, "functionTool")) {
235956
- componentType = "functionTool";
235957
- } else if (registry2.get(toolId, "tool")) {
235958
- componentType = "tool";
235959
- }
235960
- referencedComponents.push({ id: toolId, type: componentType });
235961
- }
235962
- }
235963
- }
235964
- if (Array.isArray(agentData.canDelegateTo)) {
235965
- for (const delegateRelation of agentData.canDelegateTo) {
235966
- let targetId;
235967
- let targetType = "agent";
235968
- if (delegateRelation && typeof delegateRelation === "object") {
235969
- if (delegateRelation.externalAgentId) {
235970
- targetId = delegateRelation.externalAgentId;
235971
- targetType = "externalAgent";
235972
- } else if (delegateRelation.agentId) {
235973
- targetId = delegateRelation.agentId;
235974
- targetType = "agent";
235975
- } else if (delegateRelation.subAgentId) {
235976
- targetId = delegateRelation.subAgentId;
235977
- targetType = "subAgent";
235978
- }
235979
- }
235980
- if (targetId) {
235981
- referencedComponents.push({ id: targetId, type: targetType });
235982
- }
235983
- }
235984
- }
235985
- if (Array.isArray(agentData.canTransferTo)) {
235986
- for (const transferId of agentData.canTransferTo) {
235987
- if (typeof transferId === "string") {
235988
- referencedComponents.push({ id: transferId, type: "subAgent" });
235989
- }
235990
- }
235991
- }
235992
- if (Array.isArray(agentData.dataComponents)) {
235993
- for (const dataCompId of agentData.dataComponents) {
235994
- if (typeof dataCompId === "string") {
235995
- referencedComponents.push({ id: dataCompId, type: "dataComponent" });
235996
- }
235997
- }
235334
+ if (contextData.contextVariables && hasFetchDefinitionsInData(contextData)) {
235335
+ coreImports.push("fetchDefinition");
235336
+ }
235337
+ coreImports.push("contextConfig");
235338
+ if (coreImports.length > 0) {
235339
+ imports.push(generateImport(coreImports, "@inkeep/agents-core", style));
235340
+ }
235341
+ if (hasSchemas(contextData)) {
235342
+ imports.push(generateImport(["z"], "zod", style));
235343
+ }
235344
+ return imports;
235345
+ }
235346
+ function hasHeadersInData(contextData) {
235347
+ return !!contextData.headers || JSON.stringify(contextData).includes("headers");
235348
+ }
235349
+ function hasFetchDefinitionsInData(contextData) {
235350
+ return JSON.stringify(contextData).includes("fetchDefinition") || contextData.contextVariables && Object.values(contextData.contextVariables).some(
235351
+ (v) => v && typeof v === "object" && (v.fetchConfig || v.responseSchema)
235352
+ );
235353
+ }
235354
+ function hasSchemas(contextData) {
235355
+ const dataStr = JSON.stringify(contextData).toLowerCase();
235356
+ return dataStr.includes("schema") || dataStr.includes("responseschema");
235357
+ }
235358
+ function generateContextConfigFile(contextId, contextData, style = DEFAULT_STYLE, registry2, agentId) {
235359
+ const imports = generateContextConfigImports(contextId, contextData, style);
235360
+ const definitions = [];
235361
+ let headersVarName;
235362
+ if (contextData.headersSchema) {
235363
+ if (typeof contextData.headers === "string") {
235364
+ headersVarName = contextData.headers;
235365
+ } else {
235366
+ headersVarName = `${toCamelCase(contextId)}Headers`;
235998
235367
  }
235999
- if (Array.isArray(agentData.artifactComponents)) {
236000
- for (const artifactCompId of agentData.artifactComponents) {
236001
- if (typeof artifactCompId === "string") {
236002
- referencedComponents.push({ id: artifactCompId, type: "artifactComponent" });
236003
- }
235368
+ const headersDefinition = generateHeadersDefinition(
235369
+ headersVarName || "headers",
235370
+ { schema: contextData.headersSchema },
235371
+ style
235372
+ );
235373
+ definitions.push(headersDefinition);
235374
+ }
235375
+ if (contextData.contextVariables) {
235376
+ for (const [varName, varData] of Object.entries(contextData.contextVariables)) {
235377
+ if (varData && typeof varData === "object" && (varData.fetchConfig || varData.responseSchema)) {
235378
+ const fetchDefinition2 = generateFetchDefinitionDefinition(
235379
+ varName,
235380
+ varData,
235381
+ style,
235382
+ headersVarName
235383
+ );
235384
+ definitions.push(fetchDefinition2);
236004
235385
  }
236005
235386
  }
236006
- if (referencedComponents.length > 0) {
236007
- const componentImports = registry2.getImportsForFile(currentFilePath, referencedComponents);
236008
- imports.push(...componentImports);
236009
- }
236010
235387
  }
236011
- return imports;
236012
- }
236013
- function generateSubAgentFile(agentId, agentData, style = DEFAULT_STYLE, registry2, parentAgentId, contextConfigData, parentModels) {
236014
- const imports = generateSubAgentImports(
236015
- agentId,
236016
- agentData,
235388
+ const contextDefinition = generateContextConfigDefinition(
235389
+ contextId,
235390
+ contextData,
236017
235391
  style,
236018
235392
  registry2,
236019
- parentAgentId,
236020
- contextConfigData
236021
- );
236022
- const definition = generateSubAgentDefinition(
236023
235393
  agentId,
236024
- agentData,
236025
- style,
236026
- registry2,
236027
- parentAgentId,
236028
- contextConfigData,
236029
- parentModels
235394
+ headersVarName
236030
235395
  );
236031
- return generateFileContent(imports, [definition]);
235396
+ definitions.push(contextDefinition);
235397
+ const contextVarName = (() => {
235398
+ if (!registry2) {
235399
+ throw new Error("Registry is required for context config variable name generation");
235400
+ }
235401
+ const varName = registry2.getVariableName(contextId, "contextConfig");
235402
+ if (!varName) {
235403
+ throw new Error(`Failed to resolve variable name for context config: ${contextId}`);
235404
+ }
235405
+ return varName;
235406
+ })();
235407
+ const exports = [contextVarName];
235408
+ if (headersVarName) {
235409
+ exports.push(headersVarName);
235410
+ }
235411
+ if (contextData.contextVariables) {
235412
+ for (const [varName, varData] of Object.entries(contextData.contextVariables)) {
235413
+ if (varData && typeof varData === "object" && (varData.fetchConfig || varData.responseSchema)) {
235414
+ exports.push(varName);
235415
+ }
235416
+ }
235417
+ }
235418
+ definitions.push(`export { ${exports.join(", ")} };`);
235419
+ return generateFileContent(imports, definitions);
236032
235420
  }
236033
- var init_sub_agent_generator = __esm({
236034
- "src/commands/pull-v3/components/sub-agent-generator.ts"() {
235421
+ var init_context_config_generator = __esm({
235422
+ "src/commands/pull-v3/components/context-config-generator.ts"() {
236035
235423
  "use strict";
236036
235424
  init_esm_shims();
236037
235425
  init_generator_utils();
236038
235426
  }
236039
235427
  });
236040
235428
 
236041
- // src/commands/pull-v3/components/external-agent-generator.ts
236042
- function generateExternalAgentDefinition(agentId, agentData, style = DEFAULT_STYLE, registry2) {
236043
- if (!agentId || typeof agentId !== "string") {
236044
- throw new Error("agentId is required and must be a string");
235429
+ // src/commands/pull-v3/components/credential-generator.ts
235430
+ function toCamelCase3(str) {
235431
+ return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
235432
+ }
235433
+ function formatString3(str, quote = "'", multiline = false) {
235434
+ if (!str) return `${quote}${quote}`;
235435
+ if (multiline && (str.includes("\n") || str.length > 80)) {
235436
+ return `\`${str.replace(/`/g, "\\`")}\``;
236045
235437
  }
236046
- if (!agentData || typeof agentData !== "object") {
236047
- throw new Error(`agentData is required for external agent '${agentId}'`);
235438
+ return `${quote}${str.replace(new RegExp(quote, "g"), "\\" + quote)}${quote}`;
235439
+ }
235440
+ function formatRetrievalParams(retrievalParams, style, indentLevel) {
235441
+ if (!retrievalParams || typeof retrievalParams !== "object") {
235442
+ return "{}";
236048
235443
  }
236049
- const requiredFields = ["name", "description", "baseUrl"];
235444
+ const { quotes, indentation } = style;
235445
+ const q = quotes === "single" ? "'" : '"';
235446
+ const baseIndent = indentation.repeat(indentLevel);
235447
+ const indent = indentation.repeat(indentLevel + 1);
235448
+ const lines = ["{"];
235449
+ for (const [key, value] of Object.entries(retrievalParams)) {
235450
+ if (typeof value === "string") {
235451
+ lines.push(`${indent}${q}${key}${q}: ${formatString3(value, q)},`);
235452
+ } else if (typeof value === "number" || typeof value === "boolean") {
235453
+ lines.push(`${indent}${q}${key}${q}: ${JSON.stringify(value)},`);
235454
+ } else if (typeof value === "object" && value !== null) {
235455
+ lines.push(
235456
+ `${indent}${q}${key}${q}: ${formatRetrievalParams(value, style, indentLevel + 1)},`
235457
+ );
235458
+ }
235459
+ }
235460
+ if (lines.length > 1 && lines[lines.length - 1].endsWith(",")) {
235461
+ lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
235462
+ }
235463
+ lines.push(`${baseIndent}}`);
235464
+ return lines.join("\n");
235465
+ }
235466
+ function generateCredentialDefinition(credentialId, credentialData, style = DEFAULT_STYLE3) {
235467
+ const { quotes, semicolons, indentation } = style;
235468
+ const q = quotes === "single" ? "'" : '"';
235469
+ const semi = semicolons ? ";" : "";
235470
+ const credentialVarName = toCamelCase3(credentialId);
235471
+ const lines = [];
235472
+ lines.push(`export const ${credentialVarName} = credential({`);
235473
+ lines.push(`${indentation}id: ${formatString3(credentialId, q)},`);
235474
+ const requiredFields = ["name", "type", "credentialStoreId"];
236050
235475
  const missingFields = requiredFields.filter(
236051
- (field) => !agentData[field] || agentData[field] === null || agentData[field] === void 0
235476
+ (field) => !credentialData[field] || credentialData[field] === null || credentialData[field] === void 0
236052
235477
  );
236053
235478
  if (missingFields.length > 0) {
236054
235479
  throw new Error(
236055
- `Missing required fields for external agent '${agentId}': ${missingFields.join(", ")}`
235480
+ `Missing required fields for credential '${credentialId}': ${missingFields.join(", ")}`
236056
235481
  );
236057
235482
  }
236058
- const { quotes, semicolons, indentation } = style;
236059
- const q = quotes === "single" ? "'" : '"';
236060
- const semi = semicolons ? ";" : "";
236061
- let agentVarName = toCamelCase(agentId);
236062
- if (registry2) {
236063
- const registryVarName = registry2.getVariableName(agentId, "externalAgent");
236064
- if (registryVarName) {
236065
- agentVarName = registryVarName;
236066
- }
236067
- }
236068
- const lines = [];
236069
- lines.push(`export const ${agentVarName} = externalAgent({`);
236070
- lines.push(`${indentation}id: ${formatString(agentId, q)},`);
236071
- if (agentData.name !== void 0 && agentData.name !== null) {
236072
- lines.push(`${indentation}name: ${formatString(agentData.name, q)},`);
236073
- } else {
236074
- lines.push(`${indentation}name: ${formatString(agentId, q)},`);
235483
+ lines.push(`${indentation}name: ${formatString3(credentialData.name, q)},`);
235484
+ lines.push(`${indentation}type: ${formatString3(credentialData.type, q)},`);
235485
+ lines.push(
235486
+ `${indentation}credentialStoreId: ${formatString3(credentialData.credentialStoreId, q)},`
235487
+ );
235488
+ if (credentialData.description) {
235489
+ lines.push(`${indentation}description: ${formatString3(credentialData.description, q, true)},`);
236075
235490
  }
236076
- if (agentData.description !== void 0 && agentData.description !== null) {
236077
- lines.push(`${indentation}description: ${formatString(agentData.description, q, true)},`);
235491
+ if (credentialData.retrievalParams) {
235492
+ const formattedParams = formatRetrievalParams(credentialData.retrievalParams, style, 1);
235493
+ if (formattedParams.includes("\n")) {
235494
+ lines.push(`${indentation}retrievalParams: ${formattedParams},`);
235495
+ } else {
235496
+ lines.push(`${indentation}retrievalParams: ${formattedParams},`);
235497
+ }
236078
235498
  } else {
236079
- lines.push(`${indentation}description: ${formatString(`External agent ${agentId}`, q)},`);
236080
- }
236081
- if (agentData.baseUrl !== void 0 && agentData.baseUrl !== null) {
236082
- lines.push(`${indentation}baseUrl: ${formatString(agentData.baseUrl, q)},`);
235499
+ const defaultKey = credentialId.toUpperCase().replace(/-/g, "_");
235500
+ lines.push(`${indentation}retrievalParams: {`);
235501
+ lines.push(`${indentation}${indentation}${q}key${q}: ${formatString3(defaultKey, q)}`);
235502
+ lines.push(`${indentation}},`);
236083
235503
  }
236084
- if (agentData.credentialReference) {
236085
- if (typeof agentData.credentialReference === "string") {
236086
- if (!registry2) {
236087
- throw new Error("Registry is required for credentialReference generation");
236088
- }
236089
- const credentialVar = registry2.getVariableName(agentData.credentialReference, "credential");
236090
- if (!credentialVar) {
236091
- throw new Error(
236092
- `Failed to resolve variable name for credential reference: ${agentData.credentialReference}`
236093
- );
236094
- }
236095
- lines.push(`${indentation}credentialReference: ${credentialVar},`);
236096
- } else if (typeof agentData.credentialReference === "object") {
236097
- const credLines = [];
236098
- if (agentData.credentialReference.id) {
236099
- credLines.push(
236100
- `${indentation}${indentation}id: ${formatString(agentData.credentialReference.id, q)},`
236101
- );
236102
- }
236103
- if (agentData.credentialReference.name) {
236104
- credLines.push(
236105
- `${indentation}${indentation}name: ${formatString(agentData.credentialReference.name, q)},`
236106
- );
236107
- }
236108
- if (agentData.credentialReference.description) {
236109
- credLines.push(
236110
- `${indentation}${indentation}description: ${formatString(agentData.credentialReference.description, q)},`
236111
- );
236112
- }
236113
- if (credLines.length > 0 && credLines[credLines.length - 1].endsWith(",")) {
236114
- credLines[credLines.length - 1] = credLines[credLines.length - 1].slice(0, -1);
236115
- }
236116
- lines.push(`${indentation}credentialReference: {`);
236117
- lines.push(...credLines);
236118
- lines.push(`${indentation}},`);
236119
- }
235504
+ if (lines.length > 0 && lines[lines.length - 1].endsWith(",")) {
235505
+ lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
236120
235506
  }
236121
- removeTrailingComma(lines);
236122
235507
  lines.push(`})${semi}`);
236123
235508
  return lines.join("\n");
236124
235509
  }
236125
- function generateExternalAgentImports(agentId, agentData, style = DEFAULT_STYLE, registry2) {
235510
+ function generateCredentialImports(credentialId, credentialData, style = DEFAULT_STYLE3) {
235511
+ const { quotes, semicolons } = style;
235512
+ const q = quotes === "single" ? "'" : '"';
235513
+ const semi = semicolons ? ";" : "";
236126
235514
  const imports = [];
236127
- imports.push(generateImport(["externalAgent"], "@inkeep/agents-sdk", style));
236128
- if (agentData.credentialReference && typeof agentData.credentialReference === "string") {
236129
- if (!registry2) {
236130
- throw new Error("Registry is required for credential reference imports");
236131
- }
236132
- const currentFilePath = `external-agents/${agentId}.ts`;
236133
- const credentialRefs = [
236134
- { id: agentData.credentialReference, type: "credential" }
236135
- ];
236136
- const componentImports = registry2.getImportsForFile(currentFilePath, credentialRefs);
236137
- imports.push(...componentImports);
236138
- }
235515
+ imports.push(`import { credential } from ${q}@inkeep/agents-sdk${q}${semi}`);
236139
235516
  return imports;
236140
235517
  }
236141
- function generateExternalAgentFile(agentId, agentData, style = DEFAULT_STYLE, registry2) {
236142
- const imports = generateExternalAgentImports(agentId, agentData, style, registry2);
236143
- const definition = generateExternalAgentDefinition(agentId, agentData, style, registry2);
236144
- return generateFileContent(imports, [definition]);
235518
+ function generateCredentialFile(credentialId, credentialData, style = DEFAULT_STYLE3) {
235519
+ const imports = generateCredentialImports(credentialId, credentialData, style);
235520
+ const definition = generateCredentialDefinition(credentialId, credentialData, style);
235521
+ return imports.join("\n") + "\n\n" + definition + "\n";
236145
235522
  }
236146
- var init_external_agent_generator = __esm({
236147
- "src/commands/pull-v3/components/external-agent-generator.ts"() {
235523
+ var DEFAULT_STYLE3;
235524
+ var init_credential_generator = __esm({
235525
+ "src/commands/pull-v3/components/credential-generator.ts"() {
236148
235526
  "use strict";
236149
235527
  init_esm_shims();
236150
- init_generator_utils();
235528
+ DEFAULT_STYLE3 = {
235529
+ quotes: "single",
235530
+ semicolons: true,
235531
+ indentation: " "
235532
+ };
236151
235533
  }
236152
235534
  });
236153
235535
 
236154
235536
  // src/commands/pull-v3/components/data-component-generator.ts
236155
- import { jsonSchemaToZod } from "json-schema-to-zod";
236156
- function toCamelCase2(str) {
235537
+ import { jsonSchemaToZod as jsonSchemaToZod3 } from "json-schema-to-zod";
235538
+ function toCamelCase4(str) {
236157
235539
  return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
236158
235540
  }
236159
- function formatString2(str, quote = "'", multiline = false) {
235541
+ function formatString4(str, quote = "'", multiline = false) {
236160
235542
  if (!str) return `${quote}${quote}`;
236161
235543
  if (multiline && (str.includes("\n") || str.length > 80)) {
236162
235544
  return `\`${str.replace(/`/g, "\\`")}\``;
236163
235545
  }
236164
235546
  return `${quote}${str.replace(new RegExp(quote, "g"), "\\" + quote)}${quote}`;
236165
235547
  }
236166
- function convertJsonSchemaToZod(schema) {
235548
+ function convertJsonSchemaToZod2(schema) {
236167
235549
  if (!schema || typeof schema !== "object") {
236168
235550
  return "z.any()";
236169
235551
  }
236170
235552
  try {
236171
- return jsonSchemaToZod(schema);
235553
+ return jsonSchemaToZod3(schema);
236172
235554
  } catch (error) {
236173
235555
  console.warn("Failed to convert JSON schema to Zod:", error);
236174
235556
  return "z.any()";
236175
235557
  }
236176
235558
  }
236177
- function generateDataComponentDefinition(componentId, componentData, style = DEFAULT_STYLE2) {
235559
+ function generateDataComponentDefinition(componentId, componentData, style = DEFAULT_STYLE4) {
236178
235560
  if (!componentId || typeof componentId !== "string") {
236179
235561
  throw new Error("componentId is required and must be a string");
236180
235562
  }
@@ -236193,15 +235575,15 @@ function generateDataComponentDefinition(componentId, componentData, style = DEF
236193
235575
  const { quotes, semicolons, indentation } = style;
236194
235576
  const q = quotes === "single" ? "'" : '"';
236195
235577
  const semi = semicolons ? ";" : "";
236196
- const componentVarName = toCamelCase2(componentId);
235578
+ const componentVarName = toCamelCase4(componentId);
236197
235579
  const lines = [];
236198
235580
  lines.push(`export const ${componentVarName} = dataComponent({`);
236199
- lines.push(`${indentation}id: ${formatString2(componentId, q)},`);
236200
- lines.push(`${indentation}name: ${formatString2(componentData.name, q)},`);
236201
- lines.push(`${indentation}description: ${formatString2(componentData.description, q, true)},`);
235581
+ lines.push(`${indentation}id: ${formatString4(componentId, q)},`);
235582
+ lines.push(`${indentation}name: ${formatString4(componentData.name, q)},`);
235583
+ lines.push(`${indentation}description: ${formatString4(componentData.description, q, true)},`);
236202
235584
  const schema = componentData.props || componentData.schema;
236203
235585
  if (schema) {
236204
- const zodSchema = convertJsonSchemaToZod(schema);
235586
+ const zodSchema = convertJsonSchemaToZod2(schema);
236205
235587
  lines.push(`${indentation}props: ${zodSchema},`);
236206
235588
  }
236207
235589
  if (lines.length > 0 && lines[lines.length - 1].endsWith(",")) {
@@ -236210,7 +235592,7 @@ function generateDataComponentDefinition(componentId, componentData, style = DEF
236210
235592
  lines.push(`})${semi}`);
236211
235593
  return lines.join("\n");
236212
235594
  }
236213
- function generateDataComponentImports(componentId, componentData, style = DEFAULT_STYLE2) {
235595
+ function generateDataComponentImports(componentId, componentData, style = DEFAULT_STYLE4) {
236214
235596
  const { quotes, semicolons } = style;
236215
235597
  const q = quotes === "single" ? "'" : '"';
236216
235598
  const semi = semicolons ? ";" : "";
@@ -236222,17 +235604,17 @@ function generateDataComponentImports(componentId, componentData, style = DEFAUL
236222
235604
  }
236223
235605
  return imports;
236224
235606
  }
236225
- function generateDataComponentFile(componentId, componentData, style = DEFAULT_STYLE2) {
235607
+ function generateDataComponentFile(componentId, componentData, style = DEFAULT_STYLE4) {
236226
235608
  const imports = generateDataComponentImports(componentId, componentData, style);
236227
235609
  const definition = generateDataComponentDefinition(componentId, componentData, style);
236228
235610
  return imports.join("\n") + "\n\n" + definition + "\n";
236229
235611
  }
236230
- var DEFAULT_STYLE2;
235612
+ var DEFAULT_STYLE4;
236231
235613
  var init_data_component_generator = __esm({
236232
235614
  "src/commands/pull-v3/components/data-component-generator.ts"() {
236233
235615
  "use strict";
236234
235616
  init_esm_shims();
236235
- DEFAULT_STYLE2 = {
235617
+ DEFAULT_STYLE4 = {
236236
235618
  quotes: "single",
236237
235619
  semicolons: true,
236238
235620
  indentation: " "
@@ -236240,140 +235622,209 @@ var init_data_component_generator = __esm({
236240
235622
  }
236241
235623
  });
236242
235624
 
236243
- // src/commands/pull-v3/components/artifact-component-generator.ts
236244
- import { jsonSchemaToZod as jsonSchemaToZod2 } from "json-schema-to-zod";
236245
- function toCamelCase3(str) {
236246
- return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
236247
- }
236248
- function formatString3(str, quote = "'", multiline = false) {
235625
+ // src/commands/pull-v3/components/environment-generator.ts
235626
+ var environment_generator_exports = {};
235627
+ __export(environment_generator_exports, {
235628
+ generateEnvironmentFile: () => generateEnvironmentFile,
235629
+ generateEnvironmentIndexDefinition: () => generateEnvironmentIndexDefinition,
235630
+ generateEnvironmentIndexFile: () => generateEnvironmentIndexFile,
235631
+ generateEnvironmentIndexImports: () => generateEnvironmentIndexImports,
235632
+ generateEnvironmentSettingsDefinition: () => generateEnvironmentSettingsDefinition,
235633
+ generateEnvironmentSettingsFile: () => generateEnvironmentSettingsFile,
235634
+ generateEnvironmentSettingsImports: () => generateEnvironmentSettingsImports
235635
+ });
235636
+ function formatString5(str, quote = "'", multiline = false) {
236249
235637
  if (!str) return `${quote}${quote}`;
236250
235638
  if (multiline && (str.includes("\n") || str.length > 80)) {
236251
235639
  return `\`${str.replace(/`/g, "\\`")}\``;
236252
235640
  }
236253
235641
  return `${quote}${str.replace(new RegExp(quote, "g"), "\\" + quote)}${quote}`;
236254
235642
  }
236255
- function hasInPreviewFields(schema) {
236256
- if (!schema || typeof schema !== "object" || schema.type !== "object" || !schema.properties) {
236257
- return false;
235643
+ function formatCredentialsObject(credentials, style, indentLevel) {
235644
+ if (!credentials || typeof credentials !== "object") {
235645
+ return "{}";
236258
235646
  }
236259
- for (const prop of Object.values(schema.properties)) {
236260
- if (prop.inPreview === true) {
236261
- return true;
235647
+ const { quotes, indentation } = style;
235648
+ const q = quotes === "single" ? "'" : '"';
235649
+ const baseIndent = indentation.repeat(indentLevel);
235650
+ const indent = indentation.repeat(indentLevel + 1);
235651
+ const nestedIndent = indentation.repeat(indentLevel + 2);
235652
+ const lines = ["{"];
235653
+ for (const [key, credentialData] of Object.entries(credentials)) {
235654
+ lines.push(`${indent}${formatString5(key, q)}: {`);
235655
+ if (credentialData.id) {
235656
+ lines.push(`${nestedIndent}id: ${formatString5(credentialData.id, q)},`);
236262
235657
  }
236263
- }
236264
- return false;
236265
- }
236266
- function formatArtifactSchema(schema, style) {
236267
- if (!schema || typeof schema !== "object") {
236268
- return "z.any()";
236269
- }
236270
- if (schema.type === "object" && schema.properties) {
236271
- const { indentation } = style;
236272
- const lines = ["z.object({"];
236273
- for (const [key, prop] of Object.entries(schema.properties)) {
236274
- const propCopy = { ...prop };
236275
- delete propCopy.inPreview;
236276
- const baseZodType = convertJsonSchemaToZod2(propCopy);
236277
- const finalZodType = prop.inPreview === true ? `preview(${baseZodType})` : baseZodType;
236278
- lines.push(`${indentation}${key}: ${finalZodType},`);
235658
+ if (credentialData.name) {
235659
+ lines.push(`${nestedIndent}name: ${formatString5(credentialData.name, q)},`);
236279
235660
  }
236280
- lines.push("})");
236281
- if (schema.description) {
236282
- return lines.join("\n") + `.describe(\`${schema.description}\`)`;
235661
+ if (credentialData.type) {
235662
+ if (typeof credentialData.type === "string") {
235663
+ const enumValue = credentialData.type === "memory" ? "CredentialStoreType.memory" : credentialData.type === "env" ? "CredentialStoreType.env" : credentialData.type === "keychain" ? "CredentialStoreType.keychain" : formatString5(credentialData.type, q);
235664
+ lines.push(`${nestedIndent}type: ${enumValue},`);
235665
+ } else {
235666
+ lines.push(`${nestedIndent}type: ${credentialData.type},`);
235667
+ }
236283
235668
  }
236284
- return lines.join("\n");
236285
- }
236286
- return convertJsonSchemaToZod2(schema);
236287
- }
236288
- function convertJsonSchemaToZod2(schema) {
236289
- if (!schema || typeof schema !== "object") {
236290
- return "z.any()";
235669
+ if (credentialData.credentialStoreId) {
235670
+ lines.push(
235671
+ `${nestedIndent}credentialStoreId: ${formatString5(credentialData.credentialStoreId, q)},`
235672
+ );
235673
+ }
235674
+ if (credentialData.description) {
235675
+ lines.push(`${nestedIndent}description: ${formatString5(credentialData.description, q)},`);
235676
+ }
235677
+ if (credentialData.retrievalParams) {
235678
+ lines.push(`${nestedIndent}retrievalParams: {`);
235679
+ for (const [paramKey, paramValue] of Object.entries(credentialData.retrievalParams)) {
235680
+ if (paramValue === null || paramValue === void 0) {
235681
+ continue;
235682
+ }
235683
+ if (typeof paramValue === "string") {
235684
+ lines.push(`${nestedIndent}${indent}${paramKey}: ${formatString5(paramValue, q)},`);
235685
+ } else {
235686
+ lines.push(`${nestedIndent}${indent}${paramKey}: ${JSON.stringify(paramValue)},`);
235687
+ }
235688
+ }
235689
+ const lastLineIndex = lines.length - 1;
235690
+ if (lines[lastLineIndex].endsWith(",")) {
235691
+ lines[lastLineIndex] = lines[lastLineIndex].slice(0, -1);
235692
+ }
235693
+ lines.push(`${nestedIndent}},`);
235694
+ }
235695
+ const lastPropIndex = lines.length - 1;
235696
+ if (lines[lastPropIndex].endsWith(",")) {
235697
+ lines[lastPropIndex] = lines[lastPropIndex].slice(0, -1);
235698
+ }
235699
+ lines.push(`${indent}},`);
236291
235700
  }
236292
- try {
236293
- return jsonSchemaToZod2(schema);
236294
- } catch (error) {
236295
- console.warn("Failed to convert JSON schema to Zod:", error);
236296
- return "z.any()";
235701
+ if (lines.length > 1 && lines[lines.length - 1].endsWith(",")) {
235702
+ lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
236297
235703
  }
235704
+ lines.push(`${baseIndent}}`);
235705
+ return lines.join("\n");
236298
235706
  }
236299
- function generateArtifactComponentDefinition(componentId, componentData, style = DEFAULT_STYLE3) {
236300
- if (!componentId || typeof componentId !== "string") {
236301
- throw new Error("componentId is required and must be a string");
236302
- }
236303
- if (!componentData || typeof componentData !== "object") {
236304
- throw new Error(`componentData is required for artifact component '${componentId}'`);
235707
+ function generateEnvironmentSettingsDefinition(environmentName, environmentData, style = DEFAULT_STYLE5) {
235708
+ if (!environmentName || typeof environmentName !== "string") {
235709
+ throw new Error("environmentName is required and must be a string");
236305
235710
  }
236306
- const requiredFields = ["name", "description", "props"];
236307
- const missingFields = requiredFields.filter(
236308
- (field) => !componentData[field] || componentData[field] === null || componentData[field] === void 0
236309
- );
236310
- if (missingFields.length > 0) {
236311
- throw new Error(
236312
- `Missing required fields for artifact component '${componentId}': ${missingFields.join(", ")}`
236313
- );
235711
+ if (!environmentData || typeof environmentData !== "object") {
235712
+ throw new Error(`environmentData is required for environment '${environmentName}'`);
236314
235713
  }
236315
235714
  const { quotes, semicolons, indentation } = style;
236316
235715
  const q = quotes === "single" ? "'" : '"';
236317
235716
  const semi = semicolons ? ";" : "";
236318
- const componentVarName = toCamelCase3(componentId);
236319
235717
  const lines = [];
236320
- lines.push(`export const ${componentVarName} = artifactComponent({`);
236321
- lines.push(`${indentation}id: ${formatString3(componentId, q)},`);
236322
- lines.push(`${indentation}name: ${formatString3(componentData.name, q)},`);
236323
- lines.push(`${indentation}description: ${formatString3(componentData.description, q, true)},`);
236324
- const schema = componentData.props || componentData.schema;
236325
- if (schema) {
236326
- const zodSchema = formatArtifactSchema(schema, style);
236327
- if (zodSchema.includes("\n")) {
236328
- const schemaLines = zodSchema.split("\n");
236329
- lines.push(`${indentation}props: ${schemaLines[0]}`);
236330
- schemaLines.slice(1, -1).forEach((line) => {
236331
- lines[lines.length - 1] += "\n" + indentation + line;
236332
- });
236333
- lines[lines.length - 1] += "\n" + indentation + schemaLines[schemaLines.length - 1] + ",";
236334
- } else {
236335
- lines.push(`${indentation}props: ${zodSchema},`);
236336
- }
235718
+ lines.push(`export const ${environmentName} = registerEnvironmentSettings({`);
235719
+ if (environmentData.credentials && Object.keys(environmentData.credentials).length > 0) {
235720
+ const formattedCredentials = formatCredentialsObject(environmentData.credentials, style, 1);
235721
+ lines.push(`${indentation}credentials: ${formattedCredentials},`);
235722
+ } else {
235723
+ lines.push(`${indentation}credentials: {},`);
236337
235724
  }
236338
- if (componentData.template) {
236339
- lines.push(`${indentation}template: ${formatString3(componentData.template, q, true)},`);
235725
+ if (lines.length > 1 && lines[lines.length - 1].endsWith(",")) {
235726
+ lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
236340
235727
  }
236341
- if (componentData.contentType) {
236342
- lines.push(`${indentation}contentType: ${formatString3(componentData.contentType, q)},`);
235728
+ lines.push(`})${semi}`);
235729
+ return lines.join("\n");
235730
+ }
235731
+ function generateEnvironmentIndexDefinition(environments, style = DEFAULT_STYLE5) {
235732
+ const { quotes, semicolons, indentation } = style;
235733
+ const q = quotes === "single" ? "'" : '"';
235734
+ const semi = semicolons ? ";" : "";
235735
+ const lines = [];
235736
+ lines.push(`export const envSettings = createEnvironmentSettings({`);
235737
+ for (const envName of environments) {
235738
+ lines.push(`${indentation}${envName},`);
236343
235739
  }
236344
- if (lines.length > 0 && lines[lines.length - 1].endsWith(",")) {
235740
+ if (lines.length > 1 && lines[lines.length - 1].endsWith(",")) {
236345
235741
  lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
236346
235742
  }
236347
235743
  lines.push(`})${semi}`);
236348
235744
  return lines.join("\n");
236349
235745
  }
236350
- function generateArtifactComponentImports(componentId, componentData, style = DEFAULT_STYLE3) {
235746
+ function generateEnvironmentSettingsImports(environmentName, environmentData, style = DEFAULT_STYLE5) {
236351
235747
  const { quotes, semicolons } = style;
236352
235748
  const q = quotes === "single" ? "'" : '"';
236353
235749
  const semi = semicolons ? ";" : "";
236354
235750
  const imports = [];
236355
- const schema = componentData.props || componentData.schema;
236356
- const needsPreviewImport = hasInPreviewFields(schema);
236357
- if (needsPreviewImport) {
236358
- imports.push(`import { preview } from ${q}@inkeep/agents-core${q}${semi}`);
235751
+ imports.push(`import { registerEnvironmentSettings } from ${q}@inkeep/agents-sdk${q}${semi}`);
235752
+ const needsCredentialStoreType = environmentData.credentials && Object.values(environmentData.credentials).some(
235753
+ (cred) => typeof cred.type === "string" && ["memory", "env", "keychain"].includes(cred.type)
235754
+ );
235755
+ if (needsCredentialStoreType) {
235756
+ imports.push(`import { CredentialStoreType } from ${q}@inkeep/agents-core${q}${semi}`);
236359
235757
  }
236360
- imports.push(`import { artifactComponent } from ${q}@inkeep/agents-sdk${q}${semi}`);
236361
- if (schema) {
236362
- imports.push(`import { z } from ${q}zod${q}${semi}`);
235758
+ return imports;
235759
+ }
235760
+ function generateEnvironmentIndexImports(environments, style = DEFAULT_STYLE5) {
235761
+ const { quotes, semicolons } = style;
235762
+ const q = quotes === "single" ? "'" : '"';
235763
+ const semi = semicolons ? ";" : "";
235764
+ const imports = [];
235765
+ imports.push(`import { createEnvironmentSettings } from ${q}@inkeep/agents-sdk${q}${semi}`);
235766
+ for (const envName of environments) {
235767
+ imports.push(`import { ${envName} } from ${q}./${envName}.env${q}${semi}`);
236363
235768
  }
236364
235769
  return imports;
236365
235770
  }
236366
- function generateArtifactComponentFile(componentId, componentData, style = DEFAULT_STYLE3) {
236367
- const imports = generateArtifactComponentImports(componentId, componentData, style);
236368
- const definition = generateArtifactComponentDefinition(componentId, componentData, style);
235771
+ function generateEnvironmentSettingsFile(environmentName, environmentData, style = DEFAULT_STYLE5) {
235772
+ const imports = generateEnvironmentSettingsImports(environmentName, environmentData, style);
235773
+ const definition = generateEnvironmentSettingsDefinition(environmentName, environmentData, style);
236369
235774
  return imports.join("\n") + "\n\n" + definition + "\n";
236370
235775
  }
236371
- var DEFAULT_STYLE3;
236372
- var init_artifact_component_generator = __esm({
236373
- "src/commands/pull-v3/components/artifact-component-generator.ts"() {
235776
+ function generateEnvironmentIndexFile(environments, style = DEFAULT_STYLE5) {
235777
+ const imports = generateEnvironmentIndexImports(environments, style);
235778
+ const definition = generateEnvironmentIndexDefinition(environments, style);
235779
+ return imports.join("\n") + "\n\n" + definition + "\n";
235780
+ }
235781
+ function generateEnvironmentFile(environmentName, environmentData, style = DEFAULT_STYLE5, registry2) {
235782
+ if (registry2 && environmentData.credentials && Array.isArray(environmentData.credentials)) {
235783
+ const { quotes, semicolons, indentation } = style;
235784
+ const q = quotes === "single" ? "'" : '"';
235785
+ const semi = semicolons ? ";" : "";
235786
+ const imports = [];
235787
+ const credentialRefs = [];
235788
+ imports.push(`import { registerEnvironmentSettings } from ${q}@inkeep/agents-sdk${q}${semi}`);
235789
+ for (const credentialId of environmentData.credentials) {
235790
+ const credentialComponent = registry2.get(credentialId, "credential");
235791
+ if (credentialComponent) {
235792
+ const relativePath = `../credentials/${credentialId}`;
235793
+ imports.push(`import { ${credentialComponent.name} } from ${q}${relativePath}${q}${semi}`);
235794
+ credentialRefs.push(credentialComponent.name);
235795
+ }
235796
+ }
235797
+ const lines = [];
235798
+ lines.push(...imports);
235799
+ lines.push("");
235800
+ lines.push(`export const ${environmentName} = registerEnvironmentSettings({`);
235801
+ if (credentialRefs.length > 0) {
235802
+ lines.push(`${indentation}credentials: {`);
235803
+ for (let i = 0; i < environmentData.credentials.length; i++) {
235804
+ const credentialId = environmentData.credentials[i];
235805
+ const credentialVarName = credentialRefs[i];
235806
+ const isLast = i === credentialRefs.length - 1;
235807
+ const validKey = registry2.getVariableName(credentialId, "credential");
235808
+ lines.push(
235809
+ `${indentation}${indentation}${validKey}: ${credentialVarName}${isLast ? "" : ","}`
235810
+ );
235811
+ }
235812
+ lines.push(`${indentation}}`);
235813
+ } else {
235814
+ lines.push(`${indentation}credentials: {}`);
235815
+ }
235816
+ lines.push(`})${semi}`);
235817
+ lines.push("");
235818
+ return lines.join("\n");
235819
+ }
235820
+ return generateEnvironmentSettingsFile(environmentName, environmentData, style);
235821
+ }
235822
+ var DEFAULT_STYLE5;
235823
+ var init_environment_generator = __esm({
235824
+ "src/commands/pull-v3/components/environment-generator.ts"() {
236374
235825
  "use strict";
236375
235826
  init_esm_shims();
236376
- DEFAULT_STYLE3 = {
235827
+ DEFAULT_STYLE5 = {
236377
235828
  quotes: "single",
236378
235829
  semicolons: true,
236379
235830
  indentation: " "
@@ -236381,102 +235832,116 @@ var init_artifact_component_generator = __esm({
236381
235832
  }
236382
235833
  });
236383
235834
 
236384
- // src/commands/pull-v3/components/status-component-generator.ts
236385
- import { jsonSchemaToZod as jsonSchemaToZod3 } from "json-schema-to-zod";
236386
- function toCamelCase4(str) {
236387
- return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
236388
- }
236389
- function formatString4(str, quote = "'", multiline = false) {
236390
- if (!str) return `${quote}${quote}`;
236391
- if (multiline && (str.includes("\n") || str.length > 80)) {
236392
- return `\`${str.replace(/`/g, "\\`")}\``;
236393
- }
236394
- return `${quote}${str.replace(new RegExp(quote, "g"), "\\" + quote)}${quote}`;
236395
- }
236396
- function convertJsonSchemaToZod3(schema) {
236397
- if (!schema || typeof schema !== "object") {
236398
- return "z.any()";
236399
- }
236400
- try {
236401
- return jsonSchemaToZod3(schema);
236402
- } catch (error) {
236403
- console.warn("Failed to convert JSON schema to Zod:", error);
236404
- return "z.any()";
236405
- }
236406
- }
236407
- function generateStatusComponentDefinition(componentId, componentData, style = DEFAULT_STYLE4) {
236408
- if (!componentId || typeof componentId !== "string") {
236409
- throw new Error("componentId is required and must be a string");
235835
+ // src/commands/pull-v3/components/external-agent-generator.ts
235836
+ function generateExternalAgentDefinition(agentId, agentData, style = DEFAULT_STYLE, registry2) {
235837
+ if (!agentId || typeof agentId !== "string") {
235838
+ throw new Error("agentId is required and must be a string");
236410
235839
  }
236411
- if (!componentData || typeof componentData !== "object") {
236412
- throw new Error(`componentData is required for status component '${componentId}'`);
235840
+ if (!agentData || typeof agentData !== "object") {
235841
+ throw new Error(`agentData is required for external agent '${agentId}'`);
236413
235842
  }
236414
- const requiredFields = ["type"];
235843
+ const requiredFields = ["name", "description", "baseUrl"];
236415
235844
  const missingFields = requiredFields.filter(
236416
- (field) => !componentData[field] || componentData[field] === null || componentData[field] === void 0
235845
+ (field) => !agentData[field] || agentData[field] === null || agentData[field] === void 0
236417
235846
  );
236418
235847
  if (missingFields.length > 0) {
236419
235848
  throw new Error(
236420
- `Missing required fields for status component '${componentId}': ${missingFields.join(", ")}`
235849
+ `Missing required fields for external agent '${agentId}': ${missingFields.join(", ")}`
236421
235850
  );
236422
235851
  }
236423
235852
  const { quotes, semicolons, indentation } = style;
236424
235853
  const q = quotes === "single" ? "'" : '"';
236425
235854
  const semi = semicolons ? ";" : "";
236426
- const componentVarName = toCamelCase4(componentId);
235855
+ let agentVarName = toCamelCase(agentId);
235856
+ if (registry2) {
235857
+ const registryVarName = registry2.getVariableName(agentId, "externalAgent");
235858
+ if (registryVarName) {
235859
+ agentVarName = registryVarName;
235860
+ }
235861
+ }
236427
235862
  const lines = [];
236428
- lines.push(`export const ${componentVarName} = statusComponent({`);
236429
- lines.push(`${indentation}type: ${formatString4(componentData.type, q)},`);
236430
- if (componentData.description) {
236431
- lines.push(`${indentation}description: ${formatString4(componentData.description, q, true)},`);
235863
+ lines.push(`export const ${agentVarName} = externalAgent({`);
235864
+ lines.push(`${indentation}id: ${formatString(agentId, q)},`);
235865
+ if (agentData.name !== void 0 && agentData.name !== null) {
235866
+ lines.push(`${indentation}name: ${formatString(agentData.name, q)},`);
235867
+ } else {
235868
+ lines.push(`${indentation}name: ${formatString(agentId, q)},`);
236432
235869
  }
236433
- const schema = componentData.detailsSchema || componentData.schema;
236434
- if (schema) {
236435
- const zodSchema = convertJsonSchemaToZod3(schema);
236436
- if (zodSchema.includes("\n")) {
236437
- const schemaLines = zodSchema.split("\n");
236438
- lines.push(`${indentation}detailsSchema: ${schemaLines[0]}`);
236439
- schemaLines.slice(1, -1).forEach((line) => {
236440
- lines[lines.length - 1] += "\n" + indentation + line;
236441
- });
236442
- lines[lines.length - 1] += "\n" + indentation + schemaLines[schemaLines.length - 1] + ",";
236443
- } else {
236444
- lines.push(`${indentation}detailsSchema: ${zodSchema},`);
236445
- }
235870
+ if (agentData.description !== void 0 && agentData.description !== null) {
235871
+ lines.push(`${indentation}description: ${formatString(agentData.description, q, true)},`);
235872
+ } else {
235873
+ lines.push(`${indentation}description: ${formatString(`External agent ${agentId}`, q)},`);
236446
235874
  }
236447
- if (lines.length > 0 && lines[lines.length - 1].endsWith(",")) {
236448
- lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
235875
+ if (agentData.baseUrl !== void 0 && agentData.baseUrl !== null) {
235876
+ lines.push(`${indentation}baseUrl: ${formatString(agentData.baseUrl, q)},`);
236449
235877
  }
235878
+ if (agentData.credentialReference) {
235879
+ if (typeof agentData.credentialReference === "string") {
235880
+ if (!registry2) {
235881
+ throw new Error("Registry is required for credentialReference generation");
235882
+ }
235883
+ const credentialVar = registry2.getVariableName(agentData.credentialReference, "credential");
235884
+ if (!credentialVar) {
235885
+ throw new Error(
235886
+ `Failed to resolve variable name for credential reference: ${agentData.credentialReference}`
235887
+ );
235888
+ }
235889
+ lines.push(`${indentation}credentialReference: ${credentialVar},`);
235890
+ } else if (typeof agentData.credentialReference === "object") {
235891
+ const credLines = [];
235892
+ if (agentData.credentialReference.id) {
235893
+ credLines.push(
235894
+ `${indentation}${indentation}id: ${formatString(agentData.credentialReference.id, q)},`
235895
+ );
235896
+ }
235897
+ if (agentData.credentialReference.name) {
235898
+ credLines.push(
235899
+ `${indentation}${indentation}name: ${formatString(agentData.credentialReference.name, q)},`
235900
+ );
235901
+ }
235902
+ if (agentData.credentialReference.description) {
235903
+ credLines.push(
235904
+ `${indentation}${indentation}description: ${formatString(agentData.credentialReference.description, q)},`
235905
+ );
235906
+ }
235907
+ if (credLines.length > 0 && credLines[credLines.length - 1].endsWith(",")) {
235908
+ credLines[credLines.length - 1] = credLines[credLines.length - 1].slice(0, -1);
235909
+ }
235910
+ lines.push(`${indentation}credentialReference: {`);
235911
+ lines.push(...credLines);
235912
+ lines.push(`${indentation}},`);
235913
+ }
235914
+ }
235915
+ removeTrailingComma(lines);
236450
235916
  lines.push(`})${semi}`);
236451
235917
  return lines.join("\n");
236452
235918
  }
236453
- function generateStatusComponentImports(componentId, componentData, style = DEFAULT_STYLE4) {
236454
- const { quotes, semicolons } = style;
236455
- const q = quotes === "single" ? "'" : '"';
236456
- const semi = semicolons ? ";" : "";
235919
+ function generateExternalAgentImports(agentId, agentData, style = DEFAULT_STYLE, registry2) {
236457
235920
  const imports = [];
236458
- imports.push(`import { statusComponent } from ${q}@inkeep/agents-sdk${q}${semi}`);
236459
- const schema = componentData.detailsSchema || componentData.schema;
236460
- if (schema) {
236461
- imports.push(`import { z } from ${q}zod${q}${semi}`);
235921
+ imports.push(generateImport(["externalAgent"], "@inkeep/agents-sdk", style));
235922
+ if (agentData.credentialReference && typeof agentData.credentialReference === "string") {
235923
+ if (!registry2) {
235924
+ throw new Error("Registry is required for credential reference imports");
235925
+ }
235926
+ const currentFilePath = `external-agents/${agentId}.ts`;
235927
+ const credentialRefs = [
235928
+ { id: agentData.credentialReference, type: "credential" }
235929
+ ];
235930
+ const componentImports = registry2.getImportsForFile(currentFilePath, credentialRefs);
235931
+ imports.push(...componentImports);
236462
235932
  }
236463
235933
  return imports;
236464
235934
  }
236465
- function generateStatusComponentFile(componentId, componentData, style = DEFAULT_STYLE4) {
236466
- const imports = generateStatusComponentImports(componentId, componentData, style);
236467
- const definition = generateStatusComponentDefinition(componentId, componentData, style);
236468
- return imports.join("\n") + "\n\n" + definition + "\n";
235935
+ function generateExternalAgentFile(agentId, agentData, style = DEFAULT_STYLE, registry2) {
235936
+ const imports = generateExternalAgentImports(agentId, agentData, style, registry2);
235937
+ const definition = generateExternalAgentDefinition(agentId, agentData, style, registry2);
235938
+ return generateFileContent(imports, [definition]);
236469
235939
  }
236470
- var DEFAULT_STYLE4;
236471
- var init_status_component_generator = __esm({
236472
- "src/commands/pull-v3/components/status-component-generator.ts"() {
235940
+ var init_external_agent_generator = __esm({
235941
+ "src/commands/pull-v3/components/external-agent-generator.ts"() {
236473
235942
  "use strict";
236474
235943
  init_esm_shims();
236475
- DEFAULT_STYLE4 = {
236476
- quotes: "single",
236477
- semicolons: true,
236478
- indentation: " "
236479
- };
235944
+ init_generator_utils();
236480
235945
  }
236481
235946
  });
236482
235947
 
@@ -236485,7 +235950,7 @@ import { jsonSchemaToZod as jsonSchemaToZod4 } from "json-schema-to-zod";
236485
235950
  function toCamelCase5(str) {
236486
235951
  return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
236487
235952
  }
236488
- function formatString5(str, quote = "'", multiline = false) {
235953
+ function formatString6(str, quote = "'", multiline = false) {
236489
235954
  if (!str) return `${quote}${quote}`;
236490
235955
  if (multiline && (str.includes("\n") || str.length > 80)) {
236491
235956
  return `\`${str.replace(/`/g, "\\`")}\``;
@@ -236515,7 +235980,7 @@ ${indentation} ${executeCode.replace(/\n/g, `
236515
235980
  ${indentation} `)}
236516
235981
  ${indentation}}`;
236517
235982
  }
236518
- function generateFunctionToolDefinition(toolId, toolData, style = DEFAULT_STYLE5) {
235983
+ function generateFunctionToolDefinition(toolId, toolData, style = DEFAULT_STYLE6) {
236519
235984
  if (!toolId || typeof toolId !== "string") {
236520
235985
  throw new Error("toolId is required and must be a string");
236521
235986
  }
@@ -236537,9 +236002,9 @@ function generateFunctionToolDefinition(toolId, toolData, style = DEFAULT_STYLE5
236537
236002
  const toolVarName = toCamelCase5(toolId);
236538
236003
  const lines = [];
236539
236004
  lines.push(`export const ${toolVarName} = functionTool({`);
236540
- lines.push(`${indentation}name: ${formatString5(toolData.name, q)},`);
236005
+ lines.push(`${indentation}name: ${formatString6(toolData.name, q)},`);
236541
236006
  if (toolData.description) {
236542
- lines.push(`${indentation}description: ${formatString5(toolData.description, q, true)},`);
236007
+ lines.push(`${indentation}description: ${formatString6(toolData.description, q, true)},`);
236543
236008
  }
236544
236009
  const inputSchema = toolData.inputSchema || toolData.schema;
236545
236010
  if (inputSchema) {
@@ -236567,7 +236032,7 @@ function generateFunctionToolDefinition(toolId, toolData, style = DEFAULT_STYLE5
236567
236032
  const result = lines.join("\n");
236568
236033
  return result;
236569
236034
  }
236570
- function generateFunctionToolImports(toolId, toolData, style = DEFAULT_STYLE5) {
236035
+ function generateFunctionToolImports(toolId, toolData, style = DEFAULT_STYLE6) {
236571
236036
  const { quotes, semicolons } = style;
236572
236037
  const q = quotes === "single" ? "'" : '"';
236573
236038
  const semi = semicolons ? ";" : "";
@@ -236575,17 +236040,17 @@ function generateFunctionToolImports(toolId, toolData, style = DEFAULT_STYLE5) {
236575
236040
  imports.push(`import { functionTool } from ${q}@inkeep/agents-sdk${q}${semi}`);
236576
236041
  return imports;
236577
236042
  }
236578
- function generateFunctionToolFile(toolId, toolData, style = DEFAULT_STYLE5) {
236043
+ function generateFunctionToolFile(toolId, toolData, style = DEFAULT_STYLE6) {
236579
236044
  const imports = generateFunctionToolImports(toolId, toolData, style);
236580
236045
  const definition = generateFunctionToolDefinition(toolId, toolData, style);
236581
236046
  return imports.join("\n") + "\n\n" + definition + "\n";
236582
236047
  }
236583
- var DEFAULT_STYLE5;
236048
+ var DEFAULT_STYLE6;
236584
236049
  var init_function_tool_generator = __esm({
236585
236050
  "src/commands/pull-v3/components/function-tool-generator.ts"() {
236586
236051
  "use strict";
236587
236052
  init_esm_shims();
236588
- DEFAULT_STYLE5 = {
236053
+ DEFAULT_STYLE6 = {
236589
236054
  quotes: "single",
236590
236055
  semicolons: true,
236591
236056
  indentation: " "
@@ -236597,14 +236062,14 @@ var init_function_tool_generator = __esm({
236597
236062
  function toCamelCase6(str) {
236598
236063
  return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
236599
236064
  }
236600
- function formatString6(str, quote = "'", multiline = false) {
236065
+ function formatString7(str, quote = "'", multiline = false) {
236601
236066
  if (!str) return `${quote}${quote}`;
236602
236067
  if (multiline && (str.includes("\n") || str.length > 80)) {
236603
236068
  return `\`${str.replace(/`/g, "\\`")}\``;
236604
236069
  }
236605
236070
  return `${quote}${str.replace(new RegExp(quote, "g"), "\\" + quote)}${quote}`;
236606
236071
  }
236607
- function generateMcpToolDefinition(toolId, toolData, style = DEFAULT_STYLE6, registry2) {
236072
+ function generateMcpToolDefinition(toolId, toolData, style = DEFAULT_STYLE7, registry2) {
236608
236073
  if (!toolId || typeof toolId !== "string") {
236609
236074
  throw new Error("toolId is required and must be a string");
236610
236075
  }
@@ -236630,14 +236095,14 @@ function generateMcpToolDefinition(toolId, toolData, style = DEFAULT_STYLE6, reg
236630
236095
  const toolVarName = toCamelCase6(toolId);
236631
236096
  const lines = [];
236632
236097
  lines.push(`export const ${toolVarName} = mcpTool({`);
236633
- lines.push(`${indentation}id: ${formatString6(toolId, q)},`);
236634
- lines.push(`${indentation}name: ${formatString6(toolData.name, q)},`);
236635
- lines.push(`${indentation}serverUrl: ${formatString6(serverUrl, q)},`);
236098
+ lines.push(`${indentation}id: ${formatString7(toolId, q)},`);
236099
+ lines.push(`${indentation}name: ${formatString7(toolData.name, q)},`);
236100
+ lines.push(`${indentation}serverUrl: ${formatString7(serverUrl, q)},`);
236636
236101
  if (toolData.description) {
236637
- lines.push(`${indentation}description: ${formatString6(toolData.description, q, true)},`);
236102
+ lines.push(`${indentation}description: ${formatString7(toolData.description, q, true)},`);
236638
236103
  }
236639
236104
  if (toolData.imageUrl) {
236640
- lines.push(`${indentation}imageUrl: ${formatString6(toolData.imageUrl, q)},`);
236105
+ lines.push(`${indentation}imageUrl: ${formatString7(toolData.imageUrl, q)},`);
236641
236106
  }
236642
236107
  if (toolData.headers && typeof toolData.headers === "object") {
236643
236108
  const headersStr = JSON.stringify(toolData.headers, null, 2);
@@ -236657,7 +236122,7 @@ function generateMcpToolDefinition(toolId, toolData, style = DEFAULT_STYLE6, reg
236657
236122
  } else if (toolData.credentialReferenceId && registry2) {
236658
236123
  const validKey = registry2.getVariableName(toolData.credentialReferenceId, "credential");
236659
236124
  lines.push(
236660
- `${indentation}credential: envSettings.getEnvironmentCredential(${formatString6(validKey, q)}),`
236125
+ `${indentation}credential: envSettings.getEnvironmentCredential(${formatString7(validKey, q)}),`
236661
236126
  );
236662
236127
  }
236663
236128
  if (lines.length > 0 && lines[lines.length - 1].endsWith(",")) {
@@ -236666,7 +236131,7 @@ function generateMcpToolDefinition(toolId, toolData, style = DEFAULT_STYLE6, reg
236666
236131
  lines.push(`})${semi}`);
236667
236132
  return lines.join("\n");
236668
236133
  }
236669
- function generateMcpToolImports(toolId, toolData, style = DEFAULT_STYLE6) {
236134
+ function generateMcpToolImports(toolId, toolData, style = DEFAULT_STYLE7) {
236670
236135
  const { quotes, semicolons } = style;
236671
236136
  const q = quotes === "single" ? "'" : '"';
236672
236137
  const semi = semicolons ? ";" : "";
@@ -236677,17 +236142,17 @@ function generateMcpToolImports(toolId, toolData, style = DEFAULT_STYLE6) {
236677
236142
  }
236678
236143
  return imports;
236679
236144
  }
236680
- function generateMcpToolFile(toolId, toolData, style = DEFAULT_STYLE6, registry2) {
236145
+ function generateMcpToolFile(toolId, toolData, style = DEFAULT_STYLE7, registry2) {
236681
236146
  const imports = generateMcpToolImports(toolId, toolData, style);
236682
236147
  const definition = generateMcpToolDefinition(toolId, toolData, style, registry2);
236683
236148
  return imports.join("\n") + "\n\n" + definition + "\n";
236684
236149
  }
236685
- var DEFAULT_STYLE6;
236150
+ var DEFAULT_STYLE7;
236686
236151
  var init_mcp_tool_generator = __esm({
236687
236152
  "src/commands/pull-v3/components/mcp-tool-generator.ts"() {
236688
236153
  "use strict";
236689
236154
  init_esm_shims();
236690
- DEFAULT_STYLE6 = {
236155
+ DEFAULT_STYLE7 = {
236691
236156
  quotes: "single",
236692
236157
  semicolons: true,
236693
236158
  indentation: " "
@@ -236695,124 +236160,200 @@ var init_mcp_tool_generator = __esm({
236695
236160
  }
236696
236161
  });
236697
236162
 
236698
- // src/commands/pull-v3/components/credential-generator.ts
236699
- function toCamelCase7(str) {
236700
- return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
236701
- }
236702
- function formatString7(str, quote = "'", multiline = false) {
236703
- if (!str) return `${quote}${quote}`;
236704
- if (multiline && (str.includes("\n") || str.length > 80)) {
236705
- return `\`${str.replace(/`/g, "\\`")}\``;
236163
+ // src/commands/pull-v3/components/project-generator.ts
236164
+ function generateProjectDefinition(projectId, projectData, style = DEFAULT_STYLE, registry2) {
236165
+ if (!projectId || typeof projectId !== "string") {
236166
+ throw new Error("projectId is required and must be a string");
236706
236167
  }
236707
- return `${quote}${str.replace(new RegExp(quote, "g"), "\\" + quote)}${quote}`;
236708
- }
236709
- function formatRetrievalParams(retrievalParams, style, indentLevel) {
236710
- if (!retrievalParams || typeof retrievalParams !== "object") {
236711
- return "{}";
236168
+ if (!projectData || typeof projectData !== "object") {
236169
+ throw new Error(`projectData is required for project '${projectId}'`);
236712
236170
  }
236713
- const { quotes, indentation } = style;
236714
- const q = quotes === "single" ? "'" : '"';
236715
- const baseIndent = indentation.repeat(indentLevel);
236716
- const indent = indentation.repeat(indentLevel + 1);
236717
- const lines = ["{"];
236718
- for (const [key, value] of Object.entries(retrievalParams)) {
236719
- if (typeof value === "string") {
236720
- lines.push(`${indent}${q}${key}${q}: ${formatString7(value, q)},`);
236721
- } else if (typeof value === "number" || typeof value === "boolean") {
236722
- lines.push(`${indent}${q}${key}${q}: ${JSON.stringify(value)},`);
236723
- } else if (typeof value === "object" && value !== null) {
236724
- lines.push(
236725
- `${indent}${q}${key}${q}: ${formatRetrievalParams(value, style, indentLevel + 1)},`
236726
- );
236727
- }
236171
+ const requiredFields = ["name", "models"];
236172
+ const missingFields = requiredFields.filter(
236173
+ (field) => !projectData[field] || projectData[field] === null || projectData[field] === void 0
236174
+ );
236175
+ if (!projectData.models?.base) {
236176
+ missingFields.push("models.base");
236728
236177
  }
236729
- if (lines.length > 1 && lines[lines.length - 1].endsWith(",")) {
236730
- lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
236178
+ if (missingFields.length > 0) {
236179
+ throw new Error(
236180
+ `Missing required fields for project '${projectId}': ${missingFields.join(", ")}`
236181
+ );
236731
236182
  }
236732
- lines.push(`${baseIndent}}`);
236733
- return lines.join("\n");
236734
- }
236735
- function generateCredentialDefinition(credentialId, credentialData, style = DEFAULT_STYLE7) {
236736
236183
  const { quotes, semicolons, indentation } = style;
236737
236184
  const q = quotes === "single" ? "'" : '"';
236738
236185
  const semi = semicolons ? ";" : "";
236739
- const credentialVarName = toCamelCase7(credentialId);
236186
+ const projectVarName = toCamelCase(projectId);
236740
236187
  const lines = [];
236741
- lines.push(`export const ${credentialVarName} = credential({`);
236742
- lines.push(`${indentation}id: ${formatString7(credentialId, q)},`);
236743
- const requiredFields = ["name", "type", "credentialStoreId"];
236744
- const missingFields = requiredFields.filter(
236745
- (field) => !credentialData[field] || credentialData[field] === null || credentialData[field] === void 0
236746
- );
236747
- if (missingFields.length > 0) {
236748
- throw new Error(
236749
- `Missing required fields for credential '${credentialId}': ${missingFields.join(", ")}`
236750
- );
236188
+ lines.push(`export const ${projectVarName} = project({`);
236189
+ lines.push(`${indentation}id: ${formatString(projectId, q)},`);
236190
+ lines.push(`${indentation}name: ${formatString(projectData.name, q)},`);
236191
+ if (shouldInclude(projectData.description)) {
236192
+ lines.push(`${indentation}description: ${formatString(projectData.description, q, true)},`);
236751
236193
  }
236752
- lines.push(`${indentation}name: ${formatString7(credentialData.name, q)},`);
236753
- lines.push(`${indentation}type: ${formatString7(credentialData.type, q)},`);
236754
- lines.push(
236755
- `${indentation}credentialStoreId: ${formatString7(credentialData.credentialStoreId, q)},`
236756
- );
236757
- if (credentialData.description) {
236758
- lines.push(`${indentation}description: ${formatString7(credentialData.description, q, true)},`);
236194
+ if (shouldInclude(projectData.models)) {
236195
+ lines.push(`${indentation}models: ${formatObject(projectData.models, style, 2)},`);
236759
236196
  }
236760
- if (credentialData.retrievalParams) {
236761
- const formattedParams = formatRetrievalParams(credentialData.retrievalParams, style, 1);
236762
- if (formattedParams.includes("\n")) {
236763
- lines.push(`${indentation}retrievalParams: ${formattedParams},`);
236764
- } else {
236765
- lines.push(`${indentation}retrievalParams: ${formattedParams},`);
236197
+ if (shouldInclude(projectData.stopWhen)) {
236198
+ lines.push(`${indentation}stopWhen: {`);
236199
+ if (projectData.stopWhen.transferCountIs !== void 0) {
236200
+ lines.push(
236201
+ `${indentation}${indentation}transferCountIs: ${projectData.stopWhen.transferCountIs}, // Max transfers for agents`
236202
+ );
236203
+ }
236204
+ if (projectData.stopWhen.stepCountIs !== void 0) {
236205
+ lines.push(
236206
+ `${indentation}${indentation}stepCountIs: ${projectData.stopWhen.stepCountIs} // Max steps for sub-agents`
236207
+ );
236208
+ }
236209
+ if (lines.length > 1) {
236210
+ const lastLine = lines[lines.length - 1];
236211
+ if (lastLine.includes(",") && (lastLine.includes("//") || lastLine.endsWith(","))) {
236212
+ if (lastLine.includes("//")) {
236213
+ lines[lines.length - 1] = lastLine.replace(", //", " //");
236214
+ } else {
236215
+ lines[lines.length - 1] = lastLine.slice(0, -1);
236216
+ }
236217
+ }
236766
236218
  }
236767
- } else {
236768
- const defaultKey = credentialId.toUpperCase().replace(/-/g, "_");
236769
- lines.push(`${indentation}retrievalParams: {`);
236770
- lines.push(`${indentation}${indentation}${q}key${q}: ${formatString7(defaultKey, q)}`);
236771
236219
  lines.push(`${indentation}},`);
236772
236220
  }
236773
- if (lines.length > 0 && lines[lines.length - 1].endsWith(",")) {
236774
- lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
236221
+ if (shouldInclude(projectData.agents)) {
236222
+ const agentsArray = registry2 ? registry2.formatReferencesForCode(projectData.agents, "agent", style, 2) : "[]";
236223
+ lines.push(`${indentation}agents: () => ${agentsArray},`);
236224
+ }
236225
+ if (shouldInclude(projectData.tools)) {
236226
+ const toolsArray = registry2 ? registry2.formatReferencesForCode(projectData.tools, "tool", style, 2) : "[]";
236227
+ lines.push(`${indentation}tools: () => ${toolsArray},`);
236228
+ }
236229
+ if (shouldInclude(projectData.externalAgents)) {
236230
+ const externalAgentsArray = registry2 ? registry2.formatReferencesForCode(projectData.externalAgents, "externalAgent", style, 2) : "[]";
236231
+ lines.push(`${indentation}externalAgents: () => ${externalAgentsArray},`);
236232
+ }
236233
+ if (shouldInclude(projectData.dataComponents)) {
236234
+ const dataComponentsArray = registry2 ? registry2.formatReferencesForCode(projectData.dataComponents, "dataComponent", style, 2) : "[]";
236235
+ lines.push(`${indentation}dataComponents: () => ${dataComponentsArray},`);
236236
+ }
236237
+ if (shouldInclude(projectData.artifactComponents)) {
236238
+ const artifactComponentsArray = registry2 ? registry2.formatReferencesForCode(
236239
+ projectData.artifactComponents,
236240
+ "artifactComponent",
236241
+ style,
236242
+ 2
236243
+ ) : "[]";
236244
+ lines.push(`${indentation}artifactComponents: () => ${artifactComponentsArray},`);
236245
+ }
236246
+ if (shouldInclude(projectData.credentialReferences)) {
236247
+ const credentialReferencesArray = registry2 ? registry2.formatReferencesForCode(projectData.credentialReferences, "credential", style, 2) : "[]";
236248
+ lines.push(`${indentation}credentialReferences: () => ${credentialReferencesArray},`);
236775
236249
  }
236250
+ removeTrailingComma(lines);
236776
236251
  lines.push(`})${semi}`);
236777
236252
  return lines.join("\n");
236778
236253
  }
236779
- function generateCredentialImports(credentialId, credentialData, style = DEFAULT_STYLE7) {
236780
- const { quotes, semicolons } = style;
236781
- const q = quotes === "single" ? "'" : '"';
236782
- const semi = semicolons ? ";" : "";
236254
+ function generateProjectImports(projectId, projectData, style = DEFAULT_STYLE, registry2) {
236783
236255
  const imports = [];
236784
- imports.push(`import { credential } from ${q}@inkeep/agents-sdk${q}${semi}`);
236256
+ imports.push(generateImport(["project"], "@inkeep/agents-sdk", style));
236257
+ if (registry2) {
236258
+ const currentFilePath = "index.ts";
236259
+ const referencedComponents = [];
236260
+ if (projectData.agents) {
236261
+ let agentIds = [];
236262
+ if (Array.isArray(projectData.agents)) {
236263
+ agentIds = projectData.agents;
236264
+ } else if (typeof projectData.agents === "object") {
236265
+ agentIds = Object.keys(projectData.agents);
236266
+ }
236267
+ for (const agentId of agentIds) {
236268
+ referencedComponents.push({ id: agentId, type: "agent" });
236269
+ }
236270
+ }
236271
+ if (projectData.tools) {
236272
+ let toolIds = [];
236273
+ if (Array.isArray(projectData.tools)) {
236274
+ toolIds = projectData.tools;
236275
+ } else if (typeof projectData.tools === "object") {
236276
+ toolIds = Object.keys(projectData.tools);
236277
+ }
236278
+ for (const toolId of toolIds) {
236279
+ let componentType = "tool";
236280
+ if (registry2 && registry2.get(toolId, "functionTool")) {
236281
+ componentType = "functionTool";
236282
+ } else if (registry2 && registry2.get(toolId, "tool")) {
236283
+ componentType = "tool";
236284
+ }
236285
+ referencedComponents.push({ id: toolId, type: componentType });
236286
+ }
236287
+ }
236288
+ if (projectData.externalAgents) {
236289
+ let extAgentIds = [];
236290
+ if (Array.isArray(projectData.externalAgents)) {
236291
+ extAgentIds = projectData.externalAgents;
236292
+ } else if (typeof projectData.externalAgents === "object") {
236293
+ extAgentIds = Object.keys(projectData.externalAgents);
236294
+ }
236295
+ for (const extAgentId of extAgentIds) {
236296
+ referencedComponents.push({ id: extAgentId, type: "externalAgent" });
236297
+ }
236298
+ }
236299
+ if (projectData.dataComponents) {
236300
+ let dataCompIds = [];
236301
+ if (Array.isArray(projectData.dataComponents)) {
236302
+ dataCompIds = projectData.dataComponents;
236303
+ } else if (typeof projectData.dataComponents === "object") {
236304
+ dataCompIds = Object.keys(projectData.dataComponents);
236305
+ }
236306
+ for (const dataCompId of dataCompIds) {
236307
+ referencedComponents.push({ id: dataCompId, type: "dataComponent" });
236308
+ }
236309
+ }
236310
+ if (projectData.artifactComponents) {
236311
+ let artifactCompIds = [];
236312
+ if (Array.isArray(projectData.artifactComponents)) {
236313
+ artifactCompIds = projectData.artifactComponents;
236314
+ } else if (typeof projectData.artifactComponents === "object") {
236315
+ artifactCompIds = Object.keys(projectData.artifactComponents);
236316
+ }
236317
+ for (const artifactCompId of artifactCompIds) {
236318
+ referencedComponents.push({ id: artifactCompId, type: "artifactComponent" });
236319
+ }
236320
+ }
236321
+ if (projectData.credentialReferences) {
236322
+ let credIds = [];
236323
+ if (Array.isArray(projectData.credentialReferences)) {
236324
+ credIds = projectData.credentialReferences;
236325
+ } else if (typeof projectData.credentialReferences === "object") {
236326
+ credIds = Object.keys(projectData.credentialReferences);
236327
+ }
236328
+ for (const credId of credIds) {
236329
+ referencedComponents.push({ id: credId, type: "credential" });
236330
+ }
236331
+ }
236332
+ if (referencedComponents.length > 0) {
236333
+ const componentImports = registry2.getImportsForFile(currentFilePath, referencedComponents);
236334
+ imports.push(...componentImports);
236335
+ }
236336
+ }
236785
236337
  return imports;
236786
236338
  }
236787
- function generateCredentialFile(credentialId, credentialData, style = DEFAULT_STYLE7) {
236788
- const imports = generateCredentialImports(credentialId, credentialData, style);
236789
- const definition = generateCredentialDefinition(credentialId, credentialData, style);
236790
- return imports.join("\n") + "\n\n" + definition + "\n";
236339
+ function generateProjectFile(projectId, projectData, style = DEFAULT_STYLE, registry2) {
236340
+ const imports = generateProjectImports(projectId, projectData, style, registry2);
236341
+ const definition = generateProjectDefinition(projectId, projectData, style, registry2);
236342
+ return generateFileContent(imports, [definition]);
236791
236343
  }
236792
- var DEFAULT_STYLE7;
236793
- var init_credential_generator = __esm({
236794
- "src/commands/pull-v3/components/credential-generator.ts"() {
236344
+ var init_project_generator = __esm({
236345
+ "src/commands/pull-v3/components/project-generator.ts"() {
236795
236346
  "use strict";
236796
236347
  init_esm_shims();
236797
- DEFAULT_STYLE7 = {
236798
- quotes: "single",
236799
- semicolons: true,
236800
- indentation: " "
236801
- };
236348
+ init_generator_utils();
236802
236349
  }
236803
236350
  });
236804
236351
 
236805
- // src/commands/pull-v3/components/environment-generator.ts
236806
- var environment_generator_exports = {};
236807
- __export(environment_generator_exports, {
236808
- generateEnvironmentFile: () => generateEnvironmentFile,
236809
- generateEnvironmentIndexDefinition: () => generateEnvironmentIndexDefinition,
236810
- generateEnvironmentIndexFile: () => generateEnvironmentIndexFile,
236811
- generateEnvironmentIndexImports: () => generateEnvironmentIndexImports,
236812
- generateEnvironmentSettingsDefinition: () => generateEnvironmentSettingsDefinition,
236813
- generateEnvironmentSettingsFile: () => generateEnvironmentSettingsFile,
236814
- generateEnvironmentSettingsImports: () => generateEnvironmentSettingsImports
236815
- });
236352
+ // src/commands/pull-v3/components/status-component-generator.ts
236353
+ import { jsonSchemaToZod as jsonSchemaToZod5 } from "json-schema-to-zod";
236354
+ function toCamelCase7(str) {
236355
+ return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
236356
+ }
236816
236357
  function formatString8(str, quote = "'", multiline = false) {
236817
236358
  if (!str) return `${quote}${quote}`;
236818
236359
  if (multiline && (str.includes("\n") || str.length > 80)) {
@@ -236820,188 +236361,83 @@ function formatString8(str, quote = "'", multiline = false) {
236820
236361
  }
236821
236362
  return `${quote}${str.replace(new RegExp(quote, "g"), "\\" + quote)}${quote}`;
236822
236363
  }
236823
- function formatCredentialsObject(credentials, style, indentLevel) {
236824
- if (!credentials || typeof credentials !== "object") {
236825
- return "{}";
236826
- }
236827
- const { quotes, indentation } = style;
236828
- const q = quotes === "single" ? "'" : '"';
236829
- const baseIndent = indentation.repeat(indentLevel);
236830
- const indent = indentation.repeat(indentLevel + 1);
236831
- const nestedIndent = indentation.repeat(indentLevel + 2);
236832
- const lines = ["{"];
236833
- for (const [key, credentialData] of Object.entries(credentials)) {
236834
- lines.push(`${indent}${formatString8(key, q)}: {`);
236835
- if (credentialData.id) {
236836
- lines.push(`${nestedIndent}id: ${formatString8(credentialData.id, q)},`);
236837
- }
236838
- if (credentialData.name) {
236839
- lines.push(`${nestedIndent}name: ${formatString8(credentialData.name, q)},`);
236840
- }
236841
- if (credentialData.type) {
236842
- if (typeof credentialData.type === "string") {
236843
- const enumValue = credentialData.type === "memory" ? "CredentialStoreType.memory" : credentialData.type === "env" ? "CredentialStoreType.env" : credentialData.type === "keychain" ? "CredentialStoreType.keychain" : formatString8(credentialData.type, q);
236844
- lines.push(`${nestedIndent}type: ${enumValue},`);
236845
- } else {
236846
- lines.push(`${nestedIndent}type: ${credentialData.type},`);
236847
- }
236848
- }
236849
- if (credentialData.credentialStoreId) {
236850
- lines.push(
236851
- `${nestedIndent}credentialStoreId: ${formatString8(credentialData.credentialStoreId, q)},`
236852
- );
236853
- }
236854
- if (credentialData.description) {
236855
- lines.push(`${nestedIndent}description: ${formatString8(credentialData.description, q)},`);
236856
- }
236857
- if (credentialData.retrievalParams) {
236858
- lines.push(`${nestedIndent}retrievalParams: {`);
236859
- for (const [paramKey, paramValue] of Object.entries(credentialData.retrievalParams)) {
236860
- if (paramValue === null || paramValue === void 0) {
236861
- continue;
236862
- }
236863
- if (typeof paramValue === "string") {
236864
- lines.push(`${nestedIndent}${indent}${paramKey}: ${formatString8(paramValue, q)},`);
236865
- } else {
236866
- lines.push(`${nestedIndent}${indent}${paramKey}: ${JSON.stringify(paramValue)},`);
236867
- }
236868
- }
236869
- const lastLineIndex = lines.length - 1;
236870
- if (lines[lastLineIndex].endsWith(",")) {
236871
- lines[lastLineIndex] = lines[lastLineIndex].slice(0, -1);
236872
- }
236873
- lines.push(`${nestedIndent}},`);
236874
- }
236875
- const lastPropIndex = lines.length - 1;
236876
- if (lines[lastPropIndex].endsWith(",")) {
236877
- lines[lastPropIndex] = lines[lastPropIndex].slice(0, -1);
236878
- }
236879
- lines.push(`${indent}},`);
236364
+ function convertJsonSchemaToZod3(schema) {
236365
+ if (!schema || typeof schema !== "object") {
236366
+ return "z.any()";
236880
236367
  }
236881
- if (lines.length > 1 && lines[lines.length - 1].endsWith(",")) {
236882
- lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
236368
+ try {
236369
+ return jsonSchemaToZod5(schema);
236370
+ } catch (error) {
236371
+ console.warn("Failed to convert JSON schema to Zod:", error);
236372
+ return "z.any()";
236883
236373
  }
236884
- lines.push(`${baseIndent}}`);
236885
- return lines.join("\n");
236886
236374
  }
236887
- function generateEnvironmentSettingsDefinition(environmentName, environmentData, style = DEFAULT_STYLE8) {
236888
- if (!environmentName || typeof environmentName !== "string") {
236889
- throw new Error("environmentName is required and must be a string");
236890
- }
236891
- if (!environmentData || typeof environmentData !== "object") {
236892
- throw new Error(`environmentData is required for environment '${environmentName}'`);
236375
+ function generateStatusComponentDefinition(componentId, componentData, style = DEFAULT_STYLE8) {
236376
+ if (!componentId || typeof componentId !== "string") {
236377
+ throw new Error("componentId is required and must be a string");
236893
236378
  }
236894
- const { quotes, semicolons, indentation } = style;
236895
- const q = quotes === "single" ? "'" : '"';
236896
- const semi = semicolons ? ";" : "";
236897
- const lines = [];
236898
- lines.push(`export const ${environmentName} = registerEnvironmentSettings({`);
236899
- if (environmentData.credentials && Object.keys(environmentData.credentials).length > 0) {
236900
- const formattedCredentials = formatCredentialsObject(environmentData.credentials, style, 1);
236901
- lines.push(`${indentation}credentials: ${formattedCredentials},`);
236902
- } else {
236903
- lines.push(`${indentation}credentials: {},`);
236379
+ if (!componentData || typeof componentData !== "object") {
236380
+ throw new Error(`componentData is required for status component '${componentId}'`);
236904
236381
  }
236905
- if (lines.length > 1 && lines[lines.length - 1].endsWith(",")) {
236906
- lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
236382
+ const requiredFields = ["type"];
236383
+ const missingFields = requiredFields.filter(
236384
+ (field) => !componentData[field] || componentData[field] === null || componentData[field] === void 0
236385
+ );
236386
+ if (missingFields.length > 0) {
236387
+ throw new Error(
236388
+ `Missing required fields for status component '${componentId}': ${missingFields.join(", ")}`
236389
+ );
236907
236390
  }
236908
- lines.push(`})${semi}`);
236909
- return lines.join("\n");
236910
- }
236911
- function generateEnvironmentIndexDefinition(environments, style = DEFAULT_STYLE8) {
236912
236391
  const { quotes, semicolons, indentation } = style;
236913
236392
  const q = quotes === "single" ? "'" : '"';
236914
236393
  const semi = semicolons ? ";" : "";
236394
+ const componentVarName = toCamelCase7(componentId);
236915
236395
  const lines = [];
236916
- lines.push(`export const envSettings = createEnvironmentSettings({`);
236917
- for (const envName of environments) {
236918
- lines.push(`${indentation}${envName},`);
236396
+ lines.push(`export const ${componentVarName} = statusComponent({`);
236397
+ lines.push(`${indentation}type: ${formatString8(componentData.type, q)},`);
236398
+ if (componentData.description) {
236399
+ lines.push(`${indentation}description: ${formatString8(componentData.description, q, true)},`);
236919
236400
  }
236920
- if (lines.length > 1 && lines[lines.length - 1].endsWith(",")) {
236401
+ const schema = componentData.detailsSchema || componentData.schema;
236402
+ if (schema) {
236403
+ const zodSchema = convertJsonSchemaToZod3(schema);
236404
+ if (zodSchema.includes("\n")) {
236405
+ const schemaLines = zodSchema.split("\n");
236406
+ lines.push(`${indentation}detailsSchema: ${schemaLines[0]}`);
236407
+ schemaLines.slice(1, -1).forEach((line) => {
236408
+ lines[lines.length - 1] += "\n" + indentation + line;
236409
+ });
236410
+ lines[lines.length - 1] += "\n" + indentation + schemaLines[schemaLines.length - 1] + ",";
236411
+ } else {
236412
+ lines.push(`${indentation}detailsSchema: ${zodSchema},`);
236413
+ }
236414
+ }
236415
+ if (lines.length > 0 && lines[lines.length - 1].endsWith(",")) {
236921
236416
  lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
236922
236417
  }
236923
236418
  lines.push(`})${semi}`);
236924
236419
  return lines.join("\n");
236925
236420
  }
236926
- function generateEnvironmentSettingsImports(environmentName, environmentData, style = DEFAULT_STYLE8) {
236927
- const { quotes, semicolons } = style;
236928
- const q = quotes === "single" ? "'" : '"';
236929
- const semi = semicolons ? ";" : "";
236930
- const imports = [];
236931
- imports.push(`import { registerEnvironmentSettings } from ${q}@inkeep/agents-sdk${q}${semi}`);
236932
- const needsCredentialStoreType = environmentData.credentials && Object.values(environmentData.credentials).some(
236933
- (cred) => typeof cred.type === "string" && ["memory", "env", "keychain"].includes(cred.type)
236934
- );
236935
- if (needsCredentialStoreType) {
236936
- imports.push(`import { CredentialStoreType } from ${q}@inkeep/agents-core${q}${semi}`);
236937
- }
236938
- return imports;
236939
- }
236940
- function generateEnvironmentIndexImports(environments, style = DEFAULT_STYLE8) {
236421
+ function generateStatusComponentImports(componentId, componentData, style = DEFAULT_STYLE8) {
236941
236422
  const { quotes, semicolons } = style;
236942
236423
  const q = quotes === "single" ? "'" : '"';
236943
236424
  const semi = semicolons ? ";" : "";
236944
236425
  const imports = [];
236945
- imports.push(`import { createEnvironmentSettings } from ${q}@inkeep/agents-sdk${q}${semi}`);
236946
- for (const envName of environments) {
236947
- imports.push(`import { ${envName} } from ${q}./${envName}.env${q}${semi}`);
236426
+ imports.push(`import { statusComponent } from ${q}@inkeep/agents-sdk${q}${semi}`);
236427
+ const schema = componentData.detailsSchema || componentData.schema;
236428
+ if (schema) {
236429
+ imports.push(`import { z } from ${q}zod${q}${semi}`);
236948
236430
  }
236949
236431
  return imports;
236950
236432
  }
236951
- function generateEnvironmentSettingsFile(environmentName, environmentData, style = DEFAULT_STYLE8) {
236952
- const imports = generateEnvironmentSettingsImports(environmentName, environmentData, style);
236953
- const definition = generateEnvironmentSettingsDefinition(environmentName, environmentData, style);
236954
- return imports.join("\n") + "\n\n" + definition + "\n";
236955
- }
236956
- function generateEnvironmentIndexFile(environments, style = DEFAULT_STYLE8) {
236957
- const imports = generateEnvironmentIndexImports(environments, style);
236958
- const definition = generateEnvironmentIndexDefinition(environments, style);
236433
+ function generateStatusComponentFile(componentId, componentData, style = DEFAULT_STYLE8) {
236434
+ const imports = generateStatusComponentImports(componentId, componentData, style);
236435
+ const definition = generateStatusComponentDefinition(componentId, componentData, style);
236959
236436
  return imports.join("\n") + "\n\n" + definition + "\n";
236960
236437
  }
236961
- function generateEnvironmentFile(environmentName, environmentData, style = DEFAULT_STYLE8, registry2) {
236962
- if (registry2 && environmentData.credentials && Array.isArray(environmentData.credentials)) {
236963
- const { quotes, semicolons, indentation } = style;
236964
- const q = quotes === "single" ? "'" : '"';
236965
- const semi = semicolons ? ";" : "";
236966
- const imports = [];
236967
- const credentialRefs = [];
236968
- imports.push(`import { registerEnvironmentSettings } from ${q}@inkeep/agents-sdk${q}${semi}`);
236969
- for (const credentialId of environmentData.credentials) {
236970
- const credentialComponent = registry2.get(credentialId, "credential");
236971
- if (credentialComponent) {
236972
- const relativePath = `../credentials/${credentialId}`;
236973
- imports.push(`import { ${credentialComponent.name} } from ${q}${relativePath}${q}${semi}`);
236974
- credentialRefs.push(credentialComponent.name);
236975
- }
236976
- }
236977
- const lines = [];
236978
- lines.push(...imports);
236979
- lines.push("");
236980
- lines.push(`export const ${environmentName} = registerEnvironmentSettings({`);
236981
- if (credentialRefs.length > 0) {
236982
- lines.push(`${indentation}credentials: {`);
236983
- for (let i = 0; i < environmentData.credentials.length; i++) {
236984
- const credentialId = environmentData.credentials[i];
236985
- const credentialVarName = credentialRefs[i];
236986
- const isLast = i === credentialRefs.length - 1;
236987
- const validKey = registry2.getVariableName(credentialId, "credential");
236988
- lines.push(
236989
- `${indentation}${indentation}${validKey}: ${credentialVarName}${isLast ? "" : ","}`
236990
- );
236991
- }
236992
- lines.push(`${indentation}}`);
236993
- } else {
236994
- lines.push(`${indentation}credentials: {}`);
236995
- }
236996
- lines.push(`})${semi}`);
236997
- lines.push("");
236998
- return lines.join("\n");
236999
- }
237000
- return generateEnvironmentSettingsFile(environmentName, environmentData, style);
237001
- }
237002
236438
  var DEFAULT_STYLE8;
237003
- var init_environment_generator = __esm({
237004
- "src/commands/pull-v3/components/environment-generator.ts"() {
236439
+ var init_status_component_generator = __esm({
236440
+ "src/commands/pull-v3/components/status-component-generator.ts"() {
237005
236441
  "use strict";
237006
236442
  init_esm_shims();
237007
236443
  DEFAULT_STYLE8 = {
@@ -237012,245 +236448,809 @@ var init_environment_generator = __esm({
237012
236448
  }
237013
236449
  });
237014
236450
 
237015
- // src/commands/pull-v3/components/context-config-generator.ts
237016
- import { jsonSchemaToZod as jsonSchemaToZod5 } from "json-schema-to-zod";
237017
- function processFetchConfigTemplates(fetchConfig, headersVarName) {
237018
- const processValue = (value) => {
237019
- if (typeof value === "string") {
237020
- if (hasTemplateVariables(value)) {
237021
- const convertedStr = value.replace(
237022
- /\{\{headers\.([^}]+)\}\}/g,
237023
- `\${${headersVarName}.toTemplate("$1")}`
237024
- );
237025
- return `\`${convertedStr.replace(/`/g, "\\`")}\``;
237026
- } else {
237027
- return `'${value.replace(/'/g, "\\'")}'`;
237028
- }
237029
- } else if (typeof value === "object" && value !== null) {
237030
- return processObject(value);
237031
- } else {
237032
- return JSON.stringify(value);
236451
+ // src/commands/pull-v3/components/sub-agent-generator.ts
236452
+ function hasDistinctModels2(subAgentModels, parentModels) {
236453
+ if (!subAgentModels) return false;
236454
+ if (!parentModels) return !!subAgentModels;
236455
+ const modelTypes = ["base", "structuredOutput", "summarizer"];
236456
+ for (const type of modelTypes) {
236457
+ const subAgentModel = subAgentModels[type]?.model;
236458
+ const parentModel = parentModels[type]?.model;
236459
+ if (subAgentModel !== parentModel) {
236460
+ return true;
237033
236461
  }
237034
- };
237035
- const processObject = (obj) => {
237036
- if (Array.isArray(obj)) {
237037
- const items = obj.map((item) => processValue(item)).join(", ");
237038
- return `[${items}]`;
236462
+ if (subAgentModel && parentModel) {
236463
+ const subAgentOptions = subAgentModels[type]?.providerOptions;
236464
+ const parentOptions = parentModels[type]?.providerOptions;
236465
+ if (subAgentOptions !== parentOptions) {
236466
+ if (!subAgentOptions && !parentOptions) {
236467
+ continue;
236468
+ }
236469
+ if (!subAgentOptions || !parentOptions) {
236470
+ return true;
236471
+ }
236472
+ if (JSON.stringify(subAgentOptions) !== JSON.stringify(parentOptions)) {
236473
+ return true;
236474
+ }
236475
+ }
237039
236476
  }
237040
- const entries = Object.entries(obj).map(([key, val]) => {
237041
- const processedKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : `'${key}'`;
237042
- return `${processedKey}: ${processValue(val)}`;
237043
- });
237044
- return `{
237045
- ${entries.join(",\n ")}
237046
- }`;
237047
- };
237048
- return processObject(fetchConfig);
237049
- }
237050
- function generateHeadersDefinition(headersId, headersData, style = DEFAULT_STYLE) {
237051
- const { quotes, semicolons, indentation } = style;
237052
- const q = quotes === "single" ? "'" : '"';
237053
- const semi = semicolons ? ";" : "";
237054
- const headersVarName = toCamelCase(headersId);
237055
- const lines = [];
237056
- lines.push(`const ${headersVarName} = headers({`);
237057
- if (headersData.schema) {
237058
- const zodSchema = jsonSchemaToZod5(headersData.schema, { module: "none" });
237059
- lines.push(`${indentation}schema: ${zodSchema},`);
237060
236477
  }
237061
- removeTrailingComma(lines);
237062
- lines.push(`})${semi}`);
237063
- return lines.join("\n");
236478
+ return false;
237064
236479
  }
237065
- function generateFetchDefinitionDefinition(fetchId, fetchData, style = DEFAULT_STYLE, headersVarName) {
237066
- const { quotes, semicolons, indentation } = style;
237067
- const q = quotes === "single" ? "'" : '"';
237068
- const semi = semicolons ? ";" : "";
237069
- const fetchVarName = toCamelCase(fetchId);
237070
- const lines = [];
237071
- lines.push(`const ${fetchVarName} = fetchDefinition({`);
237072
- lines.push(`${indentation}id: ${formatString(fetchData.id || fetchId, q)},`);
237073
- if (fetchData.name) {
237074
- lines.push(`${indentation}name: ${formatString(fetchData.name, q)},`);
236480
+ function generateSubAgentDefinition(agentId, agentData, style = DEFAULT_STYLE, registry2, parentAgentId, contextConfigData, parentModels) {
236481
+ if (!agentId || typeof agentId !== "string") {
236482
+ throw new Error("agentId is required and must be a string");
237075
236483
  }
237076
- if (fetchData.trigger) {
237077
- lines.push(`${indentation}trigger: ${formatString(fetchData.trigger, q)},`);
236484
+ if (!agentData || typeof agentData !== "object") {
236485
+ throw new Error(`agentData is required for sub-agent '${agentId}'`);
237078
236486
  }
237079
- if (fetchData.fetchConfig) {
237080
- const processedFetchConfig = processFetchConfigTemplates(
237081
- fetchData.fetchConfig,
237082
- headersVarName || "headers"
236487
+ const requiredFields = ["name", "description", "prompt"];
236488
+ const missingFields = requiredFields.filter(
236489
+ (field) => !agentData[field] || agentData[field] === null || agentData[field] === void 0
236490
+ );
236491
+ if (missingFields.length > 0) {
236492
+ throw new Error(
236493
+ `Missing required fields for sub-agent '${agentId}': ${missingFields.join(", ")}`
237083
236494
  );
237084
- lines.push(`${indentation}fetchConfig: ${processedFetchConfig},`);
237085
236495
  }
237086
- if (fetchData.responseSchema) {
237087
- const zodSchema = jsonSchemaToZod5(fetchData.responseSchema, { module: "none" });
237088
- lines.push(`${indentation}responseSchema: ${zodSchema},`);
236496
+ const { quotes, semicolons, indentation } = style;
236497
+ const q = quotes === "single" ? "'" : '"';
236498
+ const semi = semicolons ? ";" : "";
236499
+ let agentVarName = toCamelCase(agentId);
236500
+ if (registry2) {
236501
+ const registryVarName = registry2.getVariableName(agentId, "subAgent");
236502
+ if (registryVarName) {
236503
+ agentVarName = registryVarName;
236504
+ }
237089
236505
  }
237090
- if (fetchData.defaultValue) {
237091
- if (typeof fetchData.defaultValue === "string") {
237092
- lines.push(`${indentation}defaultValue: ${formatString(fetchData.defaultValue, q)},`);
236506
+ const lines = [];
236507
+ lines.push(`export const ${agentVarName} = subAgent({`);
236508
+ lines.push(`${indentation}id: ${formatString(agentId, q)},`);
236509
+ lines.push(`${indentation}name: ${formatString(agentData.name, q)},`);
236510
+ lines.push(`${indentation}description: ${formatString(agentData.description, q, true)},`);
236511
+ if (agentData.prompt !== void 0 && agentData.prompt !== null) {
236512
+ if (hasTemplateVariables(agentData.prompt) && parentAgentId && registry2 && contextConfigData) {
236513
+ const contextVarName = registry2.getVariableName(contextConfigData.id, "contextConfig");
236514
+ if (!contextVarName) {
236515
+ throw new Error(
236516
+ `Failed to resolve context config variable name for: ${contextConfigData.id}`
236517
+ );
236518
+ }
236519
+ const headersVarName = "headersSchema";
236520
+ lines.push(
236521
+ `${indentation}prompt: ${formatPromptWithContext(agentData.prompt, contextVarName, headersVarName, contextConfigData, q, true)},`
236522
+ );
237093
236523
  } else {
237094
- lines.push(`${indentation}defaultValue: ${JSON.stringify(fetchData.defaultValue)},`);
236524
+ lines.push(`${indentation}prompt: ${formatString(agentData.prompt, q, true)},`);
237095
236525
  }
237096
236526
  }
237097
- removeTrailingComma(lines);
237098
- lines.push(`})${semi}`);
237099
- return lines.join("\n");
237100
- }
237101
- function generateContextConfigDefinition(contextId, contextData, style = DEFAULT_STYLE, registry2, agentId, headersVarName) {
237102
- if (!contextId || typeof contextId !== "string") {
237103
- throw new Error("contextId is required and must be a string");
236527
+ if (agentData.models && hasDistinctModels2(agentData.models, parentModels)) {
236528
+ lines.push(`${indentation}models: {`);
236529
+ if (agentData.models.base?.model) {
236530
+ lines.push(`${indentation}${indentation}base: {`);
236531
+ lines.push(
236532
+ `${indentation}${indentation}${indentation}model: ${formatString(agentData.models.base.model, q)}`
236533
+ );
236534
+ if (agentData.models.base.providerOptions) {
236535
+ lines.push(`${indentation}${indentation}${indentation},`);
236536
+ lines.push(
236537
+ `${indentation}${indentation}${indentation}providerOptions: ${JSON.stringify(agentData.models.base.providerOptions)}`
236538
+ );
236539
+ }
236540
+ lines.push(`${indentation}${indentation}},`);
236541
+ }
236542
+ if (agentData.models.structuredOutput?.model) {
236543
+ lines.push(`${indentation}${indentation}structuredOutput: {`);
236544
+ lines.push(
236545
+ `${indentation}${indentation}${indentation}model: ${formatString(agentData.models.structuredOutput.model, q)}`
236546
+ );
236547
+ if (agentData.models.structuredOutput.providerOptions) {
236548
+ lines.push(`${indentation}${indentation}${indentation},`);
236549
+ lines.push(
236550
+ `${indentation}${indentation}${indentation}providerOptions: ${JSON.stringify(agentData.models.structuredOutput.providerOptions)}`
236551
+ );
236552
+ }
236553
+ lines.push(`${indentation}${indentation}},`);
236554
+ }
236555
+ if (agentData.models.summarizer?.model) {
236556
+ lines.push(`${indentation}${indentation}summarizer: {`);
236557
+ lines.push(
236558
+ `${indentation}${indentation}${indentation}model: ${formatString(agentData.models.summarizer.model, q)}`
236559
+ );
236560
+ if (agentData.models.summarizer.providerOptions) {
236561
+ lines.push(`${indentation}${indentation}${indentation},`);
236562
+ lines.push(
236563
+ `${indentation}${indentation}${indentation}providerOptions: ${JSON.stringify(agentData.models.summarizer.providerOptions)}`
236564
+ );
236565
+ }
236566
+ lines.push(`${indentation}${indentation}},`);
236567
+ }
236568
+ removeTrailingComma(lines);
236569
+ lines.push(`${indentation}},`);
237104
236570
  }
237105
- if (!contextData || typeof contextData !== "object") {
237106
- throw new Error(`contextData is required for context config '${contextId}'`);
236571
+ if (agentData.canUse && Array.isArray(agentData.canUse) && agentData.canUse.length > 0) {
236572
+ const toolReferences = [];
236573
+ if (!registry2) {
236574
+ throw new Error("Registry is required for canUse generation");
236575
+ }
236576
+ for (const toolRelation of agentData.canUse) {
236577
+ const toolId = toolRelation.toolId;
236578
+ let toolVarName = registry2.getVariableName(toolId, "tool");
236579
+ if (!toolVarName) {
236580
+ toolVarName = registry2.getVariableName(toolId, "functionTool");
236581
+ }
236582
+ if (!toolVarName) {
236583
+ throw new Error(
236584
+ `Failed to resolve variable name for tool: ${toolId} (tried both 'tool' and 'functionTool' types)`
236585
+ );
236586
+ }
236587
+ const hasToolSelection = toolRelation.toolSelection && toolRelation.toolSelection.length > 0;
236588
+ const hasHeaders = toolRelation.headers && Object.keys(toolRelation.headers).length > 0;
236589
+ if (hasToolSelection || hasHeaders) {
236590
+ const configLines = [];
236591
+ if (hasToolSelection) {
236592
+ const selectedToolsStr = JSON.stringify(toolRelation.toolSelection);
236593
+ configLines.push(`selectedTools: ${selectedToolsStr}`);
236594
+ }
236595
+ if (hasHeaders) {
236596
+ const headersStr = JSON.stringify(toolRelation.headers);
236597
+ configLines.push(`headers: ${headersStr}`);
236598
+ }
236599
+ const configStr = configLines.join(", ");
236600
+ const finalRef = `${toolVarName}.with({ ${configStr} })`;
236601
+ toolReferences.push(finalRef);
236602
+ } else {
236603
+ toolReferences.push(toolVarName);
236604
+ }
236605
+ }
236606
+ const { indentation: indent } = style;
236607
+ const nestedIndent = indent.repeat(2);
236608
+ if (toolReferences.length === 1) {
236609
+ lines.push(`${indentation}canUse: () => [${toolReferences[0]}],`);
236610
+ } else {
236611
+ lines.push(`${indentation}canUse: () => [`);
236612
+ toolReferences.forEach((ref, index2) => {
236613
+ const isLast = index2 === toolReferences.length - 1;
236614
+ lines.push(`${indentation}${nestedIndent}${ref}${isLast ? "" : ","}`);
236615
+ });
236616
+ lines.push(`${indentation}],`);
236617
+ }
237107
236618
  }
237108
- const { quotes, semicolons, indentation } = style;
237109
- const q = quotes === "single" ? "'" : '"';
237110
- const semi = semicolons ? ";" : "";
237111
- const contextVarName = (() => {
236619
+ if (agentData.canDelegateTo && Array.isArray(agentData.canDelegateTo) && agentData.canDelegateTo.length > 0) {
237112
236620
  if (!registry2) {
237113
- throw new Error("Registry is required for context config variable name generation");
236621
+ throw new Error("Registry is required for canDelegateTo generation");
237114
236622
  }
237115
- const varName = registry2.getVariableName(contextId, "contextConfig");
237116
- if (!varName) {
237117
- throw new Error(`Failed to resolve variable name for context config: ${contextId}`);
236623
+ const delegateReferences = [];
236624
+ for (const delegateRelation of agentData.canDelegateTo) {
236625
+ let targetAgentId;
236626
+ let targetType;
236627
+ let hasHeaders = false;
236628
+ if (typeof delegateRelation === "string") {
236629
+ targetAgentId = delegateRelation;
236630
+ targetType = "subAgent";
236631
+ hasHeaders = false;
236632
+ } else if (delegateRelation && typeof delegateRelation === "object") {
236633
+ hasHeaders = delegateRelation.headers && Object.keys(delegateRelation.headers).length > 0;
236634
+ if (delegateRelation.externalAgentId) {
236635
+ targetAgentId = delegateRelation.externalAgentId;
236636
+ targetType = "externalAgent";
236637
+ } else if (delegateRelation.agentId) {
236638
+ targetAgentId = delegateRelation.agentId;
236639
+ targetType = "agent";
236640
+ } else if (delegateRelation.subAgentId) {
236641
+ targetAgentId = delegateRelation.subAgentId;
236642
+ targetType = "subAgent";
236643
+ } else {
236644
+ throw new Error(
236645
+ `Delegate relation missing agentId, subAgentId, or externalAgentId: ${JSON.stringify(delegateRelation)}`
236646
+ );
236647
+ }
236648
+ } else {
236649
+ throw new Error(`Invalid delegate relation format: ${JSON.stringify(delegateRelation)}`);
236650
+ }
236651
+ if (!targetAgentId) {
236652
+ throw new Error(
236653
+ `Failed to extract target agent ID from delegate relation: ${JSON.stringify(delegateRelation)}`
236654
+ );
236655
+ }
236656
+ const agentVarName2 = registry2.getVariableName(targetAgentId, targetType);
236657
+ if (!agentVarName2) {
236658
+ throw new Error(
236659
+ `Failed to resolve variable name for delegate ${targetType}: ${targetAgentId}`
236660
+ );
236661
+ }
236662
+ if (hasHeaders) {
236663
+ const headersStr = JSON.stringify(delegateRelation.headers);
236664
+ const finalRef = `${agentVarName2}.with({ headers: ${headersStr} })`;
236665
+ delegateReferences.push(finalRef);
236666
+ } else {
236667
+ delegateReferences.push(agentVarName2);
236668
+ }
236669
+ }
236670
+ const { indentation: indent } = style;
236671
+ const nestedIndent = indent.repeat(2);
236672
+ if (delegateReferences.length === 1) {
236673
+ lines.push(`${indentation}canDelegateTo: () => [${delegateReferences[0]}],`);
236674
+ } else {
236675
+ lines.push(`${indentation}canDelegateTo: () => [`);
236676
+ delegateReferences.forEach((ref, index2) => {
236677
+ const isLast = index2 === delegateReferences.length - 1;
236678
+ lines.push(`${indentation}${nestedIndent}${ref}${isLast ? "" : ","}`);
236679
+ });
236680
+ lines.push(`${indentation}],`);
237118
236681
  }
237119
- return varName;
237120
- })();
237121
- const lines = [];
237122
- lines.push(`const ${contextVarName} = contextConfig({`);
237123
- if (contextData.id) {
237124
- lines.push(`${indentation}id: ${formatString(contextData.id, q)},`);
237125
236682
  }
237126
- if (headersVarName) {
237127
- lines.push(`${indentation}headers: ${headersVarName},`);
237128
- } else if (contextData.headers) {
237129
- lines.push(`${indentation}headers: ${contextData.headers},`);
236683
+ if (agentData.canTransferTo && Array.isArray(agentData.canTransferTo) && agentData.canTransferTo.length > 0) {
236684
+ if (!registry2) {
236685
+ throw new Error("Registry is required for canTransferTo generation");
236686
+ }
236687
+ const transferArray = registry2.formatReferencesForCode(
236688
+ agentData.canTransferTo,
236689
+ "subAgent",
236690
+ style,
236691
+ 2
236692
+ );
236693
+ if (!transferArray) {
236694
+ throw new Error(
236695
+ `Failed to resolve variable names for canTransferTo agents: ${agentData.canTransferTo.join(", ")}`
236696
+ );
236697
+ }
236698
+ lines.push(`${indentation}canTransferTo: () => ${transferArray},`);
237130
236699
  }
237131
- if (contextData.contextVariables) {
237132
- const contextVarLines = [`${indentation}contextVariables: {`];
237133
- for (const [varName, varData] of Object.entries(contextData.contextVariables)) {
237134
- if (typeof varData === "string") {
237135
- contextVarLines.push(`${indentation} ${varName}: ${varData},`);
237136
- } else if (varData && typeof varData === "object" && (varData.fetchConfig || varData.responseSchema)) {
237137
- contextVarLines.push(`${indentation} ${varName},`);
237138
- }
236700
+ if (agentData.dataComponents && Array.isArray(agentData.dataComponents) && agentData.dataComponents.length > 0) {
236701
+ if (!registry2) {
236702
+ throw new Error("Registry is required for dataComponents generation");
237139
236703
  }
237140
- if (contextVarLines[contextVarLines.length - 1].endsWith(",")) {
237141
- contextVarLines[contextVarLines.length - 1] = contextVarLines[contextVarLines.length - 1].slice(0, -1);
236704
+ const dataComponentsArray = registry2.formatReferencesForCode(
236705
+ agentData.dataComponents,
236706
+ "dataComponent",
236707
+ style,
236708
+ 2
236709
+ );
236710
+ if (!dataComponentsArray) {
236711
+ throw new Error(
236712
+ `Failed to resolve variable names for data components: ${agentData.dataComponents.join(", ")}`
236713
+ );
237142
236714
  }
237143
- contextVarLines.push(`${indentation}},`);
237144
- lines.push(...contextVarLines);
236715
+ lines.push(`${indentation}dataComponents: () => ${dataComponentsArray},`);
236716
+ }
236717
+ if (agentData.artifactComponents && Array.isArray(agentData.artifactComponents) && agentData.artifactComponents.length > 0) {
236718
+ if (!registry2) {
236719
+ throw new Error("Registry is required for artifactComponents generation");
236720
+ }
236721
+ const artifactComponentsArray = registry2.formatReferencesForCode(
236722
+ agentData.artifactComponents,
236723
+ "artifactComponent",
236724
+ style,
236725
+ 2
236726
+ );
236727
+ if (!artifactComponentsArray) {
236728
+ throw new Error(
236729
+ `Failed to resolve variable names for artifact components: ${agentData.artifactComponents.join(", ")}`
236730
+ );
236731
+ }
236732
+ lines.push(`${indentation}artifactComponents: () => ${artifactComponentsArray},`);
236733
+ }
236734
+ if (agentData.stopWhen && agentData.stopWhen.stepCountIs !== void 0) {
236735
+ lines.push(`${indentation}stopWhen: {`);
236736
+ lines.push(
236737
+ `${indentation}${indentation}stepCountIs: ${agentData.stopWhen.stepCountIs} // Max tool calls + LLM responses`
236738
+ );
236739
+ lines.push(`${indentation}},`);
237145
236740
  }
237146
236741
  removeTrailingComma(lines);
237147
236742
  lines.push(`})${semi}`);
237148
236743
  return lines.join("\n");
237149
236744
  }
237150
- function generateContextConfigImports(contextId, contextData, style = DEFAULT_STYLE) {
236745
+ function generateSubAgentImports(agentId, agentData, style = DEFAULT_STYLE, registry2, parentAgentId, contextConfigData) {
237151
236746
  const imports = [];
237152
- const coreImports = [];
237153
- if (contextData.headers || hasHeadersInData(contextData)) {
237154
- coreImports.push("headers");
237155
- }
237156
- if (contextData.contextVariables && hasFetchDefinitionsInData(contextData)) {
237157
- coreImports.push("fetchDefinition");
237158
- }
237159
- coreImports.push("contextConfig");
237160
- if (coreImports.length > 0) {
237161
- imports.push(generateImport(coreImports, "@inkeep/agents-core", style));
236747
+ imports.push(generateImport(["subAgent"], "@inkeep/agents-sdk", style));
236748
+ if (hasTemplateVariables(agentData.prompt) && parentAgentId && registry2 && contextConfigData) {
236749
+ const contextConfigId = contextConfigData.id;
236750
+ const currentFilePath = `agents/sub-agents/${agentId}.ts`;
236751
+ const importStatement = registry2.getImportStatement(
236752
+ currentFilePath,
236753
+ contextConfigId,
236754
+ "contextConfig"
236755
+ );
236756
+ if (importStatement) {
236757
+ imports.push(importStatement);
236758
+ }
237162
236759
  }
237163
- if (hasSchemas(contextData)) {
237164
- imports.push(generateImport(["z"], "zod", style));
236760
+ if (registry2) {
236761
+ const currentFilePath = `agents/sub-agents/${agentId}.ts`;
236762
+ const referencedComponents = [];
236763
+ if (Array.isArray(agentData.canUse)) {
236764
+ for (const toolRelation of agentData.canUse) {
236765
+ const toolId = toolRelation.toolId;
236766
+ if (toolId) {
236767
+ let componentType = "tool";
236768
+ if (registry2.get(toolId, "functionTool")) {
236769
+ componentType = "functionTool";
236770
+ } else if (registry2.get(toolId, "tool")) {
236771
+ componentType = "tool";
236772
+ }
236773
+ referencedComponents.push({ id: toolId, type: componentType });
236774
+ }
236775
+ }
236776
+ }
236777
+ if (Array.isArray(agentData.canDelegateTo)) {
236778
+ for (const delegateRelation of agentData.canDelegateTo) {
236779
+ let targetId;
236780
+ let targetType = "agent";
236781
+ if (delegateRelation && typeof delegateRelation === "object") {
236782
+ if (delegateRelation.externalAgentId) {
236783
+ targetId = delegateRelation.externalAgentId;
236784
+ targetType = "externalAgent";
236785
+ } else if (delegateRelation.agentId) {
236786
+ targetId = delegateRelation.agentId;
236787
+ targetType = "agent";
236788
+ } else if (delegateRelation.subAgentId) {
236789
+ targetId = delegateRelation.subAgentId;
236790
+ targetType = "subAgent";
236791
+ }
236792
+ }
236793
+ if (targetId) {
236794
+ referencedComponents.push({ id: targetId, type: targetType });
236795
+ }
236796
+ }
236797
+ }
236798
+ if (Array.isArray(agentData.canTransferTo)) {
236799
+ for (const transferId of agentData.canTransferTo) {
236800
+ if (typeof transferId === "string") {
236801
+ referencedComponents.push({ id: transferId, type: "subAgent" });
236802
+ }
236803
+ }
236804
+ }
236805
+ if (Array.isArray(agentData.dataComponents)) {
236806
+ for (const dataCompId of agentData.dataComponents) {
236807
+ if (typeof dataCompId === "string") {
236808
+ referencedComponents.push({ id: dataCompId, type: "dataComponent" });
236809
+ }
236810
+ }
236811
+ }
236812
+ if (Array.isArray(agentData.artifactComponents)) {
236813
+ for (const artifactCompId of agentData.artifactComponents) {
236814
+ if (typeof artifactCompId === "string") {
236815
+ referencedComponents.push({ id: artifactCompId, type: "artifactComponent" });
236816
+ }
236817
+ }
236818
+ }
236819
+ if (referencedComponents.length > 0) {
236820
+ const componentImports = registry2.getImportsForFile(currentFilePath, referencedComponents);
236821
+ imports.push(...componentImports);
236822
+ }
237165
236823
  }
237166
236824
  return imports;
237167
236825
  }
237168
- function hasHeadersInData(contextData) {
237169
- return !!contextData.headers || JSON.stringify(contextData).includes("headers");
237170
- }
237171
- function hasFetchDefinitionsInData(contextData) {
237172
- return JSON.stringify(contextData).includes("fetchDefinition") || contextData.contextVariables && Object.values(contextData.contextVariables).some(
237173
- (v) => v && typeof v === "object" && (v.fetchConfig || v.responseSchema)
236826
+ function generateSubAgentFile(agentId, agentData, style = DEFAULT_STYLE, registry2, parentAgentId, contextConfigData, parentModels) {
236827
+ const imports = generateSubAgentImports(
236828
+ agentId,
236829
+ agentData,
236830
+ style,
236831
+ registry2,
236832
+ parentAgentId,
236833
+ contextConfigData
237174
236834
  );
236835
+ const definition = generateSubAgentDefinition(
236836
+ agentId,
236837
+ agentData,
236838
+ style,
236839
+ registry2,
236840
+ parentAgentId,
236841
+ contextConfigData,
236842
+ parentModels
236843
+ );
236844
+ return generateFileContent(imports, [definition]);
237175
236845
  }
237176
- function hasSchemas(contextData) {
237177
- const dataStr = JSON.stringify(contextData).toLowerCase();
237178
- return dataStr.includes("schema") || dataStr.includes("responseschema");
237179
- }
237180
- function generateContextConfigFile(contextId, contextData, style = DEFAULT_STYLE, registry2, agentId) {
237181
- const imports = generateContextConfigImports(contextId, contextData, style);
237182
- const definitions = [];
237183
- let headersVarName;
237184
- if (contextData.headersSchema) {
237185
- if (typeof contextData.headers === "string") {
237186
- headersVarName = contextData.headers;
237187
- } else {
237188
- headersVarName = `${toCamelCase(contextId)}Headers`;
236846
+ var init_sub_agent_generator = __esm({
236847
+ "src/commands/pull-v3/components/sub-agent-generator.ts"() {
236848
+ "use strict";
236849
+ init_esm_shims();
236850
+ init_generator_utils();
236851
+ }
236852
+ });
236853
+
236854
+ // src/commands/pull-v3/utils/component-registry.ts
236855
+ function registerAllComponents(project, registry2) {
236856
+ registry2.register(project.id, "project", "index.ts");
236857
+ if (project.credentialReferences) {
236858
+ for (const credId of Object.keys(project.credentialReferences)) {
236859
+ registry2.register(credId, "credential", `credentials/${credId}.ts`);
237189
236860
  }
237190
- const headersDefinition = generateHeadersDefinition(
237191
- headersVarName || "headers",
237192
- { schema: contextData.headersSchema },
237193
- style
237194
- );
237195
- definitions.push(headersDefinition);
237196
236861
  }
237197
- if (contextData.contextVariables) {
237198
- for (const [varName, varData] of Object.entries(contextData.contextVariables)) {
237199
- if (varData && typeof varData === "object" && (varData.fetchConfig || varData.responseSchema)) {
237200
- const fetchDefinition2 = generateFetchDefinitionDefinition(
237201
- varName,
237202
- varData,
237203
- style,
237204
- headersVarName
237205
- );
237206
- definitions.push(fetchDefinition2);
236862
+ if (project.tools) {
236863
+ for (const toolId of Object.keys(project.tools)) {
236864
+ registry2.register(toolId, "tool", `tools/${toolId}.ts`);
236865
+ }
236866
+ }
236867
+ const processedFunctionIds = /* @__PURE__ */ new Set();
236868
+ if (project.functions) {
236869
+ for (const funcId of Object.keys(project.functions)) {
236870
+ registry2.register(funcId, "functionTool", `tools/functions/${funcId}.ts`);
236871
+ processedFunctionIds.add(funcId);
236872
+ }
236873
+ }
236874
+ if (project.functionTools) {
236875
+ for (const funcToolId of Object.keys(project.functionTools)) {
236876
+ if (!processedFunctionIds.has(funcToolId)) {
236877
+ registry2.register(funcToolId, "functionTool", `tools/functions/${funcToolId}.ts`);
237207
236878
  }
237208
236879
  }
237209
236880
  }
237210
- const contextDefinition = generateContextConfigDefinition(
237211
- contextId,
237212
- contextData,
237213
- style,
237214
- registry2,
237215
- agentId,
237216
- headersVarName
237217
- );
237218
- definitions.push(contextDefinition);
237219
- const contextVarName = (() => {
237220
- if (!registry2) {
237221
- throw new Error("Registry is required for context config variable name generation");
236881
+ if (project.dataComponents) {
236882
+ for (const componentId of Object.keys(project.dataComponents)) {
236883
+ registry2.register(componentId, "dataComponent", `data-components/${componentId}.ts`);
237222
236884
  }
237223
- const varName = registry2.getVariableName(contextId, "contextConfig");
237224
- if (!varName) {
237225
- throw new Error(`Failed to resolve variable name for context config: ${contextId}`);
236885
+ }
236886
+ if (project.artifactComponents) {
236887
+ for (const componentId of Object.keys(project.artifactComponents)) {
236888
+ registry2.register(componentId, "artifactComponent", `artifact-components/${componentId}.ts`);
237226
236889
  }
237227
- return varName;
237228
- })();
237229
- const exports = [contextVarName];
237230
- if (headersVarName) {
237231
- exports.push(headersVarName);
237232
236890
  }
237233
- if (contextData.contextVariables) {
237234
- for (const [varName, varData] of Object.entries(contextData.contextVariables)) {
237235
- if (varData && typeof varData === "object" && (varData.fetchConfig || varData.responseSchema)) {
237236
- exports.push(varName);
236891
+ if (project.externalAgents) {
236892
+ for (const extAgentId of Object.keys(project.externalAgents)) {
236893
+ registry2.register(extAgentId, "externalAgent", `external-agents/${extAgentId}.ts`);
236894
+ }
236895
+ }
236896
+ const statusComponents = extractStatusComponents(project);
236897
+ for (const statusId of Object.keys(statusComponents)) {
236898
+ registry2.register(statusId, "statusComponent", `status-components/${statusId}.ts`);
236899
+ }
236900
+ if (project.agents) {
236901
+ for (const agentId of Object.keys(project.agents)) {
236902
+ registry2.register(agentId, "agent", `agents/${agentId}.ts`);
236903
+ }
236904
+ }
236905
+ const subAgents2 = extractSubAgents(project);
236906
+ for (const subAgentId of Object.keys(subAgents2)) {
236907
+ registry2.register(subAgentId, "subAgent", `agents/sub-agents/${subAgentId}.ts`);
236908
+ }
236909
+ const contextConfigs2 = extractContextConfigs(project);
236910
+ for (const contextId of Object.keys(contextConfigs2)) {
236911
+ registry2.register(contextId, "contextConfig", `context-configs/${contextId}.ts`);
236912
+ }
236913
+ }
236914
+ function extractStatusComponents(project) {
236915
+ const statusComponents = {};
236916
+ if (project.agents) {
236917
+ for (const [agentId, agentData] of Object.entries(project.agents)) {
236918
+ if (agentData.statusUpdates && agentData.statusUpdates.statusComponents) {
236919
+ for (const statusComp of agentData.statusUpdates.statusComponents) {
236920
+ let statusId;
236921
+ if (typeof statusComp === "string") {
236922
+ statusId = statusComp;
236923
+ } else if (typeof statusComp === "object" && statusComp) {
236924
+ statusId = statusComp.type;
236925
+ } else {
236926
+ continue;
236927
+ }
236928
+ if (statusId && !statusComponents[statusId]) {
236929
+ statusComponents[statusId] = {
236930
+ // Include any other properties from the actual data first
236931
+ ...statusComp,
236932
+ id: statusId,
236933
+ type: statusComp.type || statusId,
236934
+ description: statusComp.description || `Status component for ${statusId}`,
236935
+ detailsSchema: statusComp.detailsSchema
236936
+ };
236937
+ }
236938
+ }
237237
236939
  }
237238
236940
  }
237239
236941
  }
237240
- definitions.push(`export { ${exports.join(", ")} };`);
237241
- return generateFileContent(imports, definitions);
236942
+ return statusComponents;
237242
236943
  }
237243
- var init_context_config_generator = __esm({
237244
- "src/commands/pull-v3/components/context-config-generator.ts"() {
236944
+ function extractSubAgents(project) {
236945
+ const subAgents2 = {};
236946
+ if (project.agents) {
236947
+ for (const [agentId, agentData] of Object.entries(project.agents)) {
236948
+ if (agentData.subAgents) {
236949
+ for (const [subAgentId, subAgentData] of Object.entries(agentData.subAgents)) {
236950
+ subAgents2[subAgentId] = subAgentData;
236951
+ }
236952
+ }
236953
+ }
236954
+ }
236955
+ return subAgents2;
236956
+ }
236957
+ function extractContextConfigs(project) {
236958
+ const contextConfigs2 = {};
236959
+ if (project.agents) {
236960
+ for (const [agentId, agentData] of Object.entries(project.agents)) {
236961
+ if (agentData.contextConfig) {
236962
+ const contextConfigId = agentData.contextConfig.id;
236963
+ if (contextConfigId) {
236964
+ contextConfigs2[contextConfigId] = agentData.contextConfig;
236965
+ } else {
236966
+ console.warn(`contextConfig for agent ${agentId} is missing required 'id' field`);
236967
+ }
236968
+ }
236969
+ }
236970
+ }
236971
+ return contextConfigs2;
236972
+ }
236973
+ function findSubAgentWithParent(project, subAgentId) {
236974
+ if (project.agents) {
236975
+ for (const [agentId, agentData] of Object.entries(project.agents)) {
236976
+ if (agentData.subAgents && agentData.subAgents[subAgentId]) {
236977
+ const contextConfigData = agentData.contextConfig?.id ? agentData.contextConfig : void 0;
236978
+ return {
236979
+ subAgentData: agentData.subAgents[subAgentId],
236980
+ parentAgentId: agentId,
236981
+ contextConfigData
236982
+ };
236983
+ }
236984
+ }
236985
+ }
236986
+ return void 0;
236987
+ }
236988
+ var ComponentRegistry;
236989
+ var init_component_registry = __esm({
236990
+ "src/commands/pull-v3/utils/component-registry.ts"() {
237245
236991
  "use strict";
237246
236992
  init_esm_shims();
237247
- init_generator_utils();
236993
+ ComponentRegistry = class {
236994
+ components = /* @__PURE__ */ new Map();
236995
+ componentsByTypeAndId = /* @__PURE__ */ new Map();
236996
+ // Type-aware lookup
236997
+ usedNames = /* @__PURE__ */ new Set();
236998
+ // Global name registry for uniqueness
236999
+ /**
237000
+ * Register a component with both unique name and file path
237001
+ */
237002
+ register(id, type, filePath, exportName, isInline = false) {
237003
+ const typeKey = `${type}:${id}`;
237004
+ const existing = this.componentsByTypeAndId.get(typeKey);
237005
+ if (existing) {
237006
+ return existing;
237007
+ }
237008
+ let name;
237009
+ let actualExportName;
237010
+ if (exportName) {
237011
+ name = exportName;
237012
+ actualExportName = exportName;
237013
+ } else {
237014
+ const baseName = this.toCamelCase(id);
237015
+ const uniqueName = this.ensureUniqueName(baseName, type);
237016
+ name = uniqueName;
237017
+ actualExportName = uniqueName;
237018
+ }
237019
+ const info = {
237020
+ id,
237021
+ name,
237022
+ type,
237023
+ filePath,
237024
+ exportName: actualExportName,
237025
+ isInline
237026
+ };
237027
+ this.components.set(id, info);
237028
+ this.componentsByTypeAndId.set(typeKey, info);
237029
+ this.usedNames.add(name);
237030
+ if (actualExportName && actualExportName !== name) {
237031
+ this.usedNames.add(actualExportName);
237032
+ }
237033
+ return info;
237034
+ }
237035
+ /**
237036
+ * Get component info by ID and type
237037
+ */
237038
+ get(id, type) {
237039
+ const typeKey = `${type}:${id}`;
237040
+ return this.componentsByTypeAndId.get(typeKey);
237041
+ }
237042
+ /**
237043
+ * Get component info by variable name (since variable names are globally unique)
237044
+ */
237045
+ getByVariableName(variableName) {
237046
+ for (const component of this.componentsByTypeAndId.values()) {
237047
+ if (component.name === variableName) {
237048
+ return component;
237049
+ }
237050
+ }
237051
+ return void 0;
237052
+ }
237053
+ /**
237054
+ * Get unique variable name for a component by ID and type
237055
+ */
237056
+ getVariableName(id, type) {
237057
+ const typeKey = `${type}:${id}`;
237058
+ const result = this.componentsByTypeAndId.get(typeKey)?.name;
237059
+ return result;
237060
+ }
237061
+ /**
237062
+ * Get import statement for a component
237063
+ */
237064
+ getImportStatement(fromFilePath, componentId, componentType) {
237065
+ const component = this.get(componentId, componentType);
237066
+ if (!component) return void 0;
237067
+ const relativePath = this.calculateRelativeImport(fromFilePath, component.filePath);
237068
+ const importStmt = `import { ${component.exportName} } from '${relativePath}';`;
237069
+ return importStmt;
237070
+ }
237071
+ /**
237072
+ * Format an array of references for code generation
237073
+ */
237074
+ formatReferencesForCode(references, componentType, style, indentLevel) {
237075
+ if (!Array.isArray(references) || references.length === 0) {
237076
+ return "[]";
237077
+ }
237078
+ const variableNames = [];
237079
+ for (const ref of references) {
237080
+ const id = this.extractIdFromReference(ref);
237081
+ if (id) {
237082
+ const component = this.get(id, componentType);
237083
+ if (component) {
237084
+ variableNames.push(component.name);
237085
+ } else {
237086
+ console.warn(`ComponentRegistry: Component not found: ${id} (type: ${componentType})`);
237087
+ variableNames.push(this.toCamelCase(id));
237088
+ }
237089
+ }
237090
+ }
237091
+ if (variableNames.length === 0) {
237092
+ return "[]";
237093
+ }
237094
+ if (variableNames.length === 1) {
237095
+ return `[${variableNames[0]}]`;
237096
+ }
237097
+ const { indentation } = style;
237098
+ const indent = indentation.repeat(indentLevel);
237099
+ const lines = ["["];
237100
+ for (let i = 0; i < variableNames.length; i++) {
237101
+ const isLast = i === variableNames.length - 1;
237102
+ lines.push(`${indent}${variableNames[i]}${isLast ? "" : ","}`);
237103
+ }
237104
+ lines.push(`${indentation.repeat(indentLevel - 1)}]`);
237105
+ return lines.join("\n");
237106
+ }
237107
+ /**
237108
+ * Get all import statements needed for a file
237109
+ */
237110
+ getImportsForFile(fromFilePath, referencedComponents) {
237111
+ const imports = [];
237112
+ const seenImports = /* @__PURE__ */ new Set();
237113
+ for (const { id, type } of referencedComponents) {
237114
+ const importStatement = this.getImportStatement(fromFilePath, id, type);
237115
+ if (importStatement && !seenImports.has(importStatement)) {
237116
+ imports.push(importStatement);
237117
+ seenImports.add(importStatement);
237118
+ }
237119
+ }
237120
+ return imports;
237121
+ }
237122
+ /**
237123
+ * Get all component IDs referenced in arrays for import generation
237124
+ */
237125
+ getReferencedComponentIds(referenceArrays) {
237126
+ const componentIds = [];
237127
+ for (const refArray of referenceArrays) {
237128
+ if (Array.isArray(refArray)) {
237129
+ for (const ref of refArray) {
237130
+ const id = this.extractIdFromReference(ref);
237131
+ if (id) {
237132
+ componentIds.push(id);
237133
+ }
237134
+ }
237135
+ }
237136
+ }
237137
+ return componentIds;
237138
+ }
237139
+ /**
237140
+ * Extract ID from a reference (string or object) based on component type
237141
+ */
237142
+ extractIdFromReference(ref) {
237143
+ if (typeof ref === "string") {
237144
+ return ref;
237145
+ } else if (typeof ref === "object" && ref) {
237146
+ if (ref.toolId) return ref.toolId;
237147
+ if (ref.agentId) return ref.agentId;
237148
+ if (ref.externalAgentId) return ref.externalAgentId;
237149
+ if (ref.credentialStoreId) return ref.credentialStoreId;
237150
+ if (ref.type && !ref.agentId && !ref.toolId && !ref.externalAgentId) return ref.type;
237151
+ if (ref.id) return ref.id;
237152
+ if (ref.name) return ref.name;
237153
+ console.warn("ComponentRegistry: Reference without recognized ID field:", ref);
237154
+ return null;
237155
+ }
237156
+ return null;
237157
+ }
237158
+ /**
237159
+ * Convert string to camelCase and ensure it's a valid JavaScript identifier
237160
+ */
237161
+ toCamelCase(str) {
237162
+ return str.toLowerCase().replace(/[-_](.)/g, (_, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
237163
+ }
237164
+ /**
237165
+ * Ensure a name is unique by adding prefixes/suffixes if needed
237166
+ */
237167
+ ensureUniqueName(baseName, type) {
237168
+ let uniqueName = baseName;
237169
+ let counter = 1;
237170
+ while (this.usedNames.has(uniqueName)) {
237171
+ if (counter === 1) {
237172
+ const typePrefix = this.getTypePrefix(type);
237173
+ uniqueName = `${typePrefix}${baseName.charAt(0).toUpperCase() + baseName.slice(1)}`;
237174
+ } else {
237175
+ uniqueName = `${baseName}${counter}`;
237176
+ }
237177
+ counter++;
237178
+ if (counter > 100) {
237179
+ uniqueName = `${baseName}_${Date.now()}`;
237180
+ break;
237181
+ }
237182
+ }
237183
+ return uniqueName;
237184
+ }
237185
+ /**
237186
+ * Get type prefix for uniqueness resolution
237187
+ */
237188
+ getTypePrefix(type) {
237189
+ switch (type) {
237190
+ case "agent":
237191
+ return "agent";
237192
+ case "subAgent":
237193
+ return "sub";
237194
+ case "externalAgent":
237195
+ return "ext";
237196
+ case "tool":
237197
+ return "tool";
237198
+ case "functionTool":
237199
+ return "func";
237200
+ case "dataComponent":
237201
+ return "data";
237202
+ case "artifactComponent":
237203
+ return "artifact";
237204
+ case "credential":
237205
+ return "cred";
237206
+ case "statusComponent":
237207
+ return "status";
237208
+ case "contextConfig":
237209
+ return "context";
237210
+ case "project":
237211
+ return "project";
237212
+ default:
237213
+ return "comp";
237214
+ }
237215
+ }
237216
+ /**
237217
+ * Calculate relative import path between files
237218
+ */
237219
+ calculateRelativeImport(fromPath, toPath) {
237220
+ const fromParts = fromPath.replace(".ts", "").split("/");
237221
+ const toParts = toPath.replace(".ts", "").split("/");
237222
+ fromParts.pop();
237223
+ let relativePath = "";
237224
+ for (let i = 0; i < fromParts.length; i++) {
237225
+ relativePath += "../";
237226
+ }
237227
+ relativePath += toParts.join("/");
237228
+ if (relativePath.startsWith("../")) {
237229
+ return relativePath;
237230
+ } else {
237231
+ return "./" + relativePath;
237232
+ }
237233
+ }
237234
+ /**
237235
+ * Get all components for debugging
237236
+ */
237237
+ getAllComponents() {
237238
+ return Array.from(this.components.values());
237239
+ }
237240
+ /**
237241
+ * Clear all components (for testing)
237242
+ */
237243
+ clear() {
237244
+ this.components.clear();
237245
+ this.usedNames.clear();
237246
+ }
237247
+ };
237248
237248
  }
237249
237249
  });
237250
237250
 
237251
237251
  // src/commands/pull-v3/introspect-generator.ts
237252
- import { writeFileSync as writeFileSync3, mkdirSync } from "fs";
237253
- import { join as join6, dirname as dirname5 } from "path";
237252
+ import { mkdirSync, writeFileSync as writeFileSync3 } from "fs";
237253
+ import { dirname as dirname5, join as join6 } from "path";
237254
237254
  import chalk8 from "chalk";
237255
237255
  function ensureDir(filePath) {
237256
237256
  const dir = dirname5(filePath);
@@ -237489,20 +237489,20 @@ var init_introspect_generator = __esm({
237489
237489
  "src/commands/pull-v3/introspect-generator.ts"() {
237490
237490
  "use strict";
237491
237491
  init_esm_shims();
237492
- init_component_registry();
237493
- init_generator_utils();
237494
- init_project_generator();
237495
237492
  init_agent_generator();
237496
- init_sub_agent_generator();
237497
- init_external_agent_generator();
237498
- init_data_component_generator();
237499
237493
  init_artifact_component_generator();
237500
- init_status_component_generator();
237501
- init_function_tool_generator();
237502
- init_mcp_tool_generator();
237494
+ init_context_config_generator();
237503
237495
  init_credential_generator();
237496
+ init_data_component_generator();
237504
237497
  init_environment_generator();
237505
- init_context_config_generator();
237498
+ init_external_agent_generator();
237499
+ init_function_tool_generator();
237500
+ init_mcp_tool_generator();
237501
+ init_project_generator();
237502
+ init_status_component_generator();
237503
+ init_sub_agent_generator();
237504
+ init_component_registry();
237505
+ init_generator_utils();
237506
237506
  }
237507
237507
  });
237508
237508
 
@@ -238493,8 +238493,8 @@ __export(component_parser_exports, {
238493
238493
  findComponentById: () => findComponentById,
238494
238494
  getAllLocalComponentIds: () => getAllLocalComponentIds
238495
238495
  });
238496
- import { existsSync as existsSync7, readFileSync as readFileSync3, readdirSync as readdirSync2, statSync } from "fs";
238497
- import { join as join8, extname as extname2, relative } from "path";
238496
+ import { existsSync as existsSync7, readdirSync as readdirSync2, readFileSync as readFileSync3, statSync } from "fs";
238497
+ import { extname as extname2, join as join8, relative } from "path";
238498
238498
  function parseFileForComponents(filePath, projectRoot, debug = false) {
238499
238499
  if (!existsSync7(filePath)) {
238500
238500
  return [];
@@ -238858,6 +238858,281 @@ var init_component_parser = __esm({
238858
238858
  }
238859
238859
  });
238860
238860
 
238861
+ // src/commands/pull-v3/targeted-typescript-placeholders.ts
238862
+ import { randomBytes as randomBytes2 } from "crypto";
238863
+ function generatePlaceholderId() {
238864
+ return randomBytes2(4).toString("hex").toUpperCase();
238865
+ }
238866
+ function createTargetedTypeScriptPlaceholders(content, debug = false) {
238867
+ const replacements = {};
238868
+ let processedContent = content;
238869
+ let replacedFields = 0;
238870
+ const originalSize = content.length;
238871
+ const promptRegex = /(\s+prompt:\s*)((['"`])([^]*?)\3)/g;
238872
+ processedContent = processedContent.replace(promptRegex, (match2, prefix, fullValue) => {
238873
+ if (fullValue.length >= MIN_REPLACEMENT_LENGTH) {
238874
+ const placeholder = `<PROMPT_${generatePlaceholderId()}>`;
238875
+ replacements[placeholder] = fullValue;
238876
+ replacedFields++;
238877
+ return `${prefix}${placeholder}`;
238878
+ }
238879
+ return match2;
238880
+ });
238881
+ const descriptionRegex = /(\s+description:\s*)((['"`])([^]*?)\3)/g;
238882
+ processedContent = processedContent.replace(descriptionRegex, (match2, prefix, fullValue) => {
238883
+ if (fullValue.length >= MIN_REPLACEMENT_LENGTH) {
238884
+ const placeholder = `<DESC_${generatePlaceholderId()}>`;
238885
+ replacements[placeholder] = fullValue;
238886
+ replacedFields++;
238887
+ return `${prefix}${placeholder}`;
238888
+ }
238889
+ return match2;
238890
+ });
238891
+ const inputSchemaRegex = /(\s+inputSchema:\s*)(\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\})/g;
238892
+ processedContent = processedContent.replace(inputSchemaRegex, (match2, prefix, schemaObject) => {
238893
+ if (schemaObject.length >= MIN_REPLACEMENT_LENGTH) {
238894
+ const placeholder = `<INPUT_SCHEMA_${generatePlaceholderId()}>`;
238895
+ replacements[placeholder] = schemaObject;
238896
+ replacedFields++;
238897
+ return `${prefix}${placeholder}`;
238898
+ }
238899
+ return match2;
238900
+ });
238901
+ const detailsSchemaRegex = /(\s+detailsSchema:\s*)(z\.object\(\{[^]*?\}\)(?:\.[^,}\s]+)*)/g;
238902
+ processedContent = processedContent.replace(detailsSchemaRegex, (match2, prefix, schemaObject) => {
238903
+ if (schemaObject.length >= MIN_REPLACEMENT_LENGTH) {
238904
+ const placeholder = `<DETAILS_SCHEMA_${generatePlaceholderId()}>`;
238905
+ replacements[placeholder] = schemaObject;
238906
+ replacedFields++;
238907
+ return `${prefix}${placeholder}`;
238908
+ }
238909
+ return match2;
238910
+ });
238911
+ const propsRegex = /(\s+props:\s*)(z\.object\(\{[^]*?\}\)(?:\.[^,}\s]+)*)/g;
238912
+ processedContent = processedContent.replace(propsRegex, (match2, prefix, propsObject) => {
238913
+ if (propsObject.length >= MIN_REPLACEMENT_LENGTH) {
238914
+ const placeholder = `<PROPS_${generatePlaceholderId()}>`;
238915
+ replacements[placeholder] = propsObject;
238916
+ replacedFields++;
238917
+ return `${prefix}${placeholder}`;
238918
+ }
238919
+ return match2;
238920
+ });
238921
+ const processedSize = processedContent.length;
238922
+ const savings = originalSize - processedSize;
238923
+ const savingsPercentage = originalSize > 0 ? savings / originalSize * 100 : 0;
238924
+ return {
238925
+ processedContent,
238926
+ replacements,
238927
+ stats: {
238928
+ originalSize,
238929
+ processedSize,
238930
+ savings,
238931
+ savingsPercentage,
238932
+ replacedFields
238933
+ }
238934
+ };
238935
+ }
238936
+ function restoreTargetedTypeScriptPlaceholders(content, replacements) {
238937
+ let restoredContent = content;
238938
+ const sortedPlaceholders = Object.keys(replacements).sort((a, b) => b.length - a.length);
238939
+ for (const placeholder of sortedPlaceholders) {
238940
+ const originalValue = replacements[placeholder];
238941
+ restoredContent = restoredContent.replace(placeholder, originalValue);
238942
+ }
238943
+ return restoredContent;
238944
+ }
238945
+ var MIN_REPLACEMENT_LENGTH;
238946
+ var init_targeted_typescript_placeholders = __esm({
238947
+ "src/commands/pull-v3/targeted-typescript-placeholders.ts"() {
238948
+ "use strict";
238949
+ init_esm_shims();
238950
+ MIN_REPLACEMENT_LENGTH = 10;
238951
+ }
238952
+ });
238953
+
238954
+ // src/commands/pull-v3/utils/model-provider-detector.ts
238955
+ import { anthropic } from "@ai-sdk/anthropic";
238956
+ import { google } from "@ai-sdk/google";
238957
+ import { openai } from "@ai-sdk/openai";
238958
+ function getAvailableModel() {
238959
+ for (const config of PROVIDER_CONFIGS) {
238960
+ const hasKey = config.envVars.some((envVar) => {
238961
+ const value = process.env[envVar];
238962
+ return value && value.trim() !== "";
238963
+ });
238964
+ if (hasKey) {
238965
+ switch (config.name) {
238966
+ case "anthropic":
238967
+ return anthropic(config.model);
238968
+ case "openai":
238969
+ return openai(config.model);
238970
+ case "google":
238971
+ return google(config.model);
238972
+ default:
238973
+ throw new Error(`Unknown provider: ${config.name}`);
238974
+ }
238975
+ }
238976
+ }
238977
+ throw new Error(
238978
+ "No API keys detected. Please set ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY"
238979
+ );
238980
+ }
238981
+ var PROVIDER_CONFIGS;
238982
+ var init_model_provider_detector = __esm({
238983
+ "src/commands/pull-v3/utils/model-provider-detector.ts"() {
238984
+ "use strict";
238985
+ init_esm_shims();
238986
+ PROVIDER_CONFIGS = [
238987
+ {
238988
+ name: "anthropic",
238989
+ envVars: ["ANTHROPIC_API_KEY"],
238990
+ model: "claude-sonnet-4-5"
238991
+ },
238992
+ {
238993
+ name: "openai",
238994
+ envVars: ["OPENAI_API_KEY"],
238995
+ model: "gpt-4.1"
238996
+ },
238997
+ {
238998
+ name: "google",
238999
+ envVars: ["GOOGLE_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"],
239000
+ model: "gemini-2.5-flash"
239001
+ }
239002
+ ];
239003
+ }
239004
+ });
239005
+
239006
+ // src/commands/pull-v3/llm-content-merger.ts
239007
+ import { generateText } from "ai";
239008
+ import chalk10 from "chalk";
239009
+ function stripCodeFences(content) {
239010
+ content = content.replace(/^```(?:typescript|ts|javascript|js)?\s*\n?/i, "");
239011
+ content = content.replace(/\n?```\s*$/i, "");
239012
+ return content;
239013
+ }
239014
+ function estimateTokens(text3) {
239015
+ return Math.ceil(text3.length / 4);
239016
+ }
239017
+ function calculateCostEstimate(promptTokens, completionTokens) {
239018
+ const promptCost = promptTokens / 1e6 * 3;
239019
+ const completionCost = completionTokens / 1e6 * 15;
239020
+ return promptCost + completionCost;
239021
+ }
239022
+ async function mergeComponentsWithLLM(request) {
239023
+ const { oldContent, newContent, modifiedComponents, filePath } = request;
239024
+ const componentList = modifiedComponents.map((c) => `- ${c.componentType}:${c.componentId}`).join("\n");
239025
+ const prompt = `You are a TypeScript code expert tasked with intelligently merging component updates.
239026
+
239027
+ ## Task
239028
+ Merge the OLD file content with NEW component definitions, preserving the original file structure while updating only the modified components.
239029
+
239030
+ ## Modified Components to Update
239031
+ ${componentList}
239032
+
239033
+ ## Instructions
239034
+ 0. **Please ensure you focus changes to minimize git diff size.** We want a clean git history.
239035
+ 1. **Preserve original structure**: Keep imports, exports, comments, and overall file organization
239036
+ 2. **Update only modified components**: Replace the specified components with their new versions
239037
+ 3. **Maintain code style**: Match the original formatting, indentation, and style
239038
+ 4. **Improve schemas**: Use better zod schemas from the new content where applicable. E.g. if the new content uses something like z.union([z.null(), z.string()]), use z.string().nullable() instead.
239039
+ 5. **Keep variable names**: Preserve original variable names and declarations
239040
+ 6. **Preserve non-component code**: Keep any non-component logic, comments, or utilities
239041
+ 7. **Please leave all imports at the top of the file.** Don't use .js imports, use .ts imports instead. (import example from './example')
239042
+ 8. **Format JavaScript functions for maximum readability**:
239043
+ - When you see compressed/minified function code like \`async({params})=>{...code...}\`, expand and prettify it
239044
+ - Add proper line breaks, spacing, and indentation to make the function readable
239045
+ - Ensure all braces \`{}\`, parentheses \`()\`, and syntax are properly balanced and valid
239046
+ - Format the function code following TypeScript/JavaScript best practices
239047
+ - Make sure the final code is compilable and syntactically correct
239048
+ - Example: \`async({a,b})=>{return a+b}\` should become:
239049
+ \`\`\`
239050
+ async ({ a, b }) => {
239051
+ return a + b;
239052
+ }
239053
+ \`\`\`
239054
+
239055
+ ## OLD Content:
239056
+ \`\`\`typescript
239057
+ ${oldContent}
239058
+ \`\`\`
239059
+
239060
+ ## NEW Component Definitions:
239061
+ \`\`\`typescript
239062
+ ${newContent}
239063
+ \`\`\`
239064
+
239065
+ ## Output
239066
+ Provide the merged TypeScript file that:
239067
+ - Keeps the original file structure
239068
+ - Updates ONLY the modified components listed above
239069
+ - Maintains consistent code style
239070
+ - Uses improved schemas where beneficial
239071
+ - Preserves all imports, exports, and other code
239072
+ - **Formats all function code beautifully with proper spacing, line breaks, and indentation**
239073
+ - **Ensures all syntax is valid and compilable TypeScript/JavaScript**
239074
+ - Start the code immidiately with the first line of the file, skip any backticks or other formatting announcing that it is a code block or typescript file.
239075
+ - Please follow biomes.dev code style.
239076
+
239077
+ Return only the merged TypeScript code without any explanation or markdown formatting.`;
239078
+ try {
239079
+ const oldPlaceholders = createTargetedTypeScriptPlaceholders(oldContent);
239080
+ const newPlaceholders = createTargetedTypeScriptPlaceholders(newContent);
239081
+ const processedPrompt = prompt.replace(oldContent, oldPlaceholders.processedContent).replace(newContent, newPlaceholders.processedContent);
239082
+ const estimatedPromptTokens = estimateTokens(processedPrompt);
239083
+ const result = await generateText({
239084
+ model: getAvailableModel(),
239085
+ prompt: processedPrompt
239086
+ });
239087
+ let mergedContent = result.text.trim();
239088
+ mergedContent = stripCodeFences(mergedContent);
239089
+ const estimatedCompletionTokens = estimateTokens(mergedContent);
239090
+ const totalTokens = estimatedPromptTokens + estimatedCompletionTokens;
239091
+ const estimatedCost = calculateCostEstimate(estimatedPromptTokens, estimatedCompletionTokens);
239092
+ console.log(
239093
+ chalk10.gray(
239094
+ ` \u{1F4B0} LLM usage: ~${totalTokens.toLocaleString()} tokens ($${estimatedCost.toFixed(4)})`
239095
+ )
239096
+ );
239097
+ const allReplacements = {
239098
+ ...oldPlaceholders.replacements,
239099
+ ...newPlaceholders.replacements
239100
+ };
239101
+ if (Object.keys(allReplacements).length > 0) {
239102
+ mergedContent = restoreTargetedTypeScriptPlaceholders(mergedContent, allReplacements);
239103
+ }
239104
+ const changes = modifiedComponents.map((c) => `Updated ${c.componentType}:${c.componentId}`);
239105
+ return {
239106
+ mergedContent,
239107
+ changes,
239108
+ success: true,
239109
+ usage: {
239110
+ promptTokens: estimatedPromptTokens,
239111
+ completionTokens: estimatedCompletionTokens,
239112
+ totalTokens,
239113
+ estimatedCost
239114
+ }
239115
+ };
239116
+ } catch (error) {
239117
+ const errorMsg = error instanceof Error ? error.message : String(error);
239118
+ return {
239119
+ mergedContent: oldContent,
239120
+ // Fallback to original
239121
+ changes: [],
239122
+ success: false,
239123
+ error: errorMsg
239124
+ };
239125
+ }
239126
+ }
239127
+ var init_llm_content_merger = __esm({
239128
+ "src/commands/pull-v3/llm-content-merger.ts"() {
239129
+ "use strict";
239130
+ init_esm_shims();
239131
+ init_targeted_typescript_placeholders();
239132
+ init_model_provider_detector();
239133
+ }
239134
+ });
239135
+
238861
239136
  // src/commands/pull-v3/project-validator.ts
238862
239137
  var project_validator_exports = {};
238863
239138
  __export(project_validator_exports, {
@@ -238875,7 +239150,7 @@ import {
238875
239150
  writeFileSync as writeFileSync4
238876
239151
  } from "fs";
238877
239152
  import { basename as basename2, dirname as dirname6, join as join9 } from "path";
238878
- import chalk10 from "chalk";
239153
+ import chalk11 from "chalk";
238879
239154
  function getComponentFromProject(project, componentType, componentId) {
238880
239155
  switch (componentType) {
238881
239156
  case "credentials":
@@ -238922,18 +239197,18 @@ async function validateProjectEquivalence(tempDir, remoteProject) {
238922
239197
  if (!hasChanges) {
238923
239198
  return true;
238924
239199
  } else {
238925
- console.log(chalk10.yellow(` \u{1F504} Found differences:`));
239200
+ console.log(chalk11.yellow(` \u{1F504} Found differences:`));
238926
239201
  for (const [componentType, changes] of Object.entries(comparison.componentChanges)) {
238927
239202
  const totalChanges = changes.added.length + changes.modified.length + changes.deleted.length;
238928
239203
  if (totalChanges > 0) {
238929
- console.log(chalk10.cyan(` ${componentType}: ${totalChanges} changes`));
239204
+ console.log(chalk11.cyan(` ${componentType}: ${totalChanges} changes`));
238930
239205
  if (changes.added.length > 0) {
238931
- console.log(chalk10.green(` \u2795 Added: ${changes.added.join(", ")}`));
239206
+ console.log(chalk11.green(` \u2795 Added: ${changes.added.join(", ")}`));
238932
239207
  }
238933
239208
  if (changes.modified.length > 0) {
238934
- console.log(chalk10.yellow(` \u{1F4DD} Modified: ${changes.modified.join(", ")}`));
239209
+ console.log(chalk11.yellow(` \u{1F4DD} Modified: ${changes.modified.join(", ")}`));
238935
239210
  for (const modifiedId of changes.modified) {
238936
- console.log(chalk10.gray(` ${modifiedId} detailed differences:`));
239211
+ console.log(chalk11.gray(` ${modifiedId} detailed differences:`));
238937
239212
  const generatedComponent = getComponentFromProject(
238938
239213
  tempProjectDefinition,
238939
239214
  componentType,
@@ -238945,15 +239220,15 @@ async function validateProjectEquivalence(tempDir, remoteProject) {
238945
239220
  modifiedId
238946
239221
  );
238947
239222
  console.log(
238948
- chalk10.gray(`Generated Component: ${JSON.stringify(generatedComponent, null, 2)}`)
239223
+ chalk11.gray(`Generated Component: ${JSON.stringify(generatedComponent, null, 2)}`)
238949
239224
  );
238950
239225
  console.log(
238951
- chalk10.gray(`Remote Component: ${JSON.stringify(remoteComponent, null, 2)}`)
239226
+ chalk11.gray(`Remote Component: ${JSON.stringify(remoteComponent, null, 2)}`)
238952
239227
  );
238953
239228
  }
238954
239229
  }
238955
239230
  if (changes.deleted.length > 0) {
238956
- console.log(chalk10.red(` \u2796 Deleted: ${changes.deleted.join(", ")}`));
239231
+ console.log(chalk11.red(` \u2796 Deleted: ${changes.deleted.join(", ")}`));
238957
239232
  }
238958
239233
  }
238959
239234
  }
@@ -238961,7 +239236,7 @@ async function validateProjectEquivalence(tempDir, remoteProject) {
238961
239236
  }
238962
239237
  } catch (error) {
238963
239238
  const errorMsg = error instanceof Error ? error.message : String(error);
238964
- console.log(chalk10.red(` \u274C Project validation failed: ${errorMsg}`));
239239
+ console.log(chalk11.red(` \u274C Project validation failed: ${errorMsg}`));
238965
239240
  return false;
238966
239241
  }
238967
239242
  }
@@ -238971,14 +239246,14 @@ async function validateTempDirectory(originalProjectRoot, tempDirName, remotePro
238971
239246
  const equivalenceSuccess = await validateProjectEquivalence(tempDir, remoteProject);
238972
239247
  if (equivalenceSuccess) {
238973
239248
  console.log(
238974
- chalk10.yellow(`
239249
+ chalk11.yellow(`
238975
239250
  \u2753 Would you like to overwrite your project files with the generated files?`)
238976
239251
  );
238977
239252
  console.log(
238978
- chalk10.gray(` This will replace your current files with the validated generated ones.`)
239253
+ chalk11.gray(` This will replace your current files with the validated generated ones.`)
238979
239254
  );
238980
- console.log(chalk10.green(` [Y] Yes - Replace files and clean up temp directory`));
238981
- console.log(chalk10.red(` [N] No - Keep temp directory for manual review`));
239255
+ console.log(chalk11.green(` [Y] Yes - Replace files and clean up temp directory`));
239256
+ console.log(chalk11.red(` [N] No - Keep temp directory for manual review`));
238982
239257
  return new Promise((resolve5) => {
238983
239258
  process.stdin.removeAllListeners("data");
238984
239259
  process.stdin.setMaxListeners(15);
@@ -238991,53 +239266,53 @@ async function validateTempDirectory(originalProjectRoot, tempDirName, remotePro
238991
239266
  process.stdin.removeAllListeners("data");
238992
239267
  const normalizedKey = key.toLowerCase();
238993
239268
  if (normalizedKey === "y") {
238994
- console.log(chalk10.green(`
239269
+ console.log(chalk11.green(`
238995
239270
  \u2705 Selected: Yes - Replacing files...`));
238996
239271
  overwriteProjectFiles(originalProjectRoot, tempDirName, tempDir);
238997
- console.log(chalk10.green(`
239272
+ console.log(chalk11.green(`
238998
239273
  \u{1F389} Pull completed successfully!`));
238999
239274
  process.exit(0);
239000
239275
  } else if (normalizedKey === "n") {
239001
- console.log(chalk10.yellow(`
239276
+ console.log(chalk11.yellow(`
239002
239277
  \u274C Selected: No - Files not replaced`));
239003
- console.log(chalk10.gray(`\u{1F4C2} Generated files remain in: ${tempDirName}`));
239004
- console.log(chalk10.gray(` You can manually review and copy files as needed.`));
239005
- console.log(chalk10.cyan(`
239278
+ console.log(chalk11.gray(`\u{1F4C2} Generated files remain in: ${tempDirName}`));
239279
+ console.log(chalk11.gray(` You can manually review and copy files as needed.`));
239280
+ console.log(chalk11.cyan(`
239006
239281
  \u2705 Pull completed - temp directory preserved for review.`));
239007
239282
  process.exit(0);
239008
239283
  } else {
239009
- console.log(chalk10.red(`
239284
+ console.log(chalk11.red(`
239010
239285
  \u274C Invalid key: "${key}". Please press Y or N.`));
239011
239286
  console.log(
239012
- chalk10.gray(`\u{1F4C2} Files not replaced. Generated files remain in: ${tempDirName}`)
239287
+ chalk11.gray(`\u{1F4C2} Files not replaced. Generated files remain in: ${tempDirName}`)
239013
239288
  );
239014
239289
  console.log(
239015
- chalk10.yellow(`
239290
+ chalk11.yellow(`
239016
239291
  \u26A0\uFE0F Pull completed with invalid input - temp directory preserved.`)
239017
239292
  );
239018
239293
  process.exit(0);
239019
239294
  }
239020
239295
  };
239021
239296
  process.stdin.on("data", onKeypress);
239022
- process.stdout.write(chalk10.cyan("\nPress [Y] for Yes or [N] for No: "));
239297
+ process.stdout.write(chalk11.cyan("\nPress [Y] for Yes or [N] for No: "));
239023
239298
  });
239024
239299
  } else {
239025
- console.log(chalk10.yellow(` \u26A0\uFE0F Generated project differs from remote project`));
239026
- console.log(chalk10.gray(` \u{1F4A1} This might be expected if there are structural changes`));
239027
- console.log(chalk10.gray(` \u{1F4C2} Generated files available in: ${tempDirName} for manual review`));
239300
+ console.log(chalk11.yellow(` \u26A0\uFE0F Generated project differs from remote project`));
239301
+ console.log(chalk11.gray(` \u{1F4A1} This might be expected if there are structural changes`));
239302
+ console.log(chalk11.gray(` \u{1F4C2} Generated files available in: ${tempDirName} for manual review`));
239028
239303
  if (compilationSuccess) {
239029
- console.log(chalk10.yellow(`
239304
+ console.log(chalk11.yellow(`
239030
239305
  \u2705 Compilation successful, but project structure differs.`));
239031
239306
  console.log(
239032
- chalk10.cyan(`
239307
+ chalk11.cyan(`
239033
239308
  \u2705 Pull completed - please review generated files in temp directory.`)
239034
239309
  );
239035
239310
  process.exit(0);
239036
239311
  } else {
239037
- console.log(chalk10.red(`
239312
+ console.log(chalk11.red(`
239038
239313
  \u274C Validation failed - please check the generated files.`));
239039
239314
  console.log(
239040
- chalk10.yellow(`
239315
+ chalk11.yellow(`
239041
239316
  \u26A0\uFE0F Pull completed with validation errors - temp directory preserved.`)
239042
239317
  );
239043
239318
  process.exit(1);
@@ -239063,27 +239338,27 @@ function overwriteProjectFiles(originalProjectRoot, tempDirName, tempDir) {
239063
239338
  copyFileSync(sourcePath, targetPath);
239064
239339
  filesReplaced++;
239065
239340
  const relativePath = targetPath.replace(originalProjectRoot + "/", "");
239066
- console.log(chalk10.green(` \u2705 Replaced: ${relativePath}`));
239341
+ console.log(chalk11.green(` \u2705 Replaced: ${relativePath}`));
239067
239342
  }
239068
239343
  }
239069
239344
  };
239070
239345
  var copyRecursively = copyRecursively2;
239071
- console.log(chalk10.cyan(`
239346
+ console.log(chalk11.cyan(`
239072
239347
  \u{1F504} Replacing project files with generated files...`));
239073
239348
  let filesReplaced = 0;
239074
239349
  copyRecursively2(tempDir, originalProjectRoot);
239075
- console.log(chalk10.cyan(`
239350
+ console.log(chalk11.cyan(`
239076
239351
  \u{1F9F9} Cleaning up temp directory...`));
239077
239352
  rmSync(tempDir, { recursive: true, force: true });
239078
- console.log(chalk10.green(`
239353
+ console.log(chalk11.green(`
239079
239354
  \u{1F389} Successfully replaced ${filesReplaced} files!`));
239080
- console.log(chalk10.gray(` Your project files have been updated with the generated content.`));
239081
- console.log(chalk10.gray(` Temp directory cleaned up.`));
239355
+ console.log(chalk11.gray(` Your project files have been updated with the generated content.`));
239356
+ console.log(chalk11.gray(` Temp directory cleaned up.`));
239082
239357
  } catch (error) {
239083
239358
  const errorMsg = error instanceof Error ? error.message : String(error);
239084
- console.log(chalk10.red(`
239359
+ console.log(chalk11.red(`
239085
239360
  \u274C Failed to overwrite project files: ${errorMsg}`));
239086
- console.log(chalk10.yellow(` Generated files remain in: ${tempDirName} for manual review`));
239361
+ console.log(chalk11.yellow(` Generated files remain in: ${tempDirName} for manual review`));
239087
239362
  }
239088
239363
  }
239089
239364
  var init_project_validator = __esm({
@@ -239096,298 +239371,23 @@ var init_project_validator = __esm({
239096
239371
  }
239097
239372
  });
239098
239373
 
239099
- // src/commands/pull-v3/targeted-typescript-placeholders.ts
239100
- import { randomBytes as randomBytes2 } from "crypto";
239101
- function generatePlaceholderId() {
239102
- return randomBytes2(4).toString("hex").toUpperCase();
239103
- }
239104
- function createTargetedTypeScriptPlaceholders(content, debug = false) {
239105
- const replacements = {};
239106
- let processedContent = content;
239107
- let replacedFields = 0;
239108
- const originalSize = content.length;
239109
- const promptRegex = /(\s+prompt:\s*)((['"`])([^]*?)\3)/g;
239110
- processedContent = processedContent.replace(promptRegex, (match2, prefix, fullValue) => {
239111
- if (fullValue.length >= MIN_REPLACEMENT_LENGTH) {
239112
- const placeholder = `<PROMPT_${generatePlaceholderId()}>`;
239113
- replacements[placeholder] = fullValue;
239114
- replacedFields++;
239115
- return `${prefix}${placeholder}`;
239116
- }
239117
- return match2;
239118
- });
239119
- const descriptionRegex = /(\s+description:\s*)((['"`])([^]*?)\3)/g;
239120
- processedContent = processedContent.replace(descriptionRegex, (match2, prefix, fullValue) => {
239121
- if (fullValue.length >= MIN_REPLACEMENT_LENGTH) {
239122
- const placeholder = `<DESC_${generatePlaceholderId()}>`;
239123
- replacements[placeholder] = fullValue;
239124
- replacedFields++;
239125
- return `${prefix}${placeholder}`;
239126
- }
239127
- return match2;
239128
- });
239129
- const inputSchemaRegex = /(\s+inputSchema:\s*)(\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\})/g;
239130
- processedContent = processedContent.replace(inputSchemaRegex, (match2, prefix, schemaObject) => {
239131
- if (schemaObject.length >= MIN_REPLACEMENT_LENGTH) {
239132
- const placeholder = `<INPUT_SCHEMA_${generatePlaceholderId()}>`;
239133
- replacements[placeholder] = schemaObject;
239134
- replacedFields++;
239135
- return `${prefix}${placeholder}`;
239136
- }
239137
- return match2;
239138
- });
239139
- const detailsSchemaRegex = /(\s+detailsSchema:\s*)(z\.object\(\{[^]*?\}\)(?:\.[^,}\s]+)*)/g;
239140
- processedContent = processedContent.replace(detailsSchemaRegex, (match2, prefix, schemaObject) => {
239141
- if (schemaObject.length >= MIN_REPLACEMENT_LENGTH) {
239142
- const placeholder = `<DETAILS_SCHEMA_${generatePlaceholderId()}>`;
239143
- replacements[placeholder] = schemaObject;
239144
- replacedFields++;
239145
- return `${prefix}${placeholder}`;
239146
- }
239147
- return match2;
239148
- });
239149
- const propsRegex = /(\s+props:\s*)(z\.object\(\{[^]*?\}\)(?:\.[^,}\s]+)*)/g;
239150
- processedContent = processedContent.replace(propsRegex, (match2, prefix, propsObject) => {
239151
- if (propsObject.length >= MIN_REPLACEMENT_LENGTH) {
239152
- const placeholder = `<PROPS_${generatePlaceholderId()}>`;
239153
- replacements[placeholder] = propsObject;
239154
- replacedFields++;
239155
- return `${prefix}${placeholder}`;
239156
- }
239157
- return match2;
239158
- });
239159
- const processedSize = processedContent.length;
239160
- const savings = originalSize - processedSize;
239161
- const savingsPercentage = originalSize > 0 ? savings / originalSize * 100 : 0;
239162
- return {
239163
- processedContent,
239164
- replacements,
239165
- stats: {
239166
- originalSize,
239167
- processedSize,
239168
- savings,
239169
- savingsPercentage,
239170
- replacedFields
239171
- }
239172
- };
239173
- }
239174
- function restoreTargetedTypeScriptPlaceholders(content, replacements) {
239175
- let restoredContent = content;
239176
- const sortedPlaceholders = Object.keys(replacements).sort((a, b) => b.length - a.length);
239177
- for (const placeholder of sortedPlaceholders) {
239178
- const originalValue = replacements[placeholder];
239179
- restoredContent = restoredContent.replace(placeholder, originalValue);
239180
- }
239181
- return restoredContent;
239182
- }
239183
- var MIN_REPLACEMENT_LENGTH;
239184
- var init_targeted_typescript_placeholders = __esm({
239185
- "src/commands/pull-v3/targeted-typescript-placeholders.ts"() {
239186
- "use strict";
239187
- init_esm_shims();
239188
- MIN_REPLACEMENT_LENGTH = 10;
239189
- }
239190
- });
239191
-
239192
- // src/commands/pull-v3/utils/model-provider-detector.ts
239193
- import { anthropic } from "@ai-sdk/anthropic";
239194
- import { openai } from "@ai-sdk/openai";
239195
- import { google } from "@ai-sdk/google";
239196
- function getAvailableModel() {
239197
- for (const config of PROVIDER_CONFIGS) {
239198
- const hasKey = config.envVars.some((envVar) => {
239199
- const value = process.env[envVar];
239200
- return value && value.trim() !== "";
239201
- });
239202
- if (hasKey) {
239203
- switch (config.name) {
239204
- case "anthropic":
239205
- return anthropic(config.model);
239206
- case "openai":
239207
- return openai(config.model);
239208
- case "google":
239209
- return google(config.model);
239210
- default:
239211
- throw new Error(`Unknown provider: ${config.name}`);
239212
- }
239213
- }
239214
- }
239215
- throw new Error(
239216
- "No API keys detected. Please set ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY"
239217
- );
239218
- }
239219
- var PROVIDER_CONFIGS;
239220
- var init_model_provider_detector = __esm({
239221
- "src/commands/pull-v3/utils/model-provider-detector.ts"() {
239222
- "use strict";
239223
- init_esm_shims();
239224
- PROVIDER_CONFIGS = [
239225
- {
239226
- name: "anthropic",
239227
- envVars: ["ANTHROPIC_API_KEY"],
239228
- model: "claude-sonnet-4-5"
239229
- },
239230
- {
239231
- name: "openai",
239232
- envVars: ["OPENAI_API_KEY"],
239233
- model: "gpt-4.1"
239234
- },
239235
- {
239236
- name: "google",
239237
- envVars: ["GOOGLE_API_KEY", "GOOGLE_GENERATIVE_AI_API_KEY"],
239238
- model: "gemini-2.5-flash"
239239
- }
239240
- ];
239241
- }
239242
- });
239243
-
239244
- // src/commands/pull-v3/llm-content-merger.ts
239245
- import { generateText } from "ai";
239246
- import chalk11 from "chalk";
239247
- function stripCodeFences(content) {
239248
- content = content.replace(/^```(?:typescript|ts|javascript|js)?\s*\n?/i, "");
239249
- content = content.replace(/\n?```\s*$/i, "");
239250
- return content;
239251
- }
239252
- function estimateTokens(text3) {
239253
- return Math.ceil(text3.length / 4);
239254
- }
239255
- function calculateCostEstimate(promptTokens, completionTokens) {
239256
- const promptCost = promptTokens / 1e6 * 3;
239257
- const completionCost = completionTokens / 1e6 * 15;
239258
- return promptCost + completionCost;
239259
- }
239260
- async function mergeComponentsWithLLM(request) {
239261
- const { oldContent, newContent, modifiedComponents, filePath } = request;
239262
- const componentList = modifiedComponents.map((c) => `- ${c.componentType}:${c.componentId}`).join("\n");
239263
- const prompt = `You are a TypeScript code expert tasked with intelligently merging component updates.
239264
-
239265
- ## Task
239266
- Merge the OLD file content with NEW component definitions, preserving the original file structure while updating only the modified components.
239267
-
239268
- ## Modified Components to Update
239269
- ${componentList}
239270
-
239271
- ## Instructions
239272
- 0. **Please ensure you focus changes to minimize git diff size.** We want a clean git history.
239273
- 1. **Preserve original structure**: Keep imports, exports, comments, and overall file organization
239274
- 2. **Update only modified components**: Replace the specified components with their new versions
239275
- 3. **Maintain code style**: Match the original formatting, indentation, and style
239276
- 4. **Improve schemas**: Use better zod schemas from the new content where applicable. E.g. if the new content uses something like z.union([z.null(), z.string()]), use z.string().nullable() instead.
239277
- 5. **Keep variable names**: Preserve original variable names and declarations
239278
- 6. **Preserve non-component code**: Keep any non-component logic, comments, or utilities
239279
- 7. **Please leave all imports at the top of the file.** Don't use .js imports, use .ts imports instead. (import example from './example')
239280
- 8. **Format JavaScript functions for maximum readability**:
239281
- - When you see compressed/minified function code like \`async({params})=>{...code...}\`, expand and prettify it
239282
- - Add proper line breaks, spacing, and indentation to make the function readable
239283
- - Ensure all braces \`{}\`, parentheses \`()\`, and syntax are properly balanced and valid
239284
- - Format the function code following TypeScript/JavaScript best practices
239285
- - Make sure the final code is compilable and syntactically correct
239286
- - Example: \`async({a,b})=>{return a+b}\` should become:
239287
- \`\`\`
239288
- async ({ a, b }) => {
239289
- return a + b;
239290
- }
239291
- \`\`\`
239292
-
239293
- ## OLD Content:
239294
- \`\`\`typescript
239295
- ${oldContent}
239296
- \`\`\`
239297
-
239298
- ## NEW Component Definitions:
239299
- \`\`\`typescript
239300
- ${newContent}
239301
- \`\`\`
239302
-
239303
- ## Output
239304
- Provide the merged TypeScript file that:
239305
- - Keeps the original file structure
239306
- - Updates ONLY the modified components listed above
239307
- - Maintains consistent code style
239308
- - Uses improved schemas where beneficial
239309
- - Preserves all imports, exports, and other code
239310
- - **Formats all function code beautifully with proper spacing, line breaks, and indentation**
239311
- - **Ensures all syntax is valid and compilable TypeScript/JavaScript**
239312
- - Start the code immidiately with the first line of the file, skip any backticks or other formatting announcing that it is a code block or typescript file.
239313
- - Please follow biomes.dev code style.
239314
-
239315
- Return only the merged TypeScript code without any explanation or markdown formatting.`;
239316
- try {
239317
- const oldPlaceholders = createTargetedTypeScriptPlaceholders(oldContent);
239318
- const newPlaceholders = createTargetedTypeScriptPlaceholders(newContent);
239319
- const processedPrompt = prompt.replace(oldContent, oldPlaceholders.processedContent).replace(newContent, newPlaceholders.processedContent);
239320
- const estimatedPromptTokens = estimateTokens(processedPrompt);
239321
- const result = await generateText({
239322
- model: getAvailableModel(),
239323
- prompt: processedPrompt
239324
- });
239325
- let mergedContent = result.text.trim();
239326
- mergedContent = stripCodeFences(mergedContent);
239327
- const estimatedCompletionTokens = estimateTokens(mergedContent);
239328
- const totalTokens = estimatedPromptTokens + estimatedCompletionTokens;
239329
- const estimatedCost = calculateCostEstimate(estimatedPromptTokens, estimatedCompletionTokens);
239330
- console.log(
239331
- chalk11.gray(
239332
- ` \u{1F4B0} LLM usage: ~${totalTokens.toLocaleString()} tokens ($${estimatedCost.toFixed(4)})`
239333
- )
239334
- );
239335
- const allReplacements = {
239336
- ...oldPlaceholders.replacements,
239337
- ...newPlaceholders.replacements
239338
- };
239339
- if (Object.keys(allReplacements).length > 0) {
239340
- mergedContent = restoreTargetedTypeScriptPlaceholders(mergedContent, allReplacements);
239341
- }
239342
- const changes = modifiedComponents.map((c) => `Updated ${c.componentType}:${c.componentId}`);
239343
- return {
239344
- mergedContent,
239345
- changes,
239346
- success: true,
239347
- usage: {
239348
- promptTokens: estimatedPromptTokens,
239349
- completionTokens: estimatedCompletionTokens,
239350
- totalTokens,
239351
- estimatedCost
239352
- }
239353
- };
239354
- } catch (error) {
239355
- const errorMsg = error instanceof Error ? error.message : String(error);
239356
- return {
239357
- mergedContent: oldContent,
239358
- // Fallback to original
239359
- changes: [],
239360
- success: false,
239361
- error: errorMsg
239362
- };
239363
- }
239364
- }
239365
- var init_llm_content_merger = __esm({
239366
- "src/commands/pull-v3/llm-content-merger.ts"() {
239367
- "use strict";
239368
- init_esm_shims();
239369
- init_targeted_typescript_placeholders();
239370
- init_model_provider_detector();
239371
- }
239372
- });
239373
-
239374
239374
  // src/commands/pull-v3/component-updater.ts
239375
239375
  var component_updater_exports = {};
239376
239376
  __export(component_updater_exports, {
239377
239377
  copyProjectToTemp: () => copyProjectToTemp,
239378
239378
  updateModifiedComponents: () => updateModifiedComponents
239379
239379
  });
239380
+ import { spawn as spawn2 } from "child_process";
239380
239381
  import {
239382
+ copyFileSync as copyFileSync2,
239383
+ existsSync as existsSync9,
239381
239384
  mkdirSync as mkdirSync3,
239382
- readFileSync as readFileSync5,
239383
- writeFileSync as writeFileSync5,
239384
239385
  readdirSync as readdirSync4,
239386
+ readFileSync as readFileSync5,
239385
239387
  statSync as statSync3,
239386
- copyFileSync as copyFileSync2,
239387
- existsSync as existsSync9
239388
+ writeFileSync as writeFileSync5
239388
239389
  } from "fs";
239389
- import { dirname as dirname7, join as join10, extname as extname3 } from "path";
239390
- import { spawn as spawn2 } from "child_process";
239390
+ import { dirname as dirname7, extname as extname3, join as join10 } from "path";
239391
239391
  import chalk12 from "chalk";
239392
239392
  function copyProjectToTemp(projectRoot, tempDirName) {
239393
239393
  const tempDir = join10(projectRoot, tempDirName);
@@ -239822,7 +239822,6 @@ var init_component_updater = __esm({
239822
239822
  "src/commands/pull-v3/component-updater.ts"() {
239823
239823
  "use strict";
239824
239824
  init_esm_shims();
239825
- init_project_validator();
239826
239825
  init_agent_generator();
239827
239826
  init_artifact_component_generator();
239828
239827
  init_context_config_generator();
@@ -239836,6 +239835,7 @@ var init_component_updater = __esm({
239836
239835
  init_status_component_generator();
239837
239836
  init_sub_agent_generator();
239838
239837
  init_llm_content_merger();
239838
+ init_project_validator();
239839
239839
  init_component_registry();
239840
239840
  }
239841
239841
  });
@@ -239845,7 +239845,7 @@ var new_component_generator_exports = {};
239845
239845
  __export(new_component_generator_exports, {
239846
239846
  createNewComponents: () => createNewComponents
239847
239847
  });
239848
- import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync6, existsSync as existsSync10 } from "fs";
239848
+ import { existsSync as existsSync10, mkdirSync as mkdirSync4, writeFileSync as writeFileSync6 } from "fs";
239849
239849
  import { dirname as dirname8, join as join11 } from "path";
239850
239850
  import chalk13 from "chalk";
239851
239851
  function toKebabCase(id) {
@@ -240049,7 +240049,7 @@ async function createNewComponents(comparison, remoteProject, localRegistry, pat
240049
240049
  } else if (componentType === "functions") {
240050
240050
  componentData = remoteProject.functions?.[componentId];
240051
240051
  } else if (componentType === "functionTools") {
240052
- let functionToolData = remoteProject.functionTools?.[componentId] || remoteProject.functions?.[componentId];
240052
+ const functionToolData = remoteProject.functionTools?.[componentId] || remoteProject.functions?.[componentId];
240053
240053
  if (functionToolData && "functionId" in functionToolData && functionToolData.functionId && remoteProject.functions?.[functionToolData.functionId]) {
240054
240054
  const functionData = remoteProject.functions[functionToolData.functionId];
240055
240055
  componentData = { ...functionData, ...functionToolData };
@@ -241545,8 +241545,8 @@ async function devCommand(options) {
241545
241545
  init_esm_shims();
241546
241546
  import { existsSync as existsSync3, readdirSync, writeFileSync as writeFileSync2 } from "fs";
241547
241547
  import { basename, dirname as dirname2, join as join3, resolve } from "path";
241548
- import chalk4 from "chalk";
241549
241548
  import * as p3 from "@clack/prompts";
241549
+ import chalk4 from "chalk";
241550
241550
  function findProjectRoot(startPath) {
241551
241551
  let currentPath = resolve(startPath);
241552
241552
  const root = dirname2(currentPath);
@@ -241702,15 +241702,15 @@ Note: Config file created in ${configDir}`));
241702
241702
  // src/commands/list-agents.ts
241703
241703
  init_esm_shims();
241704
241704
  init_api();
241705
+ import * as p5 from "@clack/prompts";
241705
241706
  import chalk6 from "chalk";
241706
241707
  import Table from "cli-table3";
241707
- import * as p5 from "@clack/prompts";
241708
241708
 
241709
241709
  // src/utils/cli-pipeline.ts
241710
241710
  init_esm_shims();
241711
241711
  init_config();
241712
- import chalk5 from "chalk";
241713
241712
  import * as p4 from "@clack/prompts";
241713
+ import chalk5 from "chalk";
241714
241714
  async function initializeCommand(options = {}) {
241715
241715
  const {
241716
241716
  configPath,
@@ -242037,8 +242037,8 @@ async function pushCommand(options) {
242037
242037
 
242038
242038
  // src/commands/update.ts
242039
242039
  init_esm_shims();
242040
- import chalk16 from "chalk";
242041
242040
  import * as p8 from "@clack/prompts";
242041
+ import chalk16 from "chalk";
242042
242042
 
242043
242043
  // src/utils/package-manager.ts
242044
242044
  init_esm_shims();