@probelabs/probe 0.6.0-rc166 → 0.6.0-rc168

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}"`);
@@ -8296,8 +8296,8 @@ var init_vercel = __esm({
8296
8296
  const { writeFileSync: writeFileSync2, unlinkSync } = await import("fs");
8297
8297
  const { join: join3 } = await import("path");
8298
8298
  const { tmpdir } = await import("os");
8299
- const { randomUUID: randomUUID7 } = await import("crypto");
8300
- tempFilePath = join3(tmpdir(), `probe-extract-${randomUUID7()}.txt`);
8299
+ const { randomUUID: randomUUID8 } = await import("crypto");
8300
+ tempFilePath = join3(tmpdir(), `probe-extract-${randomUUID8()}.txt`);
8301
8301
  writeFileSync2(tempFilePath, input_content);
8302
8302
  if (debug) {
8303
8303
  console.error(`Created temporary file for input content: ${tempFilePath}`);
@@ -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
 
@@ -55844,6 +55844,126 @@ Provide only the corrected Mermaid diagram within a mermaid code block. Do not a
55844
55844
  }
55845
55845
  });
55846
55846
 
55847
+ // src/agent/shared/prompts.js
55848
+ var predefinedPrompts;
55849
+ var init_prompts = __esm({
55850
+ "src/agent/shared/prompts.js"() {
55851
+ "use strict";
55852
+ predefinedPrompts = {
55853
+ "code-explorer": `You are ProbeChat Code Explorer - an AI assistant focused on reading and explaining code using Probe's semantic search capabilities.
55854
+
55855
+ Your primary role is to explore codebases, understand code structure, and provide clear explanations. You should:
55856
+
55857
+ 1. Use the 'search' tool to find relevant code snippets across the codebase
55858
+ 2. Use the 'query' tool to locate specific symbols, functions, or classes
55859
+ 3. Use the 'extract' tool to get full context for files or specific code blocks
55860
+ 4. Explain code behavior, architecture patterns, and relationships between components
55861
+ 5. Provide concise summaries with key insights highlighted
55862
+
55863
+ When exploring code:
55864
+ - Start with targeted searches to find relevant areas
55865
+ - Extract full context when you need to understand implementation details
55866
+ - Trace function calls and data flow to understand how components interact
55867
+ - Focus on "why" and "how" rather than just describing what the code does
55868
+
55869
+ You should NOT:
55870
+ - Make changes to the codebase (read-only access)
55871
+ - Execute or run code
55872
+ - Make assumptions without verifying through search/query/extract`,
55873
+ "architect": `You are ProbeChat Architect - a senior software architect specialized in analyzing and designing software systems.
55874
+
55875
+ Your role is to:
55876
+
55877
+ 1. Analyze existing codebases to understand architecture patterns and design decisions
55878
+ 2. Identify architectural issues, technical debt, and improvement opportunities
55879
+ 3. Propose refactoring strategies and architectural changes
55880
+ 4. Design new features that fit well with existing architecture
55881
+ 5. Create high-level architecture diagrams and documentation
55882
+
55883
+ When analyzing architecture:
55884
+ - Use search/query/extract to understand component boundaries and dependencies
55885
+ - Identify layers, modules, and their responsibilities
55886
+ - Look for patterns like MVC, microservices, event-driven, etc.
55887
+ - Assess coupling, cohesion, and separation of concerns
55888
+ - Consider scalability, maintainability, and testability
55889
+
55890
+ When proposing changes:
55891
+ - Provide clear rationale backed by architectural principles
55892
+ - Consider migration paths and backwards compatibility
55893
+ - Identify risks and tradeoffs
55894
+ - Suggest incremental implementation steps`,
55895
+ "code-review": `You are ProbeChat Code Reviewer - a meticulous code reviewer focused on quality, best practices, and maintainability.
55896
+
55897
+ Your role is to:
55898
+
55899
+ 1. Review code changes for correctness, clarity, and best practices
55900
+ 2. Identify bugs, security issues, and performance problems
55901
+ 3. Suggest improvements for readability and maintainability
55902
+ 4. Ensure consistency with project conventions and patterns
55903
+ 5. Verify test coverage and edge case handling
55904
+
55905
+ When reviewing code:
55906
+ - Use search to find similar patterns in the codebase for consistency
55907
+ - Look for common issues: null checks, error handling, resource leaks
55908
+ - Check for security vulnerabilities: injection, XSS, etc.
55909
+ - Assess complexity and suggest simplifications
55910
+ - Verify naming conventions and code organization
55911
+
55912
+ Provide constructive feedback:
55913
+ - Start with what's good about the code
55914
+ - Be specific about issues with examples
55915
+ - Suggest concrete improvements with code snippets
55916
+ - Prioritize critical issues over style preferences
55917
+ - Explain the "why" behind your suggestions`,
55918
+ "engineer": `You are a senior engineer who helps implement features and fix bugs.
55919
+
55920
+ Your role is to:
55921
+
55922
+ 1. Implement new features following project conventions
55923
+ 2. Fix bugs by understanding root causes
55924
+ 3. Refactor code to improve quality
55925
+ 4. Write clear, maintainable code
55926
+ 5. Add appropriate tests and documentation
55927
+
55928
+ When implementing:
55929
+ - Use search/query to understand existing patterns
55930
+ - Follow the project's coding style and conventions
55931
+ - Consider edge cases and error handling
55932
+ - Write self-documenting code with clear names
55933
+ - Add comments for complex logic
55934
+
55935
+ You have access to:
55936
+ - search: Find relevant code patterns
55937
+ - query: Locate specific symbols/functions
55938
+ - extract: Get full file context
55939
+ - implement: Create or modify files (use carefully)
55940
+ - delegate: Break down complex tasks`,
55941
+ "support": `You are ProbeChat Support - a helpful assistant focused on answering questions about codebases.
55942
+
55943
+ Your role is to:
55944
+
55945
+ 1. Answer questions about how code works
55946
+ 2. Help users locate specific functionality
55947
+ 3. Explain error messages and debugging approaches
55948
+ 4. Guide users to relevant documentation
55949
+ 5. Provide examples and usage patterns
55950
+
55951
+ When helping users:
55952
+ - Ask clarifying questions if the request is ambiguous
55953
+ - Use search/query to find relevant code quickly
55954
+ - Provide clear, step-by-step explanations
55955
+ - Include code examples when helpful
55956
+ - Point to relevant files and line numbers
55957
+
55958
+ You should be:
55959
+ - Patient and encouraging
55960
+ - Clear and concise
55961
+ - Thorough but not overwhelming
55962
+ - Honest about limitations (say "I don't know" when appropriate)`
55963
+ };
55964
+ }
55965
+ });
55966
+
55847
55967
  // src/agent/mcp/config.js
55848
55968
  import { readFileSync, existsSync as existsSync4, mkdirSync as mkdirSync2, writeFileSync } from "fs";
55849
55969
  import { join as join2, dirname as dirname3 } from "path";
@@ -57380,6 +57500,1471 @@ var init_contextCompactor = __esm({
57380
57500
  }
57381
57501
  });
57382
57502
 
57503
+ // src/agent/mcp/built-in-server.js
57504
+ import { createServer } from "http";
57505
+ import { EventEmitter as EventEmitter3 } from "events";
57506
+ import { randomUUID as randomUUID4 } from "crypto";
57507
+ import { Server as MCPServer } from "@modelcontextprotocol/sdk/server/index.js";
57508
+ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
57509
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
57510
+ import {
57511
+ CallToolRequestSchema,
57512
+ ListToolsRequestSchema,
57513
+ isInitializeRequest
57514
+ } from "@modelcontextprotocol/sdk/types.js";
57515
+ var InMemoryEventStore, BuiltInMCPServer;
57516
+ var init_built_in_server = __esm({
57517
+ "src/agent/mcp/built-in-server.js"() {
57518
+ "use strict";
57519
+ InMemoryEventStore = class {
57520
+ constructor() {
57521
+ this.events = /* @__PURE__ */ new Map();
57522
+ }
57523
+ generateEventId(streamId) {
57524
+ return `${streamId}_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`;
57525
+ }
57526
+ getStreamIdFromEventId(eventId) {
57527
+ const parts = eventId.split("_");
57528
+ return parts.length > 0 ? parts[0] : "";
57529
+ }
57530
+ async storeEvent(streamId, message) {
57531
+ const eventId = this.generateEventId(streamId);
57532
+ this.events.set(eventId, { streamId, message });
57533
+ return eventId;
57534
+ }
57535
+ async replayEventsAfter(lastEventId, { send }) {
57536
+ if (!lastEventId || !this.events.has(lastEventId)) {
57537
+ return "";
57538
+ }
57539
+ const streamId = this.getStreamIdFromEventId(lastEventId);
57540
+ if (!streamId) {
57541
+ return "";
57542
+ }
57543
+ let foundLastEvent = false;
57544
+ const sortedEvents = [...this.events.entries()].sort((a, b) => a[0].localeCompare(b[0]));
57545
+ for (const [eventId, { streamId: eventStreamId, message }] of sortedEvents) {
57546
+ if (eventStreamId !== streamId) {
57547
+ continue;
57548
+ }
57549
+ if (eventId === lastEventId) {
57550
+ foundLastEvent = true;
57551
+ continue;
57552
+ }
57553
+ if (foundLastEvent) {
57554
+ await send(eventId, message);
57555
+ }
57556
+ }
57557
+ return streamId;
57558
+ }
57559
+ };
57560
+ BuiltInMCPServer = class extends EventEmitter3 {
57561
+ constructor(agent, options = {}) {
57562
+ super();
57563
+ this.agent = agent;
57564
+ this.port = options.port || 0;
57565
+ this.host = options.host || "127.0.0.1";
57566
+ this.httpServer = null;
57567
+ this.mcpServer = null;
57568
+ this.sseTransports = /* @__PURE__ */ new Map();
57569
+ this.streamableTransports = /* @__PURE__ */ new Map();
57570
+ this.connections = /* @__PURE__ */ new Set();
57571
+ this.debug = options.debug || false;
57572
+ }
57573
+ /**
57574
+ * Start the built-in MCP server
57575
+ */
57576
+ async start() {
57577
+ this.httpServer = createServer();
57578
+ this.httpServer.on("request", (req, res) => {
57579
+ this.handleRequest(req, res);
57580
+ });
57581
+ this.mcpServer = new MCPServer({
57582
+ name: "probe-builtin",
57583
+ version: "1.0.0"
57584
+ }, {
57585
+ capabilities: {
57586
+ tools: {}
57587
+ }
57588
+ });
57589
+ this.registerHandlers();
57590
+ return new Promise((resolve6, reject2) => {
57591
+ this.httpServer.listen(this.port, this.host, async () => {
57592
+ const address = this.httpServer.address();
57593
+ this.port = address.port;
57594
+ if (this.debug) {
57595
+ console.log(`[MCP] Built-in server started at http://${this.host}:${this.port}`);
57596
+ console.log(`[MCP] SSE endpoint: http://${this.host}:${this.port}/sse`);
57597
+ console.log(`[MCP] Messages endpoint: http://${this.host}:${this.port}/messages`);
57598
+ }
57599
+ this.emit("ready", { host: this.host, port: this.port });
57600
+ resolve6({ host: this.host, port: this.port });
57601
+ });
57602
+ this.httpServer.on("error", reject2);
57603
+ });
57604
+ }
57605
+ /**
57606
+ * Handle HTTP requests (SSE and JSON-RPC)
57607
+ */
57608
+ handleRequest(req, res) {
57609
+ const { method, url } = req;
57610
+ if (this.debug) {
57611
+ console.log(`[MCP] Request: ${method} ${url}`);
57612
+ }
57613
+ res.setHeader("Access-Control-Allow-Origin", "*");
57614
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
57615
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
57616
+ if (method === "OPTIONS") {
57617
+ res.writeHead(204);
57618
+ res.end();
57619
+ return;
57620
+ }
57621
+ if (url === "/sse" && method === "GET") {
57622
+ if (this.debug) {
57623
+ console.log("[MCP] Routing to handleSSEConnection");
57624
+ }
57625
+ this.handleSSEConnection(req, res);
57626
+ return;
57627
+ }
57628
+ if (url.startsWith("/messages") && method === "POST") {
57629
+ this.handleSSEMessage(req, res);
57630
+ return;
57631
+ }
57632
+ if (url === "/rpc" && method === "POST") {
57633
+ this.handleJSONRPC(req, res);
57634
+ return;
57635
+ }
57636
+ if (url === "/mcp") {
57637
+ this.handleStreamableHTTP(req, res);
57638
+ return;
57639
+ }
57640
+ if (url === "/health") {
57641
+ res.writeHead(200, { "Content-Type": "application/json" });
57642
+ res.end(JSON.stringify({
57643
+ status: "ok",
57644
+ server: "probe-builtin-mcp",
57645
+ tools: this.getToolCount()
57646
+ }));
57647
+ return;
57648
+ }
57649
+ res.writeHead(404);
57650
+ res.end("Not Found");
57651
+ }
57652
+ /**
57653
+ * Handle SSE connection (GET /sse) - creates new transport
57654
+ */
57655
+ async handleSSEConnection(req, res) {
57656
+ if (this.debug) {
57657
+ console.log("[MCP] New SSE connection request");
57658
+ }
57659
+ const transport = new SSEServerTransport("/messages", res);
57660
+ this.sseTransports.set(transport.sessionId, transport);
57661
+ res.on("close", () => {
57662
+ if (this.debug) {
57663
+ console.log("[MCP] SSE connection closed, sessionId:", transport.sessionId);
57664
+ }
57665
+ this.sseTransports.delete(transport.sessionId);
57666
+ });
57667
+ try {
57668
+ await this.mcpServer.connect(transport);
57669
+ if (this.debug) {
57670
+ console.log("[MCP] MCP server connected to SSE transport, sessionId:", transport.sessionId);
57671
+ }
57672
+ } catch (error) {
57673
+ if (this.debug) {
57674
+ console.error("[MCP] Error connecting MCP server to transport:", error);
57675
+ }
57676
+ this.sseTransports.delete(transport.sessionId);
57677
+ }
57678
+ }
57679
+ /**
57680
+ * Handle SSE message (POST /messages?sessionId=...) - routes to existing transport
57681
+ */
57682
+ async handleSSEMessage(req, res) {
57683
+ const url = new URL(req.url, `http://${req.headers.host}`);
57684
+ const sessionId = url.searchParams.get("sessionId");
57685
+ if (!sessionId) {
57686
+ res.writeHead(400, { "Content-Type": "application/json" });
57687
+ res.end(JSON.stringify({
57688
+ jsonrpc: "2.0",
57689
+ error: {
57690
+ code: -32e3,
57691
+ message: "Bad Request: sessionId query parameter is required"
57692
+ },
57693
+ id: null
57694
+ }));
57695
+ return;
57696
+ }
57697
+ const transport = this.sseTransports.get(sessionId);
57698
+ if (!transport) {
57699
+ res.writeHead(400, { "Content-Type": "application/json" });
57700
+ res.end(JSON.stringify({
57701
+ jsonrpc: "2.0",
57702
+ error: {
57703
+ code: -32e3,
57704
+ message: `Bad Request: No transport found for sessionId: ${sessionId}`
57705
+ },
57706
+ id: null
57707
+ }));
57708
+ return;
57709
+ }
57710
+ let body = "";
57711
+ req.on("data", (chunk) => {
57712
+ body += chunk.toString();
57713
+ });
57714
+ req.on("end", async () => {
57715
+ try {
57716
+ const message = JSON.parse(body);
57717
+ await transport.handlePostMessage(req, res, message);
57718
+ } catch (error) {
57719
+ res.writeHead(500, { "Content-Type": "application/json" });
57720
+ res.end(JSON.stringify({
57721
+ jsonrpc: "2.0",
57722
+ error: {
57723
+ code: -32603,
57724
+ message: "Internal error",
57725
+ data: error.message
57726
+ },
57727
+ id: null
57728
+ }));
57729
+ }
57730
+ });
57731
+ }
57732
+ /**
57733
+ * Handle Streamable HTTP protocol (GET/POST/DELETE on /mcp)
57734
+ */
57735
+ async handleStreamableHTTP(req, res) {
57736
+ const { method } = req;
57737
+ if (this.debug) {
57738
+ console.log(`[MCP] Streamable HTTP ${method} request`);
57739
+ }
57740
+ try {
57741
+ let body = null;
57742
+ if (method === "POST") {
57743
+ body = await this.parseRequestBody(req);
57744
+ }
57745
+ const sessionId = req.headers["mcp-session-id"];
57746
+ let transport;
57747
+ if (sessionId && this.streamableTransports.has(sessionId)) {
57748
+ transport = this.streamableTransports.get(sessionId);
57749
+ if (this.debug) {
57750
+ console.log(`[MCP] Reusing existing transport for session: ${sessionId}`);
57751
+ }
57752
+ } else if (!sessionId && method === "POST" && body && isInitializeRequest(body)) {
57753
+ if (this.debug) {
57754
+ console.log("[MCP] Creating new Streamable HTTP transport for initialization");
57755
+ }
57756
+ const eventStore = new InMemoryEventStore();
57757
+ transport = new StreamableHTTPServerTransport({
57758
+ sessionIdGenerator: () => randomUUID4(),
57759
+ eventStore,
57760
+ // Enable resumability
57761
+ onsessioninitialized: (newSessionId) => {
57762
+ if (this.debug) {
57763
+ console.log(`[MCP] Streamable HTTP session initialized: ${newSessionId}`);
57764
+ }
57765
+ this.streamableTransports.set(newSessionId, transport);
57766
+ },
57767
+ onsessionclosed: (closedSessionId) => {
57768
+ if (this.debug) {
57769
+ console.log(`[MCP] Streamable HTTP session closed: ${closedSessionId}`);
57770
+ }
57771
+ this.streamableTransports.delete(closedSessionId);
57772
+ }
57773
+ });
57774
+ transport.onclose = () => {
57775
+ const sid = transport.sessionId;
57776
+ if (sid && this.streamableTransports.has(sid)) {
57777
+ if (this.debug) {
57778
+ console.log(`[MCP] Transport closed for session ${sid}`);
57779
+ }
57780
+ this.streamableTransports.delete(sid);
57781
+ }
57782
+ };
57783
+ await this.mcpServer.connect(transport);
57784
+ } else {
57785
+ res.writeHead(400, { "Content-Type": "application/json" });
57786
+ res.end(JSON.stringify({
57787
+ jsonrpc: "2.0",
57788
+ error: {
57789
+ code: -32e3,
57790
+ message: "Bad Request: No valid session ID provided or not an initialization request"
57791
+ },
57792
+ id: null
57793
+ }));
57794
+ return;
57795
+ }
57796
+ await transport.handleRequest(req, res, body);
57797
+ } catch (error) {
57798
+ if (this.debug) {
57799
+ console.error("[MCP] Error handling Streamable HTTP request:", error);
57800
+ }
57801
+ if (!res.headersSent) {
57802
+ res.writeHead(500, { "Content-Type": "application/json" });
57803
+ res.end(JSON.stringify({
57804
+ jsonrpc: "2.0",
57805
+ error: {
57806
+ code: -32603,
57807
+ message: "Internal server error",
57808
+ data: error.message
57809
+ },
57810
+ id: null
57811
+ }));
57812
+ }
57813
+ }
57814
+ }
57815
+ /**
57816
+ * Parse request body as JSON
57817
+ */
57818
+ async parseRequestBody(req) {
57819
+ return new Promise((resolve6, reject2) => {
57820
+ let body = "";
57821
+ req.on("data", (chunk) => {
57822
+ body += chunk.toString();
57823
+ });
57824
+ req.on("end", () => {
57825
+ try {
57826
+ const parsed = body ? JSON.parse(body) : null;
57827
+ resolve6(parsed);
57828
+ } catch (error) {
57829
+ reject2(error);
57830
+ }
57831
+ });
57832
+ req.on("error", reject2);
57833
+ });
57834
+ }
57835
+ /**
57836
+ * Handle Server-Sent Events connection (DEPRECATED - use handleSSEConnection instead)
57837
+ */
57838
+ handleSSE(req, res) {
57839
+ res.writeHead(200, {
57840
+ "Content-Type": "text/event-stream",
57841
+ "Cache-Control": "no-cache",
57842
+ "Connection": "keep-alive"
57843
+ });
57844
+ res.write("event: connected\n");
57845
+ res.write(`data: ${JSON.stringify({ type: "connected", server: "probe-builtin" })}
57846
+
57847
+ `);
57848
+ this.connections.add(res);
57849
+ req.on("close", () => {
57850
+ this.connections.delete(res);
57851
+ });
57852
+ }
57853
+ /**
57854
+ * Handle JSON-RPC requests
57855
+ */
57856
+ async handleJSONRPC(req, res) {
57857
+ let body = "";
57858
+ req.on("data", (chunk) => {
57859
+ body += chunk.toString();
57860
+ });
57861
+ req.on("end", async () => {
57862
+ try {
57863
+ const request = JSON.parse(body);
57864
+ const response = await this.processRequest(request);
57865
+ res.writeHead(200, { "Content-Type": "application/json" });
57866
+ res.end(JSON.stringify(response));
57867
+ } catch (error) {
57868
+ res.writeHead(400, { "Content-Type": "application/json" });
57869
+ res.end(JSON.stringify({
57870
+ jsonrpc: "2.0",
57871
+ error: {
57872
+ code: -32700,
57873
+ message: "Parse error",
57874
+ data: error.message
57875
+ },
57876
+ id: null
57877
+ }));
57878
+ }
57879
+ });
57880
+ }
57881
+ /**
57882
+ * Handle MCP protocol messages
57883
+ */
57884
+ async handleMCPProtocol(req, res) {
57885
+ let body = "";
57886
+ req.on("data", (chunk) => {
57887
+ body += chunk.toString();
57888
+ });
57889
+ req.on("end", async () => {
57890
+ try {
57891
+ const message = JSON.parse(body);
57892
+ let response;
57893
+ if (message.method === "tools/list") {
57894
+ response = await this.handleListTools();
57895
+ } else if (message.method === "tools/call") {
57896
+ response = await this.handleCallTool(message.params);
57897
+ } else {
57898
+ response = {
57899
+ error: {
57900
+ code: -32601,
57901
+ message: "Method not found"
57902
+ }
57903
+ };
57904
+ }
57905
+ res.writeHead(200, { "Content-Type": "application/json" });
57906
+ res.end(JSON.stringify(response));
57907
+ } catch (error) {
57908
+ res.writeHead(500, { "Content-Type": "application/json" });
57909
+ res.end(JSON.stringify({
57910
+ error: {
57911
+ code: -32603,
57912
+ message: "Internal error",
57913
+ data: error.message
57914
+ }
57915
+ }));
57916
+ }
57917
+ });
57918
+ }
57919
+ /**
57920
+ * Process JSON-RPC request
57921
+ */
57922
+ async processRequest(request) {
57923
+ const { jsonrpc, method, params, id } = request;
57924
+ try {
57925
+ let result;
57926
+ switch (method) {
57927
+ case "tools/list":
57928
+ result = await this.handleListTools();
57929
+ break;
57930
+ case "tools/call":
57931
+ result = await this.handleCallTool(params);
57932
+ break;
57933
+ default:
57934
+ return {
57935
+ jsonrpc: "2.0",
57936
+ error: {
57937
+ code: -32601,
57938
+ message: "Method not found"
57939
+ },
57940
+ id
57941
+ };
57942
+ }
57943
+ return {
57944
+ jsonrpc: "2.0",
57945
+ result,
57946
+ id
57947
+ };
57948
+ } catch (error) {
57949
+ return {
57950
+ jsonrpc: "2.0",
57951
+ error: {
57952
+ code: -32603,
57953
+ message: "Internal error",
57954
+ data: error.message
57955
+ },
57956
+ id
57957
+ };
57958
+ }
57959
+ }
57960
+ /**
57961
+ * Register MCP protocol handlers
57962
+ */
57963
+ registerHandlers() {
57964
+ this.mcpServer.setRequestHandler(ListToolsRequestSchema, async () => {
57965
+ return this.handleListTools();
57966
+ });
57967
+ this.mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
57968
+ return this.handleCallTool(request.params);
57969
+ });
57970
+ }
57971
+ /**
57972
+ * Handle list tools request
57973
+ */
57974
+ async handleListTools() {
57975
+ const tools2 = [];
57976
+ if (this.agent && this.agent.allowedTools) {
57977
+ const toolDefs = {
57978
+ search: {
57979
+ description: "Search for code patterns using semantic search",
57980
+ inputSchema: {
57981
+ type: "object",
57982
+ properties: {
57983
+ query: { type: "string", description: "Search query" },
57984
+ path: { type: "string", description: "Directory to search", default: "." },
57985
+ maxResults: { type: "integer", default: 10 }
57986
+ },
57987
+ required: ["query"]
57988
+ }
57989
+ },
57990
+ extract: {
57991
+ description: "Extract code from specific file location",
57992
+ inputSchema: {
57993
+ type: "object",
57994
+ properties: {
57995
+ path: { type: "string", description: "File path with optional line number" }
57996
+ },
57997
+ required: ["path"]
57998
+ }
57999
+ },
58000
+ listFiles: {
58001
+ description: "List files in a directory",
58002
+ inputSchema: {
58003
+ type: "object",
58004
+ properties: {
58005
+ path: { type: "string", description: "Directory path" },
58006
+ pattern: { type: "string", description: "File pattern" }
58007
+ },
58008
+ required: ["path"]
58009
+ }
58010
+ },
58011
+ searchFiles: {
58012
+ description: "Search for files by name pattern",
58013
+ inputSchema: {
58014
+ type: "object",
58015
+ properties: {
58016
+ pattern: { type: "string", description: "File name pattern" },
58017
+ path: { type: "string", description: "Directory to search" }
58018
+ },
58019
+ required: ["pattern"]
58020
+ }
58021
+ },
58022
+ query: {
58023
+ description: "Query code using AST patterns",
58024
+ inputSchema: {
58025
+ type: "object",
58026
+ properties: {
58027
+ query: { type: "string", description: "AST query" },
58028
+ path: { type: "string", description: "Directory to search" }
58029
+ },
58030
+ required: ["query"]
58031
+ }
58032
+ }
58033
+ };
58034
+ for (const [name, def] of Object.entries(toolDefs)) {
58035
+ if (this.agent.allowedTools.isEnabled(name)) {
58036
+ tools2.push({
58037
+ name: `mcp__probe__${name}`,
58038
+ description: def.description,
58039
+ inputSchema: def.inputSchema
58040
+ });
58041
+ }
58042
+ }
58043
+ }
58044
+ return { tools: tools2 };
58045
+ }
58046
+ /**
58047
+ * Handle tool execution
58048
+ */
58049
+ async handleCallTool(params) {
58050
+ const { name, arguments: args } = params;
58051
+ const toolName = name.replace("mcp__probe__", "");
58052
+ if (!this.agent.allowedTools.isEnabled(toolName)) {
58053
+ throw new Error(`Tool ${name} is not enabled`);
58054
+ }
58055
+ const tool4 = this.agent.toolImplementations[toolName];
58056
+ if (!tool4) {
58057
+ throw new Error(`Tool ${name} not found`);
58058
+ }
58059
+ try {
58060
+ const result = await tool4.execute(args);
58061
+ return {
58062
+ content: [{
58063
+ type: "text",
58064
+ text: typeof result === "string" ? result : JSON.stringify(result, null, 2)
58065
+ }]
58066
+ };
58067
+ } catch (error) {
58068
+ return {
58069
+ content: [{
58070
+ type: "text",
58071
+ text: `Error executing ${name}: ${error.message}`
58072
+ }],
58073
+ isError: true
58074
+ };
58075
+ }
58076
+ }
58077
+ /**
58078
+ * Get the number of available tools
58079
+ */
58080
+ getToolCount() {
58081
+ if (!this.agent || !this.agent.allowedTools) {
58082
+ return 0;
58083
+ }
58084
+ const tools2 = ["search", "extract", "listFiles", "searchFiles", "query"];
58085
+ return tools2.filter((name) => this.agent.allowedTools.isEnabled(name)).length;
58086
+ }
58087
+ /**
58088
+ * Broadcast message to all SSE connections
58089
+ */
58090
+ broadcast(event, data) {
58091
+ const message = `event: ${event}
58092
+ data: ${JSON.stringify(data)}
58093
+
58094
+ `;
58095
+ for (const connection of this.connections) {
58096
+ connection.write(message);
58097
+ }
58098
+ }
58099
+ /**
58100
+ * Stop the server
58101
+ */
58102
+ async stop() {
58103
+ for (const [sessionId, transport] of this.streamableTransports.entries()) {
58104
+ try {
58105
+ await transport.close();
58106
+ if (this.debug) {
58107
+ console.log(`[MCP] Closed Streamable HTTP transport for session: ${sessionId}`);
58108
+ }
58109
+ } catch (error) {
58110
+ if (this.debug) {
58111
+ console.error(`[MCP] Error closing Streamable HTTP transport ${sessionId}:`, error);
58112
+ }
58113
+ }
58114
+ }
58115
+ this.streamableTransports.clear();
58116
+ for (const [sessionId, transport] of this.sseTransports.entries()) {
58117
+ try {
58118
+ await transport.close();
58119
+ if (this.debug) {
58120
+ console.log(`[MCP] Closed SSE transport for session: ${sessionId}`);
58121
+ }
58122
+ } catch (error) {
58123
+ if (this.debug) {
58124
+ console.error(`[MCP] Error closing SSE transport ${sessionId}:`, error);
58125
+ }
58126
+ }
58127
+ }
58128
+ this.sseTransports.clear();
58129
+ for (const connection of this.connections) {
58130
+ connection.end();
58131
+ }
58132
+ this.connections.clear();
58133
+ if (this.httpServer) {
58134
+ return new Promise((resolve6) => {
58135
+ this.httpServer.close(() => {
58136
+ if (this.debug) {
58137
+ console.log("[MCP] Built-in server stopped");
58138
+ }
58139
+ resolve6();
58140
+ });
58141
+ });
58142
+ }
58143
+ }
58144
+ /**
58145
+ * Get server configuration for MCP clients
58146
+ */
58147
+ getConfig() {
58148
+ return {
58149
+ transport: "http",
58150
+ url: `http://${this.host}:${this.port}/mcp`
58151
+ // Alternative transports:
58152
+ // sse: `http://${this.host}:${this.port}/sse`,
58153
+ // rpc: `http://${this.host}:${this.port}/rpc`
58154
+ };
58155
+ }
58156
+ };
58157
+ }
58158
+ });
58159
+
58160
+ // src/agent/shared/Session.js
58161
+ var Session;
58162
+ var init_Session = __esm({
58163
+ "src/agent/shared/Session.js"() {
58164
+ "use strict";
58165
+ Session = class {
58166
+ constructor(id, debug = false) {
58167
+ this.id = id;
58168
+ this.conversationId = null;
58169
+ this.messageCount = 0;
58170
+ this.debug = debug;
58171
+ }
58172
+ /**
58173
+ * Set the conversation ID for session resumption
58174
+ * @param {string} conversationId - Provider's conversation/thread ID
58175
+ */
58176
+ setConversationId(conversationId) {
58177
+ this.conversationId = conversationId;
58178
+ if (this.debug) {
58179
+ console.log(`[Session ${this.id}] Conversation ID: ${conversationId}`);
58180
+ }
58181
+ }
58182
+ /**
58183
+ * Increment the message count
58184
+ */
58185
+ incrementMessageCount() {
58186
+ this.messageCount++;
58187
+ }
58188
+ /**
58189
+ * Get session info as plain object
58190
+ * @returns {Object} Session information
58191
+ */
58192
+ getInfo() {
58193
+ return {
58194
+ id: this.id,
58195
+ conversationId: this.conversationId,
58196
+ messageCount: this.messageCount
58197
+ };
58198
+ }
58199
+ /**
58200
+ * Get resume arguments for CLI commands (used by Claude Code)
58201
+ * @returns {Array<string>} CLI arguments for resuming conversation
58202
+ */
58203
+ getResumeArgs() {
58204
+ if (this.conversationId && this.messageCount > 0) {
58205
+ return ["--resume", this.conversationId];
58206
+ }
58207
+ return [];
58208
+ }
58209
+ };
58210
+ }
58211
+ });
58212
+
58213
+ // src/agent/engines/enhanced-claude-code.js
58214
+ var enhanced_claude_code_exports = {};
58215
+ __export(enhanced_claude_code_exports, {
58216
+ createEnhancedClaudeCLIEngine: () => createEnhancedClaudeCLIEngine
58217
+ });
58218
+ import { spawn as spawn3 } from "child_process";
58219
+ import { randomBytes } from "crypto";
58220
+ import fs7 from "fs/promises";
58221
+ import path7 from "path";
58222
+ import os3 from "os";
58223
+ import { EventEmitter as EventEmitter4 } from "events";
58224
+ async function createEnhancedClaudeCLIEngine(options = {}) {
58225
+ const { agent, systemPrompt, customPrompt, debug, sessionId, allowedTools } = options;
58226
+ const session = new Session(
58227
+ sessionId || randomBytes(8).toString("hex"),
58228
+ debug
58229
+ );
58230
+ let mcpServer = null;
58231
+ let mcpConfigPath = null;
58232
+ if (agent) {
58233
+ mcpServer = new BuiltInMCPServer(agent, {
58234
+ port: 0,
58235
+ // Ephemeral port
58236
+ host: "127.0.0.1",
58237
+ debug
58238
+ });
58239
+ const { host, port } = await mcpServer.start();
58240
+ if (debug) {
58241
+ console.log("[DEBUG] Built-in MCP server started");
58242
+ console.log("[DEBUG] MCP URL:", `http://${host}:${port}/mcp`);
58243
+ }
58244
+ mcpConfigPath = path7.join(os3.tmpdir(), `probe-mcp-${session.id}.json`);
58245
+ const mcpConfig = {
58246
+ mcpServers: {
58247
+ probe: {
58248
+ command: "node",
58249
+ args: [path7.join(process.cwd(), "mcp-probe-server.js")],
58250
+ env: {
58251
+ PROBE_WORKSPACE: process.cwd(),
58252
+ DEBUG: debug ? "true" : "false"
58253
+ }
58254
+ }
58255
+ }
58256
+ };
58257
+ await fs7.writeFile(mcpConfigPath, JSON.stringify(mcpConfig, null, 2));
58258
+ }
58259
+ if (debug) {
58260
+ console.log("[DEBUG] Enhanced Claude Code Engine");
58261
+ console.log("[DEBUG] Session:", session.id);
58262
+ console.log("[DEBUG] MCP Config:", mcpConfigPath);
58263
+ }
58264
+ const fullSystemPrompt = combinePrompts(systemPrompt, customPrompt, agent);
58265
+ return {
58266
+ sessionId: session.id,
58267
+ session,
58268
+ /**
58269
+ * Query Claude with advanced streaming
58270
+ */
58271
+ async *query(prompt, opts = {}) {
58272
+ const emitter = new EventEmitter4();
58273
+ let buffer = "";
58274
+ let processEnded = false;
58275
+ let currentToolCall = null;
58276
+ let isSchemaMode = false;
58277
+ if (opts.schema || prompt.includes("JSON schema") || prompt.includes("mermaid diagram")) {
58278
+ isSchemaMode = true;
58279
+ if (debug) {
58280
+ console.log("[DEBUG] Schema/validation mode - treating as black box");
58281
+ }
58282
+ }
58283
+ let finalPrompt = prompt;
58284
+ if (opts.schema && isSchemaMode) {
58285
+ finalPrompt = `${prompt}
58286
+
58287
+ Please provide your response in the following JSON format:
58288
+ ${opts.schema}`;
58289
+ }
58290
+ const args = buildClaudeArgs({
58291
+ systemPrompt: fullSystemPrompt,
58292
+ mcpConfigPath,
58293
+ session,
58294
+ debug,
58295
+ prompt: finalPrompt,
58296
+ // Use finalPrompt which may include schema
58297
+ allowedTools: allowedTools || opts.allowedTools
58298
+ // Support tool filtering
58299
+ });
58300
+ if (debug) {
58301
+ console.log("[DEBUG] Executing: claude", args.join(" "));
58302
+ }
58303
+ const shellCmd = `echo "" | claude ${args.map((arg) => {
58304
+ if (typeof arg !== "string") {
58305
+ throw new TypeError(`Invalid argument type: expected string, got ${typeof arg}`);
58306
+ }
58307
+ const escaped = arg.replace(/'/g, "'\\''");
58308
+ return `'${escaped}'`;
58309
+ }).join(" ")}`;
58310
+ if (debug) {
58311
+ console.log("[DEBUG] Shell command length:", shellCmd.length);
58312
+ if (shellCmd.length < 500) {
58313
+ console.log("[DEBUG] Shell command:", shellCmd);
58314
+ } else {
58315
+ console.log("[DEBUG] Shell command (truncated):", shellCmd.substring(0, 200) + "...");
58316
+ }
58317
+ }
58318
+ const toolCollector = [];
58319
+ const proc2 = spawn3("sh", ["-c", shellCmd], {
58320
+ env: { ...process.env, FORCE_COLOR: "0" },
58321
+ stdio: ["ignore", "pipe", "pipe"]
58322
+ // Ignore stdin since echo handles it
58323
+ });
58324
+ proc2.stdout.on("data", (data) => {
58325
+ buffer += data.toString();
58326
+ processJsonBuffer(buffer, emitter, session, debug, toolCollector);
58327
+ const lines = buffer.split("\n");
58328
+ buffer = lines[lines.length - 1] || "";
58329
+ });
58330
+ proc2.stderr.on("data", (data) => {
58331
+ const stderr = data.toString();
58332
+ if (debug) {
58333
+ console.error("[STDERR]", stderr);
58334
+ }
58335
+ if (stderr.includes("command not found")) {
58336
+ emitter.emit("error", new Error("Claude Code not found. Please install it first."));
58337
+ }
58338
+ });
58339
+ proc2.on("close", (code) => {
58340
+ processEnded = true;
58341
+ if (code !== 0 && debug) {
58342
+ console.log(`[DEBUG] Process exited with code ${code}`);
58343
+ }
58344
+ if (buffer.trim()) {
58345
+ processJsonBuffer(buffer, emitter, session, debug, toolCollector);
58346
+ }
58347
+ if (toolCollector.length > 0) {
58348
+ emitter.emit("toolBatch", {
58349
+ tools: toolCollector,
58350
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
58351
+ });
58352
+ if (debug) {
58353
+ console.log(`[DEBUG] Emitting batch of ${toolCollector.length} tool events`);
58354
+ }
58355
+ }
58356
+ emitter.emit("end");
58357
+ });
58358
+ proc2.on("error", (error) => {
58359
+ emitter.emit("error", error);
58360
+ });
58361
+ const messageQueue = [];
58362
+ let resolver = null;
58363
+ emitter.on("message", (msg) => {
58364
+ messageQueue.push(msg);
58365
+ if (resolver) {
58366
+ resolver();
58367
+ resolver = null;
58368
+ }
58369
+ });
58370
+ emitter.on("toolBatch", (batch) => {
58371
+ messageQueue.push({ type: "toolBatch", ...batch });
58372
+ if (resolver) {
58373
+ resolver();
58374
+ resolver = null;
58375
+ }
58376
+ });
58377
+ emitter.on("end", () => {
58378
+ processEnded = true;
58379
+ if (resolver) {
58380
+ resolver();
58381
+ resolver = null;
58382
+ }
58383
+ });
58384
+ emitter.on("error", (error) => {
58385
+ messageQueue.push({ type: "error", error });
58386
+ if (resolver) {
58387
+ resolver();
58388
+ resolver = null;
58389
+ }
58390
+ });
58391
+ while (!processEnded || messageQueue.length > 0) {
58392
+ if (messageQueue.length > 0) {
58393
+ const msg = messageQueue.shift();
58394
+ if (msg.type === "text") {
58395
+ yield { type: "text", content: msg.content };
58396
+ } else if (msg.type === "tool_use") {
58397
+ currentToolCall = msg;
58398
+ yield {
58399
+ type: "text",
58400
+ content: `
58401
+ \u{1F527} Using ${msg.name}: ${JSON.stringify(msg.input)}
58402
+ `
58403
+ };
58404
+ const result = await executeProbleTool(agent, msg.name, msg.input);
58405
+ yield { type: "text", content: `${result}
58406
+ ` };
58407
+ } else if (msg.type === "toolBatch") {
58408
+ yield { type: "toolBatch", tools: msg.tools, timestamp: msg.timestamp };
58409
+ } else if (msg.type === "session_update") {
58410
+ if (debug) {
58411
+ console.log("[DEBUG] Session updated:", msg.conversationId);
58412
+ }
58413
+ } else if (msg.type === "error") {
58414
+ yield { type: "error", error: msg.error };
58415
+ break;
58416
+ }
58417
+ } else if (!processEnded) {
58418
+ await new Promise((resolve6) => {
58419
+ resolver = resolve6;
58420
+ });
58421
+ }
58422
+ }
58423
+ session.incrementMessageCount();
58424
+ yield {
58425
+ type: "metadata",
58426
+ data: {
58427
+ sessionId: session.id,
58428
+ conversationId: session.conversationId,
58429
+ messageCount: session.messageCount
58430
+ }
58431
+ };
58432
+ },
58433
+ /**
58434
+ * Get session info
58435
+ */
58436
+ getSession() {
58437
+ return session.getInfo();
58438
+ },
58439
+ /**
58440
+ * Clean up - MUST be called to stop MCP server and clean resources
58441
+ */
58442
+ async close() {
58443
+ try {
58444
+ if (mcpServer) {
58445
+ await mcpServer.stop();
58446
+ if (debug) {
58447
+ console.log("[DEBUG] Built-in MCP server stopped");
58448
+ }
58449
+ }
58450
+ if (mcpConfigPath) {
58451
+ await fs7.unlink(mcpConfigPath).catch(() => {
58452
+ });
58453
+ if (debug) {
58454
+ console.log("[DEBUG] MCP config file removed");
58455
+ }
58456
+ }
58457
+ if (debug) {
58458
+ console.log("[DEBUG] Engine closed, session:", session.id);
58459
+ }
58460
+ } catch (error) {
58461
+ if (debug) {
58462
+ console.error("[DEBUG] Error during cleanup:", error.message);
58463
+ }
58464
+ }
58465
+ }
58466
+ };
58467
+ }
58468
+ function processJsonBuffer(buffer, emitter, session, debug, toolCollector = null) {
58469
+ const lines = buffer.split("\n");
58470
+ for (const line of lines) {
58471
+ if (!line.trim()) continue;
58472
+ try {
58473
+ const parsed = JSON.parse(line);
58474
+ const messages = Array.isArray(parsed) ? parsed : [parsed];
58475
+ for (const msg of messages) {
58476
+ switch (msg.type) {
58477
+ case "result":
58478
+ if (msg.result) {
58479
+ emitter.emit("message", { type: "text", content: msg.result });
58480
+ }
58481
+ if (msg.session_id) {
58482
+ session.setConversationId(msg.session_id);
58483
+ emitter.emit("message", { type: "session_update", conversationId: msg.session_id });
58484
+ }
58485
+ break;
58486
+ case "conversation":
58487
+ session.setConversationId(msg.id);
58488
+ emitter.emit("message", { type: "session_update", conversationId: msg.id });
58489
+ break;
58490
+ case "text":
58491
+ if (msg.text) {
58492
+ emitter.emit("message", { type: "text", content: msg.text });
58493
+ }
58494
+ break;
58495
+ case "assistant":
58496
+ if (msg.message && msg.message.content) {
58497
+ for (const content of msg.message.content) {
58498
+ if (content.type === "text" && content.text) {
58499
+ emitter.emit("message", { type: "text", content: content.text });
58500
+ } else if (content.type === "tool_use") {
58501
+ if (toolCollector) {
58502
+ toolCollector.push({
58503
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
58504
+ name: content.name,
58505
+ args: content.input || {},
58506
+ id: content.id,
58507
+ status: "started"
58508
+ });
58509
+ }
58510
+ if (debug) {
58511
+ console.log("[DEBUG] Assistant internal tool use:", content.name);
58512
+ }
58513
+ }
58514
+ }
58515
+ }
58516
+ break;
58517
+ case "tool_use":
58518
+ if (toolCollector) {
58519
+ toolCollector.push({
58520
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
58521
+ name: msg.name,
58522
+ args: msg.input || {},
58523
+ id: msg.id,
58524
+ status: "started"
58525
+ });
58526
+ }
58527
+ emitter.emit("message", {
58528
+ type: "tool_use",
58529
+ id: msg.id,
58530
+ name: msg.name,
58531
+ input: msg.input
58532
+ });
58533
+ break;
58534
+ case "tool_result":
58535
+ if (toolCollector && msg.tool_use_id) {
58536
+ const toolCall = toolCollector.find((t) => t.id === msg.tool_use_id);
58537
+ if (toolCall) {
58538
+ toolCall.status = "completed";
58539
+ toolCall.resultPreview = msg.content ? (typeof msg.content === "string" ? msg.content.substring(0, 200) : JSON.stringify(msg.content).substring(0, 200)) + "..." : "No Result";
58540
+ }
58541
+ }
58542
+ if (debug) {
58543
+ console.log("[DEBUG] Tool result:", msg);
58544
+ }
58545
+ break;
58546
+ case "error":
58547
+ emitter.emit("error", new Error(msg.message || "Unknown error"));
58548
+ break;
58549
+ default:
58550
+ if (debug) {
58551
+ console.log("[DEBUG] Unknown message type:", msg.type);
58552
+ console.log("[DEBUG] Full message:", JSON.stringify(msg).substring(0, 200));
58553
+ }
58554
+ }
58555
+ }
58556
+ } catch (e) {
58557
+ if (debug && line.trim()) {
58558
+ console.log("[DEBUG] Non-JSON output:", line);
58559
+ }
58560
+ }
58561
+ }
58562
+ }
58563
+ function buildClaudeArgs({ systemPrompt, mcpConfigPath, session, debug, prompt, allowedTools }) {
58564
+ const args = [
58565
+ "-p",
58566
+ // Short form of --print
58567
+ prompt,
58568
+ // The prompt text goes right after -p
58569
+ "--output-format",
58570
+ "json"
58571
+ ];
58572
+ const resumeArgs = session.getResumeArgs();
58573
+ if (resumeArgs.length > 0) {
58574
+ args.push(...resumeArgs);
58575
+ }
58576
+ if (systemPrompt) {
58577
+ args.push("--system-prompt", systemPrompt);
58578
+ }
58579
+ args.push("--mcp-config", mcpConfigPath);
58580
+ if (allowedTools && Array.isArray(allowedTools) && allowedTools.length > 0) {
58581
+ const mcpTools = allowedTools.map(
58582
+ (tool4) => tool4.startsWith("mcp__") ? tool4 : `mcp__probe__${tool4}`
58583
+ ).join(",");
58584
+ args.push("--allowedTools", mcpTools);
58585
+ } else {
58586
+ args.push("--allowedTools", "mcp__probe__*");
58587
+ }
58588
+ if (debug) {
58589
+ args.push("--verbose");
58590
+ }
58591
+ return args;
58592
+ }
58593
+ async function executeProbleTool(agent, toolName, params) {
58594
+ if (!agent || !agent.toolImplementations) {
58595
+ return "Tool execution not available";
58596
+ }
58597
+ const name = toolName.replace(/^mcp__probe__/, "");
58598
+ const tool4 = agent.toolImplementations[name];
58599
+ if (!tool4) {
58600
+ return `Unknown tool: ${name}`;
58601
+ }
58602
+ try {
58603
+ const result = await tool4.execute(params);
58604
+ return typeof result === "string" ? result : JSON.stringify(result, null, 2);
58605
+ } catch (error) {
58606
+ return `Tool error: ${error.message}`;
58607
+ }
58608
+ }
58609
+ function combinePrompts(systemPrompt, customPrompt, agent) {
58610
+ if (!systemPrompt && customPrompt) {
58611
+ return customPrompt;
58612
+ }
58613
+ if (systemPrompt && customPrompt) {
58614
+ return systemPrompt + "\n\n## Additional Instructions\n" + customPrompt;
58615
+ }
58616
+ return systemPrompt || "";
58617
+ }
58618
+ var init_enhanced_claude_code = __esm({
58619
+ "src/agent/engines/enhanced-claude-code.js"() {
58620
+ "use strict";
58621
+ init_built_in_server();
58622
+ init_Session();
58623
+ }
58624
+ });
58625
+
58626
+ // src/agent/engines/codex.js
58627
+ var codex_exports = {};
58628
+ __export(codex_exports, {
58629
+ createCodexEngine: () => createCodexEngine
58630
+ });
58631
+ import { spawn as spawn4 } from "child_process";
58632
+ import { randomBytes as randomBytes2 } from "crypto";
58633
+ import { createInterface } from "readline";
58634
+ async function createCodexEngine(options = {}) {
58635
+ const { agent, systemPrompt, customPrompt, debug, sessionId, allowedTools, model } = options;
58636
+ const session = new Session(
58637
+ sessionId || randomBytes2(8).toString("hex"),
58638
+ debug
58639
+ );
58640
+ let mcpServer = null;
58641
+ let mcpServerUrl = null;
58642
+ let mcpServerName = null;
58643
+ if (agent) {
58644
+ mcpServer = new BuiltInMCPServer(agent, {
58645
+ port: 0,
58646
+ host: "127.0.0.1",
58647
+ debug
58648
+ });
58649
+ const { host, port } = await mcpServer.start();
58650
+ mcpServerUrl = `http://${host}:${port}/mcp`;
58651
+ mcpServerName = `probe_${session.id}`;
58652
+ if (debug) {
58653
+ console.log("[DEBUG] Built-in Probe MCP server started");
58654
+ console.log("[DEBUG] Probe MCP URL:", mcpServerUrl);
58655
+ }
58656
+ }
58657
+ if (debug) {
58658
+ console.log("[DEBUG] Starting Codex MCP server...");
58659
+ }
58660
+ const codexProcess = spawn4("codex", ["mcp-server"], {
58661
+ stdio: ["pipe", "pipe", "pipe"]
58662
+ });
58663
+ let requestId = 0;
58664
+ const pendingRequests = /* @__PURE__ */ new Map();
58665
+ const eventHandlers = /* @__PURE__ */ new Map();
58666
+ const stdoutReader = createInterface({
58667
+ input: codexProcess.stdout,
58668
+ crlfDelay: Infinity
58669
+ });
58670
+ stdoutReader.on("line", (line) => {
58671
+ try {
58672
+ const message = JSON.parse(line);
58673
+ if (debug) {
58674
+ if (message.method === "codex/event") {
58675
+ console.log(`[DEBUG] Codex event: ${message.params?.msg?.type}`);
58676
+ }
58677
+ }
58678
+ if (message.id !== void 0 && pendingRequests.has(message.id)) {
58679
+ const { resolve: resolve6, reject: reject2 } = pendingRequests.get(message.id);
58680
+ pendingRequests.delete(message.id);
58681
+ if (message.error) {
58682
+ reject2(new Error(message.error.message || JSON.stringify(message.error)));
58683
+ } else {
58684
+ resolve6(message.result);
58685
+ }
58686
+ }
58687
+ if (message.method === "codex/event" && message.params) {
58688
+ const requestId2 = message.params._meta?.requestId;
58689
+ if (requestId2 !== void 0 && eventHandlers.has(requestId2)) {
58690
+ eventHandlers.get(requestId2)(message.params);
58691
+ }
58692
+ }
58693
+ } catch (e) {
58694
+ if (debug) {
58695
+ console.error("[DEBUG] Failed to parse message:", line);
58696
+ }
58697
+ }
58698
+ });
58699
+ if (debug) {
58700
+ codexProcess.stderr.on("data", (data) => {
58701
+ console.error("[CODEX STDERR]", data.toString());
58702
+ });
58703
+ }
58704
+ function sendRequest(method, params = {}) {
58705
+ return new Promise((resolve6, reject2) => {
58706
+ const id = ++requestId;
58707
+ const request = {
58708
+ jsonrpc: "2.0",
58709
+ id,
58710
+ method,
58711
+ params
58712
+ };
58713
+ pendingRequests.set(id, { resolve: resolve6, reject: reject2 });
58714
+ setTimeout(() => {
58715
+ if (pendingRequests.has(id)) {
58716
+ pendingRequests.delete(id);
58717
+ reject2(new Error(`Request ${method} timed out after 10 minutes`));
58718
+ }
58719
+ }, 6e5);
58720
+ codexProcess.stdin.write(JSON.stringify(request) + "\n");
58721
+ });
58722
+ }
58723
+ await sendRequest("initialize", {
58724
+ protocolVersion: "2024-11-05",
58725
+ capabilities: { tools: {} },
58726
+ clientInfo: {
58727
+ name: "probe-codex-client",
58728
+ version: "1.0.0"
58729
+ }
58730
+ });
58731
+ if (debug) {
58732
+ console.log("[DEBUG] Connected to Codex MCP server");
58733
+ console.log("[DEBUG] Session:", session.id);
58734
+ }
58735
+ const fullPrompt = combinePrompts2(systemPrompt, customPrompt, agent);
58736
+ return {
58737
+ sessionId: session.id,
58738
+ session,
58739
+ /**
58740
+ * Query Codex via MCP protocol with event streaming
58741
+ */
58742
+ async *query(prompt, opts = {}) {
58743
+ let finalPrompt = prompt;
58744
+ if (!session.conversationId && fullPrompt) {
58745
+ finalPrompt = `${fullPrompt}
58746
+
58747
+ ${prompt}`;
58748
+ }
58749
+ const isFollowUp = session.conversationId !== null;
58750
+ const toolName = isFollowUp ? "codex-reply" : "codex";
58751
+ const toolArgs = { prompt: finalPrompt };
58752
+ if (isFollowUp) {
58753
+ toolArgs.conversationId = session.conversationId;
58754
+ if (debug) {
58755
+ console.log(`[DEBUG] Follow-up with conversationId: ${session.conversationId}`);
58756
+ }
58757
+ } else {
58758
+ if (model) {
58759
+ toolArgs.model = model;
58760
+ }
58761
+ if (mcpServerUrl && mcpServerName) {
58762
+ toolArgs.config = {
58763
+ mcp_servers: {
58764
+ [mcpServerName]: { url: mcpServerUrl }
58765
+ }
58766
+ };
58767
+ }
58768
+ if (debug) {
58769
+ console.log(`[DEBUG] Initial query with tool: ${toolName}`);
58770
+ }
58771
+ }
58772
+ try {
58773
+ const reqId = requestId + 1;
58774
+ let fullResponse = "";
58775
+ let gotSessionId = false;
58776
+ const eventPromise = new Promise((resolve6) => {
58777
+ eventHandlers.set(reqId, (eventParams) => {
58778
+ const msg = eventParams.msg;
58779
+ if (msg.type === "session_configured" && msg.session_id && !gotSessionId) {
58780
+ session.setConversationId(msg.session_id);
58781
+ gotSessionId = true;
58782
+ }
58783
+ if (msg.type === "raw_response_item" && msg.item?.role === "assistant") {
58784
+ const content = msg.item.content;
58785
+ if (Array.isArray(content)) {
58786
+ for (const part of content) {
58787
+ if (part.type === "text" && part.text) {
58788
+ fullResponse += part.text;
58789
+ }
58790
+ }
58791
+ }
58792
+ }
58793
+ });
58794
+ setTimeout(() => {
58795
+ eventHandlers.delete(reqId);
58796
+ resolve6();
58797
+ }, 6e5);
58798
+ });
58799
+ const resultPromise = sendRequest("tools/call", {
58800
+ name: toolName,
58801
+ arguments: toolArgs
58802
+ });
58803
+ const result = await resultPromise;
58804
+ eventHandlers.delete(reqId);
58805
+ if (result && result.content && Array.isArray(result.content)) {
58806
+ for (const item of result.content) {
58807
+ if (item.type === "text" && item.text) {
58808
+ yield {
58809
+ type: "text",
58810
+ content: item.text
58811
+ };
58812
+ fullResponse = item.text;
58813
+ }
58814
+ }
58815
+ }
58816
+ if (fullResponse && (!result.content || result.content.length === 0)) {
58817
+ yield {
58818
+ type: "text",
58819
+ content: fullResponse
58820
+ };
58821
+ }
58822
+ session.incrementMessageCount();
58823
+ yield {
58824
+ type: "metadata",
58825
+ data: {
58826
+ sessionId: session.id,
58827
+ conversationId: session.conversationId,
58828
+ messageCount: session.messageCount
58829
+ }
58830
+ };
58831
+ } catch (error) {
58832
+ if (debug) {
58833
+ console.error("[DEBUG] Codex query error:", error);
58834
+ }
58835
+ yield {
58836
+ type: "error",
58837
+ error
58838
+ };
58839
+ }
58840
+ },
58841
+ /**
58842
+ * Get session info
58843
+ */
58844
+ getSession() {
58845
+ return session.getInfo();
58846
+ },
58847
+ /**
58848
+ * Clean up resources
58849
+ */
58850
+ async close() {
58851
+ try {
58852
+ if (stdoutReader) {
58853
+ stdoutReader.close();
58854
+ if (debug) {
58855
+ console.log("[DEBUG] Closed stdout reader");
58856
+ }
58857
+ }
58858
+ pendingRequests.clear();
58859
+ eventHandlers.clear();
58860
+ if (codexProcess && !codexProcess.killed) {
58861
+ codexProcess.kill();
58862
+ if (debug) {
58863
+ console.log("[DEBUG] Killed Codex MCP server process");
58864
+ }
58865
+ }
58866
+ if (mcpServer) {
58867
+ await mcpServer.stop();
58868
+ if (debug) {
58869
+ console.log("[DEBUG] Stopped Probe MCP server");
58870
+ }
58871
+ }
58872
+ if (debug) {
58873
+ console.log("[DEBUG] Engine closed, session:", session.id);
58874
+ }
58875
+ } catch (error) {
58876
+ if (debug) {
58877
+ console.error("[DEBUG] Error during cleanup:", error.message);
58878
+ }
58879
+ }
58880
+ }
58881
+ };
58882
+ }
58883
+ function combinePrompts2(systemPrompt, customPrompt, agent) {
58884
+ if (!systemPrompt && customPrompt) {
58885
+ return customPrompt;
58886
+ }
58887
+ if (systemPrompt && customPrompt) {
58888
+ return systemPrompt + "\n\n## Additional Instructions\n" + customPrompt;
58889
+ }
58890
+ return systemPrompt || "";
58891
+ }
58892
+ var init_codex = __esm({
58893
+ "src/agent/engines/codex.js"() {
58894
+ "use strict";
58895
+ init_built_in_server();
58896
+ init_Session();
58897
+ }
58898
+ });
58899
+
58900
+ // src/agent/engines/enhanced-vercel.js
58901
+ var enhanced_vercel_exports = {};
58902
+ __export(enhanced_vercel_exports, {
58903
+ createEnhancedVercelEngine: () => createEnhancedVercelEngine
58904
+ });
58905
+ import { streamText } from "ai";
58906
+ function createEnhancedVercelEngine(agent) {
58907
+ return {
58908
+ /**
58909
+ * Query the model using existing Vercel AI SDK implementation
58910
+ * @param {string} prompt - The prompt to send
58911
+ * @param {Object} options - Additional options
58912
+ * @returns {AsyncIterable} Response stream
58913
+ */
58914
+ async *query(prompt, options = {}) {
58915
+ const systemMessage = await agent.getSystemMessage();
58916
+ const messages = [
58917
+ { role: "system", content: systemMessage },
58918
+ ...agent.history,
58919
+ { role: "user", content: prompt }
58920
+ ];
58921
+ const result = await agent.streamTextWithRetryAndFallback({
58922
+ model: agent.provider(agent.model),
58923
+ messages,
58924
+ maxTokens: options.maxTokens || agent.maxResponseTokens,
58925
+ temperature: options.temperature || 0.3,
58926
+ // Note: Vercel AI SDK doesn't use structured tools for XML format
58927
+ // The tools are embedded in the system prompt
58928
+ experimental_telemetry: options.telemetry
58929
+ });
58930
+ let fullContent = "";
58931
+ for await (const chunk of result.textStream) {
58932
+ fullContent += chunk;
58933
+ yield { type: "text", content: chunk };
58934
+ }
58935
+ const toolCalls = agent.parseXmlToolCalls ? agent.parseXmlToolCalls(fullContent) : null;
58936
+ if (toolCalls && toolCalls.length > 0) {
58937
+ yield { type: "tool_calls", toolCalls };
58938
+ }
58939
+ if (result.finishReason) {
58940
+ yield { type: "finish", reason: result.finishReason };
58941
+ }
58942
+ },
58943
+ /**
58944
+ * Get available tools for this engine
58945
+ */
58946
+ getTools() {
58947
+ return agent.toolImplementations || {};
58948
+ },
58949
+ /**
58950
+ * Get system prompt for this engine
58951
+ */
58952
+ async getSystemPrompt() {
58953
+ return agent.getSystemMessage();
58954
+ },
58955
+ /**
58956
+ * Optional cleanup
58957
+ */
58958
+ async close() {
58959
+ }
58960
+ };
58961
+ }
58962
+ var init_enhanced_vercel = __esm({
58963
+ "src/agent/engines/enhanced-vercel.js"() {
58964
+ "use strict";
58965
+ }
58966
+ });
58967
+
57383
58968
  // src/agent/ProbeAgent.js
57384
58969
  var ProbeAgent_exports = {};
57385
58970
  __export(ProbeAgent_exports, {
@@ -57390,9 +58975,9 @@ import { createAnthropic as createAnthropic2 } from "@ai-sdk/anthropic";
57390
58975
  import { createOpenAI as createOpenAI2 } from "@ai-sdk/openai";
57391
58976
  import { createGoogleGenerativeAI as createGoogleGenerativeAI2 } from "@ai-sdk/google";
57392
58977
  import { createAmazonBedrock as createAmazonBedrock2 } from "@ai-sdk/amazon-bedrock";
57393
- import { streamText } from "ai";
57394
- import { randomUUID as randomUUID4 } from "crypto";
57395
- import { EventEmitter as EventEmitter3 } from "events";
58978
+ import { streamText as streamText2 } from "ai";
58979
+ import { randomUUID as randomUUID5 } from "crypto";
58980
+ import { EventEmitter as EventEmitter5 } from "events";
57396
58981
  import { existsSync as existsSync5 } from "fs";
57397
58982
  import { readFile, stat } from "fs/promises";
57398
58983
  import { resolve as resolve4, isAbsolute as isAbsolute2, dirname as dirname4 } from "path";
@@ -57411,6 +58996,7 @@ var init_ProbeAgent = __esm({
57411
58996
  init_index();
57412
58997
  init_schemaUtils();
57413
58998
  init_xmlParsingUtils();
58999
+ init_prompts();
57414
59000
  init_mcp();
57415
59001
  init_RetryManager();
57416
59002
  init_FallbackManager();
@@ -57432,6 +59018,7 @@ var init_ProbeAgent = __esm({
57432
59018
  * @param {Object} options - Configuration options
57433
59019
  * @param {string} [options.sessionId] - Optional session ID
57434
59020
  * @param {string} [options.customPrompt] - Custom prompt to replace the default system message
59021
+ * @param {string} [options.systemPrompt] - Alias for customPrompt; takes precedence when both are provided
57435
59022
  * @param {string} [options.promptType] - Predefined prompt type (architect, code-review, support)
57436
59023
  * @param {boolean} [options.allowEdit=false] - Allow the use of the 'implement' tool
57437
59024
  * @param {boolean} [options.enableDelegate=false] - Enable the delegate tool for task distribution to subagents
@@ -57466,8 +59053,8 @@ var init_ProbeAgent = __esm({
57466
59053
  * @param {number} [options.fallback.maxTotalAttempts=10] - Maximum total attempts across all providers
57467
59054
  */
57468
59055
  constructor(options = {}) {
57469
- this.sessionId = options.sessionId || randomUUID4();
57470
- this.customPrompt = options.customPrompt || null;
59056
+ this.sessionId = options.sessionId || randomUUID5();
59057
+ this.customPrompt = options.systemPrompt || options.customPrompt || null;
57471
59058
  this.promptType = options.promptType || "code-explorer";
57472
59059
  this.allowEdit = !!options.allowEdit;
57473
59060
  this.enableDelegate = !!options.enableDelegate;
@@ -57517,7 +59104,7 @@ var init_ProbeAgent = __esm({
57517
59104
  this.history = [];
57518
59105
  this.pendingImages = /* @__PURE__ */ new Map();
57519
59106
  this.currentImages = [];
57520
- this.events = new EventEmitter3();
59107
+ this.events = new EventEmitter5();
57521
59108
  this.enableMcp = !!options.enableMcp || process.env.ENABLE_MCP === "1";
57522
59109
  this.mcpConfigPath = options.mcpConfigPath || null;
57523
59110
  this.mcpConfig = options.mcpConfig || null;
@@ -57528,6 +59115,7 @@ var init_ProbeAgent = __esm({
57528
59115
  this.retryManager = null;
57529
59116
  this.fallbackConfig = options.fallback || null;
57530
59117
  this.fallbackManager = null;
59118
+ this.engine = null;
57531
59119
  this.initializeModel();
57532
59120
  }
57533
59121
  /**
@@ -57590,6 +59178,33 @@ var init_ProbeAgent = __esm({
57590
59178
  * This method initializes MCP and merges MCP tools into the tool list, and loads history from storage
57591
59179
  */
57592
59180
  async initialize() {
59181
+ if (!this.provider && !this.clientApiProvider && this.apiType !== "claude-code" && this.apiType !== "codex") {
59182
+ if (this.apiType === "uninitialized") {
59183
+ const claudeAvailable = await this.isClaudeCommandAvailable();
59184
+ const codexAvailable = await this.isCodexCommandAvailable();
59185
+ if (claudeAvailable) {
59186
+ if (this.debug) {
59187
+ console.log("[DEBUG] No API keys found, but claude command detected");
59188
+ console.log("[DEBUG] Auto-switching to claude-code provider");
59189
+ }
59190
+ this.clientApiProvider = "claude-code";
59191
+ this.provider = null;
59192
+ this.model = this.clientApiModel || "claude-3-5-sonnet-20241022";
59193
+ this.apiType = "claude-code";
59194
+ } else if (codexAvailable) {
59195
+ if (this.debug) {
59196
+ console.log("[DEBUG] No API keys found, but codex command detected");
59197
+ console.log("[DEBUG] Auto-switching to codex provider");
59198
+ }
59199
+ this.clientApiProvider = "codex";
59200
+ this.provider = null;
59201
+ this.model = this.clientApiModel || "gpt-4o";
59202
+ this.apiType = "codex";
59203
+ } else {
59204
+ throw new Error("No API key provided and neither claude nor codex command 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\n3. Install codex command from https://openai.com/codex");
59205
+ }
59206
+ }
59207
+ }
57593
59208
  try {
57594
59209
  const history = await this.storageAdapter.loadHistory(this.sessionId);
57595
59210
  this.history = history;
@@ -57706,6 +59321,40 @@ var init_ProbeAgent = __esm({
57706
59321
  console.error("[DEBUG] ========================================\n");
57707
59322
  }
57708
59323
  }
59324
+ /**
59325
+ * Check if claude command is available on the system
59326
+ * Uses execFile instead of exec to avoid shell injection risks
59327
+ * @returns {Promise<boolean>} True if claude command is available
59328
+ * @private
59329
+ */
59330
+ async isClaudeCommandAvailable() {
59331
+ try {
59332
+ const { execFile: execFile3 } = await import("child_process");
59333
+ const { promisify: promisify8 } = await import("util");
59334
+ const execFileAsync3 = promisify8(execFile3);
59335
+ await execFileAsync3("claude", ["--version"], { timeout: 5e3 });
59336
+ return true;
59337
+ } catch (error) {
59338
+ return false;
59339
+ }
59340
+ }
59341
+ /**
59342
+ * Check if codex command is available on the system
59343
+ * Uses execFile instead of exec to avoid shell injection risks
59344
+ * @returns {Promise<boolean>} True if codex command is available
59345
+ * @private
59346
+ */
59347
+ async isCodexCommandAvailable() {
59348
+ try {
59349
+ const { execFile: execFile3 } = await import("child_process");
59350
+ const { promisify: promisify8 } = await import("util");
59351
+ const execFileAsync3 = promisify8(execFile3);
59352
+ await execFileAsync3("codex", ["--version"], { timeout: 5e3 });
59353
+ return true;
59354
+ } catch (error) {
59355
+ return false;
59356
+ }
59357
+ }
57709
59358
  /**
57710
59359
  * Initialize the AI model based on available API keys and forced provider setting
57711
59360
  */
@@ -57715,6 +59364,29 @@ var init_ProbeAgent = __esm({
57715
59364
  this.initializeMockModel(modelName);
57716
59365
  return;
57717
59366
  }
59367
+ if (this.clientApiProvider === "claude-code" || process.env.USE_CLAUDE_CODE === "true") {
59368
+ this.provider = null;
59369
+ this.model = modelName || "claude-3-5-sonnet-20241022";
59370
+ this.apiType = "claude-code";
59371
+ if (this.debug) {
59372
+ console.log("[DEBUG] Claude Code engine selected - will use built-in access if available");
59373
+ }
59374
+ return;
59375
+ }
59376
+ if (this.clientApiProvider === "codex" || process.env.USE_CODEX === "true") {
59377
+ this.provider = null;
59378
+ this.model = modelName || null;
59379
+ this.apiType = "codex";
59380
+ if (this.debug) {
59381
+ console.log("[DEBUG] Codex CLI engine selected - will use built-in access if available");
59382
+ if (this.model) {
59383
+ console.log(`[DEBUG] Using model: ${this.model}`);
59384
+ } else {
59385
+ console.log("[DEBUG] Using Codex account default model");
59386
+ }
59387
+ }
59388
+ return;
59389
+ }
57718
59390
  const anthropicApiKey = process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN;
57719
59391
  const openaiApiKey = process.env.OPENAI_API_KEY;
57720
59392
  const googleApiKey = process.env.GOOGLE_GENERATIVE_AI_API_KEY || process.env.GOOGLE_API_KEY;
@@ -57772,7 +59444,10 @@ var init_ProbeAgent = __esm({
57772
59444
  this.initializeBedrockModel(awsAccessKeyId, awsSecretAccessKey, awsRegion, awsSessionToken, awsApiKey, awsBedrockBaseUrl, modelName);
57773
59445
  this.initializeFallbackManager("bedrock", modelName);
57774
59446
  } 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.");
59447
+ this.apiType = "uninitialized";
59448
+ if (this.debug) {
59449
+ console.log("[DEBUG] No API keys found - will check for claude command in initialize()");
59450
+ }
57776
59451
  }
57777
59452
  }
57778
59453
  /**
@@ -57835,6 +59510,82 @@ var init_ProbeAgent = __esm({
57835
59510
  * @private
57836
59511
  */
57837
59512
  async streamTextWithRetryAndFallback(options) {
59513
+ if (this.clientApiProvider === "claude-code" || process.env.USE_CLAUDE_CODE === "true") {
59514
+ try {
59515
+ const engine = await this.getEngine();
59516
+ if (engine && engine.query) {
59517
+ const userMessages = options.messages.filter(
59518
+ (m) => m.role === "user" && !m.content.includes("WARNING: You have reached the maximum tool iterations limit")
59519
+ );
59520
+ const lastUserMessage = userMessages[userMessages.length - 1];
59521
+ const prompt = lastUserMessage ? lastUserMessage.content : "";
59522
+ const engineOptions = {
59523
+ maxTokens: options.maxTokens,
59524
+ temperature: options.temperature,
59525
+ messages: options.messages,
59526
+ systemPrompt: options.messages.find((m) => m.role === "system")?.content
59527
+ };
59528
+ const engineStream = engine.query(prompt, engineOptions);
59529
+ async function* createTextStream() {
59530
+ for await (const message of engineStream) {
59531
+ if (message.type === "text" && message.content) {
59532
+ yield message.content;
59533
+ } else if (typeof message === "string") {
59534
+ yield message;
59535
+ }
59536
+ }
59537
+ }
59538
+ return {
59539
+ textStream: createTextStream(),
59540
+ usage: Promise.resolve({})
59541
+ // Engine should handle its own usage tracking
59542
+ // Add other streamText-compatible properties as needed
59543
+ };
59544
+ }
59545
+ } catch (error) {
59546
+ if (this.debug) {
59547
+ console.log(`[DEBUG] Failed to use Claude Code engine, falling back to Vercel:`, error.message);
59548
+ }
59549
+ }
59550
+ }
59551
+ if (this.clientApiProvider === "codex" || process.env.USE_CODEX === "true") {
59552
+ try {
59553
+ const engine = await this.getEngine();
59554
+ if (engine && engine.query) {
59555
+ const userMessages = options.messages.filter(
59556
+ (m) => m.role === "user" && !m.content.includes("WARNING: You have reached the maximum tool iterations limit")
59557
+ );
59558
+ const lastUserMessage = userMessages[userMessages.length - 1];
59559
+ const prompt = lastUserMessage ? lastUserMessage.content : "";
59560
+ const engineOptions = {
59561
+ maxTokens: options.maxTokens,
59562
+ temperature: options.temperature,
59563
+ messages: options.messages,
59564
+ systemPrompt: options.messages.find((m) => m.role === "system")?.content
59565
+ };
59566
+ const engineStream = engine.query(prompt, engineOptions);
59567
+ async function* createTextStream() {
59568
+ for await (const message of engineStream) {
59569
+ if (message.type === "text" && message.content) {
59570
+ yield message.content;
59571
+ } else if (typeof message === "string") {
59572
+ yield message;
59573
+ }
59574
+ }
59575
+ }
59576
+ return {
59577
+ textStream: createTextStream(),
59578
+ usage: Promise.resolve({})
59579
+ // Engine should handle its own usage tracking
59580
+ // Add other streamText-compatible properties as needed
59581
+ };
59582
+ }
59583
+ } catch (error) {
59584
+ if (this.debug) {
59585
+ console.log(`[DEBUG] Failed to use Codex engine, falling back to Vercel:`, error.message);
59586
+ }
59587
+ }
59588
+ }
57838
59589
  if (!this.retryManager) {
57839
59590
  this.retryManager = new RetryManager({
57840
59591
  maxRetries: this.retryConfig.maxRetries ?? 3,
@@ -57847,7 +59598,7 @@ var init_ProbeAgent = __esm({
57847
59598
  }
57848
59599
  if (!this.fallbackManager) {
57849
59600
  return await this.retryManager.executeWithRetry(
57850
- () => streamText(options),
59601
+ () => streamText2(options),
57851
59602
  {
57852
59603
  provider: this.apiType,
57853
59604
  model: this.model
@@ -57869,7 +59620,7 @@ var init_ProbeAgent = __esm({
57869
59620
  debug: this.debug
57870
59621
  });
57871
59622
  return await providerRetryManager.executeWithRetry(
57872
- () => streamText(fallbackOptions),
59623
+ () => streamText2(fallbackOptions),
57873
59624
  {
57874
59625
  provider: config.provider,
57875
59626
  model
@@ -57951,6 +59702,104 @@ var init_ProbeAgent = __esm({
57951
59702
  console.log(`Using AWS Bedrock API with model: ${this.model}${regionInfo} [Auth: ${authMethod}]${baseUrlInfo}`);
57952
59703
  }
57953
59704
  }
59705
+ /**
59706
+ * Get or create the AI engine based on configuration
59707
+ * @returns {Promise<Object>} Engine interface
59708
+ * @private
59709
+ */
59710
+ async getEngine() {
59711
+ if (this.engine) {
59712
+ return this.engine;
59713
+ }
59714
+ if (this.clientApiProvider === "claude-code" || process.env.USE_CLAUDE_CODE === "true") {
59715
+ try {
59716
+ const { createEnhancedClaudeCLIEngine: createEnhancedClaudeCLIEngine2 } = await Promise.resolve().then(() => (init_enhanced_claude_code(), enhanced_claude_code_exports));
59717
+ const systemPrompt = this.customPrompt || this.getClaudeNativeSystemPrompt();
59718
+ this.engine = await createEnhancedClaudeCLIEngine2({
59719
+ agent: this,
59720
+ // Pass reference to ProbeAgent for tool access
59721
+ systemPrompt,
59722
+ customPrompt: this.customPrompt,
59723
+ sessionId: this.options?.sessionId,
59724
+ debug: this.debug,
59725
+ allowedTools: this.allowedTools
59726
+ // Pass tool filtering configuration
59727
+ });
59728
+ if (this.debug) {
59729
+ console.log("[DEBUG] Using Claude Code engine with Probe tools");
59730
+ if (this.customPrompt) {
59731
+ console.log("[DEBUG] Using custom prompt/persona");
59732
+ }
59733
+ }
59734
+ return this.engine;
59735
+ } catch (error) {
59736
+ console.warn("[WARNING] Failed to load Claude Code engine:", error.message);
59737
+ console.warn("[WARNING] Falling back to Vercel AI SDK");
59738
+ this.clientApiProvider = null;
59739
+ }
59740
+ }
59741
+ if (this.clientApiProvider === "codex" || process.env.USE_CODEX === "true") {
59742
+ try {
59743
+ const { createCodexEngine: createCodexEngine2 } = await Promise.resolve().then(() => (init_codex(), codex_exports));
59744
+ const systemPrompt = this.customPrompt || this.getCodexNativeSystemPrompt();
59745
+ this.engine = await createCodexEngine2({
59746
+ agent: this,
59747
+ // Pass reference to ProbeAgent for tool access
59748
+ systemPrompt,
59749
+ customPrompt: this.customPrompt,
59750
+ sessionId: this.options?.sessionId,
59751
+ debug: this.debug,
59752
+ allowedTools: this.allowedTools,
59753
+ // Pass tool filtering configuration
59754
+ model: this.model
59755
+ // Pass model name (e.g., gpt-4o, o3, etc.)
59756
+ });
59757
+ if (this.debug) {
59758
+ console.log("[DEBUG] Using Codex CLI engine with Probe tools");
59759
+ if (this.customPrompt) {
59760
+ console.log("[DEBUG] Using custom prompt/persona");
59761
+ }
59762
+ }
59763
+ return this.engine;
59764
+ } catch (error) {
59765
+ console.warn("[WARNING] Failed to load Codex CLI engine:", error.message);
59766
+ console.warn("[WARNING] Falling back to Vercel AI SDK");
59767
+ this.clientApiProvider = null;
59768
+ }
59769
+ }
59770
+ const { createEnhancedVercelEngine: createEnhancedVercelEngine2 } = await Promise.resolve().then(() => (init_enhanced_vercel(), enhanced_vercel_exports));
59771
+ this.engine = createEnhancedVercelEngine2(this);
59772
+ if (this.debug) {
59773
+ console.log("[DEBUG] Using Vercel AI SDK engine");
59774
+ }
59775
+ return this.engine;
59776
+ }
59777
+ /**
59778
+ * Get session information including thread ID for resumability
59779
+ * @returns {Object} Session info with sessionId, threadId, messageCount
59780
+ */
59781
+ getSessionInfo() {
59782
+ if (this.engine && this.engine.getSession) {
59783
+ return this.engine.getSession();
59784
+ }
59785
+ return {
59786
+ id: this.sessionId,
59787
+ threadId: null,
59788
+ messageCount: 0
59789
+ };
59790
+ }
59791
+ /**
59792
+ * Close the agent and clean up resources (e.g., MCP servers)
59793
+ * @returns {Promise<void>}
59794
+ */
59795
+ async close() {
59796
+ if (this.engine && this.engine.close) {
59797
+ await this.engine.close();
59798
+ }
59799
+ if (this.mcpBridge) {
59800
+ this.mcpBridge = null;
59801
+ }
59802
+ }
57954
59803
  /**
57955
59804
  * Process assistant response content and detect/load image references
57956
59805
  * @param {string} content - The assistant's response content
@@ -58237,6 +60086,105 @@ var init_ProbeAgent = __esm({
58237
60086
  this.mcpBridge = null;
58238
60087
  }
58239
60088
  }
60089
+ /**
60090
+ * Get system prompt for Claude native engines (CLI/SDK) without XML formatting
60091
+ * These engines have native MCP support and don't need XML instructions
60092
+ */
60093
+ getClaudeNativeSystemPrompt() {
60094
+ let systemPrompt = "";
60095
+ if (this.customPrompt) {
60096
+ systemPrompt += this.customPrompt + "\n\n";
60097
+ } else if (this.promptType && predefinedPrompts[this.promptType]) {
60098
+ systemPrompt += predefinedPrompts[this.promptType] + "\n\n";
60099
+ } else {
60100
+ systemPrompt += predefinedPrompts["code-explorer"] + "\n\n";
60101
+ }
60102
+ systemPrompt += `You have access to powerful code search and analysis tools through MCP:
60103
+ - search: Find code patterns using semantic search
60104
+ - extract: Extract specific code sections with context
60105
+ - query: Use AST patterns for structural code matching
60106
+ - listFiles: Browse directory contents
60107
+ - searchFiles: Find files by name patterns`;
60108
+ if (this.enableBash) {
60109
+ systemPrompt += `
60110
+ - bash: Execute bash commands for system operations`;
60111
+ }
60112
+ systemPrompt += `
60113
+
60114
+ When exploring code:
60115
+ 1. Start with search to find relevant code patterns
60116
+ 2. Use extract to get detailed context when needed
60117
+ 3. Prefer focused, specific searches over broad queries
60118
+ 4. Combine multiple tools to build complete understanding`;
60119
+ if (this.allowedFolders && this.allowedFolders.length > 0) {
60120
+ systemPrompt += `
60121
+
60122
+ Workspace: ${this.allowedFolders.join(", ")}`;
60123
+ }
60124
+ if (this.fileList) {
60125
+ systemPrompt += `
60126
+
60127
+ # Repository Structure
60128
+ `;
60129
+ systemPrompt += `You are working with a repository located at: ${this.allowedFolders[0]}
60130
+
60131
+ `;
60132
+ systemPrompt += `Here's an overview of the repository structure (showing up to 100 most relevant files):
60133
+
60134
+ `;
60135
+ systemPrompt += "```\n" + this.fileList + "\n```\n";
60136
+ }
60137
+ return systemPrompt;
60138
+ }
60139
+ /**
60140
+ * Get system prompt for Codex CLI (similar to Claude but optimized for Codex)
60141
+ */
60142
+ getCodexNativeSystemPrompt() {
60143
+ let systemPrompt = "";
60144
+ if (this.customPrompt) {
60145
+ systemPrompt += this.customPrompt + "\n\n";
60146
+ } else if (this.promptType && predefinedPrompts[this.promptType]) {
60147
+ systemPrompt += predefinedPrompts[this.promptType] + "\n\n";
60148
+ } else {
60149
+ systemPrompt += predefinedPrompts["code-explorer"] + "\n\n";
60150
+ }
60151
+ systemPrompt += `You have access to powerful code search and analysis tools through MCP:
60152
+ - search: Find code patterns using semantic search
60153
+ - extract: Extract specific code sections with context
60154
+ - query: Use AST patterns for structural code matching
60155
+ - listFiles: Browse directory contents
60156
+ - searchFiles: Find files by name patterns`;
60157
+ if (this.enableBash) {
60158
+ systemPrompt += `
60159
+ - bash: Execute bash commands for system operations`;
60160
+ }
60161
+ systemPrompt += `
60162
+
60163
+ When exploring code:
60164
+ 1. Start with search to find relevant code patterns
60165
+ 2. Use extract to get detailed context when needed
60166
+ 3. Prefer focused, specific searches over broad queries
60167
+ 4. Combine multiple tools to build complete understanding`;
60168
+ if (this.allowedFolders && this.allowedFolders.length > 0) {
60169
+ systemPrompt += `
60170
+
60171
+ Workspace: ${this.allowedFolders.join(", ")}`;
60172
+ }
60173
+ if (this.fileList) {
60174
+ systemPrompt += `
60175
+
60176
+ # Repository Structure
60177
+ `;
60178
+ systemPrompt += `You are working with a repository located at: ${this.allowedFolders[0]}
60179
+
60180
+ `;
60181
+ systemPrompt += `Here's an overview of the repository structure (showing up to 100 most relevant files):
60182
+
60183
+ `;
60184
+ systemPrompt += "```\n" + this.fileList + "\n```\n";
60185
+ }
60186
+ return systemPrompt;
60187
+ }
58240
60188
  /**
58241
60189
  * Get the system message with instructions for the AI (XML Tool Format)
58242
60190
  */
@@ -58394,7 +60342,7 @@ Follow these instructions carefully:
58394
60342
  - Use 'create' for new files or complete file rewrites` : ""}
58395
60343
  </instructions>
58396
60344
  `;
58397
- const predefinedPrompts = {
60345
+ const predefinedPrompts2 = {
58398
60346
  "code-explorer": `You are ProbeChat Code Explorer, a specialized AI assistant focused on helping developers, product managers, and QAs understand and navigate codebases. Your primary function is to answer questions based on code, explain how systems work, and provide insights into code functionality using the provided code analysis tools.
58399
60347
 
58400
60348
  When exploring code:
@@ -58450,14 +60398,14 @@ When troubleshooting:
58450
60398
  if (this.debug) {
58451
60399
  console.log(`[DEBUG] Using custom prompt`);
58452
60400
  }
58453
- } else if (this.promptType && predefinedPrompts[this.promptType]) {
58454
- systemMessage = "<role>" + predefinedPrompts[this.promptType] + "</role>";
60401
+ } else if (this.promptType && predefinedPrompts2[this.promptType]) {
60402
+ systemMessage = "<role>" + predefinedPrompts2[this.promptType] + "</role>";
58455
60403
  if (this.debug) {
58456
60404
  console.log(`[DEBUG] Using predefined prompt: ${this.promptType}`);
58457
60405
  }
58458
60406
  systemMessage += commonInstructions;
58459
60407
  } else {
58460
- systemMessage = "<role>" + predefinedPrompts["code-explorer"] + "</role>";
60408
+ systemMessage = "<role>" + predefinedPrompts2["code-explorer"] + "</role>";
58461
60409
  if (this.debug) {
58462
60410
  console.log(`[DEBUG] Using default prompt: code explorer`);
58463
60411
  }
@@ -58597,6 +60545,112 @@ You are working with a repository located at: ${searchDirectory}
58597
60545
  let finalResult = "I was unable to complete your request due to reaching the maximum number of tool iterations.";
58598
60546
  const baseMaxIterations = this.maxIterations || MAX_TOOL_ITERATIONS;
58599
60547
  const maxIterations = options.schema ? baseMaxIterations + 4 : baseMaxIterations;
60548
+ const isClaudeCode = this.clientApiProvider === "claude-code" || process.env.USE_CLAUDE_CODE === "true";
60549
+ const isCodex = this.clientApiProvider === "codex" || process.env.USE_CODEX === "true";
60550
+ if (isClaudeCode) {
60551
+ if (this.debug) {
60552
+ console.log(`[DEBUG] Using Claude Code engine - bypassing tool loop (black box mode)`);
60553
+ console.log(`[DEBUG] Sending question directly to Claude Code: ${message.substring(0, 100)}...`);
60554
+ }
60555
+ try {
60556
+ const engine = await this.getEngine();
60557
+ if (engine && engine.query) {
60558
+ let assistantResponseContent = "";
60559
+ let toolBatch = null;
60560
+ for await (const chunk of engine.query(message, options)) {
60561
+ if (chunk.type === "text" && chunk.content) {
60562
+ assistantResponseContent += chunk.content;
60563
+ if (options.onStream) {
60564
+ options.onStream(chunk.content);
60565
+ }
60566
+ } else if (chunk.type === "toolBatch" && chunk.tools) {
60567
+ toolBatch = chunk.tools;
60568
+ if (this.debug) {
60569
+ console.log(`[DEBUG] Received batch of ${chunk.tools.length} tool events from Claude Code`);
60570
+ }
60571
+ } else if (chunk.type === "error") {
60572
+ throw chunk.error;
60573
+ }
60574
+ }
60575
+ if (toolBatch && toolBatch.length > 0 && this.events) {
60576
+ if (this.debug) {
60577
+ console.log(`[DEBUG] Emitting ${toolBatch.length} tool events from Claude Code batch`);
60578
+ }
60579
+ for (const toolEvent of toolBatch) {
60580
+ this.events.emit("toolCall", toolEvent);
60581
+ }
60582
+ }
60583
+ this.history.push(userMessage);
60584
+ this.history.push({
60585
+ role: "assistant",
60586
+ content: assistantResponseContent
60587
+ });
60588
+ await this.hooks.emit(HOOK_TYPES.COMPLETION, {
60589
+ sessionId: this.sessionId,
60590
+ prompt: message,
60591
+ response: assistantResponseContent
60592
+ });
60593
+ return assistantResponseContent;
60594
+ }
60595
+ } catch (error) {
60596
+ if (this.debug) {
60597
+ console.error("[DEBUG] Claude Code error:", error);
60598
+ }
60599
+ throw error;
60600
+ }
60601
+ }
60602
+ if (isCodex) {
60603
+ if (this.debug) {
60604
+ console.log(`[DEBUG] Using Codex engine - bypassing tool loop (black box mode)`);
60605
+ console.log(`[DEBUG] Sending question directly to Codex: ${message.substring(0, 100)}...`);
60606
+ }
60607
+ try {
60608
+ const engine = await this.getEngine();
60609
+ if (engine && engine.query) {
60610
+ let assistantResponseContent = "";
60611
+ let toolBatch = null;
60612
+ for await (const chunk of engine.query(message, options)) {
60613
+ if (chunk.type === "text" && chunk.content) {
60614
+ assistantResponseContent += chunk.content;
60615
+ if (options.onStream) {
60616
+ options.onStream(chunk.content);
60617
+ }
60618
+ } else if (chunk.type === "toolBatch" && chunk.tools) {
60619
+ toolBatch = chunk.tools;
60620
+ if (this.debug) {
60621
+ console.log(`[DEBUG] Received batch of ${chunk.tools.length} tool events from Codex`);
60622
+ }
60623
+ } else if (chunk.type === "error") {
60624
+ throw chunk.error;
60625
+ }
60626
+ }
60627
+ if (toolBatch && toolBatch.length > 0 && this.events) {
60628
+ if (this.debug) {
60629
+ console.log(`[DEBUG] Emitting ${toolBatch.length} tool events from Codex batch`);
60630
+ }
60631
+ for (const toolEvent of toolBatch) {
60632
+ this.events.emit("toolCall", toolEvent);
60633
+ }
60634
+ }
60635
+ this.history.push(userMessage);
60636
+ this.history.push({
60637
+ role: "assistant",
60638
+ content: assistantResponseContent
60639
+ });
60640
+ await this.hooks.emit(HOOK_TYPES.COMPLETION, {
60641
+ sessionId: this.sessionId,
60642
+ prompt: message,
60643
+ response: assistantResponseContent
60644
+ });
60645
+ return assistantResponseContent;
60646
+ }
60647
+ } catch (error) {
60648
+ if (this.debug) {
60649
+ console.error("[DEBUG] Codex error:", error);
60650
+ }
60651
+ throw error;
60652
+ }
60653
+ }
58600
60654
  if (this.debug) {
58601
60655
  console.log(`[DEBUG] Starting agentic flow for question: ${message.substring(0, 100)}...`);
58602
60656
  if (options.schema) {
@@ -58655,7 +60709,7 @@ You are working with a repository located at: ${searchDirectory}
58655
60709
  const executeAIRequest = async () => {
58656
60710
  const messagesForAI = this.prepareMessagesWithImages(currentMessages);
58657
60711
  const result = await this.streamTextWithRetryAndFallback({
58658
- model: this.provider(this.model),
60712
+ model: this.provider ? this.provider(this.model) : this.model,
58659
60713
  messages: messagesForAI,
58660
60714
  maxTokens: maxResponseTokens,
58661
60715
  temperature: 0.3
@@ -59477,7 +61531,7 @@ Convert your previous response content into actual JSON data that follows this s
59477
61531
  */
59478
61532
  clone(options = {}) {
59479
61533
  const {
59480
- sessionId = randomUUID4(),
61534
+ sessionId = randomUUID5(),
59481
61535
  stripInternalMessages = true,
59482
61536
  keepSystemMessage = true,
59483
61537
  deepCopy = true,
@@ -59686,20 +61740,20 @@ import dotenv3 from "dotenv";
59686
61740
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
59687
61741
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
59688
61742
  import {
59689
- CallToolRequestSchema,
61743
+ CallToolRequestSchema as CallToolRequestSchema2,
59690
61744
  ErrorCode as ErrorCode2,
59691
61745
  InitializeRequestSchema,
59692
- ListToolsRequestSchema,
61746
+ ListToolsRequestSchema as ListToolsRequestSchema2,
59693
61747
  McpError
59694
61748
  } from "@modelcontextprotocol/sdk/types.js";
59695
61749
  import { readFileSync as readFileSync2, existsSync as existsSync6 } from "fs";
59696
61750
  import { resolve as resolve5 } from "path";
59697
61751
 
59698
61752
  // src/agent/acp/server.js
59699
- import { randomUUID as randomUUID5 } from "crypto";
61753
+ import { randomUUID as randomUUID6 } from "crypto";
59700
61754
 
59701
61755
  // src/agent/acp/connection.js
59702
- import { EventEmitter as EventEmitter4 } from "events";
61756
+ import { EventEmitter as EventEmitter6 } from "events";
59703
61757
 
59704
61758
  // src/agent/acp/types.js
59705
61759
  var ACP_PROTOCOL_VERSION = "1";
@@ -59816,7 +61870,7 @@ function validateMessage(message) {
59816
61870
  }
59817
61871
 
59818
61872
  // src/agent/acp/connection.js
59819
- var ACPConnection = class extends EventEmitter4 {
61873
+ var ACPConnection = class extends EventEmitter6 {
59820
61874
  constructor(inputStream = process.stdin, outputStream = process.stdout) {
59821
61875
  super();
59822
61876
  this.inputStream = inputStream;
@@ -60188,7 +62242,7 @@ var ACPServer = class {
60188
62242
  * Handle new session request
60189
62243
  */
60190
62244
  async handleNewSession(params) {
60191
- const sessionId = params?.sessionId || randomUUID5();
62245
+ const sessionId = params?.sessionId || randomUUID6();
60192
62246
  const mode = params?.mode || SessionMode.NORMAL;
60193
62247
  const session = new ACPSession(sessionId, mode);
60194
62248
  this.sessions.set(sessionId, session);
@@ -60360,7 +62414,7 @@ var ACPServer = class {
60360
62414
  };
60361
62415
 
60362
62416
  // src/agent/acp/tools.js
60363
- import { randomUUID as randomUUID6 } from "crypto";
62417
+ import { randomUUID as randomUUID7 } from "crypto";
60364
62418
 
60365
62419
  // src/agent/index.js
60366
62420
  dotenv3.config();
@@ -60655,7 +62709,7 @@ var ProbeAgentMcpServer = class {
60655
62709
  }
60656
62710
  };
60657
62711
  });
60658
- this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
62712
+ this.server.setRequestHandler(ListToolsRequestSchema2, async () => ({
60659
62713
  tools: [
60660
62714
  {
60661
62715
  name: "search_code",
@@ -60690,7 +62744,7 @@ var ProbeAgentMcpServer = class {
60690
62744
  }
60691
62745
  ]
60692
62746
  }));
60693
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
62747
+ this.server.setRequestHandler(CallToolRequestSchema2, async (request) => {
60694
62748
  if (request.params.name !== "search_code") {
60695
62749
  throw new McpError(
60696
62750
  ErrorCode2.MethodNotFound,