@probelabs/probe 0.6.0-rc166 → 0.6.0-rc167

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.
@@ -3404,7 +3404,7 @@ async function delegate({
3404
3404
  maxIterations = 30,
3405
3405
  tracer = null,
3406
3406
  parentSessionId = null,
3407
- path: path7 = null,
3407
+ path: path8 = null,
3408
3408
  provider = null,
3409
3409
  model = null
3410
3410
  }) {
@@ -3444,7 +3444,7 @@ async function delegate({
3444
3444
  maxIterations: remainingIterations,
3445
3445
  debug,
3446
3446
  tracer,
3447
- path: path7,
3447
+ path: path8,
3448
3448
  // Inherit from parent
3449
3449
  provider,
3450
3450
  // Inherit from parent
@@ -4062,8 +4062,8 @@ var init_parseUtil = __esm({
4062
4062
  init_errors();
4063
4063
  init_en();
4064
4064
  makeIssue = (params) => {
4065
- const { data, path: path7, errorMaps, issueData } = params;
4066
- const fullPath = [...path7, ...issueData.path || []];
4065
+ const { data, path: path8, errorMaps, issueData } = params;
4066
+ const fullPath = [...path8, ...issueData.path || []];
4067
4067
  const fullIssue = {
4068
4068
  ...issueData,
4069
4069
  path: fullPath
@@ -4371,11 +4371,11 @@ var init_types = __esm({
4371
4371
  init_parseUtil();
4372
4372
  init_util2();
4373
4373
  ParseInputLazyPath = class {
4374
- constructor(parent, value, path7, key) {
4374
+ constructor(parent, value, path8, key) {
4375
4375
  this._cachedPath = [];
4376
4376
  this.parent = parent;
4377
4377
  this.data = value;
4378
- this._path = path7;
4378
+ this._path = path8;
4379
4379
  this._key = key;
4380
4380
  }
4381
4381
  get path() {
@@ -8198,10 +8198,10 @@ var init_vercel = __esm({
8198
8198
  name: "search",
8199
8199
  description: searchDescription,
8200
8200
  inputSchema: searchSchema,
8201
- execute: async ({ query: searchQuery, path: path7, allow_tests, exact, maxTokens: paramMaxTokens, language }) => {
8201
+ execute: async ({ query: searchQuery, path: path8, allow_tests, exact, maxTokens: paramMaxTokens, language }) => {
8202
8202
  try {
8203
8203
  const effectiveMaxTokens = paramMaxTokens || maxTokens;
8204
- let searchPath = path7 || options.defaultPath || ".";
8204
+ let searchPath = path8 || options.defaultPath || ".";
8205
8205
  if ((searchPath === "." || searchPath === "./") && options.defaultPath) {
8206
8206
  if (debug) {
8207
8207
  console.error(`Using default path "${options.defaultPath}" instead of "${searchPath}"`);
@@ -8241,9 +8241,9 @@ var init_vercel = __esm({
8241
8241
  name: "query",
8242
8242
  description: queryDescription,
8243
8243
  inputSchema: querySchema,
8244
- execute: async ({ pattern, path: path7, language, allow_tests }) => {
8244
+ execute: async ({ pattern, path: path8, language, allow_tests }) => {
8245
8245
  try {
8246
- let queryPath = path7 || options.defaultPath || ".";
8246
+ let queryPath = path8 || options.defaultPath || ".";
8247
8247
  if ((queryPath === "." || queryPath === "./") && options.defaultPath) {
8248
8248
  if (debug) {
8249
8249
  console.error(`Using default path "${options.defaultPath}" instead of "${queryPath}"`);
@@ -8353,7 +8353,7 @@ var init_vercel = __esm({
8353
8353
  name: "delegate",
8354
8354
  description: delegateDescription,
8355
8355
  inputSchema: delegateSchema,
8356
- execute: async ({ task, currentIteration, maxIterations, parentSessionId, path: path7, provider, model, tracer }) => {
8356
+ execute: async ({ task, currentIteration, maxIterations, parentSessionId, path: path8, provider, model, tracer }) => {
8357
8357
  if (!task || typeof task !== "string") {
8358
8358
  throw new Error("Task parameter is required and must be a non-empty string");
8359
8359
  }
@@ -8369,7 +8369,7 @@ var init_vercel = __esm({
8369
8369
  if (parentSessionId !== void 0 && parentSessionId !== null && typeof parentSessionId !== "string") {
8370
8370
  throw new TypeError("parentSessionId must be a string, null, or undefined");
8371
8371
  }
8372
- if (path7 !== void 0 && path7 !== null && typeof path7 !== "string") {
8372
+ if (path8 !== void 0 && path8 !== null && typeof path8 !== "string") {
8373
8373
  throw new TypeError("path must be a string, null, or undefined");
8374
8374
  }
8375
8375
  if (provider !== void 0 && provider !== null && typeof provider !== "string") {
@@ -8391,7 +8391,7 @@ var init_vercel = __esm({
8391
8391
  currentIteration: currentIteration || 0,
8392
8392
  maxIterations: maxIterations || 30,
8393
8393
  parentSessionId,
8394
- path: path7,
8394
+ path: path8,
8395
8395
  provider,
8396
8396
  model,
8397
8397
  tracer
@@ -14519,12 +14519,12 @@ var init_esm4 = __esm({
14519
14519
  /**
14520
14520
  * Get the Path object referenced by the string path, resolved from this Path
14521
14521
  */
14522
- resolve(path7) {
14523
- if (!path7) {
14522
+ resolve(path8) {
14523
+ if (!path8) {
14524
14524
  return this;
14525
14525
  }
14526
- const rootPath = this.getRootString(path7);
14527
- const dir = path7.substring(rootPath.length);
14526
+ const rootPath = this.getRootString(path8);
14527
+ const dir = path8.substring(rootPath.length);
14528
14528
  const dirParts = dir.split(this.splitSep);
14529
14529
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
14530
14530
  return result;
@@ -15276,8 +15276,8 @@ var init_esm4 = __esm({
15276
15276
  /**
15277
15277
  * @internal
15278
15278
  */
15279
- getRootString(path7) {
15280
- return win32.parse(path7).root;
15279
+ getRootString(path8) {
15280
+ return win32.parse(path8).root;
15281
15281
  }
15282
15282
  /**
15283
15283
  * @internal
@@ -15323,8 +15323,8 @@ var init_esm4 = __esm({
15323
15323
  /**
15324
15324
  * @internal
15325
15325
  */
15326
- getRootString(path7) {
15327
- return path7.startsWith("/") ? "/" : "";
15326
+ getRootString(path8) {
15327
+ return path8.startsWith("/") ? "/" : "";
15328
15328
  }
15329
15329
  /**
15330
15330
  * @internal
@@ -15373,8 +15373,8 @@ var init_esm4 = __esm({
15373
15373
  *
15374
15374
  * @internal
15375
15375
  */
15376
- constructor(cwd = process.cwd(), pathImpl, sep3, { nocase, childrenCacheSize = 16 * 1024, fs: fs7 = defaultFS } = {}) {
15377
- this.#fs = fsFromOption(fs7);
15376
+ constructor(cwd = process.cwd(), pathImpl, sep3, { nocase, childrenCacheSize = 16 * 1024, fs: fs8 = defaultFS } = {}) {
15377
+ this.#fs = fsFromOption(fs8);
15378
15378
  if (cwd instanceof URL || cwd.startsWith("file://")) {
15379
15379
  cwd = fileURLToPath4(cwd);
15380
15380
  }
@@ -15413,11 +15413,11 @@ var init_esm4 = __esm({
15413
15413
  /**
15414
15414
  * Get the depth of a provided path, string, or the cwd
15415
15415
  */
15416
- depth(path7 = this.cwd) {
15417
- if (typeof path7 === "string") {
15418
- path7 = this.cwd.resolve(path7);
15416
+ depth(path8 = this.cwd) {
15417
+ if (typeof path8 === "string") {
15418
+ path8 = this.cwd.resolve(path8);
15419
15419
  }
15420
- return path7.depth();
15420
+ return path8.depth();
15421
15421
  }
15422
15422
  /**
15423
15423
  * Return the cache of child entries. Exposed so subclasses can create
@@ -15904,9 +15904,9 @@ var init_esm4 = __esm({
15904
15904
  process2();
15905
15905
  return results;
15906
15906
  }
15907
- chdir(path7 = this.cwd) {
15907
+ chdir(path8 = this.cwd) {
15908
15908
  const oldCwd = this.cwd;
15909
- this.cwd = typeof path7 === "string" ? this.cwd.resolve(path7) : path7;
15909
+ this.cwd = typeof path8 === "string" ? this.cwd.resolve(path8) : path8;
15910
15910
  this.cwd[setAsCwd](oldCwd);
15911
15911
  }
15912
15912
  };
@@ -15932,8 +15932,8 @@ var init_esm4 = __esm({
15932
15932
  /**
15933
15933
  * @internal
15934
15934
  */
15935
- newRoot(fs7) {
15936
- return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs7 });
15935
+ newRoot(fs8) {
15936
+ return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs8 });
15937
15937
  }
15938
15938
  /**
15939
15939
  * Return true if the provided path string is an absolute path
@@ -15961,8 +15961,8 @@ var init_esm4 = __esm({
15961
15961
  /**
15962
15962
  * @internal
15963
15963
  */
15964
- newRoot(fs7) {
15965
- return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs7 });
15964
+ newRoot(fs8) {
15965
+ return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs8 });
15966
15966
  }
15967
15967
  /**
15968
15968
  * Return true if the provided path string is an absolute path
@@ -16281,8 +16281,8 @@ var init_processor = __esm({
16281
16281
  }
16282
16282
  // match, absolute, ifdir
16283
16283
  entries() {
16284
- return [...this.store.entries()].map(([path7, n]) => [
16285
- path7,
16284
+ return [...this.store.entries()].map(([path8, n]) => [
16285
+ path8,
16286
16286
  !!(n & 2),
16287
16287
  !!(n & 1)
16288
16288
  ]);
@@ -16495,9 +16495,9 @@ var init_walker = __esm({
16495
16495
  signal;
16496
16496
  maxDepth;
16497
16497
  includeChildMatches;
16498
- constructor(patterns, path7, opts) {
16498
+ constructor(patterns, path8, opts) {
16499
16499
  this.patterns = patterns;
16500
- this.path = path7;
16500
+ this.path = path8;
16501
16501
  this.opts = opts;
16502
16502
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
16503
16503
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -16516,11 +16516,11 @@ var init_walker = __esm({
16516
16516
  });
16517
16517
  }
16518
16518
  }
16519
- #ignored(path7) {
16520
- return this.seen.has(path7) || !!this.#ignore?.ignored?.(path7);
16519
+ #ignored(path8) {
16520
+ return this.seen.has(path8) || !!this.#ignore?.ignored?.(path8);
16521
16521
  }
16522
- #childrenIgnored(path7) {
16523
- return !!this.#ignore?.childrenIgnored?.(path7);
16522
+ #childrenIgnored(path8) {
16523
+ return !!this.#ignore?.childrenIgnored?.(path8);
16524
16524
  }
16525
16525
  // backpressure mechanism
16526
16526
  pause() {
@@ -16735,8 +16735,8 @@ var init_walker = __esm({
16735
16735
  };
16736
16736
  GlobWalker = class extends GlobUtil {
16737
16737
  matches = /* @__PURE__ */ new Set();
16738
- constructor(patterns, path7, opts) {
16739
- super(patterns, path7, opts);
16738
+ constructor(patterns, path8, opts) {
16739
+ super(patterns, path8, opts);
16740
16740
  }
16741
16741
  matchEmit(e) {
16742
16742
  this.matches.add(e);
@@ -16773,8 +16773,8 @@ var init_walker = __esm({
16773
16773
  };
16774
16774
  GlobStream = class extends GlobUtil {
16775
16775
  results;
16776
- constructor(patterns, path7, opts) {
16777
- super(patterns, path7, opts);
16776
+ constructor(patterns, path8, opts) {
16777
+ super(patterns, path8, opts);
16778
16778
  this.results = new Minipass({
16779
16779
  signal: this.signal,
16780
16780
  objectMode: true
@@ -19467,11 +19467,11 @@ var init_toKey = __esm({
19467
19467
  });
19468
19468
 
19469
19469
  // node_modules/lodash-es/_baseGet.js
19470
- function baseGet(object, path7) {
19471
- path7 = castPath_default(path7, object);
19472
- var index = 0, length = path7.length;
19470
+ function baseGet(object, path8) {
19471
+ path8 = castPath_default(path8, object);
19472
+ var index = 0, length = path8.length;
19473
19473
  while (object != null && index < length) {
19474
- object = object[toKey_default(path7[index++])];
19474
+ object = object[toKey_default(path8[index++])];
19475
19475
  }
19476
19476
  return index && index == length ? object : void 0;
19477
19477
  }
@@ -19485,8 +19485,8 @@ var init_baseGet = __esm({
19485
19485
  });
19486
19486
 
19487
19487
  // node_modules/lodash-es/get.js
19488
- function get(object, path7, defaultValue) {
19489
- var result = object == null ? void 0 : baseGet_default(object, path7);
19488
+ function get(object, path8, defaultValue) {
19489
+ var result = object == null ? void 0 : baseGet_default(object, path8);
19490
19490
  return result === void 0 ? defaultValue : result;
19491
19491
  }
19492
19492
  var get_default;
@@ -20849,11 +20849,11 @@ var init_baseHasIn = __esm({
20849
20849
  });
20850
20850
 
20851
20851
  // node_modules/lodash-es/_hasPath.js
20852
- function hasPath(object, path7, hasFunc) {
20853
- path7 = castPath_default(path7, object);
20854
- var index = -1, length = path7.length, result = false;
20852
+ function hasPath(object, path8, hasFunc) {
20853
+ path8 = castPath_default(path8, object);
20854
+ var index = -1, length = path8.length, result = false;
20855
20855
  while (++index < length) {
20856
- var key = toKey_default(path7[index]);
20856
+ var key = toKey_default(path8[index]);
20857
20857
  if (!(result = object != null && hasFunc(object, key))) {
20858
20858
  break;
20859
20859
  }
@@ -20879,8 +20879,8 @@ var init_hasPath = __esm({
20879
20879
  });
20880
20880
 
20881
20881
  // node_modules/lodash-es/hasIn.js
20882
- function hasIn(object, path7) {
20883
- return object != null && hasPath_default(object, path7, baseHasIn_default);
20882
+ function hasIn(object, path8) {
20883
+ return object != null && hasPath_default(object, path8, baseHasIn_default);
20884
20884
  }
20885
20885
  var hasIn_default;
20886
20886
  var init_hasIn = __esm({
@@ -20892,13 +20892,13 @@ var init_hasIn = __esm({
20892
20892
  });
20893
20893
 
20894
20894
  // node_modules/lodash-es/_baseMatchesProperty.js
20895
- function baseMatchesProperty(path7, srcValue) {
20896
- if (isKey_default(path7) && isStrictComparable_default(srcValue)) {
20897
- return matchesStrictComparable_default(toKey_default(path7), srcValue);
20895
+ function baseMatchesProperty(path8, srcValue) {
20896
+ if (isKey_default(path8) && isStrictComparable_default(srcValue)) {
20897
+ return matchesStrictComparable_default(toKey_default(path8), srcValue);
20898
20898
  }
20899
20899
  return function(object) {
20900
- var objValue = get_default(object, path7);
20901
- return objValue === void 0 && objValue === srcValue ? hasIn_default(object, path7) : baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG6 | COMPARE_UNORDERED_FLAG4);
20900
+ var objValue = get_default(object, path8);
20901
+ return objValue === void 0 && objValue === srcValue ? hasIn_default(object, path8) : baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG6 | COMPARE_UNORDERED_FLAG4);
20902
20902
  };
20903
20903
  }
20904
20904
  var COMPARE_PARTIAL_FLAG6, COMPARE_UNORDERED_FLAG4, baseMatchesProperty_default;
@@ -20931,9 +20931,9 @@ var init_baseProperty = __esm({
20931
20931
  });
20932
20932
 
20933
20933
  // node_modules/lodash-es/_basePropertyDeep.js
20934
- function basePropertyDeep(path7) {
20934
+ function basePropertyDeep(path8) {
20935
20935
  return function(object) {
20936
- return baseGet_default(object, path7);
20936
+ return baseGet_default(object, path8);
20937
20937
  };
20938
20938
  }
20939
20939
  var basePropertyDeep_default;
@@ -20945,8 +20945,8 @@ var init_basePropertyDeep = __esm({
20945
20945
  });
20946
20946
 
20947
20947
  // node_modules/lodash-es/property.js
20948
- function property(path7) {
20949
- return isKey_default(path7) ? baseProperty_default(toKey_default(path7)) : basePropertyDeep_default(path7);
20948
+ function property(path8) {
20949
+ return isKey_default(path8) ? baseProperty_default(toKey_default(path8)) : basePropertyDeep_default(path8);
20950
20950
  }
20951
20951
  var property_default;
20952
20952
  var init_property = __esm({
@@ -21565,8 +21565,8 @@ var init_baseHas = __esm({
21565
21565
  });
21566
21566
 
21567
21567
  // node_modules/lodash-es/has.js
21568
- function has(object, path7) {
21569
- return object != null && hasPath_default(object, path7, baseHas_default);
21568
+ function has(object, path8) {
21569
+ return object != null && hasPath_default(object, path8, baseHas_default);
21570
21570
  }
21571
21571
  var has_default;
21572
21572
  var init_has = __esm({
@@ -21772,14 +21772,14 @@ var init_negate = __esm({
21772
21772
  });
21773
21773
 
21774
21774
  // node_modules/lodash-es/_baseSet.js
21775
- function baseSet(object, path7, value, customizer) {
21775
+ function baseSet(object, path8, value, customizer) {
21776
21776
  if (!isObject_default(object)) {
21777
21777
  return object;
21778
21778
  }
21779
- path7 = castPath_default(path7, object);
21780
- var index = -1, length = path7.length, lastIndex = length - 1, nested = object;
21779
+ path8 = castPath_default(path8, object);
21780
+ var index = -1, length = path8.length, lastIndex = length - 1, nested = object;
21781
21781
  while (nested != null && ++index < length) {
21782
- var key = toKey_default(path7[index]), newValue = value;
21782
+ var key = toKey_default(path8[index]), newValue = value;
21783
21783
  if (key === "__proto__" || key === "constructor" || key === "prototype") {
21784
21784
  return object;
21785
21785
  }
@@ -21787,7 +21787,7 @@ function baseSet(object, path7, value, customizer) {
21787
21787
  var objValue = nested[key];
21788
21788
  newValue = customizer ? customizer(objValue, key, nested) : void 0;
21789
21789
  if (newValue === void 0) {
21790
- newValue = isObject_default(objValue) ? objValue : isIndex_default(path7[index + 1]) ? [] : {};
21790
+ newValue = isObject_default(objValue) ? objValue : isIndex_default(path8[index + 1]) ? [] : {};
21791
21791
  }
21792
21792
  }
21793
21793
  assignValue_default(nested, key, newValue);
@@ -21811,9 +21811,9 @@ var init_baseSet = __esm({
21811
21811
  function basePickBy(object, paths, predicate) {
21812
21812
  var index = -1, length = paths.length, result = {};
21813
21813
  while (++index < length) {
21814
- var path7 = paths[index], value = baseGet_default(object, path7);
21815
- if (predicate(value, path7)) {
21816
- baseSet_default(result, castPath_default(path7, object), value);
21814
+ var path8 = paths[index], value = baseGet_default(object, path8);
21815
+ if (predicate(value, path8)) {
21816
+ baseSet_default(result, castPath_default(path8, object), value);
21817
21817
  }
21818
21818
  }
21819
21819
  return result;
@@ -21837,8 +21837,8 @@ function pickBy(object, predicate) {
21837
21837
  return [prop];
21838
21838
  });
21839
21839
  predicate = baseIteratee_default(predicate);
21840
- return basePickBy_default(object, props, function(value, path7) {
21841
- return predicate(value, path7[0]);
21840
+ return basePickBy_default(object, props, function(value, path8) {
21841
+ return predicate(value, path8[0]);
21842
21842
  });
21843
21843
  }
21844
21844
  var pickBy_default;
@@ -24551,12 +24551,12 @@ function assignCategoriesMapProp(tokenTypes) {
24551
24551
  singleAssignCategoriesToksMap([], currTokType);
24552
24552
  });
24553
24553
  }
24554
- function singleAssignCategoriesToksMap(path7, nextNode) {
24555
- forEach_default(path7, (pathNode) => {
24554
+ function singleAssignCategoriesToksMap(path8, nextNode) {
24555
+ forEach_default(path8, (pathNode) => {
24556
24556
  nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true;
24557
24557
  });
24558
24558
  forEach_default(nextNode.CATEGORIES, (nextCategory) => {
24559
- const newPath = path7.concat(nextNode);
24559
+ const newPath = path8.concat(nextNode);
24560
24560
  if (!includes_default(newPath, nextCategory)) {
24561
24561
  singleAssignCategoriesToksMap(newPath, nextCategory);
24562
24562
  }
@@ -25726,10 +25726,10 @@ var init_interpreter = __esm({
25726
25726
  init_rest();
25727
25727
  init_api2();
25728
25728
  AbstractNextPossibleTokensWalker = class extends RestWalker {
25729
- constructor(topProd, path7) {
25729
+ constructor(topProd, path8) {
25730
25730
  super();
25731
25731
  this.topProd = topProd;
25732
- this.path = path7;
25732
+ this.path = path8;
25733
25733
  this.possibleTokTypes = [];
25734
25734
  this.nextProductionName = "";
25735
25735
  this.nextProductionOccurrence = 0;
@@ -25773,9 +25773,9 @@ var init_interpreter = __esm({
25773
25773
  }
25774
25774
  };
25775
25775
  NextAfterTokenWalker = class extends AbstractNextPossibleTokensWalker {
25776
- constructor(topProd, path7) {
25777
- super(topProd, path7);
25778
- this.path = path7;
25776
+ constructor(topProd, path8) {
25777
+ super(topProd, path8);
25778
+ this.path = path8;
25779
25779
  this.nextTerminalName = "";
25780
25780
  this.nextTerminalOccurrence = 0;
25781
25781
  this.nextTerminalName = this.path.lastTok.name;
@@ -26016,10 +26016,10 @@ function initializeArrayOfArrays(size) {
26016
26016
  }
26017
26017
  return result;
26018
26018
  }
26019
- function pathToHashKeys(path7) {
26019
+ function pathToHashKeys(path8) {
26020
26020
  let keys2 = [""];
26021
- for (let i = 0; i < path7.length; i++) {
26022
- const tokType = path7[i];
26021
+ for (let i = 0; i < path8.length; i++) {
26022
+ const tokType = path8[i];
26023
26023
  const longerKeys = [];
26024
26024
  for (let j = 0; j < keys2.length; j++) {
26025
26025
  const currShorterKey = keys2[j];
@@ -26322,7 +26322,7 @@ function validateRuleIsOverridden(ruleName, definedRulesNames, className) {
26322
26322
  }
26323
26323
  return errors;
26324
26324
  }
26325
- function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path7 = []) {
26325
+ function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path8 = []) {
26326
26326
  const errors = [];
26327
26327
  const nextNonTerminals = getFirstNoneTerminal(currRule.definition);
26328
26328
  if (isEmpty_default(nextNonTerminals)) {
@@ -26334,15 +26334,15 @@ function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path7 = [])
26334
26334
  errors.push({
26335
26335
  message: errMsgProvider.buildLeftRecursionError({
26336
26336
  topLevelRule: topRule,
26337
- leftRecursionPath: path7
26337
+ leftRecursionPath: path8
26338
26338
  }),
26339
26339
  type: ParserDefinitionErrorType.LEFT_RECURSION,
26340
26340
  ruleName
26341
26341
  });
26342
26342
  }
26343
- const validNextSteps = difference_default(nextNonTerminals, path7.concat([topRule]));
26343
+ const validNextSteps = difference_default(nextNonTerminals, path8.concat([topRule]));
26344
26344
  const errorsFromNextSteps = flatMap_default(validNextSteps, (currRefRule) => {
26345
- const newPath = clone_default(path7);
26345
+ const newPath = clone_default(path8);
26346
26346
  newPath.push(currRefRule);
26347
26347
  return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath);
26348
26348
  });
@@ -38939,11 +38939,11 @@ var require_baseGet = __commonJS({
38939
38939
  "node_modules/lodash/_baseGet.js"(exports2, module2) {
38940
38940
  var castPath2 = require_castPath();
38941
38941
  var toKey2 = require_toKey();
38942
- function baseGet2(object, path7) {
38943
- path7 = castPath2(path7, object);
38944
- var index = 0, length = path7.length;
38942
+ function baseGet2(object, path8) {
38943
+ path8 = castPath2(path8, object);
38944
+ var index = 0, length = path8.length;
38945
38945
  while (object != null && index < length) {
38946
- object = object[toKey2(path7[index++])];
38946
+ object = object[toKey2(path8[index++])];
38947
38947
  }
38948
38948
  return index && index == length ? object : void 0;
38949
38949
  }
@@ -38955,8 +38955,8 @@ var require_baseGet = __commonJS({
38955
38955
  var require_get = __commonJS({
38956
38956
  "node_modules/lodash/get.js"(exports2, module2) {
38957
38957
  var baseGet2 = require_baseGet();
38958
- function get2(object, path7, defaultValue) {
38959
- var result = object == null ? void 0 : baseGet2(object, path7);
38958
+ function get2(object, path8, defaultValue) {
38959
+ var result = object == null ? void 0 : baseGet2(object, path8);
38960
38960
  return result === void 0 ? defaultValue : result;
38961
38961
  }
38962
38962
  module2.exports = get2;
@@ -38982,11 +38982,11 @@ var require_hasPath = __commonJS({
38982
38982
  var isIndex2 = require_isIndex();
38983
38983
  var isLength2 = require_isLength();
38984
38984
  var toKey2 = require_toKey();
38985
- function hasPath2(object, path7, hasFunc) {
38986
- path7 = castPath2(path7, object);
38987
- var index = -1, length = path7.length, result = false;
38985
+ function hasPath2(object, path8, hasFunc) {
38986
+ path8 = castPath2(path8, object);
38987
+ var index = -1, length = path8.length, result = false;
38988
38988
  while (++index < length) {
38989
- var key = toKey2(path7[index]);
38989
+ var key = toKey2(path8[index]);
38990
38990
  if (!(result = object != null && hasFunc(object, key))) {
38991
38991
  break;
38992
38992
  }
@@ -39007,8 +39007,8 @@ var require_hasIn = __commonJS({
39007
39007
  "node_modules/lodash/hasIn.js"(exports2, module2) {
39008
39008
  var baseHasIn2 = require_baseHasIn();
39009
39009
  var hasPath2 = require_hasPath();
39010
- function hasIn2(object, path7) {
39011
- return object != null && hasPath2(object, path7, baseHasIn2);
39010
+ function hasIn2(object, path8) {
39011
+ return object != null && hasPath2(object, path8, baseHasIn2);
39012
39012
  }
39013
39013
  module2.exports = hasIn2;
39014
39014
  }
@@ -39026,13 +39026,13 @@ var require_baseMatchesProperty = __commonJS({
39026
39026
  var toKey2 = require_toKey();
39027
39027
  var COMPARE_PARTIAL_FLAG7 = 1;
39028
39028
  var COMPARE_UNORDERED_FLAG5 = 2;
39029
- function baseMatchesProperty2(path7, srcValue) {
39030
- if (isKey2(path7) && isStrictComparable2(srcValue)) {
39031
- return matchesStrictComparable2(toKey2(path7), srcValue);
39029
+ function baseMatchesProperty2(path8, srcValue) {
39030
+ if (isKey2(path8) && isStrictComparable2(srcValue)) {
39031
+ return matchesStrictComparable2(toKey2(path8), srcValue);
39032
39032
  }
39033
39033
  return function(object) {
39034
- var objValue = get2(object, path7);
39035
- return objValue === void 0 && objValue === srcValue ? hasIn2(object, path7) : baseIsEqual2(srcValue, objValue, COMPARE_PARTIAL_FLAG7 | COMPARE_UNORDERED_FLAG5);
39034
+ var objValue = get2(object, path8);
39035
+ return objValue === void 0 && objValue === srcValue ? hasIn2(object, path8) : baseIsEqual2(srcValue, objValue, COMPARE_PARTIAL_FLAG7 | COMPARE_UNORDERED_FLAG5);
39036
39036
  };
39037
39037
  }
39038
39038
  module2.exports = baseMatchesProperty2;
@@ -39055,9 +39055,9 @@ var require_baseProperty = __commonJS({
39055
39055
  var require_basePropertyDeep = __commonJS({
39056
39056
  "node_modules/lodash/_basePropertyDeep.js"(exports2, module2) {
39057
39057
  var baseGet2 = require_baseGet();
39058
- function basePropertyDeep2(path7) {
39058
+ function basePropertyDeep2(path8) {
39059
39059
  return function(object) {
39060
- return baseGet2(object, path7);
39060
+ return baseGet2(object, path8);
39061
39061
  };
39062
39062
  }
39063
39063
  module2.exports = basePropertyDeep2;
@@ -39071,8 +39071,8 @@ var require_property = __commonJS({
39071
39071
  var basePropertyDeep2 = require_basePropertyDeep();
39072
39072
  var isKey2 = require_isKey();
39073
39073
  var toKey2 = require_toKey();
39074
- function property2(path7) {
39075
- return isKey2(path7) ? baseProperty2(toKey2(path7)) : basePropertyDeep2(path7);
39074
+ function property2(path8) {
39075
+ return isKey2(path8) ? baseProperty2(toKey2(path8)) : basePropertyDeep2(path8);
39076
39076
  }
39077
39077
  module2.exports = property2;
39078
39078
  }
@@ -39134,8 +39134,8 @@ var require_has = __commonJS({
39134
39134
  "node_modules/lodash/has.js"(exports2, module2) {
39135
39135
  var baseHas2 = require_baseHas();
39136
39136
  var hasPath2 = require_hasPath();
39137
- function has2(object, path7) {
39138
- return object != null && hasPath2(object, path7, baseHas2);
39137
+ function has2(object, path8) {
39138
+ return object != null && hasPath2(object, path8, baseHas2);
39139
39139
  }
39140
39140
  module2.exports = has2;
39141
39141
  }
@@ -41409,14 +41409,14 @@ var require_baseSet = __commonJS({
41409
41409
  var isIndex2 = require_isIndex();
41410
41410
  var isObject2 = require_isObject();
41411
41411
  var toKey2 = require_toKey();
41412
- function baseSet2(object, path7, value, customizer) {
41412
+ function baseSet2(object, path8, value, customizer) {
41413
41413
  if (!isObject2(object)) {
41414
41414
  return object;
41415
41415
  }
41416
- path7 = castPath2(path7, object);
41417
- var index = -1, length = path7.length, lastIndex = length - 1, nested = object;
41416
+ path8 = castPath2(path8, object);
41417
+ var index = -1, length = path8.length, lastIndex = length - 1, nested = object;
41418
41418
  while (nested != null && ++index < length) {
41419
- var key = toKey2(path7[index]), newValue = value;
41419
+ var key = toKey2(path8[index]), newValue = value;
41420
41420
  if (key === "__proto__" || key === "constructor" || key === "prototype") {
41421
41421
  return object;
41422
41422
  }
@@ -41424,7 +41424,7 @@ var require_baseSet = __commonJS({
41424
41424
  var objValue = nested[key];
41425
41425
  newValue = customizer ? customizer(objValue, key, nested) : void 0;
41426
41426
  if (newValue === void 0) {
41427
- newValue = isObject2(objValue) ? objValue : isIndex2(path7[index + 1]) ? [] : {};
41427
+ newValue = isObject2(objValue) ? objValue : isIndex2(path8[index + 1]) ? [] : {};
41428
41428
  }
41429
41429
  }
41430
41430
  assignValue2(nested, key, newValue);
@@ -41445,9 +41445,9 @@ var require_basePickBy = __commonJS({
41445
41445
  function basePickBy2(object, paths, predicate) {
41446
41446
  var index = -1, length = paths.length, result = {};
41447
41447
  while (++index < length) {
41448
- var path7 = paths[index], value = baseGet2(object, path7);
41449
- if (predicate(value, path7)) {
41450
- baseSet2(result, castPath2(path7, object), value);
41448
+ var path8 = paths[index], value = baseGet2(object, path8);
41449
+ if (predicate(value, path8)) {
41450
+ baseSet2(result, castPath2(path8, object), value);
41451
41451
  }
41452
41452
  }
41453
41453
  return result;
@@ -41462,8 +41462,8 @@ var require_basePick = __commonJS({
41462
41462
  var basePickBy2 = require_basePickBy();
41463
41463
  var hasIn2 = require_hasIn();
41464
41464
  function basePick(object, paths) {
41465
- return basePickBy2(object, paths, function(value, path7) {
41466
- return hasIn2(object, path7);
41465
+ return basePickBy2(object, paths, function(value, path8) {
41466
+ return hasIn2(object, path8);
41467
41467
  });
41468
41468
  }
41469
41469
  module2.exports = basePick;
@@ -42517,15 +42517,15 @@ var require_parent_dummy_chains = __commonJS({
42517
42517
  var node = g.node(v);
42518
42518
  var edgeObj = node.edgeObj;
42519
42519
  var pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w);
42520
- var path7 = pathData.path;
42520
+ var path8 = pathData.path;
42521
42521
  var lca = pathData.lca;
42522
42522
  var pathIdx = 0;
42523
- var pathV = path7[pathIdx];
42523
+ var pathV = path8[pathIdx];
42524
42524
  var ascending = true;
42525
42525
  while (v !== edgeObj.w) {
42526
42526
  node = g.node(v);
42527
42527
  if (ascending) {
42528
- while ((pathV = path7[pathIdx]) !== lca && g.node(pathV).maxRank < node.rank) {
42528
+ while ((pathV = path8[pathIdx]) !== lca && g.node(pathV).maxRank < node.rank) {
42529
42529
  pathIdx++;
42530
42530
  }
42531
42531
  if (pathV === lca) {
@@ -42533,10 +42533,10 @@ var require_parent_dummy_chains = __commonJS({
42533
42533
  }
42534
42534
  }
42535
42535
  if (!ascending) {
42536
- while (pathIdx < path7.length - 1 && g.node(pathV = path7[pathIdx + 1]).minRank <= node.rank) {
42536
+ while (pathIdx < path8.length - 1 && g.node(pathV = path8[pathIdx + 1]).minRank <= node.rank) {
42537
42537
  pathIdx++;
42538
42538
  }
42539
- pathV = path7[pathIdx];
42539
+ pathV = path8[pathIdx];
42540
42540
  }
42541
42541
  g.setParent(v, pathV);
42542
42542
  v = g.successors(v)[0];
@@ -44709,8 +44709,8 @@ var init_svg_generator = __esm({
44709
44709
  elements.push(this.generateNodeWithPad(node, padX, padY));
44710
44710
  }
44711
44711
  for (const edge of layout.edges) {
44712
- const { path: path7, overlay } = this.generateEdge(edge, padX, padY, nodeMap);
44713
- elements.push(path7);
44712
+ const { path: path8, overlay } = this.generateEdge(edge, padX, padY, nodeMap);
44713
+ elements.push(path8);
44714
44714
  if (overlay)
44715
44715
  overlays.push(overlay);
44716
44716
  }
@@ -51026,8 +51026,8 @@ var require_utils = __commonJS({
51026
51026
  }
51027
51027
  return ind;
51028
51028
  }
51029
- function removeDotSegments(path7) {
51030
- let input = path7;
51029
+ function removeDotSegments(path8) {
51030
+ let input = path8;
51031
51031
  const output = [];
51032
51032
  let nextSlash = -1;
51033
51033
  let len = 0;
@@ -51226,8 +51226,8 @@ var require_schemes = __commonJS({
51226
51226
  wsComponent.secure = void 0;
51227
51227
  }
51228
51228
  if (wsComponent.resourceName) {
51229
- const [path7, query2] = wsComponent.resourceName.split("?");
51230
- wsComponent.path = path7 && path7 !== "/" ? path7 : void 0;
51229
+ const [path8, query2] = wsComponent.resourceName.split("?");
51230
+ wsComponent.path = path8 && path8 !== "/" ? path8 : void 0;
51231
51231
  wsComponent.query = query2;
51232
51232
  wsComponent.resourceName = void 0;
51233
51233
  }
@@ -54570,7 +54570,7 @@ function validateJsonResponse(response, options = {}) {
54570
54570
  }
54571
54571
  if (!valid) {
54572
54572
  const formattedErrors = validate2.errors.map((err) => {
54573
- const path7 = err.instancePath ? err.instancePath.substring(1).replace(/\//g, ".") : "<root>";
54573
+ const path8 = err.instancePath ? err.instancePath.substring(1).replace(/\//g, ".") : "<root>";
54574
54574
  let message = "";
54575
54575
  let suggestion = "";
54576
54576
  if (err.keyword === "additionalProperties") {
@@ -54608,7 +54608,7 @@ function validateJsonResponse(response, options = {}) {
54608
54608
  message = err.message;
54609
54609
  suggestion = "";
54610
54610
  }
54611
- const location = path7 ? `at '${path7}'` : "at root";
54611
+ const location = path8 ? `at '${path8}'` : "at root";
54612
54612
  return suggestion ? `${location}: ${message} \u2192 ${suggestion}` : `${location}: ${message}`;
54613
54613
  });
54614
54614
  const errorSummary = formattedErrors.join("\n ");
@@ -54931,7 +54931,7 @@ function extractMermaidFromJson(response) {
54931
54931
  }
54932
54932
  const diagrams = [];
54933
54933
  const jsonPaths = [];
54934
- function searchObject(obj, path7 = []) {
54934
+ function searchObject(obj, path8 = []) {
54935
54935
  if (typeof obj === "string") {
54936
54936
  const mermaidPattern = /```mermaid([^\n`]*?)(?:\n|\\n)([\s\S]*?)```/gi;
54937
54937
  let match2;
@@ -54945,14 +54945,14 @@ function extractMermaidFromJson(response) {
54945
54945
  endIndex: match2.index + match2[0].length,
54946
54946
  attributes,
54947
54947
  isInJson: true,
54948
- jsonPath: path7.join(".")
54948
+ jsonPath: path8.join(".")
54949
54949
  });
54950
- jsonPaths.push(path7.join("."));
54950
+ jsonPaths.push(path8.join("."));
54951
54951
  }
54952
54952
  } else if (Array.isArray(obj)) {
54953
- obj.forEach((item, index) => searchObject(item, [...path7, `[${index}]`]));
54953
+ obj.forEach((item, index) => searchObject(item, [...path8, `[${index}]`]));
54954
54954
  } else if (obj && typeof obj === "object") {
54955
- Object.entries(obj).forEach(([key, value]) => searchObject(value, [...path7, key]));
54955
+ Object.entries(obj).forEach(([key, value]) => searchObject(value, [...path8, key]));
54956
54956
  }
54957
54957
  }
54958
54958
  searchObject(parsedJson);
@@ -55209,7 +55209,7 @@ async function tryMaidAutoFix(diagramContent, options = {}) {
55209
55209
  }
55210
55210
  }
55211
55211
  async function validateAndFixMermaidResponse(response, options = {}) {
55212
- const { schema, debug, path: path7, provider, model, tracer } = options;
55212
+ const { schema, debug, path: path8, provider, model, tracer } = options;
55213
55213
  const startTime = Date.now();
55214
55214
  if (debug) {
55215
55215
  console.log(`[DEBUG] Mermaid validation: Starting maid-based validation for response (${response.length} chars)`);
@@ -55366,7 +55366,7 @@ ${maidResult.fixed}
55366
55366
  }
55367
55367
  const aiFixingStart = Date.now();
55368
55368
  const mermaidFixer = new MermaidFixingAgent({
55369
- path: path7,
55369
+ path: path8,
55370
55370
  provider,
55371
55371
  model,
55372
55372
  debug,
@@ -55608,8 +55608,8 @@ Schema Validation Errors:
55608
55608
  ${validationResult.errorSummary}`;
55609
55609
  } else if (validationResult.schemaErrors && validationResult.schemaErrors.length > 0) {
55610
55610
  const errors = validationResult.schemaErrors.map((err) => {
55611
- const path7 = err.instancePath || "(root)";
55612
- return ` ${path7}: ${err.message}`;
55611
+ const path8 = err.instancePath || "(root)";
55612
+ return ` ${path8}: ${err.message}`;
55613
55613
  }).join("\n");
55614
55614
  schemaErrorDetails = `
55615
55615
 
@@ -57380,6 +57380,909 @@ var init_contextCompactor = __esm({
57380
57380
  }
57381
57381
  });
57382
57382
 
57383
+ // src/agent/mcp/built-in-server.js
57384
+ import { createServer } from "http";
57385
+ import { EventEmitter as EventEmitter3 } from "events";
57386
+ import { Server as MCPServer } from "@modelcontextprotocol/sdk/server/index.js";
57387
+ import {
57388
+ CallToolRequestSchema,
57389
+ ListToolsRequestSchema
57390
+ } from "@modelcontextprotocol/sdk/types.js";
57391
+ var BuiltInMCPServer;
57392
+ var init_built_in_server = __esm({
57393
+ "src/agent/mcp/built-in-server.js"() {
57394
+ "use strict";
57395
+ BuiltInMCPServer = class extends EventEmitter3 {
57396
+ constructor(agent, options = {}) {
57397
+ super();
57398
+ this.agent = agent;
57399
+ this.port = options.port || 0;
57400
+ this.host = options.host || "127.0.0.1";
57401
+ this.httpServer = null;
57402
+ this.mcpServer = null;
57403
+ this.connections = /* @__PURE__ */ new Set();
57404
+ this.debug = options.debug || false;
57405
+ }
57406
+ /**
57407
+ * Start the built-in MCP server
57408
+ */
57409
+ async start() {
57410
+ this.httpServer = createServer();
57411
+ this.httpServer.on("request", (req, res) => {
57412
+ this.handleRequest(req, res);
57413
+ });
57414
+ this.mcpServer = new MCPServer({
57415
+ name: "probe-builtin",
57416
+ version: "1.0.0"
57417
+ }, {
57418
+ capabilities: {
57419
+ tools: {}
57420
+ }
57421
+ });
57422
+ this.registerHandlers();
57423
+ return new Promise((resolve6, reject2) => {
57424
+ this.httpServer.listen(this.port, this.host, () => {
57425
+ const address = this.httpServer.address();
57426
+ this.port = address.port;
57427
+ if (this.debug) {
57428
+ console.log(`[MCP] Built-in server started at http://${this.host}:${this.port}`);
57429
+ }
57430
+ this.emit("ready", { host: this.host, port: this.port });
57431
+ resolve6({ host: this.host, port: this.port });
57432
+ });
57433
+ this.httpServer.on("error", reject2);
57434
+ });
57435
+ }
57436
+ /**
57437
+ * Handle HTTP requests (SSE and JSON-RPC)
57438
+ */
57439
+ handleRequest(req, res) {
57440
+ const { method, url } = req;
57441
+ res.setHeader("Access-Control-Allow-Origin", "*");
57442
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
57443
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
57444
+ if (method === "OPTIONS") {
57445
+ res.writeHead(204);
57446
+ res.end();
57447
+ return;
57448
+ }
57449
+ if (url === "/sse" && method === "GET") {
57450
+ this.handleSSE(req, res);
57451
+ return;
57452
+ }
57453
+ if (url === "/rpc" && method === "POST") {
57454
+ this.handleJSONRPC(req, res);
57455
+ return;
57456
+ }
57457
+ if (url === "/mcp" && method === "POST") {
57458
+ this.handleMCPProtocol(req, res);
57459
+ return;
57460
+ }
57461
+ if (url === "/health") {
57462
+ res.writeHead(200, { "Content-Type": "application/json" });
57463
+ res.end(JSON.stringify({
57464
+ status: "ok",
57465
+ server: "probe-builtin-mcp",
57466
+ tools: this.getToolCount()
57467
+ }));
57468
+ return;
57469
+ }
57470
+ res.writeHead(404);
57471
+ res.end("Not Found");
57472
+ }
57473
+ /**
57474
+ * Handle Server-Sent Events connection
57475
+ */
57476
+ handleSSE(req, res) {
57477
+ res.writeHead(200, {
57478
+ "Content-Type": "text/event-stream",
57479
+ "Cache-Control": "no-cache",
57480
+ "Connection": "keep-alive"
57481
+ });
57482
+ res.write("event: connected\n");
57483
+ res.write(`data: ${JSON.stringify({ type: "connected", server: "probe-builtin" })}
57484
+
57485
+ `);
57486
+ this.connections.add(res);
57487
+ req.on("close", () => {
57488
+ this.connections.delete(res);
57489
+ });
57490
+ }
57491
+ /**
57492
+ * Handle JSON-RPC requests
57493
+ */
57494
+ async handleJSONRPC(req, res) {
57495
+ let body = "";
57496
+ req.on("data", (chunk) => {
57497
+ body += chunk.toString();
57498
+ });
57499
+ req.on("end", async () => {
57500
+ try {
57501
+ const request = JSON.parse(body);
57502
+ const response = await this.processRequest(request);
57503
+ res.writeHead(200, { "Content-Type": "application/json" });
57504
+ res.end(JSON.stringify(response));
57505
+ } catch (error) {
57506
+ res.writeHead(400, { "Content-Type": "application/json" });
57507
+ res.end(JSON.stringify({
57508
+ jsonrpc: "2.0",
57509
+ error: {
57510
+ code: -32700,
57511
+ message: "Parse error",
57512
+ data: error.message
57513
+ },
57514
+ id: null
57515
+ }));
57516
+ }
57517
+ });
57518
+ }
57519
+ /**
57520
+ * Handle MCP protocol messages
57521
+ */
57522
+ async handleMCPProtocol(req, res) {
57523
+ let body = "";
57524
+ req.on("data", (chunk) => {
57525
+ body += chunk.toString();
57526
+ });
57527
+ req.on("end", async () => {
57528
+ try {
57529
+ const message = JSON.parse(body);
57530
+ let response;
57531
+ if (message.method === "tools/list") {
57532
+ response = await this.handleListTools();
57533
+ } else if (message.method === "tools/call") {
57534
+ response = await this.handleCallTool(message.params);
57535
+ } else {
57536
+ response = {
57537
+ error: {
57538
+ code: -32601,
57539
+ message: "Method not found"
57540
+ }
57541
+ };
57542
+ }
57543
+ res.writeHead(200, { "Content-Type": "application/json" });
57544
+ res.end(JSON.stringify(response));
57545
+ } catch (error) {
57546
+ res.writeHead(500, { "Content-Type": "application/json" });
57547
+ res.end(JSON.stringify({
57548
+ error: {
57549
+ code: -32603,
57550
+ message: "Internal error",
57551
+ data: error.message
57552
+ }
57553
+ }));
57554
+ }
57555
+ });
57556
+ }
57557
+ /**
57558
+ * Process JSON-RPC request
57559
+ */
57560
+ async processRequest(request) {
57561
+ const { jsonrpc, method, params, id } = request;
57562
+ try {
57563
+ let result;
57564
+ switch (method) {
57565
+ case "tools/list":
57566
+ result = await this.handleListTools();
57567
+ break;
57568
+ case "tools/call":
57569
+ result = await this.handleCallTool(params);
57570
+ break;
57571
+ default:
57572
+ return {
57573
+ jsonrpc: "2.0",
57574
+ error: {
57575
+ code: -32601,
57576
+ message: "Method not found"
57577
+ },
57578
+ id
57579
+ };
57580
+ }
57581
+ return {
57582
+ jsonrpc: "2.0",
57583
+ result,
57584
+ id
57585
+ };
57586
+ } catch (error) {
57587
+ return {
57588
+ jsonrpc: "2.0",
57589
+ error: {
57590
+ code: -32603,
57591
+ message: "Internal error",
57592
+ data: error.message
57593
+ },
57594
+ id
57595
+ };
57596
+ }
57597
+ }
57598
+ /**
57599
+ * Register MCP protocol handlers
57600
+ */
57601
+ registerHandlers() {
57602
+ this.mcpServer.setRequestHandler(ListToolsRequestSchema, async () => {
57603
+ return this.handleListTools();
57604
+ });
57605
+ this.mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
57606
+ return this.handleCallTool(request.params);
57607
+ });
57608
+ }
57609
+ /**
57610
+ * Handle list tools request
57611
+ */
57612
+ async handleListTools() {
57613
+ const tools2 = [];
57614
+ if (this.agent && this.agent.allowedTools) {
57615
+ const toolDefs = {
57616
+ search: {
57617
+ description: "Search for code patterns using semantic search",
57618
+ inputSchema: {
57619
+ type: "object",
57620
+ properties: {
57621
+ query: { type: "string", description: "Search query" },
57622
+ path: { type: "string", description: "Directory to search", default: "." },
57623
+ maxResults: { type: "integer", default: 10 }
57624
+ },
57625
+ required: ["query"]
57626
+ }
57627
+ },
57628
+ extract: {
57629
+ description: "Extract code from specific file location",
57630
+ inputSchema: {
57631
+ type: "object",
57632
+ properties: {
57633
+ path: { type: "string", description: "File path with optional line number" }
57634
+ },
57635
+ required: ["path"]
57636
+ }
57637
+ },
57638
+ listFiles: {
57639
+ description: "List files in a directory",
57640
+ inputSchema: {
57641
+ type: "object",
57642
+ properties: {
57643
+ path: { type: "string", description: "Directory path" },
57644
+ pattern: { type: "string", description: "File pattern" }
57645
+ },
57646
+ required: ["path"]
57647
+ }
57648
+ },
57649
+ searchFiles: {
57650
+ description: "Search for files by name pattern",
57651
+ inputSchema: {
57652
+ type: "object",
57653
+ properties: {
57654
+ pattern: { type: "string", description: "File name pattern" },
57655
+ path: { type: "string", description: "Directory to search" }
57656
+ },
57657
+ required: ["pattern"]
57658
+ }
57659
+ },
57660
+ query: {
57661
+ description: "Query code using AST patterns",
57662
+ inputSchema: {
57663
+ type: "object",
57664
+ properties: {
57665
+ query: { type: "string", description: "AST query" },
57666
+ path: { type: "string", description: "Directory to search" }
57667
+ },
57668
+ required: ["query"]
57669
+ }
57670
+ }
57671
+ };
57672
+ for (const [name, def] of Object.entries(toolDefs)) {
57673
+ if (this.agent.allowedTools.isEnabled(name)) {
57674
+ tools2.push({
57675
+ name: `mcp__probe__${name}`,
57676
+ description: def.description,
57677
+ inputSchema: def.inputSchema
57678
+ });
57679
+ }
57680
+ }
57681
+ }
57682
+ return { tools: tools2 };
57683
+ }
57684
+ /**
57685
+ * Handle tool execution
57686
+ */
57687
+ async handleCallTool(params) {
57688
+ const { name, arguments: args } = params;
57689
+ const toolName = name.replace("mcp__probe__", "");
57690
+ if (!this.agent.allowedTools.isEnabled(toolName)) {
57691
+ throw new Error(`Tool ${name} is not enabled`);
57692
+ }
57693
+ const tool4 = this.agent.toolImplementations[toolName];
57694
+ if (!tool4) {
57695
+ throw new Error(`Tool ${name} not found`);
57696
+ }
57697
+ try {
57698
+ const result = await tool4.execute(args);
57699
+ return {
57700
+ content: [{
57701
+ type: "text",
57702
+ text: typeof result === "string" ? result : JSON.stringify(result, null, 2)
57703
+ }]
57704
+ };
57705
+ } catch (error) {
57706
+ return {
57707
+ content: [{
57708
+ type: "text",
57709
+ text: `Error executing ${name}: ${error.message}`
57710
+ }],
57711
+ isError: true
57712
+ };
57713
+ }
57714
+ }
57715
+ /**
57716
+ * Get the number of available tools
57717
+ */
57718
+ getToolCount() {
57719
+ if (!this.agent || !this.agent.allowedTools) {
57720
+ return 0;
57721
+ }
57722
+ const tools2 = ["search", "extract", "listFiles", "searchFiles", "query"];
57723
+ return tools2.filter((name) => this.agent.allowedTools.isEnabled(name)).length;
57724
+ }
57725
+ /**
57726
+ * Broadcast message to all SSE connections
57727
+ */
57728
+ broadcast(event, data) {
57729
+ const message = `event: ${event}
57730
+ data: ${JSON.stringify(data)}
57731
+
57732
+ `;
57733
+ for (const connection of this.connections) {
57734
+ connection.write(message);
57735
+ }
57736
+ }
57737
+ /**
57738
+ * Stop the server
57739
+ */
57740
+ async stop() {
57741
+ for (const connection of this.connections) {
57742
+ connection.end();
57743
+ }
57744
+ this.connections.clear();
57745
+ if (this.httpServer) {
57746
+ return new Promise((resolve6) => {
57747
+ this.httpServer.close(() => {
57748
+ if (this.debug) {
57749
+ console.log("[MCP] Built-in server stopped");
57750
+ }
57751
+ resolve6();
57752
+ });
57753
+ });
57754
+ }
57755
+ }
57756
+ /**
57757
+ * Get server configuration for MCP clients
57758
+ */
57759
+ getConfig() {
57760
+ return {
57761
+ transport: "http",
57762
+ url: `http://${this.host}:${this.port}/mcp`
57763
+ // Alternative transports:
57764
+ // sse: `http://${this.host}:${this.port}/sse`,
57765
+ // rpc: `http://${this.host}:${this.port}/rpc`
57766
+ };
57767
+ }
57768
+ };
57769
+ }
57770
+ });
57771
+
57772
+ // src/agent/engines/enhanced-claude-code.js
57773
+ var enhanced_claude_code_exports = {};
57774
+ __export(enhanced_claude_code_exports, {
57775
+ createEnhancedClaudeCLIEngine: () => createEnhancedClaudeCLIEngine
57776
+ });
57777
+ import { spawn as spawn3 } from "child_process";
57778
+ import { randomBytes } from "crypto";
57779
+ import fs7 from "fs/promises";
57780
+ import path7 from "path";
57781
+ import os3 from "os";
57782
+ import { EventEmitter as EventEmitter4 } from "events";
57783
+ async function createEnhancedClaudeCLIEngine(options = {}) {
57784
+ const { agent, systemPrompt, customPrompt, debug, sessionId, allowedTools } = options;
57785
+ const session = new ClaudeSession(
57786
+ sessionId || randomBytes(8).toString("hex"),
57787
+ debug
57788
+ );
57789
+ let mcpServer = null;
57790
+ let mcpConfigPath = null;
57791
+ if (agent) {
57792
+ mcpServer = new BuiltInMCPServer(agent, {
57793
+ port: 0,
57794
+ // Ephemeral port
57795
+ host: "127.0.0.1",
57796
+ debug
57797
+ });
57798
+ const { host, port } = await mcpServer.start();
57799
+ if (debug) {
57800
+ console.log("[DEBUG] Built-in MCP server started");
57801
+ console.log("[DEBUG] MCP URL:", `http://${host}:${port}/mcp`);
57802
+ }
57803
+ mcpConfigPath = path7.join(os3.tmpdir(), `probe-mcp-${session.id}.json`);
57804
+ const mcpConfig = {
57805
+ mcpServers: {
57806
+ probe: {
57807
+ command: "node",
57808
+ args: [path7.join(process.cwd(), "mcp-probe-server.js")],
57809
+ env: {
57810
+ PROBE_WORKSPACE: process.cwd(),
57811
+ DEBUG: debug ? "true" : "false"
57812
+ }
57813
+ }
57814
+ }
57815
+ };
57816
+ await fs7.writeFile(mcpConfigPath, JSON.stringify(mcpConfig, null, 2));
57817
+ }
57818
+ if (debug) {
57819
+ console.log("[DEBUG] Enhanced Claude Code Engine");
57820
+ console.log("[DEBUG] Session:", session.id);
57821
+ console.log("[DEBUG] MCP Config:", mcpConfigPath);
57822
+ }
57823
+ const fullSystemPrompt = combinePrompts(systemPrompt, customPrompt, agent);
57824
+ return {
57825
+ sessionId: session.id,
57826
+ session,
57827
+ /**
57828
+ * Query Claude with advanced streaming
57829
+ */
57830
+ async *query(prompt, opts = {}) {
57831
+ const emitter = new EventEmitter4();
57832
+ let buffer = "";
57833
+ let processEnded = false;
57834
+ let currentToolCall = null;
57835
+ let isSchemaMode = false;
57836
+ if (opts.schema || prompt.includes("JSON schema") || prompt.includes("mermaid diagram")) {
57837
+ isSchemaMode = true;
57838
+ if (debug) {
57839
+ console.log("[DEBUG] Schema/validation mode - treating as black box");
57840
+ }
57841
+ }
57842
+ let finalPrompt = prompt;
57843
+ if (opts.schema && isSchemaMode) {
57844
+ finalPrompt = `${prompt}
57845
+
57846
+ Please provide your response in the following JSON format:
57847
+ ${opts.schema}`;
57848
+ }
57849
+ const args = buildClaudeArgs({
57850
+ systemPrompt: fullSystemPrompt,
57851
+ mcpConfigPath,
57852
+ session,
57853
+ debug,
57854
+ prompt: finalPrompt,
57855
+ // Use finalPrompt which may include schema
57856
+ allowedTools: allowedTools || opts.allowedTools
57857
+ // Support tool filtering
57858
+ });
57859
+ if (debug) {
57860
+ console.log("[DEBUG] Executing: claude", args.join(" "));
57861
+ }
57862
+ const shellCmd = `echo "" | claude ${args.map((arg) => {
57863
+ if (typeof arg !== "string") {
57864
+ throw new TypeError(`Invalid argument type: expected string, got ${typeof arg}`);
57865
+ }
57866
+ const escaped = arg.replace(/'/g, "'\\''");
57867
+ return `'${escaped}'`;
57868
+ }).join(" ")}`;
57869
+ if (debug) {
57870
+ console.log("[DEBUG] Shell command length:", shellCmd.length);
57871
+ if (shellCmd.length < 500) {
57872
+ console.log("[DEBUG] Shell command:", shellCmd);
57873
+ } else {
57874
+ console.log("[DEBUG] Shell command (truncated):", shellCmd.substring(0, 200) + "...");
57875
+ }
57876
+ }
57877
+ const toolCollector = [];
57878
+ const proc2 = spawn3("sh", ["-c", shellCmd], {
57879
+ env: { ...process.env, FORCE_COLOR: "0" },
57880
+ stdio: ["ignore", "pipe", "pipe"]
57881
+ // Ignore stdin since echo handles it
57882
+ });
57883
+ proc2.stdout.on("data", (data) => {
57884
+ buffer += data.toString();
57885
+ processJsonBuffer(buffer, emitter, session, debug, toolCollector);
57886
+ const lines = buffer.split("\n");
57887
+ buffer = lines[lines.length - 1] || "";
57888
+ });
57889
+ proc2.stderr.on("data", (data) => {
57890
+ const stderr = data.toString();
57891
+ if (debug) {
57892
+ console.error("[STDERR]", stderr);
57893
+ }
57894
+ if (stderr.includes("command not found")) {
57895
+ emitter.emit("error", new Error("Claude Code not found. Please install it first."));
57896
+ }
57897
+ });
57898
+ proc2.on("close", (code) => {
57899
+ processEnded = true;
57900
+ if (code !== 0 && debug) {
57901
+ console.log(`[DEBUG] Process exited with code ${code}`);
57902
+ }
57903
+ if (buffer.trim()) {
57904
+ processJsonBuffer(buffer, emitter, session, debug, toolCollector);
57905
+ }
57906
+ if (toolCollector.length > 0) {
57907
+ emitter.emit("toolBatch", {
57908
+ tools: toolCollector,
57909
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
57910
+ });
57911
+ if (debug) {
57912
+ console.log(`[DEBUG] Emitting batch of ${toolCollector.length} tool events`);
57913
+ }
57914
+ }
57915
+ emitter.emit("end");
57916
+ });
57917
+ proc2.on("error", (error) => {
57918
+ emitter.emit("error", error);
57919
+ });
57920
+ const messageQueue = [];
57921
+ let resolver = null;
57922
+ emitter.on("message", (msg) => {
57923
+ messageQueue.push(msg);
57924
+ if (resolver) {
57925
+ resolver();
57926
+ resolver = null;
57927
+ }
57928
+ });
57929
+ emitter.on("toolBatch", (batch) => {
57930
+ messageQueue.push({ type: "toolBatch", ...batch });
57931
+ if (resolver) {
57932
+ resolver();
57933
+ resolver = null;
57934
+ }
57935
+ });
57936
+ emitter.on("end", () => {
57937
+ processEnded = true;
57938
+ if (resolver) {
57939
+ resolver();
57940
+ resolver = null;
57941
+ }
57942
+ });
57943
+ emitter.on("error", (error) => {
57944
+ messageQueue.push({ type: "error", error });
57945
+ if (resolver) {
57946
+ resolver();
57947
+ resolver = null;
57948
+ }
57949
+ });
57950
+ while (!processEnded || messageQueue.length > 0) {
57951
+ if (messageQueue.length > 0) {
57952
+ const msg = messageQueue.shift();
57953
+ if (msg.type === "text") {
57954
+ yield { type: "text", content: msg.content };
57955
+ } else if (msg.type === "tool_use") {
57956
+ currentToolCall = msg;
57957
+ yield {
57958
+ type: "text",
57959
+ content: `
57960
+ \u{1F527} Using ${msg.name}: ${JSON.stringify(msg.input)}
57961
+ `
57962
+ };
57963
+ const result = await executeProbleTool(agent, msg.name, msg.input);
57964
+ yield { type: "text", content: `${result}
57965
+ ` };
57966
+ } else if (msg.type === "toolBatch") {
57967
+ yield { type: "toolBatch", tools: msg.tools, timestamp: msg.timestamp };
57968
+ } else if (msg.type === "session_update") {
57969
+ if (debug) {
57970
+ console.log("[DEBUG] Session updated:", msg.conversationId);
57971
+ }
57972
+ } else if (msg.type === "error") {
57973
+ yield { type: "error", error: msg.error };
57974
+ break;
57975
+ }
57976
+ } else if (!processEnded) {
57977
+ await new Promise((resolve6) => {
57978
+ resolver = resolve6;
57979
+ });
57980
+ }
57981
+ }
57982
+ session.incrementMessageCount();
57983
+ yield {
57984
+ type: "metadata",
57985
+ data: {
57986
+ sessionId: session.id,
57987
+ conversationId: session.conversationId,
57988
+ messageCount: session.messageCount
57989
+ }
57990
+ };
57991
+ },
57992
+ /**
57993
+ * Get session info
57994
+ */
57995
+ getSession() {
57996
+ return {
57997
+ id: session.id,
57998
+ conversationId: session.conversationId,
57999
+ messageCount: session.messageCount
58000
+ };
58001
+ },
58002
+ /**
58003
+ * Clean up - MUST be called to stop MCP server and clean resources
58004
+ */
58005
+ async close() {
58006
+ try {
58007
+ if (mcpServer) {
58008
+ await mcpServer.stop();
58009
+ if (debug) {
58010
+ console.log("[DEBUG] Built-in MCP server stopped");
58011
+ }
58012
+ }
58013
+ if (mcpConfigPath) {
58014
+ await fs7.unlink(mcpConfigPath).catch(() => {
58015
+ });
58016
+ if (debug) {
58017
+ console.log("[DEBUG] MCP config file removed");
58018
+ }
58019
+ }
58020
+ if (debug) {
58021
+ console.log("[DEBUG] Engine closed, session:", session.id);
58022
+ }
58023
+ } catch (error) {
58024
+ if (debug) {
58025
+ console.error("[DEBUG] Error during cleanup:", error.message);
58026
+ }
58027
+ }
58028
+ }
58029
+ };
58030
+ }
58031
+ function processJsonBuffer(buffer, emitter, session, debug, toolCollector = null) {
58032
+ const lines = buffer.split("\n");
58033
+ for (const line of lines) {
58034
+ if (!line.trim()) continue;
58035
+ try {
58036
+ const parsed = JSON.parse(line);
58037
+ const messages = Array.isArray(parsed) ? parsed : [parsed];
58038
+ for (const msg of messages) {
58039
+ switch (msg.type) {
58040
+ case "result":
58041
+ if (msg.result) {
58042
+ emitter.emit("message", { type: "text", content: msg.result });
58043
+ }
58044
+ if (msg.session_id) {
58045
+ session.setConversationId(msg.session_id);
58046
+ emitter.emit("message", { type: "session_update", conversationId: msg.session_id });
58047
+ }
58048
+ break;
58049
+ case "conversation":
58050
+ session.setConversationId(msg.id);
58051
+ emitter.emit("message", { type: "session_update", conversationId: msg.id });
58052
+ break;
58053
+ case "text":
58054
+ if (msg.text) {
58055
+ emitter.emit("message", { type: "text", content: msg.text });
58056
+ }
58057
+ break;
58058
+ case "assistant":
58059
+ if (msg.message && msg.message.content) {
58060
+ for (const content of msg.message.content) {
58061
+ if (content.type === "text" && content.text) {
58062
+ emitter.emit("message", { type: "text", content: content.text });
58063
+ } else if (content.type === "tool_use") {
58064
+ if (toolCollector) {
58065
+ toolCollector.push({
58066
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
58067
+ name: content.name,
58068
+ args: content.input || {},
58069
+ id: content.id,
58070
+ status: "started"
58071
+ });
58072
+ }
58073
+ if (debug) {
58074
+ console.log("[DEBUG] Assistant internal tool use:", content.name);
58075
+ }
58076
+ }
58077
+ }
58078
+ }
58079
+ break;
58080
+ case "tool_use":
58081
+ if (toolCollector) {
58082
+ toolCollector.push({
58083
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
58084
+ name: msg.name,
58085
+ args: msg.input || {},
58086
+ id: msg.id,
58087
+ status: "started"
58088
+ });
58089
+ }
58090
+ emitter.emit("message", {
58091
+ type: "tool_use",
58092
+ id: msg.id,
58093
+ name: msg.name,
58094
+ input: msg.input
58095
+ });
58096
+ break;
58097
+ case "tool_result":
58098
+ if (toolCollector && msg.tool_use_id) {
58099
+ const toolCall = toolCollector.find((t) => t.id === msg.tool_use_id);
58100
+ if (toolCall) {
58101
+ toolCall.status = "completed";
58102
+ toolCall.resultPreview = msg.content ? (typeof msg.content === "string" ? msg.content.substring(0, 200) : JSON.stringify(msg.content).substring(0, 200)) + "..." : "No Result";
58103
+ }
58104
+ }
58105
+ if (debug) {
58106
+ console.log("[DEBUG] Tool result:", msg);
58107
+ }
58108
+ break;
58109
+ case "error":
58110
+ emitter.emit("error", new Error(msg.message || "Unknown error"));
58111
+ break;
58112
+ default:
58113
+ if (debug) {
58114
+ console.log("[DEBUG] Unknown message type:", msg.type);
58115
+ console.log("[DEBUG] Full message:", JSON.stringify(msg).substring(0, 200));
58116
+ }
58117
+ }
58118
+ }
58119
+ } catch (e) {
58120
+ if (debug && line.trim()) {
58121
+ console.log("[DEBUG] Non-JSON output:", line);
58122
+ }
58123
+ }
58124
+ }
58125
+ }
58126
+ function buildClaudeArgs({ systemPrompt, mcpConfigPath, session, debug, prompt, allowedTools }) {
58127
+ const args = [
58128
+ "-p",
58129
+ // Short form of --print
58130
+ prompt,
58131
+ // The prompt text goes right after -p
58132
+ "--output-format",
58133
+ "json"
58134
+ ];
58135
+ const resumeArgs = session.getResumeArgs();
58136
+ if (resumeArgs.length > 0) {
58137
+ args.push(...resumeArgs);
58138
+ }
58139
+ if (systemPrompt) {
58140
+ args.push("--system-prompt", systemPrompt);
58141
+ }
58142
+ args.push("--mcp-config", mcpConfigPath);
58143
+ if (allowedTools && Array.isArray(allowedTools) && allowedTools.length > 0) {
58144
+ const mcpTools = allowedTools.map(
58145
+ (tool4) => tool4.startsWith("mcp__") ? tool4 : `mcp__probe__${tool4}`
58146
+ ).join(",");
58147
+ args.push("--allowedTools", mcpTools);
58148
+ } else {
58149
+ args.push("--allowedTools", "mcp__probe__*");
58150
+ }
58151
+ if (debug) {
58152
+ args.push("--verbose");
58153
+ }
58154
+ return args;
58155
+ }
58156
+ async function executeProbleTool(agent, toolName, params) {
58157
+ if (!agent || !agent.toolImplementations) {
58158
+ return "Tool execution not available";
58159
+ }
58160
+ const name = toolName.replace(/^mcp__probe__/, "");
58161
+ const tool4 = agent.toolImplementations[name];
58162
+ if (!tool4) {
58163
+ return `Unknown tool: ${name}`;
58164
+ }
58165
+ try {
58166
+ const result = await tool4.execute(params);
58167
+ return typeof result === "string" ? result : JSON.stringify(result, null, 2);
58168
+ } catch (error) {
58169
+ return `Tool error: ${error.message}`;
58170
+ }
58171
+ }
58172
+ function combinePrompts(systemPrompt, customPrompt, agent) {
58173
+ if (!systemPrompt && customPrompt) {
58174
+ return customPrompt;
58175
+ }
58176
+ if (systemPrompt && customPrompt) {
58177
+ return systemPrompt + "\n\n## Additional Instructions\n" + customPrompt;
58178
+ }
58179
+ return systemPrompt || "";
58180
+ }
58181
+ var ClaudeSession;
58182
+ var init_enhanced_claude_code = __esm({
58183
+ "src/agent/engines/enhanced-claude-code.js"() {
58184
+ "use strict";
58185
+ init_built_in_server();
58186
+ ClaudeSession = class {
58187
+ constructor(id, debug = false) {
58188
+ this.id = id;
58189
+ this.conversationId = null;
58190
+ this.messageCount = 0;
58191
+ this.debug = debug;
58192
+ }
58193
+ /**
58194
+ * Update session with Claude's conversation ID
58195
+ */
58196
+ setConversationId(convId) {
58197
+ this.conversationId = convId;
58198
+ if (this.debug) {
58199
+ console.log(`[Session ${this.id}] Conversation ID: ${convId}`);
58200
+ }
58201
+ }
58202
+ /**
58203
+ * Get resume arguments for continuing conversation
58204
+ */
58205
+ getResumeArgs() {
58206
+ if (this.conversationId && this.messageCount > 0) {
58207
+ return ["--resume", this.conversationId];
58208
+ }
58209
+ return [];
58210
+ }
58211
+ incrementMessageCount() {
58212
+ this.messageCount++;
58213
+ }
58214
+ };
58215
+ }
58216
+ });
58217
+
58218
+ // src/agent/engines/enhanced-vercel.js
58219
+ var enhanced_vercel_exports = {};
58220
+ __export(enhanced_vercel_exports, {
58221
+ createEnhancedVercelEngine: () => createEnhancedVercelEngine
58222
+ });
58223
+ import { streamText } from "ai";
58224
+ function createEnhancedVercelEngine(agent) {
58225
+ return {
58226
+ /**
58227
+ * Query the model using existing Vercel AI SDK implementation
58228
+ * @param {string} prompt - The prompt to send
58229
+ * @param {Object} options - Additional options
58230
+ * @returns {AsyncIterable} Response stream
58231
+ */
58232
+ async *query(prompt, options = {}) {
58233
+ const systemMessage = await agent.getSystemMessage();
58234
+ const messages = [
58235
+ { role: "system", content: systemMessage },
58236
+ ...agent.history,
58237
+ { role: "user", content: prompt }
58238
+ ];
58239
+ const result = await agent.streamTextWithRetryAndFallback({
58240
+ model: agent.provider(agent.model),
58241
+ messages,
58242
+ maxTokens: options.maxTokens || agent.maxResponseTokens,
58243
+ temperature: options.temperature || 0.3,
58244
+ // Note: Vercel AI SDK doesn't use structured tools for XML format
58245
+ // The tools are embedded in the system prompt
58246
+ experimental_telemetry: options.telemetry
58247
+ });
58248
+ let fullContent = "";
58249
+ for await (const chunk of result.textStream) {
58250
+ fullContent += chunk;
58251
+ yield { type: "text", content: chunk };
58252
+ }
58253
+ const toolCalls = agent.parseXmlToolCalls ? agent.parseXmlToolCalls(fullContent) : null;
58254
+ if (toolCalls && toolCalls.length > 0) {
58255
+ yield { type: "tool_calls", toolCalls };
58256
+ }
58257
+ if (result.finishReason) {
58258
+ yield { type: "finish", reason: result.finishReason };
58259
+ }
58260
+ },
58261
+ /**
58262
+ * Get available tools for this engine
58263
+ */
58264
+ getTools() {
58265
+ return agent.toolImplementations || {};
58266
+ },
58267
+ /**
58268
+ * Get system prompt for this engine
58269
+ */
58270
+ async getSystemPrompt() {
58271
+ return agent.getSystemMessage();
58272
+ },
58273
+ /**
58274
+ * Optional cleanup
58275
+ */
58276
+ async close() {
58277
+ }
58278
+ };
58279
+ }
58280
+ var init_enhanced_vercel = __esm({
58281
+ "src/agent/engines/enhanced-vercel.js"() {
58282
+ "use strict";
58283
+ }
58284
+ });
58285
+
57383
58286
  // src/agent/ProbeAgent.js
57384
58287
  var ProbeAgent_exports = {};
57385
58288
  __export(ProbeAgent_exports, {
@@ -57390,9 +58293,9 @@ import { createAnthropic as createAnthropic2 } from "@ai-sdk/anthropic";
57390
58293
  import { createOpenAI as createOpenAI2 } from "@ai-sdk/openai";
57391
58294
  import { createGoogleGenerativeAI as createGoogleGenerativeAI2 } from "@ai-sdk/google";
57392
58295
  import { createAmazonBedrock as createAmazonBedrock2 } from "@ai-sdk/amazon-bedrock";
57393
- import { streamText } from "ai";
58296
+ import { streamText as streamText2 } from "ai";
57394
58297
  import { randomUUID as randomUUID4 } from "crypto";
57395
- import { EventEmitter as EventEmitter3 } from "events";
58298
+ import { EventEmitter as EventEmitter5 } from "events";
57396
58299
  import { existsSync as existsSync5 } from "fs";
57397
58300
  import { readFile, stat } from "fs/promises";
57398
58301
  import { resolve as resolve4, isAbsolute as isAbsolute2, dirname as dirname4 } from "path";
@@ -57517,7 +58420,7 @@ var init_ProbeAgent = __esm({
57517
58420
  this.history = [];
57518
58421
  this.pendingImages = /* @__PURE__ */ new Map();
57519
58422
  this.currentImages = [];
57520
- this.events = new EventEmitter3();
58423
+ this.events = new EventEmitter5();
57521
58424
  this.enableMcp = !!options.enableMcp || process.env.ENABLE_MCP === "1";
57522
58425
  this.mcpConfigPath = options.mcpConfigPath || null;
57523
58426
  this.mcpConfig = options.mcpConfig || null;
@@ -57528,6 +58431,7 @@ var init_ProbeAgent = __esm({
57528
58431
  this.retryManager = null;
57529
58432
  this.fallbackConfig = options.fallback || null;
57530
58433
  this.fallbackManager = null;
58434
+ this.engine = null;
57531
58435
  this.initializeModel();
57532
58436
  }
57533
58437
  /**
@@ -57590,6 +58494,23 @@ var init_ProbeAgent = __esm({
57590
58494
  * This method initializes MCP and merges MCP tools into the tool list, and loads history from storage
57591
58495
  */
57592
58496
  async initialize() {
58497
+ if (!this.provider && !this.clientApiProvider && this.apiType !== "claude-code") {
58498
+ if (this.apiType === "uninitialized") {
58499
+ const claudeAvailable = await this.isClaudeCommandAvailable();
58500
+ if (claudeAvailable) {
58501
+ if (this.debug) {
58502
+ console.log("[DEBUG] No API keys found, but claude command detected");
58503
+ console.log("[DEBUG] Auto-switching to claude-code provider");
58504
+ }
58505
+ this.clientApiProvider = "claude-code";
58506
+ this.provider = null;
58507
+ this.model = this.clientApiModel || "claude-3-5-sonnet-20241022";
58508
+ this.apiType = "claude-code";
58509
+ } else {
58510
+ throw new Error("No API key provided and claude command not found. Please either:\n1. Set an API key: ANTHROPIC_API_KEY, OPENAI_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY, or AWS credentials\n2. Install claude command from https://docs.claude.com/en/docs/claude-code");
58511
+ }
58512
+ }
58513
+ }
57593
58514
  try {
57594
58515
  const history = await this.storageAdapter.loadHistory(this.sessionId);
57595
58516
  this.history = history;
@@ -57706,6 +58627,20 @@ var init_ProbeAgent = __esm({
57706
58627
  console.error("[DEBUG] ========================================\n");
57707
58628
  }
57708
58629
  }
58630
+ /**
58631
+ * Check if claude command is available on the system
58632
+ * @returns {Promise<boolean>} True if claude command is available
58633
+ * @private
58634
+ */
58635
+ async isClaudeCommandAvailable() {
58636
+ try {
58637
+ const { execSync } = await import("child_process");
58638
+ execSync("claude --version", { stdio: "ignore" });
58639
+ return true;
58640
+ } catch (error) {
58641
+ return false;
58642
+ }
58643
+ }
57709
58644
  /**
57710
58645
  * Initialize the AI model based on available API keys and forced provider setting
57711
58646
  */
@@ -57715,6 +58650,15 @@ var init_ProbeAgent = __esm({
57715
58650
  this.initializeMockModel(modelName);
57716
58651
  return;
57717
58652
  }
58653
+ if (this.clientApiProvider === "claude-code" || process.env.USE_CLAUDE_CODE === "true") {
58654
+ this.provider = null;
58655
+ this.model = modelName || "claude-3-5-sonnet-20241022";
58656
+ this.apiType = "claude-code";
58657
+ if (this.debug) {
58658
+ console.log("[DEBUG] Claude Code engine selected - will use built-in access if available");
58659
+ }
58660
+ return;
58661
+ }
57718
58662
  const anthropicApiKey = process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN;
57719
58663
  const openaiApiKey = process.env.OPENAI_API_KEY;
57720
58664
  const googleApiKey = process.env.GOOGLE_GENERATIVE_AI_API_KEY || process.env.GOOGLE_API_KEY;
@@ -57772,7 +58716,10 @@ var init_ProbeAgent = __esm({
57772
58716
  this.initializeBedrockModel(awsAccessKeyId, awsSecretAccessKey, awsRegion, awsSessionToken, awsApiKey, awsBedrockBaseUrl, modelName);
57773
58717
  this.initializeFallbackManager("bedrock", modelName);
57774
58718
  } else {
57775
- throw new Error("No API key provided. Please set ANTHROPIC_API_KEY (or ANTHROPIC_AUTH_TOKEN), OPENAI_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY), AWS credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION), or AWS_BEDROCK_API_KEY environment variables.");
58719
+ this.apiType = "uninitialized";
58720
+ if (this.debug) {
58721
+ console.log("[DEBUG] No API keys found - will check for claude command in initialize()");
58722
+ }
57776
58723
  }
57777
58724
  }
57778
58725
  /**
@@ -57835,6 +58782,44 @@ var init_ProbeAgent = __esm({
57835
58782
  * @private
57836
58783
  */
57837
58784
  async streamTextWithRetryAndFallback(options) {
58785
+ if (this.clientApiProvider === "claude-code" || process.env.USE_CLAUDE_CODE === "true") {
58786
+ try {
58787
+ const engine = await this.getEngine();
58788
+ if (engine && engine.query) {
58789
+ const userMessages = options.messages.filter(
58790
+ (m) => m.role === "user" && !m.content.includes("WARNING: You have reached the maximum tool iterations limit")
58791
+ );
58792
+ const lastUserMessage = userMessages[userMessages.length - 1];
58793
+ const prompt = lastUserMessage ? lastUserMessage.content : "";
58794
+ const engineOptions = {
58795
+ maxTokens: options.maxTokens,
58796
+ temperature: options.temperature,
58797
+ messages: options.messages,
58798
+ systemPrompt: options.messages.find((m) => m.role === "system")?.content
58799
+ };
58800
+ const engineStream = engine.query(prompt, engineOptions);
58801
+ async function* createTextStream() {
58802
+ for await (const message of engineStream) {
58803
+ if (message.type === "text" && message.content) {
58804
+ yield message.content;
58805
+ } else if (typeof message === "string") {
58806
+ yield message;
58807
+ }
58808
+ }
58809
+ }
58810
+ return {
58811
+ textStream: createTextStream(),
58812
+ usage: Promise.resolve({})
58813
+ // Engine should handle its own usage tracking
58814
+ // Add other streamText-compatible properties as needed
58815
+ };
58816
+ }
58817
+ } catch (error) {
58818
+ if (this.debug) {
58819
+ console.log(`[DEBUG] Failed to use Claude Code engine, falling back to Vercel:`, error.message);
58820
+ }
58821
+ }
58822
+ }
57838
58823
  if (!this.retryManager) {
57839
58824
  this.retryManager = new RetryManager({
57840
58825
  maxRetries: this.retryConfig.maxRetries ?? 3,
@@ -57847,7 +58832,7 @@ var init_ProbeAgent = __esm({
57847
58832
  }
57848
58833
  if (!this.fallbackManager) {
57849
58834
  return await this.retryManager.executeWithRetry(
57850
- () => streamText(options),
58835
+ () => streamText2(options),
57851
58836
  {
57852
58837
  provider: this.apiType,
57853
58838
  model: this.model
@@ -57869,7 +58854,7 @@ var init_ProbeAgent = __esm({
57869
58854
  debug: this.debug
57870
58855
  });
57871
58856
  return await providerRetryManager.executeWithRetry(
57872
- () => streamText(fallbackOptions),
58857
+ () => streamText2(fallbackOptions),
57873
58858
  {
57874
58859
  provider: config.provider,
57875
58860
  model
@@ -57951,6 +58936,49 @@ var init_ProbeAgent = __esm({
57951
58936
  console.log(`Using AWS Bedrock API with model: ${this.model}${regionInfo} [Auth: ${authMethod}]${baseUrlInfo}`);
57952
58937
  }
57953
58938
  }
58939
+ /**
58940
+ * Get or create the AI engine based on configuration
58941
+ * @returns {Promise<Object>} Engine interface
58942
+ * @private
58943
+ */
58944
+ async getEngine() {
58945
+ if (this.engine) {
58946
+ return this.engine;
58947
+ }
58948
+ if (this.clientApiProvider === "claude-code" || process.env.USE_CLAUDE_CODE === "true") {
58949
+ try {
58950
+ const { createEnhancedClaudeCLIEngine: createEnhancedClaudeCLIEngine2 } = await Promise.resolve().then(() => (init_enhanced_claude_code(), enhanced_claude_code_exports));
58951
+ const systemPrompt = this.customPrompt || this.getClaudeNativeSystemPrompt();
58952
+ this.engine = await createEnhancedClaudeCLIEngine2({
58953
+ agent: this,
58954
+ // Pass reference to ProbeAgent for tool access
58955
+ systemPrompt,
58956
+ customPrompt: this.customPrompt,
58957
+ sessionId: this.options?.sessionId,
58958
+ debug: this.debug,
58959
+ allowedTools: this.allowedTools
58960
+ // Pass tool filtering configuration
58961
+ });
58962
+ if (this.debug) {
58963
+ console.log("[DEBUG] Using Claude Code engine with Probe tools");
58964
+ if (this.customPrompt) {
58965
+ console.log("[DEBUG] Using custom prompt/persona");
58966
+ }
58967
+ }
58968
+ return this.engine;
58969
+ } catch (error) {
58970
+ console.warn("[WARNING] Failed to load Claude Code engine:", error.message);
58971
+ console.warn("[WARNING] Falling back to Vercel AI SDK");
58972
+ this.clientApiProvider = null;
58973
+ }
58974
+ }
58975
+ const { createEnhancedVercelEngine: createEnhancedVercelEngine2 } = await Promise.resolve().then(() => (init_enhanced_vercel(), enhanced_vercel_exports));
58976
+ this.engine = createEnhancedVercelEngine2(this);
58977
+ if (this.debug) {
58978
+ console.log("[DEBUG] Using Vercel AI SDK engine");
58979
+ }
58980
+ return this.engine;
58981
+ }
57954
58982
  /**
57955
58983
  * Process assistant response content and detect/load image references
57956
58984
  * @param {string} content - The assistant's response content
@@ -58237,6 +59265,55 @@ var init_ProbeAgent = __esm({
58237
59265
  this.mcpBridge = null;
58238
59266
  }
58239
59267
  }
59268
+ /**
59269
+ * Get system prompt for Claude native engines (CLI/SDK) without XML formatting
59270
+ * These engines have native MCP support and don't need XML instructions
59271
+ */
59272
+ getClaudeNativeSystemPrompt() {
59273
+ let systemPrompt = "";
59274
+ if (this.predefinedPrompt) {
59275
+ const personaPrompt = getPromptByType(this.predefinedPrompt);
59276
+ if (personaPrompt?.system) {
59277
+ systemPrompt += personaPrompt.system + "\n\n";
59278
+ }
59279
+ }
59280
+ systemPrompt += `You have access to powerful code search and analysis tools through MCP:
59281
+ - search: Find code patterns using semantic search
59282
+ - extract: Extract specific code sections with context
59283
+ - query: Use AST patterns for structural code matching
59284
+ - listFiles: Browse directory contents
59285
+ - searchFiles: Find files by name patterns`;
59286
+ if (this.enableBash) {
59287
+ systemPrompt += `
59288
+ - bash: Execute bash commands for system operations`;
59289
+ }
59290
+ systemPrompt += `
59291
+
59292
+ When exploring code:
59293
+ 1. Start with search to find relevant code patterns
59294
+ 2. Use extract to get detailed context when needed
59295
+ 3. Prefer focused, specific searches over broad queries
59296
+ 4. Combine multiple tools to build complete understanding`;
59297
+ if (this.allowedFolders && this.allowedFolders.length > 0) {
59298
+ systemPrompt += `
59299
+
59300
+ Workspace: ${this.allowedFolders.join(", ")}`;
59301
+ }
59302
+ if (this.fileList) {
59303
+ systemPrompt += `
59304
+
59305
+ # Repository Structure
59306
+ `;
59307
+ systemPrompt += `You are working with a repository located at: ${this.allowedFolders[0]}
59308
+
59309
+ `;
59310
+ systemPrompt += `Here's an overview of the repository structure (showing up to 100 most relevant files):
59311
+
59312
+ `;
59313
+ systemPrompt += "```\n" + this.fileList + "\n```\n";
59314
+ }
59315
+ return systemPrompt;
59316
+ }
58240
59317
  /**
58241
59318
  * Get the system message with instructions for the AI (XML Tool Format)
58242
59319
  */
@@ -58597,6 +59674,59 @@ You are working with a repository located at: ${searchDirectory}
58597
59674
  let finalResult = "I was unable to complete your request due to reaching the maximum number of tool iterations.";
58598
59675
  const baseMaxIterations = this.maxIterations || MAX_TOOL_ITERATIONS;
58599
59676
  const maxIterations = options.schema ? baseMaxIterations + 4 : baseMaxIterations;
59677
+ const isClaudeCode = this.clientApiProvider === "claude-code" || process.env.USE_CLAUDE_CODE === "true";
59678
+ if (isClaudeCode) {
59679
+ if (this.debug) {
59680
+ console.log(`[DEBUG] Using Claude Code engine - bypassing tool loop (black box mode)`);
59681
+ console.log(`[DEBUG] Sending question directly to Claude Code: ${message.substring(0, 100)}...`);
59682
+ }
59683
+ try {
59684
+ const engine = await this.getEngine();
59685
+ if (engine && engine.query) {
59686
+ let assistantResponseContent = "";
59687
+ let toolBatch = null;
59688
+ for await (const chunk of engine.query(message, options)) {
59689
+ if (chunk.type === "text" && chunk.content) {
59690
+ assistantResponseContent += chunk.content;
59691
+ if (options.onStream) {
59692
+ options.onStream(chunk.content);
59693
+ }
59694
+ } else if (chunk.type === "toolBatch" && chunk.tools) {
59695
+ toolBatch = chunk.tools;
59696
+ if (this.debug) {
59697
+ console.log(`[DEBUG] Received batch of ${chunk.tools.length} tool events from Claude Code`);
59698
+ }
59699
+ } else if (chunk.type === "error") {
59700
+ throw chunk.error;
59701
+ }
59702
+ }
59703
+ if (toolBatch && toolBatch.length > 0 && this.events) {
59704
+ if (this.debug) {
59705
+ console.log(`[DEBUG] Emitting ${toolBatch.length} tool events from Claude Code batch`);
59706
+ }
59707
+ for (const toolEvent of toolBatch) {
59708
+ this.events.emit("toolCall", toolEvent);
59709
+ }
59710
+ }
59711
+ this.history.push(userMessage);
59712
+ this.history.push({
59713
+ role: "assistant",
59714
+ content: assistantResponseContent
59715
+ });
59716
+ await this.hooks.emit(HOOK_TYPES.COMPLETION, {
59717
+ sessionId: this.sessionId,
59718
+ prompt: message,
59719
+ response: assistantResponseContent
59720
+ });
59721
+ return assistantResponseContent;
59722
+ }
59723
+ } catch (error) {
59724
+ if (this.debug) {
59725
+ console.error("[DEBUG] Claude Code error:", error);
59726
+ }
59727
+ throw error;
59728
+ }
59729
+ }
58600
59730
  if (this.debug) {
58601
59731
  console.log(`[DEBUG] Starting agentic flow for question: ${message.substring(0, 100)}...`);
58602
59732
  if (options.schema) {
@@ -58655,7 +59785,7 @@ You are working with a repository located at: ${searchDirectory}
58655
59785
  const executeAIRequest = async () => {
58656
59786
  const messagesForAI = this.prepareMessagesWithImages(currentMessages);
58657
59787
  const result = await this.streamTextWithRetryAndFallback({
58658
- model: this.provider(this.model),
59788
+ model: this.provider ? this.provider(this.model) : this.model,
58659
59789
  messages: messagesForAI,
58660
59790
  maxTokens: maxResponseTokens,
58661
59791
  temperature: 0.3
@@ -59686,10 +60816,10 @@ import dotenv3 from "dotenv";
59686
60816
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
59687
60817
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
59688
60818
  import {
59689
- CallToolRequestSchema,
60819
+ CallToolRequestSchema as CallToolRequestSchema2,
59690
60820
  ErrorCode as ErrorCode2,
59691
60821
  InitializeRequestSchema,
59692
- ListToolsRequestSchema,
60822
+ ListToolsRequestSchema as ListToolsRequestSchema2,
59693
60823
  McpError
59694
60824
  } from "@modelcontextprotocol/sdk/types.js";
59695
60825
  import { readFileSync as readFileSync2, existsSync as existsSync6 } from "fs";
@@ -59699,7 +60829,7 @@ import { resolve as resolve5 } from "path";
59699
60829
  import { randomUUID as randomUUID5 } from "crypto";
59700
60830
 
59701
60831
  // src/agent/acp/connection.js
59702
- import { EventEmitter as EventEmitter4 } from "events";
60832
+ import { EventEmitter as EventEmitter6 } from "events";
59703
60833
 
59704
60834
  // src/agent/acp/types.js
59705
60835
  var ACP_PROTOCOL_VERSION = "1";
@@ -59816,7 +60946,7 @@ function validateMessage(message) {
59816
60946
  }
59817
60947
 
59818
60948
  // src/agent/acp/connection.js
59819
- var ACPConnection = class extends EventEmitter4 {
60949
+ var ACPConnection = class extends EventEmitter6 {
59820
60950
  constructor(inputStream = process.stdin, outputStream = process.stdout) {
59821
60951
  super();
59822
60952
  this.inputStream = inputStream;
@@ -60655,7 +61785,7 @@ var ProbeAgentMcpServer = class {
60655
61785
  }
60656
61786
  };
60657
61787
  });
60658
- this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
61788
+ this.server.setRequestHandler(ListToolsRequestSchema2, async () => ({
60659
61789
  tools: [
60660
61790
  {
60661
61791
  name: "search_code",
@@ -60690,7 +61820,7 @@ var ProbeAgentMcpServer = class {
60690
61820
  }
60691
61821
  ]
60692
61822
  }));
60693
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
61823
+ this.server.setRequestHandler(CallToolRequestSchema2, async (request) => {
60694
61824
  if (request.params.name !== "search_code") {
60695
61825
  throw new McpError(
60696
61826
  ErrorCode2.MethodNotFound,