@inkeep/agents-cli 0.33.0 → 0.33.1

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 +1153 -471
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -14067,7 +14067,7 @@ var require_typescript = __commonJS({
14067
14067
  SymbolDisplayPartKind: () => SymbolDisplayPartKind,
14068
14068
  SymbolFlags: () => SymbolFlags,
14069
14069
  SymbolFormatFlags: () => SymbolFormatFlags,
14070
- SyntaxKind: () => SyntaxKind,
14070
+ SyntaxKind: () => SyntaxKind2,
14071
14071
  Ternary: () => Ternary,
14072
14072
  ThrottledCancellationToken: () => ThrottledCancellationToken,
14073
14073
  TokenClass: () => TokenClass,
@@ -17954,7 +17954,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`,
17954
17954
  function formatSyntaxKind(kind) {
17955
17955
  return formatEnum(
17956
17956
  kind,
17957
- SyntaxKind,
17957
+ SyntaxKind2,
17958
17958
  /*isFlags*/
17959
17959
  false
17960
17960
  );
@@ -19402,7 +19402,7 @@ ${lanes.join("\n")}
19402
19402
  })(tracingEnabled || (tracingEnabled = {}));
19403
19403
  var startTracing = tracingEnabled.startTracing;
19404
19404
  var dumpTracingLegend = tracingEnabled.dumpLegend;
19405
- var SyntaxKind = /* @__PURE__ */ ((SyntaxKind5) => {
19405
+ var SyntaxKind2 = /* @__PURE__ */ ((SyntaxKind5) => {
19406
19406
  SyntaxKind5[SyntaxKind5["Unknown"] = 0] = "Unknown";
19407
19407
  SyntaxKind5[SyntaxKind5["EndOfFileToken"] = 1] = "EndOfFileToken";
19408
19408
  SyntaxKind5[SyntaxKind5["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
@@ -19908,7 +19908,7 @@ ${lanes.join("\n")}
19908
19908
  /* LastKeyword */
19909
19909
  ] = "LastContextualKeyword";
19910
19910
  return SyntaxKind5;
19911
- })(SyntaxKind || {});
19911
+ })(SyntaxKind2 || {});
19912
19912
  var NodeFlags = /* @__PURE__ */ ((NodeFlags3) => {
19913
19913
  NodeFlags3[NodeFlags3["None"] = 0] = "None";
19914
19914
  NodeFlags3[NodeFlags3["Let"] = 1] = "Let";
@@ -35992,7 +35992,7 @@ ${lanes.join("\n")}
35992
35992
  this.checker = checker;
35993
35993
  }
35994
35994
  }
35995
- function Node4(kind, pos, end) {
35995
+ function Node42(kind, pos, end) {
35996
35996
  this.pos = pos;
35997
35997
  this.end = end;
35998
35998
  this.kind = kind;
@@ -36031,11 +36031,11 @@ ${lanes.join("\n")}
36031
36031
  this.skipTrivia = skipTrivia2 || ((pos) => pos);
36032
36032
  }
36033
36033
  var objectAllocator = {
36034
- getNodeConstructor: () => Node4,
36034
+ getNodeConstructor: () => Node42,
36035
36035
  getTokenConstructor: () => Token,
36036
36036
  getIdentifierConstructor: () => Identifier2,
36037
- getPrivateIdentifierConstructor: () => Node4,
36038
- getSourceFileConstructor: () => Node4,
36037
+ getPrivateIdentifierConstructor: () => Node42,
36038
+ getSourceFileConstructor: () => Node42,
36039
36039
  getSymbolConstructor: () => Symbol4,
36040
36040
  getTypeConstructor: () => Type3,
36041
36041
  getSignatureConstructor: () => Signature2,
@@ -209570,7 +209570,7 @@ ${options.prefix}` : "\n" : options.prefix
209570
209570
  SymbolDisplayPartKind: () => SymbolDisplayPartKind,
209571
209571
  SymbolFlags: () => SymbolFlags,
209572
209572
  SymbolFormatFlags: () => SymbolFormatFlags,
209573
- SyntaxKind: () => SyntaxKind,
209573
+ SyntaxKind: () => SyntaxKind2,
209574
209574
  Ternary: () => Ternary,
209575
209575
  ThrottledCancellationToken: () => ThrottledCancellationToken,
209576
209576
  TokenClass: () => TokenClass,
@@ -211813,7 +211813,7 @@ ${options.prefix}` : "\n" : options.prefix
211813
211813
  LogLevel: () => LogLevel2,
211814
211814
  Msg: () => Msg,
211815
211815
  OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent,
211816
- Project: () => Project2,
211816
+ Project: () => Project22,
211817
211817
  ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent,
211818
211818
  ProjectKind: () => ProjectKind,
211819
211819
  ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent,
@@ -213269,7 +213269,7 @@ ${options.prefix}` : "\n" : options.prefix
213269
213269
  }
213270
213270
  return !arrayIsEqualTo(imports1, imports2);
213271
213271
  }
213272
- var Project2 = class _Project {
213272
+ var Project22 = class _Project {
213273
213273
  /** @internal */
213274
213274
  constructor(projectName, projectKind, projectService, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, directoryStructureHost, currentDirectory) {
213275
213275
  this.projectKind = projectKind;
@@ -214938,7 +214938,7 @@ ${options.prefix}` : "\n" : options.prefix
214938
214938
  return unresolvedImports || emptyArray2;
214939
214939
  });
214940
214940
  }
214941
- var InferredProject2 = class extends Project2 {
214941
+ var InferredProject2 = class extends Project22 {
214942
214942
  /** @internal */
214943
214943
  constructor(projectService, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) {
214944
214944
  super(
@@ -215030,7 +215030,7 @@ ${options.prefix}` : "\n" : options.prefix
215030
215030
  };
215031
215031
  }
215032
215032
  };
215033
- var AuxiliaryProject = class extends Project2 {
215033
+ var AuxiliaryProject = class extends Project22 {
215034
215034
  constructor(hostProject) {
215035
215035
  super(
215036
215036
  hostProject.projectService.newAuxiliaryProjectName(),
@@ -215056,7 +215056,7 @@ ${options.prefix}` : "\n" : options.prefix
215056
215056
  return;
215057
215057
  }
215058
215058
  };
215059
- var _AutoImportProviderProject = class _AutoImportProviderProject2 extends Project2 {
215059
+ var _AutoImportProviderProject = class _AutoImportProviderProject2 extends Project22 {
215060
215060
  /** @internal */
215061
215061
  constructor(hostProject, initialRootNames, compilerOptions) {
215062
215062
  super(
@@ -215325,7 +215325,7 @@ ${options.prefix}` : "\n" : options.prefix
215325
215325
  noLib: true
215326
215326
  };
215327
215327
  var AutoImportProviderProject = _AutoImportProviderProject;
215328
- var ConfiguredProject2 = class extends Project2 {
215328
+ var ConfiguredProject2 = class extends Project22 {
215329
215329
  /** @internal */
215330
215330
  constructor(configFileName, canonicalConfigFilePath, projectService, cachedDirectoryStructureHost, pendingUpdateReason) {
215331
215331
  super(
@@ -215527,7 +215527,7 @@ ${options.prefix}` : "\n" : options.prefix
215527
215527
  );
215528
215528
  }
215529
215529
  };
215530
- var ExternalProject = class extends Project2 {
215530
+ var ExternalProject = class extends Project22 {
215531
215531
  /** @internal */
215532
215532
  constructor(externalProjectName, projectService, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) {
215533
215533
  super(
@@ -219314,7 +219314,7 @@ Dynamic files must always be opened with service's current directory or service
219314
219314
  return;
219315
219315
  }
219316
219316
  if (this.host.importPlugin) {
219317
- const importPromise = Project2.importServicePluginAsync(
219317
+ const importPromise = Project22.importServicePluginAsync(
219318
219318
  pluginConfigEntry,
219319
219319
  searchPaths,
219320
219320
  this.host,
@@ -219328,7 +219328,7 @@ Dynamic files must always be opened with service's current directory or service
219328
219328
  }
219329
219329
  this.endEnablePlugin(
219330
219330
  project,
219331
- Project2.importServicePluginSync(
219331
+ Project22.importServicePluginSync(
219332
219332
  pluginConfigEntry,
219333
219333
  searchPaths,
219334
219334
  this.host,
@@ -224552,7 +224552,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
224552
224552
  LogLevel: () => LogLevel2,
224553
224553
  Msg: () => Msg,
224554
224554
  OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent,
224555
- Project: () => Project2,
224555
+ Project: () => Project22,
224556
224556
  ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent,
224557
224557
  ProjectKind: () => ProjectKind,
224558
224558
  ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent,
@@ -226534,7 +226534,7 @@ var require_codegen = __commonJS({
226534
226534
  AND: new code_1._Code("&&"),
226535
226535
  ADD: new code_1._Code("+")
226536
226536
  };
226537
- var Node3 = class {
226537
+ var Node5 = class {
226538
226538
  optimizeNodes() {
226539
226539
  return this;
226540
226540
  }
@@ -226542,7 +226542,7 @@ var require_codegen = __commonJS({
226542
226542
  return this;
226543
226543
  }
226544
226544
  };
226545
- var Def = class extends Node3 {
226545
+ var Def = class extends Node5 {
226546
226546
  constructor(varKind, name2, rhs) {
226547
226547
  super();
226548
226548
  this.varKind = varKind;
@@ -226565,7 +226565,7 @@ var require_codegen = __commonJS({
226565
226565
  return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
226566
226566
  }
226567
226567
  };
226568
- var Assign = class extends Node3 {
226568
+ var Assign = class extends Node5 {
226569
226569
  constructor(lhs, rhs, sideEffects) {
226570
226570
  super();
226571
226571
  this.lhs = lhs;
@@ -226595,7 +226595,7 @@ var require_codegen = __commonJS({
226595
226595
  return `${this.lhs} ${this.op}= ${this.rhs};` + _n2;
226596
226596
  }
226597
226597
  };
226598
- var Label = class extends Node3 {
226598
+ var Label = class extends Node5 {
226599
226599
  constructor(label) {
226600
226600
  super();
226601
226601
  this.label = label;
@@ -226605,7 +226605,7 @@ var require_codegen = __commonJS({
226605
226605
  return `${this.label}:` + _n2;
226606
226606
  }
226607
226607
  };
226608
- var Break = class extends Node3 {
226608
+ var Break = class extends Node5 {
226609
226609
  constructor(label) {
226610
226610
  super();
226611
226611
  this.label = label;
@@ -226616,7 +226616,7 @@ var require_codegen = __commonJS({
226616
226616
  return `break${label};` + _n2;
226617
226617
  }
226618
226618
  };
226619
- var Throw = class extends Node3 {
226619
+ var Throw = class extends Node5 {
226620
226620
  constructor(error) {
226621
226621
  super();
226622
226622
  this.error = error;
@@ -226628,7 +226628,7 @@ var require_codegen = __commonJS({
226628
226628
  return this.error.names;
226629
226629
  }
226630
226630
  };
226631
- var AnyCode = class extends Node3 {
226631
+ var AnyCode = class extends Node5 {
226632
226632
  constructor(code) {
226633
226633
  super();
226634
226634
  this.code = code;
@@ -226647,7 +226647,7 @@ var require_codegen = __commonJS({
226647
226647
  return this.code instanceof code_1._CodeOrName ? this.code.names : {};
226648
226648
  }
226649
226649
  };
226650
- var ParentNode = class extends Node3 {
226650
+ var ParentNode = class extends Node5 {
226651
226651
  constructor(nodes = []) {
226652
226652
  super();
226653
226653
  this.nodes = nodes;
@@ -235263,6 +235263,171 @@ var init_project_loader = __esm({
235263
235263
  }
235264
235264
  });
235265
235265
 
235266
+ // src/utils/json-comparator.ts
235267
+ function compareJsonObjects(obj1, obj2, options = {}) {
235268
+ const {
235269
+ ignoreArrayOrder = true,
235270
+ ignoreCase = false,
235271
+ ignoreWhitespace = false,
235272
+ ignorePaths = []
235273
+ } = options;
235274
+ const differences = [];
235275
+ const stats = {
235276
+ totalKeys: 0,
235277
+ differentKeys: 0,
235278
+ missingKeys: 0,
235279
+ extraKeys: 0
235280
+ };
235281
+ function normalizeValue(value) {
235282
+ if (typeof value === "string") {
235283
+ let normalized = value;
235284
+ if (ignoreCase) {
235285
+ normalized = normalized.toLowerCase();
235286
+ }
235287
+ if (ignoreWhitespace) {
235288
+ normalized = normalized.trim().replace(/\s+/g, " ");
235289
+ }
235290
+ return normalized;
235291
+ }
235292
+ return value;
235293
+ }
235294
+ function shouldIgnorePath(path5) {
235295
+ return ignorePaths.some((ignorePath) => {
235296
+ if (ignorePath.endsWith("*")) {
235297
+ return path5.startsWith(ignorePath.slice(0, -1));
235298
+ }
235299
+ return path5 === ignorePath;
235300
+ });
235301
+ }
235302
+ function compareValues(value1, value2, path5 = "") {
235303
+ if (shouldIgnorePath(path5)) {
235304
+ return true;
235305
+ }
235306
+ if (value1 === null || value1 === void 0) {
235307
+ if (value2 === null || value2 === void 0) {
235308
+ return true;
235309
+ }
235310
+ differences.push({
235311
+ path: path5,
235312
+ type: "different",
235313
+ value1,
235314
+ value2,
235315
+ description: `Null/undefined mismatch: ${value1} vs ${value2}`
235316
+ });
235317
+ return false;
235318
+ }
235319
+ if (value2 === null || value2 === void 0) {
235320
+ differences.push({
235321
+ path: path5,
235322
+ type: "different",
235323
+ value1,
235324
+ value2,
235325
+ description: `Null/undefined mismatch: ${value1} vs ${value2}`
235326
+ });
235327
+ return false;
235328
+ }
235329
+ if (typeof value1 !== typeof value2) {
235330
+ differences.push({
235331
+ path: path5,
235332
+ type: "type_mismatch",
235333
+ value1,
235334
+ value2,
235335
+ description: `Type mismatch: ${typeof value1} vs ${typeof value2}`
235336
+ });
235337
+ return false;
235338
+ }
235339
+ if (typeof value1 !== "object") {
235340
+ const normalized1 = normalizeValue(value1);
235341
+ const normalized2 = normalizeValue(value2);
235342
+ if (normalized1 !== normalized2) {
235343
+ differences.push({
235344
+ path: path5,
235345
+ type: "different",
235346
+ value1,
235347
+ value2,
235348
+ description: `Value mismatch: ${value1} vs ${value2}`
235349
+ });
235350
+ return false;
235351
+ }
235352
+ return true;
235353
+ }
235354
+ if (Array.isArray(value1) && Array.isArray(value2)) {
235355
+ if (value1.length !== value2.length) {
235356
+ differences.push({
235357
+ path: path5,
235358
+ type: "different",
235359
+ value1: value1.length,
235360
+ value2: value2.length,
235361
+ description: `Array length mismatch: ${value1.length} vs ${value2.length}`
235362
+ });
235363
+ return false;
235364
+ }
235365
+ if (ignoreArrayOrder) {
235366
+ const sorted1 = [...value1].sort(
235367
+ (a2, b3) => JSON.stringify(a2).localeCompare(JSON.stringify(b3))
235368
+ );
235369
+ const sorted2 = [...value2].sort(
235370
+ (a2, b3) => JSON.stringify(a2).localeCompare(JSON.stringify(b3))
235371
+ );
235372
+ for (let i3 = 0; i3 < sorted1.length; i3++) {
235373
+ compareValues(sorted1[i3], sorted2[i3], `${path5}[${i3}]`);
235374
+ }
235375
+ } else {
235376
+ for (let i3 = 0; i3 < value1.length; i3++) {
235377
+ compareValues(value1[i3], value2[i3], `${path5}[${i3}]`);
235378
+ }
235379
+ }
235380
+ return true;
235381
+ }
235382
+ if (typeof value1 === "object" && typeof value2 === "object") {
235383
+ const keys1 = Object.keys(value1);
235384
+ const keys2 = Object.keys(value2);
235385
+ const allKeys = /* @__PURE__ */ new Set([...keys1, ...keys2]);
235386
+ stats.totalKeys += allKeys.size;
235387
+ for (const key of allKeys) {
235388
+ const currentPath = path5 ? `${path5}.${key}` : key;
235389
+ if (!keys1.includes(key)) {
235390
+ differences.push({
235391
+ path: currentPath,
235392
+ type: "missing",
235393
+ value2: value2[key],
235394
+ description: `Missing key in first object: ${key}`
235395
+ });
235396
+ stats.missingKeys++;
235397
+ continue;
235398
+ }
235399
+ if (!keys2.includes(key)) {
235400
+ differences.push({
235401
+ path: currentPath,
235402
+ type: "extra",
235403
+ value1: value1[key],
235404
+ description: `Extra key in first object: ${key}`
235405
+ });
235406
+ stats.extraKeys++;
235407
+ continue;
235408
+ }
235409
+ if (!compareValues(value1[key], value2[key], currentPath)) {
235410
+ stats.differentKeys++;
235411
+ }
235412
+ }
235413
+ return true;
235414
+ }
235415
+ return true;
235416
+ }
235417
+ compareValues(obj1, obj2);
235418
+ return {
235419
+ isEqual: differences.length === 0,
235420
+ differences,
235421
+ stats
235422
+ };
235423
+ }
235424
+ var init_json_comparator = __esm({
235425
+ "src/utils/json-comparator.ts"() {
235426
+ "use strict";
235427
+ init_esm_shims();
235428
+ }
235429
+ });
235430
+
235266
235431
  // src/commands/pull-v3/utils/generator-utils.ts
235267
235432
  function toCamelCase(str) {
235268
235433
  const result = str.replace(/[-_](.)/g, (_3, char) => char.toUpperCase()).replace(/[^a-zA-Z0-9]/g, "").replace(/^[0-9]/, "_$&");
@@ -235464,7 +235629,11 @@ function hasDistinctModels(agentModels, projectModels) {
235464
235629
  if (!agentOptions || !projectOptions) {
235465
235630
  return true;
235466
235631
  }
235467
- if (JSON.stringify(agentOptions) !== JSON.stringify(projectOptions)) {
235632
+ const comparison = compareJsonObjects(agentOptions, projectOptions, {
235633
+ ignoreArrayOrder: true,
235634
+ showDetails: false
235635
+ });
235636
+ if (!comparison.isEqual) {
235468
235637
  return true;
235469
235638
  }
235470
235639
  }
@@ -235593,6 +235762,20 @@ function generateAgentDefinition(agentId, agentData, style = DEFAULT_STYLE, regi
235593
235762
  lines.push(`${indentation}contextConfig: undefined,`);
235594
235763
  }
235595
235764
  }
235765
+ if (agentData.credentials && Array.isArray(agentData.credentials) && agentData.credentials.length > 0) {
235766
+ if (!registry2) {
235767
+ throw new Error("Registry is required for credentials generation");
235768
+ }
235769
+ const credentialVars = agentData.credentials.map((cred) => {
235770
+ const credVarName = registry2.getVariableName(cred.id, "credentials");
235771
+ if (!credVarName) {
235772
+ throw new Error(`Failed to resolve variable name for credential: ${cred.id}`);
235773
+ }
235774
+ return credVarName;
235775
+ });
235776
+ const credentialsArray = `[${credentialVars.join(", ")}]`;
235777
+ lines.push(`${indentation}credentials: () => ${credentialsArray},`);
235778
+ }
235596
235779
  if (agentData.stopWhen) {
235597
235780
  const stopWhenFormatted = formatStopWhen(agentData.stopWhen, style, 1);
235598
235781
  if (stopWhenFormatted) {
@@ -235616,11 +235799,11 @@ function generateAgentDefinition(agentId, agentData, style = DEFAULT_STYLE, regi
235616
235799
  lines.push(`})${semi}`);
235617
235800
  return lines.join("\n");
235618
235801
  }
235619
- function generateAgentImports(agentId, agentData, style = DEFAULT_STYLE, registry2, contextConfigData) {
235802
+ function generateAgentImports(agentId, agentData, style = DEFAULT_STYLE, registry2, contextConfigData, actualFilePath) {
235620
235803
  const imports = [];
235621
235804
  imports.push(generateImport(["agent"], "@inkeep/agents-sdk", style));
235622
235805
  if (registry2) {
235623
- const currentFilePath = `agents/${agentId}.ts`;
235806
+ const currentFilePath = actualFilePath || `agents/${agentId}.ts`;
235624
235807
  const referencedComponents = [];
235625
235808
  if (agentData.subAgents && typeof agentData.subAgents === "object") {
235626
235809
  const subAgentIds = Object.keys(agentData.subAgents);
@@ -235650,8 +235833,15 @@ function generateAgentImports(agentId, agentData, style = DEFAULT_STYLE, registr
235650
235833
  }
235651
235834
  return imports;
235652
235835
  }
235653
- function generateAgentFile(agentId, agentData, style = DEFAULT_STYLE, registry2, contextConfigData, projectModels) {
235654
- const imports = generateAgentImports(agentId, agentData, style, registry2, contextConfigData);
235836
+ function generateAgentFile(agentId, agentData, style = DEFAULT_STYLE, registry2, contextConfigData, projectModels, actualFilePath) {
235837
+ const imports = generateAgentImports(
235838
+ agentId,
235839
+ agentData,
235840
+ style,
235841
+ registry2,
235842
+ contextConfigData,
235843
+ actualFilePath
235844
+ );
235655
235845
  const definition = generateAgentDefinition(
235656
235846
  agentId,
235657
235847
  agentData,
@@ -235666,6 +235856,7 @@ var init_agent_generator = __esm({
235666
235856
  "src/commands/pull-v3/components/agent-generator.ts"() {
235667
235857
  "use strict";
235668
235858
  init_esm_shims();
235859
+ init_json_comparator();
235669
235860
  init_generator_utils();
235670
235861
  }
235671
235862
  });
@@ -235823,7 +236014,12 @@ function processFetchConfigTemplates(fetchConfig, headersVarName) {
235823
236014
  );
235824
236015
  return `\`${convertedStr.replace(/`/g, "\\`")}\``;
235825
236016
  } else {
235826
- return `'${value.replace(/'/g, "\\'")}'`;
236017
+ const isMultiline = value.includes("\n") || value.length > 80;
236018
+ if (isMultiline) {
236019
+ return `\`${value.replace(/`/g, "\\`")}\``;
236020
+ } else {
236021
+ return `'${value.replace(/'/g, "\\'")}'`;
236022
+ }
235827
236023
  }
235828
236024
  } else if (typeof value === "object" && value !== null) {
235829
236025
  return processObject(value);
@@ -235836,7 +236032,7 @@ function processFetchConfigTemplates(fetchConfig, headersVarName) {
235836
236032
  const items = obj.map((item) => processValue(item)).join(", ");
235837
236033
  return `[${items}]`;
235838
236034
  }
235839
- const entries = Object.entries(obj).map(([key, val]) => {
236035
+ const entries = Object.entries(obj).filter(([key, val]) => val !== void 0 && val !== null).map(([key, val]) => {
235840
236036
  const processedKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : `'${key}'`;
235841
236037
  return `${processedKey}: ${processValue(val)}`;
235842
236038
  });
@@ -235861,7 +236057,7 @@ function generateHeadersDefinition(headersId, headersData, style = DEFAULT_STYLE
235861
236057
  lines.push(`})${semi}`);
235862
236058
  return lines.join("\n");
235863
236059
  }
235864
- function generateFetchDefinitionDefinition(fetchId, fetchData, style = DEFAULT_STYLE, headersVarName) {
236060
+ function generateFetchDefinitionDefinition(fetchId, fetchData, style = DEFAULT_STYLE, headersVarName, registry2) {
235865
236061
  const { quotes, semicolons, indentation } = style;
235866
236062
  const q3 = quotes === "single" ? "'" : '"';
235867
236063
  const semi = semicolons ? ";" : "";
@@ -235888,11 +236084,18 @@ function generateFetchDefinitionDefinition(fetchId, fetchData, style = DEFAULT_S
235888
236084
  }
235889
236085
  if (fetchData.defaultValue) {
235890
236086
  if (typeof fetchData.defaultValue === "string") {
235891
- lines.push(`${indentation}defaultValue: ${formatString(fetchData.defaultValue, q3)},`);
236087
+ const isMultiline = fetchData.defaultValue.includes("\n") || fetchData.defaultValue.length > 80;
236088
+ lines.push(
236089
+ `${indentation}defaultValue: ${formatString(fetchData.defaultValue, q3, isMultiline)},`
236090
+ );
235892
236091
  } else {
235893
236092
  lines.push(`${indentation}defaultValue: ${JSON.stringify(fetchData.defaultValue)},`);
235894
236093
  }
235895
236094
  }
236095
+ if (fetchData.credentialReferenceId && registry2) {
236096
+ const validKey = registry2.getVariableName(fetchData.credentialReferenceId, "credentials");
236097
+ lines.push(`${indentation}credentialReference: ${validKey},`);
236098
+ }
235896
236099
  removeTrailingComma(lines);
235897
236100
  lines.push(`})${semi}`);
235898
236101
  return lines.join("\n");
@@ -235946,7 +236149,7 @@ function generateContextConfigDefinition(contextId, contextData, style = DEFAULT
235946
236149
  lines.push(`})${semi}`);
235947
236150
  return lines.join("\n");
235948
236151
  }
235949
- function generateContextConfigImports(contextId, contextData, style = DEFAULT_STYLE) {
236152
+ function generateContextConfigImports(contextId, contextData, style = DEFAULT_STYLE, registry2) {
235950
236153
  const imports = [];
235951
236154
  const coreImports = [];
235952
236155
  if (contextData.headers || hasHeadersInData(contextData)) {
@@ -235962,6 +236165,27 @@ function generateContextConfigImports(contextId, contextData, style = DEFAULT_ST
235962
236165
  if (hasSchemas(contextData)) {
235963
236166
  imports.push(generateImport(["z"], "zod", style));
235964
236167
  }
236168
+ if (registry2 && contextData.contextVariables) {
236169
+ const credentialRefs = [];
236170
+ for (const [varName, varData] of Object.entries(contextData.contextVariables)) {
236171
+ if (varData && typeof varData === "object" && varData.credentialReferenceId) {
236172
+ credentialRefs.push({
236173
+ id: varData.credentialReferenceId,
236174
+ type: "credentials"
236175
+ });
236176
+ }
236177
+ }
236178
+ if (credentialRefs.length > 0) {
236179
+ const contextComponent = registry2.get(contextId, "contextConfigs");
236180
+ if (contextComponent) {
236181
+ const credentialImports = registry2.getImportsForFile(
236182
+ contextComponent.filePath,
236183
+ credentialRefs
236184
+ );
236185
+ imports.push(...credentialImports);
236186
+ }
236187
+ }
236188
+ }
235965
236189
  return imports;
235966
236190
  }
235967
236191
  function hasHeadersInData(contextData) {
@@ -235977,7 +236201,7 @@ function hasSchemas(contextData) {
235977
236201
  return dataStr.includes("schema") || dataStr.includes("responseschema");
235978
236202
  }
235979
236203
  function generateContextConfigFile(contextId, contextData, style = DEFAULT_STYLE, registry2, agentId) {
235980
- const imports = generateContextConfigImports(contextId, contextData, style);
236204
+ const imports = generateContextConfigImports(contextId, contextData, style, registry2);
235981
236205
  const definitions = [];
235982
236206
  let headersVarName;
235983
236207
  if (contextData.headersSchema) {
@@ -236000,7 +236224,8 @@ function generateContextConfigFile(contextId, contextData, style = DEFAULT_STYLE
236000
236224
  varName,
236001
236225
  varData,
236002
236226
  style,
236003
- headersVarName
236227
+ headersVarName,
236228
+ registry2
236004
236229
  );
236005
236230
  definitions.push(fetchDefinition2);
236006
236231
  }
@@ -236068,13 +236293,14 @@ function formatRetrievalParams(retrievalParams, style, indentLevel) {
236068
236293
  const indent = indentation.repeat(indentLevel + 1);
236069
236294
  const lines = ["{"];
236070
236295
  for (const [key, value] of Object.entries(retrievalParams)) {
236296
+ const formattedKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key) ? key : `${q3}${key}${q3}`;
236071
236297
  if (typeof value === "string") {
236072
- lines.push(`${indent}${q3}${key}${q3}: ${formatString3(value, q3)},`);
236298
+ lines.push(`${indent}${formattedKey}: ${formatString3(value, q3)},`);
236073
236299
  } else if (typeof value === "number" || typeof value === "boolean") {
236074
- lines.push(`${indent}${q3}${key}${q3}: ${JSON.stringify(value)},`);
236300
+ lines.push(`${indent}${formattedKey}: ${JSON.stringify(value)},`);
236075
236301
  } else if (typeof value === "object" && value !== null) {
236076
236302
  lines.push(
236077
- `${indent}${q3}${key}${q3}: ${formatRetrievalParams(value, style, indentLevel + 1)},`
236303
+ `${indent}${formattedKey}: ${formatRetrievalParams(value, style, indentLevel + 1)},`
236078
236304
  );
236079
236305
  }
236080
236306
  }
@@ -236116,11 +236342,6 @@ function generateCredentialDefinition(credentialId, credentialData, style = DEFA
236116
236342
  } else {
236117
236343
  lines.push(`${indentation}retrievalParams: ${formattedParams},`);
236118
236344
  }
236119
- } else {
236120
- const defaultKey = credentialId.toUpperCase().replace(/-/g, "_");
236121
- lines.push(`${indentation}retrievalParams: {`);
236122
- lines.push(`${indentation}${indentation}${q3}key${q3}: ${formatString3(defaultKey, q3)}`);
236123
- lines.push(`${indentation}},`);
236124
236345
  }
236125
236346
  if (lines.length > 0 && lines[lines.length - 1].endsWith(",")) {
236126
236347
  lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
@@ -236207,6 +236428,23 @@ function generateDataComponentDefinition(componentId, componentData, style = DEF
236207
236428
  const zodSchema = convertJsonSchemaToZod2(schema);
236208
236429
  lines.push(`${indentation}props: ${zodSchema},`);
236209
236430
  }
236431
+ if (componentData.render && typeof componentData.render === "object") {
236432
+ const render = componentData.render;
236433
+ if (render.component && typeof render.component === "string") {
236434
+ lines.push(`${indentation}render: {`);
236435
+ const componentString = JSON.stringify(render.component);
236436
+ lines.push(`${indentation}${indentation}component: ${componentString},`);
236437
+ if (render.mockData && typeof render.mockData === "object") {
236438
+ const mockDataStr = JSON.stringify(render.mockData, null, 2);
236439
+ const formattedMockData = mockDataStr.split("\n").map((line, index2) => {
236440
+ if (index2 === 0) return line;
236441
+ return `${indentation}${indentation}${line}`;
236442
+ }).join("\n");
236443
+ lines.push(`${indentation}${indentation}mockData: ${formattedMockData},`);
236444
+ }
236445
+ lines.push(`${indentation}},`);
236446
+ }
236447
+ }
236210
236448
  if (lines.length > 0 && lines[lines.length - 1].endsWith(",")) {
236211
236449
  lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1);
236212
236450
  }
@@ -236724,6 +236962,9 @@ function generateMcpToolDefinition(toolId, toolData, style = DEFAULT_STYLE7, reg
236724
236962
  if (mcpConfig.transport) {
236725
236963
  lines.push(`${indentation}transport: ${JSON.stringify(mcpConfig.transport, null, 2)},`);
236726
236964
  }
236965
+ if (mcpConfig.activeTools && Array.isArray(mcpConfig.activeTools)) {
236966
+ lines.push(`${indentation}activeTools: ${JSON.stringify(mcpConfig.activeTools)},`);
236967
+ }
236727
236968
  }
236728
236969
  if (toolData.description) {
236729
236970
  lines.push(`${indentation}description: ${formatString7(toolData.description, q3, true)},`);
@@ -237096,7 +237337,11 @@ function hasDistinctModels2(subAgentModels, parentModels) {
237096
237337
  if (!subAgentOptions || !parentOptions) {
237097
237338
  return true;
237098
237339
  }
237099
- if (JSON.stringify(subAgentOptions) !== JSON.stringify(parentOptions)) {
237340
+ const comparison = compareJsonObjects(subAgentOptions, parentOptions, {
237341
+ ignoreArrayOrder: true,
237342
+ showDetails: false
237343
+ });
237344
+ if (!comparison.isEqual) {
237100
237345
  return true;
237101
237346
  }
237102
237347
  }
@@ -237369,12 +237614,12 @@ function generateSubAgentDefinition(agentId, agentData, style = DEFAULT_STYLE, r
237369
237614
  lines.push(`})${semi}`);
237370
237615
  return lines.join("\n");
237371
237616
  }
237372
- function generateSubAgentImports(agentId, agentData, style = DEFAULT_STYLE, registry2, parentAgentId, contextConfigData) {
237617
+ function generateSubAgentImports(agentId, agentData, style = DEFAULT_STYLE, registry2, parentAgentId, contextConfigData, actualFilePath) {
237373
237618
  const imports = [];
237374
237619
  imports.push(generateImport(["subAgent"], "@inkeep/agents-sdk", style));
237375
237620
  if (hasTemplateVariables(agentData.prompt) && parentAgentId && registry2 && contextConfigData) {
237376
237621
  const contextConfigId = contextConfigData.id;
237377
- const currentFilePath = `agents/sub-agents/${agentId}.ts`;
237622
+ const currentFilePath = actualFilePath || `agents/sub-agents/${agentId}.ts`;
237378
237623
  const importStatement = registry2.getImportStatement(
237379
237624
  currentFilePath,
237380
237625
  contextConfigId,
@@ -237385,7 +237630,7 @@ function generateSubAgentImports(agentId, agentData, style = DEFAULT_STYLE, regi
237385
237630
  }
237386
237631
  }
237387
237632
  if (registry2) {
237388
- const currentFilePath = `agents/sub-agents/${agentId}.ts`;
237633
+ const currentFilePath = actualFilePath || `agents/sub-agents/${agentId}.ts`;
237389
237634
  const referencedComponents = [];
237390
237635
  if (Array.isArray(agentData.canUse)) {
237391
237636
  for (const toolRelation of agentData.canUse) {
@@ -237450,14 +237695,15 @@ function generateSubAgentImports(agentId, agentData, style = DEFAULT_STYLE, regi
237450
237695
  }
237451
237696
  return imports;
237452
237697
  }
237453
- function generateSubAgentFile(agentId, agentData, style = DEFAULT_STYLE, registry2, parentAgentId, contextConfigData, parentModels) {
237698
+ function generateSubAgentFile(agentId, agentData, style = DEFAULT_STYLE, registry2, parentAgentId, contextConfigData, parentModels, actualFilePath) {
237454
237699
  const imports = generateSubAgentImports(
237455
237700
  agentId,
237456
237701
  agentData,
237457
237702
  style,
237458
237703
  registry2,
237459
237704
  parentAgentId,
237460
- contextConfigData
237705
+ contextConfigData,
237706
+ actualFilePath
237461
237707
  );
237462
237708
  const definition = generateSubAgentDefinition(
237463
237709
  agentId,
@@ -237474,6 +237720,7 @@ var init_sub_agent_generator = __esm({
237474
237720
  "src/commands/pull-v3/components/sub-agent-generator.ts"() {
237475
237721
  "use strict";
237476
237722
  init_esm_shims();
237723
+ init_json_comparator();
237477
237724
  init_generator_utils();
237478
237725
  }
237479
237726
  });
@@ -237526,14 +237773,11 @@ function registerAllComponents(project, registry2) {
237526
237773
  }
237527
237774
  if (project.agents) {
237528
237775
  for (const agentId of Object.keys(project.agents)) {
237529
- console.log(`\u{1F527} Registering agent: ${agentId}`);
237530
237776
  registry2.register(agentId, "agents", `agents/${agentId}.ts`);
237531
237777
  }
237532
237778
  }
237533
237779
  const subAgents2 = extractSubAgents(project);
237534
- console.log(`\u{1F527} Found subAgents:`, Object.keys(subAgents2));
237535
237780
  for (const subAgentId of Object.keys(subAgents2)) {
237536
- console.log(`\u{1F527} Registering subAgent: ${subAgentId}`);
237537
237781
  registry2.register(subAgentId, "subAgents", `agents/sub-agents/${subAgentId}.ts`);
237538
237782
  }
237539
237783
  const contextConfigs2 = extractContextConfigs(project);
@@ -237643,9 +237887,6 @@ var init_component_registry = __esm({
237643
237887
  } else {
237644
237888
  const baseName = this.toCamelCase(id);
237645
237889
  const uniqueName = this.ensureUniqueName(baseName, type);
237646
- console.log(
237647
- `\u{1F527} Registry: ${type}:${id} -> baseName: "${baseName}" -> uniqueName: "${uniqueName}"`
237648
- );
237649
237890
  name2 = uniqueName;
237650
237891
  actualExportName = uniqueName;
237651
237892
  }
@@ -237665,6 +237906,25 @@ var init_component_registry = __esm({
237665
237906
  }
237666
237907
  return info2;
237667
237908
  }
237909
+ /**
237910
+ * Override a credential component with environment settings key
237911
+ * This allows env settings registration to take precedence over standalone credentials
237912
+ */
237913
+ overrideCredentialWithEnvKey(id, filePath, envKey) {
237914
+ const typeKey = `credentials:${id}`;
237915
+ const info2 = {
237916
+ id,
237917
+ type: "credentials",
237918
+ name: envKey,
237919
+ // Use the environment settings key
237920
+ filePath,
237921
+ exportName: envKey,
237922
+ isInline: true
237923
+ };
237924
+ this.componentsByTypeAndId.set(typeKey, info2);
237925
+ this.components.set(`${filePath}:${envKey}`, info2);
237926
+ return info2;
237927
+ }
237668
237928
  /**
237669
237929
  * Get component info by ID and type
237670
237930
  */
@@ -237697,6 +237957,11 @@ var init_component_registry = __esm({
237697
237957
  getImportStatement(fromFilePath, componentId, componentType) {
237698
237958
  const component = this.get(componentId, componentType);
237699
237959
  if (!component) return void 0;
237960
+ const normalizedFrom = this.normalizeToProjectPath(fromFilePath);
237961
+ const normalizedTo = this.normalizeToProjectPath(component.filePath);
237962
+ if (normalizedFrom === normalizedTo) {
237963
+ return void 0;
237964
+ }
237700
237965
  const relativePath = this.calculateRelativeImport(fromFilePath, component.filePath);
237701
237966
  const importStmt = `import { ${component.exportName} } from '${relativePath}';`;
237702
237967
  return importStmt;
@@ -237856,18 +238121,45 @@ var init_component_registry = __esm({
237856
238121
  return "comp";
237857
238122
  }
237858
238123
  }
238124
+ /**
238125
+ * Normalize path to project-relative format using existing registry paths as templates
238126
+ */
238127
+ normalizeToProjectPath(filePath) {
238128
+ if (!filePath.includes("/") || filePath.match(/^(agents|tools|environments|data-components)/)) {
238129
+ return filePath;
238130
+ }
238131
+ const knownDirs = /* @__PURE__ */ new Set();
238132
+ for (const component of this.components.values()) {
238133
+ const firstDir = component.filePath.split("/")[0];
238134
+ if (firstDir) knownDirs.add(firstDir);
238135
+ }
238136
+ const segments = filePath.split("/");
238137
+ for (let i3 = segments.length - 1; i3 >= 0; i3--) {
238138
+ if (knownDirs.has(segments[i3])) {
238139
+ return segments.slice(i3).join("/");
238140
+ }
238141
+ }
238142
+ return segments[segments.length - 1] || filePath;
238143
+ }
237859
238144
  /**
237860
238145
  * Calculate relative import path between files
237861
238146
  */
237862
238147
  calculateRelativeImport(fromPath, toPath) {
237863
238148
  const fromParts = fromPath.replace(".ts", "").split("/");
237864
238149
  const toParts = toPath.replace(".ts", "").split("/");
237865
- fromParts.pop();
238150
+ const fromDir = fromParts.slice(0, -1);
238151
+ const toFile = toParts;
238152
+ let commonLength = 0;
238153
+ while (commonLength < fromDir.length && commonLength < toFile.length - 1 && fromDir[commonLength] === toFile[commonLength]) {
238154
+ commonLength++;
238155
+ }
237866
238156
  let relativePath = "";
237867
- for (let i3 = 0; i3 < fromParts.length; i3++) {
238157
+ const upLevels = fromDir.length - commonLength;
238158
+ for (let i3 = 0; i3 < upLevels; i3++) {
237868
238159
  relativePath += "../";
237869
238160
  }
237870
- relativePath += toParts.join("/");
238161
+ const remainingPath = toFile.slice(commonLength).join("/");
238162
+ relativePath += remainingPath;
237871
238163
  if (relativePath.startsWith("../")) {
237872
238164
  return relativePath;
237873
238165
  } else {
@@ -238578,16 +238870,31 @@ function compareComponentMaps(componentType, localMap, remoteMap, debug) {
238578
238870
  });
238579
238871
  const commonIds = localIds.filter((id) => remoteIds.includes(id));
238580
238872
  commonIds.forEach((id) => {
238581
- const fieldChanges = getDetailedFieldChanges("", localMap[id], remoteMap[id]);
238582
- if (fieldChanges.length > 0) {
238583
- const summary = generateComponentChangeSummary(componentType, fieldChanges);
238584
- changes.push({
238585
- componentType,
238586
- componentId: id,
238587
- changeType: "modified",
238588
- changedFields: fieldChanges,
238589
- summary
238873
+ if (componentType === "artifactComponents") {
238874
+ const comparison = compareJsonObjects(localMap[id], remoteMap[id], {
238875
+ ignoreArrayOrder: true,
238876
+ showDetails: false
238590
238877
  });
238878
+ if (!comparison.isEqual) {
238879
+ changes.push({
238880
+ componentType,
238881
+ componentId: id,
238882
+ changeType: "modified",
238883
+ summary: `Modified ${componentType}: ${id}`
238884
+ });
238885
+ }
238886
+ } else {
238887
+ const fieldChanges = getDetailedFieldChanges("", localMap[id], remoteMap[id]);
238888
+ if (fieldChanges.length > 0) {
238889
+ const summary = generateComponentChangeSummary(componentType, fieldChanges);
238890
+ changes.push({
238891
+ componentType,
238892
+ componentId: id,
238893
+ changeType: "modified",
238894
+ changedFields: fieldChanges,
238895
+ summary
238896
+ });
238897
+ }
238591
238898
  }
238592
238899
  });
238593
238900
  return changes;
@@ -238657,6 +238964,24 @@ function compareArraysAsSet(basePath, oldArray, newArray, depth) {
238657
238964
  }
238658
238965
  return changes;
238659
238966
  }
238967
+ function extractCredentialIds(agentObj) {
238968
+ const credentialIds = [];
238969
+ if (agentObj.credentials && Array.isArray(agentObj.credentials)) {
238970
+ agentObj.credentials.forEach((cred) => {
238971
+ if (cred.id) {
238972
+ credentialIds.push(cred.id);
238973
+ }
238974
+ });
238975
+ }
238976
+ if (agentObj.contextConfig?.contextVariables) {
238977
+ Object.values(agentObj.contextConfig.contextVariables).forEach((variable) => {
238978
+ if (variable && typeof variable === "object" && variable.credentialReferenceId) {
238979
+ credentialIds.push(variable.credentialReferenceId);
238980
+ }
238981
+ });
238982
+ }
238983
+ return [...new Set(credentialIds)];
238984
+ }
238660
238985
  function getDetailedFieldChanges(basePath, oldObj, newObj, depth = 0) {
238661
238986
  const changes = [];
238662
238987
  if (depth > 10) return changes;
@@ -238743,8 +239068,21 @@ function getDetailedFieldChanges(basePath, oldObj, newObj, depth = 0) {
238743
239068
  return false;
238744
239069
  });
238745
239070
  if (shouldIgnore) {
238746
- if (basePath === "" && key === "statusUpdates") {
238747
- console.log(` \u26A0\uFE0F statusUpdates field is being IGNORED due to ignored fields check`);
239071
+ continue;
239072
+ }
239073
+ if (key === "credentials" && basePath === "") {
239074
+ const oldCredIds = extractCredentialIds(oldObj);
239075
+ const newCredIds = extractCredentialIds(newObj);
239076
+ oldCredIds.sort();
239077
+ newCredIds.sort();
239078
+ if (JSON.stringify(oldCredIds) !== JSON.stringify(newCredIds)) {
239079
+ changes.push({
239080
+ field: fieldPath,
239081
+ changeType: "modified",
239082
+ oldValue: oldCredIds,
239083
+ newValue: newCredIds,
239084
+ description: `Credential usage differs: [${oldCredIds.join(", ")}] vs [${newCredIds.join(", ")}]`
239085
+ });
238748
239086
  }
238749
239087
  continue;
238750
239088
  }
@@ -238769,6 +239107,18 @@ function getDetailedFieldChanges(basePath, oldObj, newObj, depth = 0) {
238769
239107
  });
238770
239108
  }
238771
239109
  } else {
239110
+ const oldIsEmpty2 = isEmpty(oldValue);
239111
+ const newIsEmpty2 = isEmpty(newValue);
239112
+ if (oldIsEmpty2 && newIsEmpty2) {
239113
+ continue;
239114
+ }
239115
+ if (key === "models") {
239116
+ const oldIsNull = oldValue === null || oldValue === void 0;
239117
+ const newIsNull = newValue === null || newValue === void 0;
239118
+ if (oldIsNull !== newIsNull) {
239119
+ continue;
239120
+ }
239121
+ }
238772
239122
  const recursiveChanges = getDetailedFieldChanges(fieldPath, oldValue, newValue, depth + 1);
238773
239123
  changes.push(...recursiveChanges);
238774
239124
  }
@@ -239048,9 +239398,11 @@ function compareFetchDefinitions(localProject, remoteProject, debug) {
239048
239398
  summary: `Removed fetchDefinition: ${fetchId}`
239049
239399
  });
239050
239400
  } else if (local && remote) {
239051
- const localStr = JSON.stringify(local, null, 2);
239052
- const remoteStr = JSON.stringify(remote, null, 2);
239053
- if (localStr !== remoteStr) {
239401
+ const comparison = compareJsonObjects(local, remote, {
239402
+ ignoreArrayOrder: true,
239403
+ showDetails: true
239404
+ });
239405
+ if (!comparison.isEqual) {
239054
239406
  changes.push({
239055
239407
  componentType: "fetchDefinitions",
239056
239408
  componentId: fetchId,
@@ -239077,6 +239429,7 @@ var init_project_comparator = __esm({
239077
239429
  "src/commands/pull-v3/project-comparator.ts"() {
239078
239430
  "use strict";
239079
239431
  init_esm_shims();
239432
+ init_json_comparator();
239080
239433
  }
239081
239434
  });
239082
239435
 
@@ -239089,6 +239442,7 @@ __export(component_parser_exports, {
239089
239442
  });
239090
239443
  import { existsSync as existsSync8, readdirSync as readdirSync2, readFileSync as readFileSync3, statSync } from "fs";
239091
239444
  import { extname as extname2, join as join10, relative } from "path";
239445
+ import { Node as Node3, Project } from "ts-morph";
239092
239446
  function parseFileForComponents(filePath, projectRoot, debug = false) {
239093
239447
  if (!existsSync8(filePath)) {
239094
239448
  return [];
@@ -239097,271 +239451,234 @@ function parseFileForComponents(filePath, projectRoot, debug = false) {
239097
239451
  const relativePath = relative(projectRoot, filePath);
239098
239452
  try {
239099
239453
  const content = readFileSync3(filePath, "utf8");
239100
- const lines = content.split("\n");
239101
- const exportedIdPattern = /export\s+const\s+(\w+)\s*=\s*(\w+)\s*\(\s*\{[^}]*?id:\s*['"`]([^'"`]+)['"`]/gs;
239102
- const exportedTypePattern = /export\s+const\s+(\w+)\s*=\s*(\w+)\s*\(\s*\{[^}]*?type:\s*['"`]([^'"`]+)['"`]/gs;
239103
- const exportedNamePattern = /export\s+const\s+(\w+)\s*=\s*(\w+)\s*\(\s*\{[^}]*?name:\s*['"`]([^'"`]+)['"`]/gs;
239104
- const declaredIdPattern = /(?:^|\n)\s*const\s+(\w+)\s*=\s*(\w+)\s*\(\s*\{[^}]*?id:\s*['"`]([^'"`]+)['"`]/gs;
239105
- const declaredTypePattern = /(?:^|\n)\s*const\s+(\w+)\s*=\s*(\w+)\s*\(\s*\{[^}]*?type:\s*['"`]([^'"`]+)['"`]/gs;
239106
- const declaredNamePattern = /(?:^|\n)\s*const\s+(\w+)\s*=\s*(\w+)\s*\(\s*\{[^}]*?name:\s*['"`]([^'"`]+)['"`]/gs;
239107
- const exportedVariables = /* @__PURE__ */ new Set();
239108
- const exportPattern = /export\s*\{\s*([^}]+)\s*\}/g;
239109
- let exportMatch;
239110
- while ((exportMatch = exportPattern.exec(content)) !== null) {
239111
- const exportList = exportMatch[1];
239112
- const variables = exportList.split(",").map((v3) => v3.trim()).filter((v3) => v3);
239113
- variables.forEach((v3) => exportedVariables.add(v3));
239114
- }
239115
- let match2;
239116
- while ((match2 = exportedIdPattern.exec(content)) !== null) {
239117
- const variableName = match2[1];
239118
- const functionName = match2[2];
239119
- const componentId = match2[3];
239120
- const componentType = FUNCTION_NAME_TO_TYPE[functionName];
239121
- if (componentType && VALID_COMPONENT_TYPES.has(componentType)) {
239122
- const lineNumber = content.substring(0, match2.index).split("\n").length;
239123
- components.push({
239124
- id: componentId,
239125
- type: componentType,
239126
- filePath: relativePath,
239127
- variableName,
239128
- startLine: lineNumber,
239129
- isInline: false
239130
- });
239131
- }
239132
- }
239133
- while ((match2 = exportedTypePattern.exec(content)) !== null) {
239134
- const variableName = match2[1];
239135
- const functionName = match2[2];
239136
- const componentId = match2[3];
239137
- const componentType = FUNCTION_NAME_TO_TYPE[functionName];
239138
- if (componentType && VALID_COMPONENT_TYPES.has(componentType) && componentType === "statusComponents") {
239139
- const lineNumber = content.substring(0, match2.index).split("\n").length;
239140
- components.push({
239141
- id: componentId,
239142
- type: componentType,
239143
- filePath: relativePath,
239144
- variableName,
239145
- startLine: lineNumber,
239146
- isInline: false
239147
- });
239148
- }
239149
- }
239150
- while ((match2 = exportedNamePattern.exec(content)) !== null) {
239151
- const variableName = match2[1];
239152
- const functionName = match2[2];
239153
- const componentId = match2[3];
239154
- const componentType = FUNCTION_NAME_TO_TYPE[functionName];
239155
- if (VALID_COMPONENT_TYPES.has(componentType) && componentType === "functionTools") {
239156
- const lineNumber = content.substring(0, match2.index).split("\n").length;
239157
- components.push({
239158
- id: componentId,
239159
- type: componentType,
239160
- filePath: relativePath,
239161
- variableName,
239162
- startLine: lineNumber,
239163
- isInline: false
239164
- });
239165
- }
239166
- }
239167
- while ((match2 = declaredIdPattern.exec(content)) !== null) {
239168
- const variableName = match2[1];
239169
- const functionName = match2[2];
239170
- const componentId = match2[3];
239171
- const componentType = FUNCTION_NAME_TO_TYPE[functionName];
239172
- if (VALID_COMPONENT_TYPES.has(componentType) && exportedVariables.has(variableName)) {
239173
- const lineNumber = content.substring(0, match2.index).split("\n").length;
239174
- components.push({
239175
- id: componentId,
239176
- type: componentType,
239177
- filePath: relativePath,
239178
- variableName,
239179
- startLine: lineNumber,
239180
- isInline: false
239181
- // It's exported via separate export statement
239182
- });
239183
- }
239184
- }
239185
- while ((match2 = declaredTypePattern.exec(content)) !== null) {
239186
- const variableName = match2[1];
239187
- const functionName = match2[2];
239188
- const componentId = match2[3];
239189
- const componentType = FUNCTION_NAME_TO_TYPE[functionName];
239190
- if (componentType && VALID_COMPONENT_TYPES.has(componentType) && componentType === "statusComponents" && exportedVariables.has(variableName)) {
239191
- const lineNumber = content.substring(0, match2.index).split("\n").length;
239192
- components.push({
239193
- id: componentId,
239194
- type: componentType,
239195
- filePath: relativePath,
239196
- variableName,
239197
- startLine: lineNumber,
239198
- isInline: false
239199
- // It's exported via separate export statement
239200
- });
239454
+ const project = new Project({
239455
+ useInMemoryFileSystem: true,
239456
+ compilerOptions: {
239457
+ allowJs: true,
239458
+ target: 99,
239459
+ // Latest
239460
+ jsx: 1
239461
+ // Preserve JSX
239201
239462
  }
239202
- }
239203
- while ((match2 = declaredNamePattern.exec(content)) !== null) {
239204
- const variableName = match2[1];
239205
- const functionName = match2[2];
239206
- const componentId = match2[3];
239207
- const componentType = FUNCTION_NAME_TO_TYPE[functionName];
239208
- if (VALID_COMPONENT_TYPES.has(componentType) && componentType === "functionTools" && exportedVariables.has(variableName)) {
239209
- const lineNumber = content.substring(0, match2.index).split("\n").length;
239210
- components.push({
239211
- id: componentId,
239212
- type: componentType,
239213
- filePath: relativePath,
239463
+ });
239464
+ const sourceFile = project.createSourceFile("temp.ts", content);
239465
+ const exportedVariableDeclarations = sourceFile.getVariableStatements().filter((statement) => statement.hasExportKeyword()).flatMap((statement) => statement.getDeclarationList().getDeclarations());
239466
+ for (const declaration of exportedVariableDeclarations) {
239467
+ const variableName = declaration.getName();
239468
+ const initializer = declaration.getInitializer();
239469
+ if (Node3.isCallExpression(initializer)) {
239470
+ const componentMatch = parseCallExpression(initializer, variableName, false, relativePath);
239471
+ if (componentMatch) {
239472
+ components.push(componentMatch);
239473
+ }
239474
+ }
239475
+ }
239476
+ const exportedNames = /* @__PURE__ */ new Set();
239477
+ sourceFile.getExportDeclarations().forEach((exportDecl) => {
239478
+ const namedExports = exportDecl.getNamedExports();
239479
+ namedExports.forEach((namedExport) => {
239480
+ exportedNames.add(namedExport.getName());
239481
+ });
239482
+ });
239483
+ const allVariableDeclarations = sourceFile.getVariableStatements().filter((statement) => !statement.hasExportKeyword()).flatMap((statement) => statement.getDeclarationList().getDeclarations());
239484
+ for (const declaration of allVariableDeclarations) {
239485
+ const variableName = declaration.getName();
239486
+ const initializer = declaration.getInitializer();
239487
+ if (Node3.isCallExpression(initializer)) {
239488
+ const isExported = exportedNames.has(variableName);
239489
+ const isInline = !isExported;
239490
+ const componentMatch = parseCallExpression(
239491
+ initializer,
239214
239492
  variableName,
239215
- startLine: lineNumber,
239216
- isInline: false
239217
- // It's exported via separate export statement
239218
- });
239493
+ isInline,
239494
+ relativePath
239495
+ );
239496
+ if (componentMatch) {
239497
+ components.push(componentMatch);
239498
+ }
239219
239499
  }
239220
239500
  }
239221
- while ((match2 = declaredIdPattern.exec(content)) !== null) {
239222
- const variableName = match2[1];
239223
- const functionName = match2[2];
239224
- const componentId = match2[3];
239225
- const componentType = FUNCTION_NAME_TO_TYPE[functionName];
239226
- if (VALID_COMPONENT_TYPES.has(componentType) && !exportedVariables.has(variableName)) {
239227
- const lineNumber = content.substring(0, match2.index).split("\n").length;
239228
- components.push({
239229
- id: componentId,
239230
- type: componentType,
239231
- filePath: relativePath,
239232
- variableName,
239233
- startLine: lineNumber,
239234
- isInline: true
239235
- // Not exported, so treated as inline but has variable name
239236
- });
239501
+ sourceFile.forEachDescendant((node) => {
239502
+ if (Node3.isCallExpression(node)) {
239503
+ const parent = node.getParent();
239504
+ const isVariableInitializer = Node3.isVariableDeclaration(parent) && parent.getInitializer() === node;
239505
+ if (!isVariableInitializer) {
239506
+ const componentMatch = parseCallExpression(node, void 0, true, relativePath);
239507
+ if (componentMatch) {
239508
+ components.push(componentMatch);
239509
+ }
239510
+ }
239237
239511
  }
239238
- }
239239
- while ((match2 = declaredTypePattern.exec(content)) !== null) {
239240
- const variableName = match2[1];
239241
- const functionName = match2[2];
239242
- const componentId = match2[3];
239243
- const componentType = FUNCTION_NAME_TO_TYPE[functionName];
239244
- if (componentType && VALID_COMPONENT_TYPES.has(componentType) && componentType === "statusComponents" && !exportedVariables.has(variableName)) {
239245
- const lineNumber = content.substring(0, match2.index).split("\n").length;
239246
- components.push({
239247
- id: componentId,
239248
- type: componentType,
239249
- filePath: relativePath,
239250
- variableName,
239251
- startLine: lineNumber,
239252
- isInline: true
239253
- // Not exported, so treated as inline but has variable name
239254
- });
239512
+ });
239513
+ sourceFile.forEachDescendant((node) => {
239514
+ if (Node3.isCallExpression(node)) {
239515
+ const expression = node.getExpression();
239516
+ if (Node3.isIdentifier(expression) && expression.getText() === "registerEnvironmentSettings") {
239517
+ const args2 = node.getArguments();
239518
+ if (args2.length > 0 && Node3.isObjectLiteralExpression(args2[0])) {
239519
+ const configObject = args2[0];
239520
+ const credentialsProperty = configObject.getProperty("credentials");
239521
+ if (credentialsProperty && Node3.isPropertyAssignment(credentialsProperty)) {
239522
+ const credentialsValue = credentialsProperty.getInitializer();
239523
+ if (Node3.isObjectLiteralExpression(credentialsValue)) {
239524
+ credentialsValue.getProperties().forEach((property) => {
239525
+ if (Node3.isPropertyAssignment(property)) {
239526
+ const credentialKey = property.getName();
239527
+ const credentialConfig = property.getInitializer();
239528
+ if (Node3.isObjectLiteralExpression(credentialConfig)) {
239529
+ const idProperty = credentialConfig.getProperty("id");
239530
+ if (idProperty && Node3.isPropertyAssignment(idProperty)) {
239531
+ const idValue = idProperty.getInitializer();
239532
+ if (Node3.isStringLiteral(idValue)) {
239533
+ const credentialId = idValue.getLiteralValue();
239534
+ const startLine = node.getStartLineNumber();
239535
+ components.push({
239536
+ id: credentialId,
239537
+ type: "credentials",
239538
+ filePath: relativePath,
239539
+ variableName: credentialKey,
239540
+ // Use the key name as variable name
239541
+ startLine,
239542
+ isInline: true
239543
+ // It's nested within environment settings
239544
+ });
239545
+ }
239546
+ }
239547
+ } else if (Node3.isIdentifier(credentialConfig)) {
239548
+ const variableName = credentialConfig.getText();
239549
+ sourceFile.forEachDescendant((varNode) => {
239550
+ if (Node3.isVariableDeclaration(varNode) && varNode.getName() === variableName) {
239551
+ const initializer = varNode.getInitializer();
239552
+ if (Node3.isCallExpression(initializer)) {
239553
+ const callExpression = initializer.getExpression();
239554
+ if (Node3.isIdentifier(callExpression) && callExpression.getText() === "credential") {
239555
+ const args3 = initializer.getArguments();
239556
+ if (args3.length > 0 && Node3.isObjectLiteralExpression(args3[0])) {
239557
+ const configObject2 = args3[0];
239558
+ const idProperty = configObject2.getProperty("id");
239559
+ if (idProperty && Node3.isPropertyAssignment(idProperty)) {
239560
+ const idValue = idProperty.getInitializer();
239561
+ if (Node3.isStringLiteral(idValue)) {
239562
+ const credentialId = idValue.getLiteralValue();
239563
+ const startLine = node.getStartLineNumber();
239564
+ components.push({
239565
+ id: credentialId,
239566
+ type: "credentials",
239567
+ filePath: relativePath,
239568
+ variableName: credentialKey,
239569
+ // Use the env settings key as variable name
239570
+ startLine,
239571
+ isInline: true,
239572
+ overrideExisting: true
239573
+ // Mark this to override any existing registration
239574
+ });
239575
+ }
239576
+ }
239577
+ }
239578
+ }
239579
+ }
239580
+ }
239581
+ });
239582
+ }
239583
+ }
239584
+ });
239585
+ }
239586
+ }
239587
+ }
239588
+ }
239255
239589
  }
239590
+ });
239591
+ return components;
239592
+ } catch (error) {
239593
+ if (debug) {
239594
+ console.warn(`Failed to parse file ${relativePath}: ${error}`);
239256
239595
  }
239257
- while ((match2 = declaredNamePattern.exec(content)) !== null) {
239258
- const variableName = match2[1];
239259
- const functionName = match2[2];
239260
- const componentId = match2[3];
239261
- const componentType = FUNCTION_NAME_TO_TYPE[functionName];
239262
- if (componentType && VALID_COMPONENT_TYPES.has(componentType) && componentType === "functionTools" && !exportedVariables.has(variableName)) {
239263
- const lineNumber = content.substring(0, match2.index).split("\n").length;
239264
- components.push({
239265
- id: componentId,
239266
- type: componentType,
239267
- filePath: relativePath,
239268
- variableName,
239269
- startLine: lineNumber,
239270
- isInline: true
239271
- // Not exported, so treated as inline but has variable name
239272
- });
239273
- }
239596
+ return [];
239597
+ }
239598
+ }
239599
+ function parseCallExpression(callExpression, variableName, isInline, relativePath) {
239600
+ const expression = callExpression.getExpression();
239601
+ let functionName;
239602
+ if (Node3.isIdentifier(expression)) {
239603
+ functionName = expression.getText();
239604
+ } else {
239605
+ return null;
239606
+ }
239607
+ const componentType = FUNCTION_NAME_TO_TYPE[functionName];
239608
+ if (!componentType || !VALID_COMPONENT_TYPES.has(componentType)) {
239609
+ return null;
239610
+ }
239611
+ const args2 = callExpression.getArguments();
239612
+ if (args2.length === 0 || !Node3.isObjectLiteralExpression(args2[0])) {
239613
+ return null;
239614
+ }
239615
+ const configObject = args2[0];
239616
+ let componentId = null;
239617
+ const idProperty = configObject.getProperty("id");
239618
+ if (idProperty && Node3.isPropertyAssignment(idProperty)) {
239619
+ const idValue = idProperty.getInitializer();
239620
+ if (Node3.isStringLiteral(idValue)) {
239621
+ componentId = idValue.getLiteralValue();
239274
239622
  }
239275
- const functionNames = Object.keys(FUNCTION_NAME_TO_TYPE);
239276
- for (const funcName of functionNames) {
239277
- const inlineIdPattern = new RegExp(
239278
- `(?<!(?:export\\s+)?const\\s+\\w+\\s*=\\s*)\\b${funcName}\\s*\\(\\s*\\{[^}]*?id:\\s*['"\`]([^'"\`]+)['"\`]`,
239279
- "gs"
239280
- );
239281
- let inlineMatch;
239282
- while ((inlineMatch = inlineIdPattern.exec(content)) !== null) {
239283
- const componentId = inlineMatch[1];
239284
- const componentType = FUNCTION_NAME_TO_TYPE[funcName];
239285
- const lineNumber = content.substring(0, inlineMatch.index).split("\n").length;
239286
- components.push({
239287
- id: componentId,
239288
- type: componentType,
239289
- filePath: relativePath,
239290
- variableName: void 0,
239291
- // No variable name for inline
239292
- startLine: lineNumber,
239293
- isInline: true
239294
- });
239295
- }
239296
- if (funcName === "functionTool") {
239297
- const inlineNamePattern = new RegExp(
239298
- `(?<!(?:export\\s+)?const\\s+\\w+\\s*=\\s*)\\b${funcName}\\s*\\(\\s*\\{[^}]*?name:\\s*['"\`]([^'"\`]+)['"\`]`,
239299
- "gs"
239300
- );
239301
- while ((inlineMatch = inlineNamePattern.exec(content)) !== null) {
239302
- const componentId = inlineMatch[1];
239303
- const componentType = FUNCTION_NAME_TO_TYPE[funcName];
239304
- const lineNumber = content.substring(0, inlineMatch.index).split("\n").length;
239305
- components.push({
239306
- id: componentId,
239307
- type: componentType,
239308
- filePath: relativePath,
239309
- variableName: void 0,
239310
- // No variable name for inline
239311
- startLine: lineNumber,
239312
- isInline: true
239313
- });
239314
- }
239623
+ }
239624
+ if (!componentId && componentType === "statusComponents") {
239625
+ const typeProperty = configObject.getProperty("type");
239626
+ if (typeProperty && Node3.isPropertyAssignment(typeProperty)) {
239627
+ const typeValue = typeProperty.getInitializer();
239628
+ if (Node3.isStringLiteral(typeValue)) {
239629
+ componentId = typeValue.getLiteralValue();
239315
239630
  }
239316
239631
  }
239317
- const envCredentialsPattern = /registerEnvironmentSettings\s*\(\s*\{[^}]*?credentials:\s*\{([^}]+?)\}/gs;
239318
- let envMatch;
239319
- while ((envMatch = envCredentialsPattern.exec(content)) !== null) {
239320
- const credentialsBlock = envMatch[1];
239321
- const credentialPattern = /(\w+):\s*\{[^}]*?id:\s*['"`]([^'"`]+)['"`]/g;
239322
- let credMatch;
239323
- while ((credMatch = credentialPattern.exec(credentialsBlock)) !== null) {
239324
- const credentialKey = credMatch[1];
239325
- const credentialId = credMatch[2];
239326
- const lineNumber = content.substring(0, envMatch.index).split("\n").length;
239327
- components.push({
239328
- id: credentialId,
239329
- type: "credentials",
239330
- filePath: relativePath,
239331
- variableName: credentialKey,
239332
- // Use the key name as variable name
239333
- startLine: lineNumber,
239334
- isInline: true
239335
- // It's nested within environment settings
239336
- });
239632
+ }
239633
+ if (!componentId && componentType === "functionTools") {
239634
+ const nameProperty = configObject.getProperty("name");
239635
+ if (nameProperty && Node3.isPropertyAssignment(nameProperty)) {
239636
+ const nameValue = nameProperty.getInitializer();
239637
+ if (Node3.isStringLiteral(nameValue)) {
239638
+ componentId = nameValue.getLiteralValue();
239337
239639
  }
239338
239640
  }
239339
- } catch (error) {
239340
- console.warn(`Failed to parse file ${filePath}: ${error}`);
239341
239641
  }
239342
- return components;
239642
+ if (!componentId) {
239643
+ return null;
239644
+ }
239645
+ const startLine = callExpression.getStartLineNumber();
239646
+ return {
239647
+ id: componentId,
239648
+ type: componentType,
239649
+ filePath: relativePath,
239650
+ variableName,
239651
+ startLine,
239652
+ isInline
239653
+ };
239343
239654
  }
239344
239655
  function scanProjectForComponents(projectRoot, debug = false) {
239345
239656
  const allComponents = [];
239346
- function scanDirectory(dirPath) {
239347
- if (!existsSync8(dirPath)) return;
239657
+ if (!existsSync8(projectRoot)) {
239658
+ return allComponents;
239659
+ }
239660
+ const scanDir = (dir) => {
239348
239661
  try {
239349
- const entries = readdirSync2(dirPath);
239350
- for (const entry of entries) {
239351
- const fullPath = join10(dirPath, entry);
239662
+ const items = readdirSync2(dir);
239663
+ for (const item of items) {
239664
+ const fullPath = join10(dir, item);
239352
239665
  const stat = statSync(fullPath);
239353
- if (stat.isFile() && extname2(entry) === ".ts") {
239666
+ if (stat.isDirectory()) {
239667
+ if (!["node_modules", ".next", ".git", "dist", "build"].includes(item) && !item.startsWith(".temp-validation-")) {
239668
+ scanDir(fullPath);
239669
+ }
239670
+ } else if (stat.isFile() && [".ts", ".tsx", ".js", ".jsx"].includes(extname2(item))) {
239354
239671
  const fileComponents = parseFileForComponents(fullPath, projectRoot, debug);
239355
239672
  allComponents.push(...fileComponents);
239356
- } else if (stat.isDirectory() && !entry.startsWith(".") && entry !== "node_modules") {
239357
- scanDirectory(fullPath);
239358
239673
  }
239359
239674
  }
239360
239675
  } catch (error) {
239361
- console.warn(`Failed to scan directory ${dirPath}: ${error}`);
239676
+ if (debug) {
239677
+ console.warn(`Failed to scan directory ${dir}: ${error}`);
239678
+ }
239362
239679
  }
239363
- }
239364
- scanDirectory(projectRoot);
239680
+ };
239681
+ scanDir(projectRoot);
239365
239682
  return allComponents;
239366
239683
  }
239367
239684
  function buildComponentRegistryFromParsing(projectRoot, debug = false) {
@@ -239381,18 +239698,26 @@ function buildComponentRegistryFromParsing(projectRoot, debug = false) {
239381
239698
  const registeredTypeIds = /* @__PURE__ */ new Set();
239382
239699
  for (const component of allComponents) {
239383
239700
  const typeId = `${component.type}:${component.id}`;
239384
- if (registeredTypeIds.has(typeId)) {
239701
+ if (registeredTypeIds.has(typeId) && !component.overrideExisting) {
239385
239702
  continue;
239386
239703
  }
239387
239704
  registeredTypeIds.add(typeId);
239388
239705
  if (component.variableName) {
239389
- registry2.register(
239390
- component.id,
239391
- component.type,
239392
- component.filePath,
239393
- component.variableName,
239394
- component.isInline
239395
- );
239706
+ if (component.overrideExisting && component.type === "credentials") {
239707
+ registry2.overrideCredentialWithEnvKey(
239708
+ component.id,
239709
+ component.filePath,
239710
+ component.variableName
239711
+ );
239712
+ } else {
239713
+ registry2.register(
239714
+ component.id,
239715
+ component.type,
239716
+ component.filePath,
239717
+ component.variableName,
239718
+ component.isInline
239719
+ );
239720
+ }
239396
239721
  } else {
239397
239722
  registry2.register(
239398
239723
  component.id,
@@ -239464,84 +239789,171 @@ var init_component_parser = __esm({
239464
239789
 
239465
239790
  // src/commands/pull-v3/targeted-typescript-placeholders.ts
239466
239791
  import { randomBytes as randomBytes2 } from "crypto";
239792
+ import { Node as Node4, Project as Project2 } from "ts-morph";
239467
239793
  function generatePlaceholderId() {
239468
239794
  return randomBytes2(4).toString("hex").toUpperCase();
239469
239795
  }
239470
239796
  function createTargetedTypeScriptPlaceholders(content, debug = false) {
239471
239797
  const replacements = {};
239472
- let processedContent = content;
239473
239798
  let replacedFields = 0;
239474
239799
  const originalSize = content.length;
239475
- const promptRegex = /(\s+prompt:\s*)((['"`])([^]*?)\3)/g;
239476
- processedContent = processedContent.replace(promptRegex, (match2, prefix, fullValue) => {
239477
- if (fullValue.length >= MIN_REPLACEMENT_LENGTH) {
239478
- const placeholder = `<PROMPT_${generatePlaceholderId()}>`;
239479
- replacements[placeholder] = fullValue;
239480
- replacedFields++;
239481
- return `${prefix}${placeholder}`;
239482
- }
239483
- return match2;
239484
- });
239485
- const descriptionRegex = /(\s+description:\s*)((['"`])([^]*?)\3)/g;
239486
- processedContent = processedContent.replace(descriptionRegex, (match2, prefix, fullValue) => {
239487
- if (fullValue.length >= MIN_REPLACEMENT_LENGTH) {
239488
- const placeholder = `<DESC_${generatePlaceholderId()}>`;
239489
- replacements[placeholder] = fullValue;
239490
- replacedFields++;
239491
- return `${prefix}${placeholder}`;
239492
- }
239493
- return match2;
239494
- });
239495
- const inputSchemaRegex = /(\s+inputSchema:\s*)(\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\})/g;
239496
- processedContent = processedContent.replace(inputSchemaRegex, (match2, prefix, schemaObject) => {
239497
- if (schemaObject.length >= MIN_REPLACEMENT_LENGTH) {
239498
- const placeholder = `<INPUT_SCHEMA_${generatePlaceholderId()}>`;
239499
- replacements[placeholder] = schemaObject;
239500
- replacedFields++;
239501
- return `${prefix}${placeholder}`;
239502
- }
239503
- return match2;
239504
- });
239505
- const detailsSchemaRegex = /(\s+detailsSchema:\s*)(z\.object\(\{[^]*?\}\)(?:\.[^,}\s]+)*)/g;
239506
- processedContent = processedContent.replace(detailsSchemaRegex, (match2, prefix, schemaObject) => {
239507
- if (schemaObject.length >= MIN_REPLACEMENT_LENGTH) {
239508
- const placeholder = `<DETAILS_SCHEMA_${generatePlaceholderId()}>`;
239509
- replacements[placeholder] = schemaObject;
239510
- replacedFields++;
239511
- return `${prefix}${placeholder}`;
239512
- }
239513
- return match2;
239514
- });
239515
- const propsRegex = /(\s+props:\s*)(z\.object\(\{[^]*?\}\)(?:\.[^,}\s]+)*)/g;
239516
- processedContent = processedContent.replace(propsRegex, (match2, prefix, propsObject) => {
239517
- if (propsObject.length >= MIN_REPLACEMENT_LENGTH) {
239518
- const placeholder = `<PROPS_${generatePlaceholderId()}>`;
239519
- replacements[placeholder] = propsObject;
239520
- replacedFields++;
239521
- return `${prefix}${placeholder}`;
239522
- }
239523
- return match2;
239524
- });
239525
- const processedSize = processedContent.length;
239526
- const savings = originalSize - processedSize;
239527
- const savingsPercentage = originalSize > 0 ? savings / originalSize * 100 : 0;
239528
- return {
239529
- processedContent,
239530
- replacements,
239531
- stats: {
239532
- originalSize,
239533
- processedSize,
239534
- savings,
239535
- savingsPercentage,
239536
- replacedFields
239537
- }
239538
- };
239800
+ try {
239801
+ const project = new Project2({ useInMemoryFileSystem: true });
239802
+ const sourceFile = project.createSourceFile("temp.ts", content);
239803
+ const replacementOperations = [];
239804
+ sourceFile.forEachDescendant((node) => {
239805
+ if (Node4.isPropertyAssignment(node)) {
239806
+ const propertyName = node.getName();
239807
+ const valueNode = node.getInitializer();
239808
+ if (!valueNode) return;
239809
+ let valueText = valueNode.getText();
239810
+ if (valueText.trim().length < MIN_REPLACEMENT_LENGTH) return;
239811
+ let placeholderPrefix = "";
239812
+ switch (propertyName) {
239813
+ case "prompt":
239814
+ placeholderPrefix = "PROMPT";
239815
+ break;
239816
+ case "description":
239817
+ placeholderPrefix = "DESC";
239818
+ break;
239819
+ case "inputSchema":
239820
+ placeholderPrefix = "INPUT_SCHEMA";
239821
+ break;
239822
+ case "detailsSchema":
239823
+ placeholderPrefix = "DETAILS_SCHEMA";
239824
+ break;
239825
+ case "props":
239826
+ placeholderPrefix = "PROPS";
239827
+ break;
239828
+ case "render":
239829
+ placeholderPrefix = "RENDER";
239830
+ break;
239831
+ default:
239832
+ return;
239833
+ }
239834
+ const start2 = valueNode.getStart();
239835
+ let end = valueNode.getEnd();
239836
+ const propertyAssignment = node;
239837
+ const propertyEnd = propertyAssignment.getEnd();
239838
+ if (propertyName === "inputSchema" || propertyName === "render") {
239839
+ let searchStart = start2;
239840
+ let braceCount = 0;
239841
+ let correctEnd = -1;
239842
+ let inString = false;
239843
+ let stringChar = "";
239844
+ for (let i3 = searchStart; i3 < content.length; i3++) {
239845
+ const char = content[i3];
239846
+ const prevChar = i3 > 0 ? content[i3 - 1] : "";
239847
+ if ((char === '"' || char === "'") && prevChar !== "\\") {
239848
+ if (!inString) {
239849
+ inString = true;
239850
+ stringChar = char;
239851
+ } else if (char === stringChar) {
239852
+ inString = false;
239853
+ stringChar = "";
239854
+ }
239855
+ }
239856
+ if (!inString) {
239857
+ if (char === "{") {
239858
+ braceCount++;
239859
+ } else if (char === "}") {
239860
+ braceCount--;
239861
+ if (braceCount === 0) {
239862
+ let j3 = i3 + 1;
239863
+ while (j3 < content.length && /\s/.test(content[j3])) {
239864
+ j3++;
239865
+ }
239866
+ if (j3 < content.length && content[j3] === ",") {
239867
+ correctEnd = j3 + 1;
239868
+ break;
239869
+ }
239870
+ }
239871
+ }
239872
+ }
239873
+ }
239874
+ if (correctEnd > start2 && correctEnd < end + 100) {
239875
+ end = correctEnd;
239876
+ valueText = content.slice(start2, end);
239877
+ }
239878
+ } else {
239879
+ const textAfterValue = content.slice(end, end + 20);
239880
+ if (!textAfterValue.match(/^\s*[,}]/)) {
239881
+ let correctEnd = end;
239882
+ while (correctEnd > start2 && !content.slice(correctEnd, correctEnd + 10).match(/^\s*[,}]/)) {
239883
+ correctEnd--;
239884
+ }
239885
+ if (correctEnd > start2) {
239886
+ end = correctEnd;
239887
+ valueText = content.slice(start2, end);
239888
+ } else {
239889
+ return;
239890
+ }
239891
+ }
239892
+ }
239893
+ if (end > propertyEnd) {
239894
+ return;
239895
+ }
239896
+ const actualText = content.slice(start2, end);
239897
+ if (valueText !== actualText) {
239898
+ return;
239899
+ }
239900
+ const finalTextAfterValue = content.slice(end, end + 20);
239901
+ if (!finalTextAfterValue.match(/^\s*[,}]/)) {
239902
+ return;
239903
+ }
239904
+ const placeholder = `<${placeholderPrefix}_${generatePlaceholderId()}>`;
239905
+ replacements[placeholder] = valueText;
239906
+ replacedFields++;
239907
+ replacementOperations.push({
239908
+ start: start2,
239909
+ end,
239910
+ placeholder,
239911
+ originalText: valueText
239912
+ // This now matches what we'll actually replace
239913
+ });
239914
+ }
239915
+ });
239916
+ replacementOperations.sort((a2, b3) => b3.start - a2.start);
239917
+ let processedContent = content;
239918
+ for (const op of replacementOperations) {
239919
+ processedContent = processedContent.slice(0, op.start) + op.placeholder + processedContent.slice(op.end);
239920
+ }
239921
+ const processedSize = processedContent.length;
239922
+ const savings = originalSize - processedSize;
239923
+ const savingsPercentage = originalSize > 0 ? savings / originalSize * 100 : 0;
239924
+ return {
239925
+ processedContent,
239926
+ replacements,
239927
+ stats: {
239928
+ originalSize,
239929
+ processedSize,
239930
+ savings,
239931
+ savingsPercentage,
239932
+ replacedFields
239933
+ }
239934
+ };
239935
+ } catch (error) {
239936
+ return {
239937
+ processedContent: content,
239938
+ replacements: {},
239939
+ stats: {
239940
+ originalSize,
239941
+ processedSize: originalSize,
239942
+ savings: 0,
239943
+ savingsPercentage: 0,
239944
+ replacedFields: 0
239945
+ }
239946
+ };
239947
+ }
239539
239948
  }
239540
239949
  function restoreTargetedTypeScriptPlaceholders(content, replacements) {
239541
239950
  let restoredContent = content;
239542
239951
  const sortedPlaceholders = Object.keys(replacements).sort((a2, b3) => b3.length - a2.length);
239543
239952
  for (const placeholder of sortedPlaceholders) {
239544
239953
  const originalValue = replacements[placeholder];
239954
+ if (!restoredContent.includes(placeholder)) {
239955
+ continue;
239956
+ }
239545
239957
  restoredContent = restoredContent.replace(placeholder, originalValue);
239546
239958
  }
239547
239959
  return restoredContent;
@@ -239624,8 +240036,46 @@ function calculateCostEstimate(promptTokens, completionTokens) {
239624
240036
  return promptCost + completionCost;
239625
240037
  }
239626
240038
  async function mergeComponentsWithLLM(request) {
239627
- const { oldContent, newContent, modifiedComponents, filePath } = request;
240039
+ const {
240040
+ oldContent,
240041
+ newContent,
240042
+ modifiedComponents,
240043
+ filePath,
240044
+ newComponents,
240045
+ componentsToExport
240046
+ } = request;
239628
240047
  const componentList = modifiedComponents.map((c2) => `- ${c2.componentType}:${c2.componentId}`).join("\n");
240048
+ const newComponentsList = newComponents && newComponents.length > 0 ? newComponents.map((c2) => {
240049
+ const currentFilePath = filePath.replace(/^.*\/([^/]+\/[^/]+)$/, "$1");
240050
+ const currentDir = currentFilePath.replace(/\/[^/]+$/, "");
240051
+ let componentPath = c2.filePath;
240052
+ if (componentPath.includes(".temp-")) {
240053
+ componentPath = componentPath.replace(/^.*\.temp-[^/]+\//, "");
240054
+ }
240055
+ componentPath = componentPath.replace(/\.ts$/, "");
240056
+ const importPath = calculateRelativeImportPath(currentDir, componentPath);
240057
+ const variableName = c2.componentId.replace(
240058
+ /-([a-z])/g,
240059
+ (_3, letter) => letter.toUpperCase()
240060
+ );
240061
+ return `- ${c2.componentType}:${c2.componentId} (import as: import { ${variableName} } from '${importPath}')`;
240062
+ }).join("\n") : "";
240063
+ function calculateRelativeImportPath(fromDir, toPath) {
240064
+ const fromParts = fromDir.split("/");
240065
+ const toParts = toPath.split("/");
240066
+ let commonLength = 0;
240067
+ while (commonLength < fromParts.length && commonLength < toParts.length - 1 && fromParts[commonLength] === toParts[commonLength]) {
240068
+ commonLength++;
240069
+ }
240070
+ const upLevels = fromParts.length - commonLength;
240071
+ let relativePath = "";
240072
+ for (let i3 = 0; i3 < upLevels; i3++) {
240073
+ relativePath += "../";
240074
+ }
240075
+ relativePath += toParts.slice(commonLength).join("/");
240076
+ return relativePath.startsWith("../") ? relativePath : "./" + relativePath;
240077
+ }
240078
+ const componentsToExportList = componentsToExport && componentsToExport.length > 0 ? componentsToExport.map((c2) => `- ${c2.variableName} (${c2.reason})`).join("\n") : "";
239629
240079
  const prompt = `You are a TypeScript code expert tasked with intelligently merging component updates.
239630
240080
 
239631
240081
  ## Task
@@ -239633,7 +240083,16 @@ Merge the OLD file content with NEW component definitions, preserving the origin
239633
240083
 
239634
240084
  ## Modified Components to Update
239635
240085
  ${componentList}
240086
+ ${newComponentsList ? `
240087
+ ## New Components Available (can be imported)
240088
+ ${newComponentsList}
240089
+ ` : ""}${componentsToExportList ? `
240090
+ ## Components That Need To Be Exported
240091
+ The following existing components are referenced by new components and must be exported:
240092
+ ${componentsToExportList}
239636
240093
 
240094
+ Ensure these components have export statements (convert \`const\` to \`export const\`, or add \`export\` to existing declarations).
240095
+ ` : ""}
239637
240096
  ## Instructions
239638
240097
  0. **Please ensure you focus changes to minimize git diff size.** We want a clean git history.
239639
240098
  1. **Preserve original structure**: Keep imports, exports, comments, and overall file organization
@@ -239642,7 +240101,13 @@ ${componentList}
239642
240101
  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.
239643
240102
  5. **Keep variable names**: Preserve original variable names and declarations
239644
240103
  6. **Preserve non-component code**: Keep any non-component logic, comments, or utilities
239645
- 7. **Please leave all imports at the top of the file.** Don't use .js imports, use .ts imports instead. (import example from './example')
240104
+ 7. **Smart import handling**:
240105
+ - Please leave all imports at the top of the file. Don't use .js imports, use .ts imports instead. (import example from './example')
240106
+ - Preserve all imports from the original content that are not modified.
240107
+ - For NEW components listed above, add proper import statements
240108
+ - For components that exist in the same file (modified components), DO NOT add import statements
240109
+ - Remove any incorrect imports from the NEW component definitions that reference same-file components
240110
+ - Use relative paths for imports (e.g., './example' not './example.js')
239646
240111
  8. **Format JavaScript functions for maximum readability**:
239647
240112
  - When you see compressed/minified function code like \`async({params})=>{...code...}\`, expand and prettify it
239648
240113
  - Add proper line breaks, spacing, and indentation to make the function readable
@@ -239656,12 +240121,12 @@ ${componentList}
239656
240121
  }
239657
240122
  \`\`\`
239658
240123
 
239659
- ## OLD Content:
240124
+ ## OLD File to be updated with new component definitions:
239660
240125
  \`\`\`typescript
239661
240126
  ${oldContent}
239662
240127
  \`\`\`
239663
240128
 
239664
- ## NEW Component Definitions:
240129
+ ## NEW Component Definitions to replace/add to the old file:
239665
240130
  \`\`\`typescript
239666
240131
  ${newContent}
239667
240132
  \`\`\`
@@ -239672,11 +240137,12 @@ Provide the merged TypeScript file that:
239672
240137
  - Updates ONLY the modified components listed above
239673
240138
  - Maintains consistent code style
239674
240139
  - Uses improved schemas where beneficial
239675
- - Preserves all imports, exports, and other code
240140
+ - Preserves all imports, exports, and other code that are necessary to keep the file working.
239676
240141
  - **Formats all function code beautifully with proper spacing, line breaks, and indentation**
239677
240142
  - **Ensures all syntax is valid and compilable TypeScript/JavaScript**
239678
240143
  - 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.
239679
240144
  - Please follow biomes.dev code style.
240145
+ - Please remember the NEW component definitions are to replace/add to the old file.
239680
240146
 
239681
240147
  Return only the merged TypeScript code without any explanation or markdown formatting.`;
239682
240148
  try {
@@ -239755,6 +240221,125 @@ import {
239755
240221
  } from "fs";
239756
240222
  import { basename as basename2, dirname as dirname7, join as join11 } from "path";
239757
240223
  import chalk11 from "chalk";
240224
+ function getObjectPreview(obj, maxLength = 200) {
240225
+ if (obj === null) return "null";
240226
+ if (obj === void 0) return "undefined";
240227
+ try {
240228
+ if (typeof obj === "object") {
240229
+ const jsonStr = JSON.stringify(obj, null, 0);
240230
+ if (jsonStr.length <= maxLength) {
240231
+ return jsonStr;
240232
+ } else {
240233
+ if (obj.component && typeof obj.component === "string") {
240234
+ const componentPreview = obj.component.length > 100 ? obj.component.substring(0, 100) + "..." : obj.component;
240235
+ return `{component: "${componentPreview}", mockData: ${obj.mockData ? "present" : "null"}}`;
240236
+ }
240237
+ return jsonStr.substring(0, maxLength) + "...";
240238
+ }
240239
+ } else {
240240
+ const str = String(obj);
240241
+ return str.length > maxLength ? str.substring(0, maxLength) + "..." : str;
240242
+ }
240243
+ } catch (error) {
240244
+ return `[Error stringifying: ${typeof obj}]`;
240245
+ }
240246
+ }
240247
+ function extractCredentialIds2(agentObj) {
240248
+ const credentialIds = [];
240249
+ if (agentObj.credentials && Array.isArray(agentObj.credentials)) {
240250
+ agentObj.credentials.forEach((cred) => {
240251
+ if (cred.id) {
240252
+ credentialIds.push(cred.id);
240253
+ }
240254
+ });
240255
+ }
240256
+ if (agentObj.contextConfig?.contextVariables) {
240257
+ Object.values(agentObj.contextConfig.contextVariables).forEach((variable) => {
240258
+ if (variable && typeof variable === "object" && variable.credentialReferenceId) {
240259
+ credentialIds.push(variable.credentialReferenceId);
240260
+ }
240261
+ });
240262
+ }
240263
+ return [...new Set(credentialIds)];
240264
+ }
240265
+ function findKeyDifferences(obj1, obj2, componentId) {
240266
+ const differences = [];
240267
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(obj1 || {}), ...Object.keys(obj2 || {})]);
240268
+ for (const key of allKeys) {
240269
+ const val1 = obj1?.[key];
240270
+ const val2 = obj2?.[key];
240271
+ if (key.startsWith("_") || key === "createdAt" || key === "updatedAt") {
240272
+ continue;
240273
+ }
240274
+ if (key === "credentials") {
240275
+ const creds1 = extractCredentialIds2(obj1);
240276
+ const creds2 = extractCredentialIds2(obj2);
240277
+ creds1.sort();
240278
+ creds2.sort();
240279
+ if (JSON.stringify(creds1) !== JSON.stringify(creds2)) {
240280
+ differences.push(
240281
+ `~ credentials: usage differs (${creds1.join(", ")} vs ${creds2.join(", ")})`
240282
+ );
240283
+ }
240284
+ continue;
240285
+ }
240286
+ const val1IsEmpty = val1 === null || val1 === void 0 || Array.isArray(val1) && val1.length === 0 || typeof val1 === "object" && val1 !== null && Object.keys(val1).length === 0;
240287
+ const val2IsEmpty = val2 === null || val2 === void 0 || Array.isArray(val2) && val2.length === 0 || typeof val2 === "object" && val2 !== null && Object.keys(val2).length === 0;
240288
+ if (val1IsEmpty && val2IsEmpty) {
240289
+ continue;
240290
+ }
240291
+ if (val1IsEmpty && !val2IsEmpty) {
240292
+ differences.push(`+ ${key}: ${typeof val2} (only in remote)`);
240293
+ } else if (!val1IsEmpty && val2IsEmpty) {
240294
+ differences.push(`- ${key}: ${typeof val1} (only in generated)`);
240295
+ } else if (val1 !== val2) {
240296
+ if (Array.isArray(val1) && Array.isArray(val2)) {
240297
+ if (val1.length !== val2.length) {
240298
+ differences.push(`~ ${key}: array length differs (${val1.length} vs ${val2.length})`);
240299
+ }
240300
+ } else if (typeof val1 === "object" && typeof val2 === "object" && val1 !== null && val2 !== null) {
240301
+ const keys1 = Object.keys(val1).filter((k4) => {
240302
+ if (k4.startsWith("_") || k4 === "createdAt" || k4 === "updatedAt" || k4 === "tenantId" || k4 === "projectId" || k4 === "agentId") {
240303
+ return false;
240304
+ }
240305
+ const v3 = val1[k4];
240306
+ return !(v3 === null || v3 === void 0 || Array.isArray(v3) && v3.length === 0 || typeof v3 === "object" && v3 !== null && Object.keys(v3).length === 0);
240307
+ });
240308
+ const keys2 = Object.keys(val2).filter((k4) => {
240309
+ if (k4.startsWith("_") || k4 === "createdAt" || k4 === "updatedAt" || k4 === "tenantId" || k4 === "projectId" || k4 === "agentId") {
240310
+ return false;
240311
+ }
240312
+ const v3 = val2[k4];
240313
+ return !(v3 === null || v3 === void 0 || Array.isArray(v3) && v3.length === 0 || typeof v3 === "object" && v3 !== null && Object.keys(v3).length === 0);
240314
+ });
240315
+ const subKeys1 = keys1.length;
240316
+ const subKeys2 = keys2.length;
240317
+ if (subKeys1 !== subKeys2) {
240318
+ differences.push(`~ ${key}: object size differs (${subKeys1} vs ${subKeys2} keys)`);
240319
+ }
240320
+ } else if (typeof val1 !== typeof val2) {
240321
+ differences.push(`~ ${key}: type differs (${typeof val1} vs ${typeof val2})`);
240322
+ } else {
240323
+ if (key === "render" || key === "component") {
240324
+ const val1Preview = getObjectPreview(val1, 200);
240325
+ const val2Preview = getObjectPreview(val2, 200);
240326
+ differences.push(`~ ${key}:`);
240327
+ differences.push(` Generated: ${val1Preview}`);
240328
+ differences.push(` Remote: ${val2Preview}`);
240329
+ } else {
240330
+ const val1Str = String(val1);
240331
+ const val2Str = String(val2);
240332
+ if (val1Str.length < 100 && val2Str.length < 100) {
240333
+ differences.push(`~ ${key}: "${val1Str}" vs "${val2Str}"`);
240334
+ } else {
240335
+ differences.push(`~ ${key}: values differ (both ${typeof val1})`);
240336
+ }
240337
+ }
240338
+ }
240339
+ }
240340
+ }
240341
+ return differences.slice(0, 10);
240342
+ }
239758
240343
  function getComponentFromProject(project, componentType, componentId) {
239759
240344
  switch (componentType) {
239760
240345
  case "credentials":
@@ -239763,6 +240348,39 @@ function getComponentFromProject(project, componentType, componentId) {
239763
240348
  return project.tools?.[componentId];
239764
240349
  case "agents":
239765
240350
  return project.agents?.[componentId];
240351
+ case "subAgents":
240352
+ if (project.agents) {
240353
+ for (const [agentId, agentData] of Object.entries(project.agents)) {
240354
+ if (agentData.subAgents && agentData.subAgents[componentId]) {
240355
+ return agentData.subAgents[componentId];
240356
+ }
240357
+ }
240358
+ }
240359
+ return null;
240360
+ case "contextConfigs":
240361
+ if (project.agents) {
240362
+ for (const [agentId, agentData] of Object.entries(project.agents)) {
240363
+ if (agentData.contextConfig && agentData.contextConfig.id === componentId) {
240364
+ return agentData.contextConfig;
240365
+ }
240366
+ }
240367
+ }
240368
+ return null;
240369
+ case "fetchDefinitions":
240370
+ if (project.agents) {
240371
+ for (const [agentId, agentData] of Object.entries(project.agents)) {
240372
+ if (agentData.contextConfig?.contextVariables) {
240373
+ for (const [varId, variable] of Object.entries(
240374
+ agentData.contextConfig.contextVariables
240375
+ )) {
240376
+ if (variable && typeof variable === "object" && variable.id === componentId) {
240377
+ return variable;
240378
+ }
240379
+ }
240380
+ }
240381
+ }
240382
+ }
240383
+ return null;
239766
240384
  case "dataComponents":
239767
240385
  return project.dataComponents?.[componentId];
239768
240386
  case "artifactComponents":
@@ -239823,12 +240441,24 @@ async function validateProjectEquivalence(tempDir, remoteProject) {
239823
240441
  componentType,
239824
240442
  modifiedId
239825
240443
  );
239826
- console.log(
239827
- chalk11.gray(`Generated Component: ${JSON.stringify(generatedComponent, null, 2)}`)
239828
- );
239829
- console.log(
239830
- chalk11.gray(`Remote Component: ${JSON.stringify(remoteComponent, null, 2)}`)
239831
- );
240444
+ if (generatedComponent && remoteComponent) {
240445
+ const differences = findKeyDifferences(
240446
+ generatedComponent,
240447
+ remoteComponent,
240448
+ modifiedId
240449
+ );
240450
+ if (differences.length > 0) {
240451
+ differences.forEach((diff) => {
240452
+ console.log(chalk11.gray(` ${diff}`));
240453
+ });
240454
+ } else {
240455
+ console.log(chalk11.gray(` No key-level differences detected`));
240456
+ }
240457
+ } else if (!generatedComponent) {
240458
+ console.log(chalk11.red(` Component missing in generated project`));
240459
+ } else if (!remoteComponent) {
240460
+ console.log(chalk11.red(` Component missing in remote project`));
240461
+ }
239832
240462
  }
239833
240463
  }
239834
240464
  if (changes.deleted.length > 0) {
@@ -240089,26 +240719,40 @@ async function runBiomeOnDirectory(dirPath) {
240089
240719
  return false;
240090
240720
  }
240091
240721
  }
240092
- function generateUpdatedComponentContent(componentType, componentId, componentData, remoteProject, localRegistry, environment) {
240722
+ function generateUpdatedComponentContent(componentType, componentId, componentData, remoteProject, localRegistry, environment, actualFilePath) {
240093
240723
  const defaultStyle = {
240094
240724
  quotes: "single",
240095
240725
  indentation: " ",
240096
240726
  semicolons: true
240097
240727
  };
240098
240728
  switch (componentType) {
240099
- case "agents":
240100
- return generateAgentFile(componentId, componentData, defaultStyle, localRegistry);
240729
+ case "agents": {
240730
+ const contextConfigData = componentData.contextConfig;
240731
+ const projectModels = remoteProject.models;
240732
+ return generateAgentFile(
240733
+ componentId,
240734
+ componentData,
240735
+ defaultStyle,
240736
+ localRegistry,
240737
+ contextConfigData,
240738
+ projectModels,
240739
+ actualFilePath
240740
+ );
240741
+ }
240101
240742
  case "subAgents": {
240102
240743
  const parentInfo = findSubAgentWithParent(remoteProject, componentId);
240103
240744
  const parentAgentId = parentInfo?.parentAgentId;
240104
240745
  const contextConfigData = parentInfo?.contextConfigData;
240746
+ const parentModels = parentInfo ? remoteProject.agents?.[parentInfo.parentAgentId]?.models : void 0;
240105
240747
  return generateSubAgentFile(
240106
240748
  componentId,
240107
240749
  componentData,
240108
240750
  defaultStyle,
240109
240751
  localRegistry,
240110
240752
  parentAgentId,
240111
- contextConfigData
240753
+ contextConfigData,
240754
+ parentModels,
240755
+ actualFilePath
240112
240756
  );
240113
240757
  }
240114
240758
  case "tools":
@@ -240148,7 +240792,7 @@ function generateUpdatedComponentContent(componentType, componentId, componentDa
240148
240792
  throw new Error(`No generator for component type: ${componentType}`);
240149
240793
  }
240150
240794
  }
240151
- async function updateModifiedComponents(comparison, remoteProject, localRegistry, projectRoot, environment, debug = false, providedTempDirName) {
240795
+ async function updateModifiedComponents(comparison, remoteProject, localRegistry, projectRoot, environment, debug = false, providedTempDirName, newComponents) {
240152
240796
  const results = [];
240153
240797
  const tempDirName = providedTempDirName || `.temp-${Date.now()}`;
240154
240798
  if (!providedTempDirName) {
@@ -240193,6 +240837,7 @@ async function updateModifiedComponents(comparison, remoteProject, localRegistry
240193
240837
  );
240194
240838
  for (const [filePath, fileComponents] of componentsByFile) {
240195
240839
  try {
240840
+ const relativeFilePath = filePath.replace(projectRoot + "/", "");
240196
240841
  const oldContent = readFileSync5(filePath, "utf8");
240197
240842
  const componentContentParts = [];
240198
240843
  const componentResults = [];
@@ -240239,9 +240884,46 @@ async function updateModifiedComponents(comparison, remoteProject, localRegistry
240239
240884
  }
240240
240885
  } else if (componentType === "credentials") {
240241
240886
  componentData = remoteProject.credentialReferences?.[componentId];
240887
+ } else if (componentType === "environments") {
240888
+ componentData = {
240889
+ name: `${componentId} Environment`,
240890
+ description: `Environment configuration for ${componentId}`,
240891
+ credentials: remoteProject.credentialReferences || {}
240892
+ };
240242
240893
  } else {
240243
240894
  const remoteComponents = remoteProject[componentType] || {};
240244
240895
  componentData = remoteComponents[componentId];
240896
+ if (componentType === "agents" && componentData && !componentData.credentials && remoteProject.credentialReferences) {
240897
+ const agentCredentials = [];
240898
+ const credentialSet = /* @__PURE__ */ new Set();
240899
+ if (componentData.contextConfig?.contextVariables) {
240900
+ for (const [varName, varData] of Object.entries(
240901
+ componentData.contextConfig.contextVariables
240902
+ )) {
240903
+ if (varData && typeof varData === "object" && varData.credentialReferenceId) {
240904
+ const credId = varData.credentialReferenceId;
240905
+ if (remoteProject.credentialReferences[credId] && !credentialSet.has(credId)) {
240906
+ credentialSet.add(credId);
240907
+ agentCredentials.push({ id: credId });
240908
+ }
240909
+ }
240910
+ }
240911
+ }
240912
+ for (const [credId, credData] of Object.entries(remoteProject.credentialReferences)) {
240913
+ if (credData.usedBy) {
240914
+ for (const usage of credData.usedBy) {
240915
+ if (usage.type === "agent" && usage.id === componentId && !credentialSet.has(credId)) {
240916
+ credentialSet.add(credId);
240917
+ agentCredentials.push({ id: credId });
240918
+ break;
240919
+ }
240920
+ }
240921
+ }
240922
+ }
240923
+ if (agentCredentials.length > 0) {
240924
+ componentData.credentials = agentCredentials;
240925
+ }
240926
+ }
240245
240927
  }
240246
240928
  if (!componentData) {
240247
240929
  componentResults.push({
@@ -240259,7 +240941,8 @@ async function updateModifiedComponents(comparison, remoteProject, localRegistry
240259
240941
  componentData,
240260
240942
  remoteProject,
240261
240943
  localRegistry,
240262
- environment
240944
+ environment,
240945
+ relativeFilePath
240263
240946
  );
240264
240947
  componentContentParts.push(`// ${componentType}:${componentId}
240265
240948
  ${componentContent}`);
@@ -240294,6 +240977,15 @@ ${componentContent}`);
240294
240977
  }
240295
240978
  }
240296
240979
  const newComponentContent = componentContentParts.join("\n\n");
240980
+ let componentsToExport = [];
240981
+ try {
240982
+ componentsToExport = analyzeComponentsToExport(
240983
+ newComponents || [],
240984
+ relativeFilePath,
240985
+ localRegistry
240986
+ );
240987
+ } catch (error) {
240988
+ }
240297
240989
  const mergeResult = await mergeComponentsWithLLM({
240298
240990
  oldContent,
240299
240991
  newContent: newComponentContent,
@@ -240301,7 +240993,9 @@ ${componentContent}`);
240301
240993
  componentId: c2.id,
240302
240994
  componentType: c2.type
240303
240995
  })),
240304
- filePath
240996
+ filePath,
240997
+ newComponents,
240998
+ componentsToExport
240305
240999
  });
240306
241000
  let finalContent;
240307
241001
  if (!mergeResult.success) {
@@ -240422,6 +241116,46 @@ ${componentContent}`);
240422
241116
  await validateTempDirectory(projectRoot, tempDirName, remoteProject);
240423
241117
  return results;
240424
241118
  }
241119
+ function analyzeComponentsToExport(newComponents, currentFilePath, localRegistry) {
241120
+ const componentsToExport = [];
241121
+ for (const newComp of newComponents) {
241122
+ if (newComp.filePath === currentFilePath) {
241123
+ continue;
241124
+ }
241125
+ const allLocalComponents = localRegistry.getAllComponents();
241126
+ for (const localComp of allLocalComponents) {
241127
+ const localCompRelativePath = localComp.filePath.startsWith("/") ? localComp.filePath.split("/").slice(-2).join("/") : localComp.filePath;
241128
+ if (localCompRelativePath === currentFilePath) {
241129
+ if (shouldComponentBeExported(localComp, newComponents)) {
241130
+ const existingExport = componentsToExport.find((c2) => c2.componentId === localComp.id);
241131
+ if (!existingExport) {
241132
+ componentsToExport.push({
241133
+ componentId: localComp.id,
241134
+ variableName: localComp.name,
241135
+ reason: `referenced by new component ${newComp.componentType}:${newComp.componentId}`
241136
+ });
241137
+ }
241138
+ }
241139
+ }
241140
+ }
241141
+ }
241142
+ return componentsToExport;
241143
+ }
241144
+ function shouldComponentBeExported(localComponent, newComponents) {
241145
+ if (localComponent.type === "agents" || localComponent.type === "subAgents") {
241146
+ return true;
241147
+ }
241148
+ if (localComponent.type === "tools" || localComponent.type === "functionTools") {
241149
+ return true;
241150
+ }
241151
+ if (localComponent.type === "contextConfigs") {
241152
+ return true;
241153
+ }
241154
+ if (localComponent.type === "artifactComponents") {
241155
+ return true;
241156
+ }
241157
+ return false;
241158
+ }
240425
241159
  var init_component_updater = __esm({
240426
241160
  "src/commands/pull-v3/component-updater.ts"() {
240427
241161
  "use strict";
@@ -240884,25 +241618,11 @@ function createProjectStructure(projectDir, projectId) {
240884
241618
  return paths;
240885
241619
  }
240886
241620
  function enrichCanDelegateToWithTypes(project, debug = false) {
240887
- if (debug) {
240888
- console.log(chalk14.gray("\u{1F527} Enriching canDelegateTo with type information..."));
240889
- }
240890
241621
  const agentIds = new Set(project.agents ? Object.keys(project.agents) : []);
240891
241622
  const subAgentIds = new Set(Object.keys(extractSubAgents(project)));
240892
241623
  const externalAgentIds = new Set(
240893
241624
  project.externalAgents ? Object.keys(project.externalAgents) : []
240894
241625
  );
240895
- if (debug) {
240896
- console.log(chalk14.gray(` Available agents: ${Array.from(agentIds).join(", ") || "none"}`));
240897
- console.log(
240898
- chalk14.gray(` Available subAgents: ${Array.from(subAgentIds).join(", ") || "none"}`)
240899
- );
240900
- console.log(
240901
- chalk14.gray(
240902
- ` Available externalAgents: ${Array.from(externalAgentIds).join(", ") || "none"}`
240903
- )
240904
- );
240905
- }
240906
241626
  const enrichCanDelegateToArray = (canDelegateTo, context) => {
240907
241627
  if (!Array.isArray(canDelegateTo)) return;
240908
241628
  for (let i3 = 0; i3 < canDelegateTo.length; i3++) {
@@ -240917,20 +241637,8 @@ function enrichCanDelegateToWithTypes(project, debug = false) {
240917
241637
  } else if (externalAgentIds.has(id)) {
240918
241638
  enrichedItem = { externalAgentId: id };
240919
241639
  } else {
240920
- if (debug) {
240921
- console.log(
240922
- chalk14.yellow(
240923
- ` Warning: canDelegateTo reference "${id}" in ${context} not found in any component collection`
240924
- )
240925
- );
240926
- }
240927
241640
  continue;
240928
241641
  }
240929
- if (debug && enrichedItem) {
240930
- console.log(
240931
- chalk14.gray(` Enriched "${id}" in ${context} -> ${JSON.stringify(enrichedItem)}`)
240932
- );
240933
- }
240934
241642
  canDelegateTo[i3] = enrichedItem;
240935
241643
  }
240936
241644
  };
@@ -240970,22 +241678,6 @@ async function readExistingProject(projectRoot, debug = false) {
240970
241678
  } catch (error) {
240971
241679
  const errorMessage = error instanceof Error ? error.message : String(error);
240972
241680
  const isCredentialError = errorMessage.includes("Credential") && errorMessage.includes("not found");
240973
- if (debug) {
240974
- if (isCredentialError) {
240975
- console.log(
240976
- chalk14.yellow(" \u26A0 Cannot load existing project - credentials not configured:")
240977
- );
240978
- console.log(chalk14.gray(` ${errorMessage}`));
240979
- console.log(
240980
- chalk14.gray(
240981
- " \u{1F4A1} This is expected if you haven't added credentials to environment files yet"
240982
- )
240983
- );
240984
- } else {
240985
- console.log(chalk14.red(" \u2717 Error parsing existing project:"));
240986
- console.log(chalk14.red(` ${errorMessage}`));
240987
- }
240988
- }
240989
241681
  return null;
240990
241682
  }
240991
241683
  }
@@ -241000,7 +241692,7 @@ async function pullV3Command(options) {
241000
241692
  }
241001
241693
  };
241002
241694
  performBackgroundVersionCheck();
241003
- console.log(chalk14.blue("\n\u{1F680} Pull v3 - Clean & Efficient"));
241695
+ console.log(chalk14.blue("\nInkeep Pull:"));
241004
241696
  if (options.introspect) {
241005
241697
  console.log(chalk14.gray(" Introspect mode \u2022 Complete regeneration \u2022 No comparison needed"));
241006
241698
  } else {
@@ -241097,16 +241789,6 @@ async function pullV3Command(options) {
241097
241789
  };
241098
241790
  }
241099
241791
  });
241100
- if (options.debug) {
241101
- const hoistedKeys = Object.keys(agentData.functions).filter(
241102
- (key) => !remoteProject.functions[key]
241103
- );
241104
- if (hoistedKeys.length > 0) {
241105
- console.log(
241106
- chalk14.gray(` Hoisted functions from agent ${agentId}: ${hoistedKeys.join(", ")}`)
241107
- );
241108
- }
241109
- }
241110
241792
  }
241111
241793
  }
241112
241794
  }
@@ -241123,14 +241805,6 @@ async function pullV3Command(options) {
241123
241805
  } else {
241124
241806
  delete agentData.tools;
241125
241807
  }
241126
- if (options.debug) {
241127
- const removedCount = originalToolCount - Object.keys(agentSpecificTools).length;
241128
- if (removedCount > 0) {
241129
- console.log(
241130
- chalk14.gray(` Filtered ${removedCount} project-level tools from agent ${agentId}`)
241131
- );
241132
- }
241133
- }
241134
241808
  }
241135
241809
  }
241136
241810
  }
@@ -241222,10 +241896,11 @@ async function pullV3Command(options) {
241222
241896
  (sum, changes) => sum + changes.added.length,
241223
241897
  0
241224
241898
  );
241899
+ let newComponentResults = [];
241225
241900
  if (newComponentCount > 0) {
241226
241901
  s4.start("Creating new component files in temp directory...");
241227
241902
  const { createNewComponents: createNewComponents2 } = await Promise.resolve().then(() => (init_new_component_generator(), new_component_generator_exports));
241228
- const newComponentResults = await createNewComponents2(
241903
+ newComponentResults = await createNewComponents2(
241229
241904
  comparison,
241230
241905
  remoteProject,
241231
241906
  localRegistry,
@@ -241266,6 +241941,12 @@ async function pullV3Command(options) {
241266
241941
  if (modifiedCount > 0) {
241267
241942
  s4.start("Applying modified components to temp directory...");
241268
241943
  const { updateModifiedComponents: updateModifiedComponents2 } = await Promise.resolve().then(() => (init_component_updater(), component_updater_exports));
241944
+ const newComponentsForContext = newComponentResults && newComponentResults.length > 0 ? newComponentResults.filter((result) => result.success).map((result) => ({
241945
+ componentId: result.componentId,
241946
+ componentType: result.componentType,
241947
+ filePath: result.filePath.replace(paths.projectRoot + "/", "")
241948
+ // Convert to relative path
241949
+ })) : void 0;
241269
241950
  const updateResults = await updateModifiedComponents2(
241270
241951
  comparison,
241271
241952
  remoteProject,
@@ -241273,8 +241954,9 @@ async function pullV3Command(options) {
241273
241954
  paths.projectRoot,
241274
241955
  options.env || "development",
241275
241956
  options.debug,
241276
- tempDirName
241957
+ tempDirName,
241277
241958
  // Use the temp directory we created
241959
+ newComponentsForContext
241278
241960
  );
241279
241961
  s4.message("Modified components applied");
241280
241962
  }