@probelabs/probe 0.6.0-rc224 → 0.6.0-rc226

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/bin/binaries/probe-v0.6.0-rc226-aarch64-apple-darwin.tar.gz +0 -0
  2. package/bin/binaries/probe-v0.6.0-rc226-aarch64-unknown-linux-musl.tar.gz +0 -0
  3. package/bin/binaries/probe-v0.6.0-rc226-x86_64-apple-darwin.tar.gz +0 -0
  4. package/bin/binaries/probe-v0.6.0-rc226-x86_64-pc-windows-msvc.zip +0 -0
  5. package/bin/binaries/probe-v0.6.0-rc226-x86_64-unknown-linux-musl.tar.gz +0 -0
  6. package/build/agent/ProbeAgent.js +361 -36
  7. package/build/agent/index.js +570 -57
  8. package/build/agent/mcp/xmlBridge.js +10 -7
  9. package/build/agent/simpleTelemetry.js +198 -0
  10. package/build/agent/tools.js +8 -5
  11. package/build/tools/analyzeAll.js +6 -1
  12. package/build/tools/bash.js +18 -3
  13. package/build/tools/edit.js +19 -10
  14. package/build/tools/vercel.js +17 -7
  15. package/build/utils/path-validation.js +148 -1
  16. package/cjs/agent/ProbeAgent.cjs +392 -56
  17. package/cjs/agent/simpleTelemetry.cjs +177 -0
  18. package/cjs/index.cjs +569 -56
  19. package/package.json +1 -1
  20. package/src/agent/ProbeAgent.js +361 -36
  21. package/src/agent/mcp/xmlBridge.js +10 -7
  22. package/src/agent/simpleTelemetry.js +198 -0
  23. package/src/agent/tools.js +8 -5
  24. package/src/tools/analyzeAll.js +6 -1
  25. package/src/tools/bash.js +18 -3
  26. package/src/tools/edit.js +19 -10
  27. package/src/tools/vercel.js +17 -7
  28. package/src/utils/path-validation.js +148 -1
  29. package/bin/binaries/probe-v0.6.0-rc224-aarch64-apple-darwin.tar.gz +0 -0
  30. package/bin/binaries/probe-v0.6.0-rc224-aarch64-unknown-linux-musl.tar.gz +0 -0
  31. package/bin/binaries/probe-v0.6.0-rc224-x86_64-apple-darwin.tar.gz +0 -0
  32. package/bin/binaries/probe-v0.6.0-rc224-x86_64-pc-windows-msvc.zip +0 -0
  33. package/bin/binaries/probe-v0.6.0-rc224-x86_64-unknown-linux-musl.tar.gz +0 -0
package/cjs/index.cjs CHANGED
@@ -1645,6 +1645,25 @@ var init_error_types = __esm({
1645
1645
  });
1646
1646
 
1647
1647
  // src/utils/path-validation.js
1648
+ function safeRealpath(inputPath) {
1649
+ try {
1650
+ return (0, import_fs3.realpathSync)(inputPath);
1651
+ } catch (error2) {
1652
+ const normalized = import_path4.default.normalize(inputPath);
1653
+ const parts = normalized.split(import_path4.default.sep);
1654
+ for (let i5 = parts.length - 1; i5 >= 0; i5--) {
1655
+ const ancestorPath = parts.slice(0, i5).join(import_path4.default.sep) || import_path4.default.sep;
1656
+ try {
1657
+ const resolvedAncestor = (0, import_fs3.realpathSync)(ancestorPath);
1658
+ const remainingParts = parts.slice(i5);
1659
+ return import_path4.default.join(resolvedAncestor, ...remainingParts);
1660
+ } catch (ancestorError) {
1661
+ continue;
1662
+ }
1663
+ }
1664
+ return normalized;
1665
+ }
1666
+ }
1648
1667
  async function validateCwdPath(inputPath, defaultPath = process.cwd()) {
1649
1668
  const targetPath = inputPath || defaultPath;
1650
1669
  const normalizedPath = import_path4.default.normalize(import_path4.default.resolve(targetPath));
@@ -1677,6 +1696,53 @@ async function validateCwdPath(inputPath, defaultPath = process.cwd()) {
1677
1696
  }
1678
1697
  return normalizedPath;
1679
1698
  }
1699
+ function getCommonPrefix(folders) {
1700
+ if (!folders || folders.length === 0) {
1701
+ return process.cwd();
1702
+ }
1703
+ if (folders.length === 1) {
1704
+ return safeRealpath(folders[0]);
1705
+ }
1706
+ const normalized = folders.map((f5) => safeRealpath(f5));
1707
+ const segments = normalized.map((f5) => f5.split(import_path4.default.sep));
1708
+ const minLen = Math.min(...segments.map((s5) => s5.length));
1709
+ const commonSegments = [];
1710
+ for (let i5 = 0; i5 < minLen; i5++) {
1711
+ const segment = segments[0][i5];
1712
+ if (segments.every((s5) => s5[i5] === segment)) {
1713
+ commonSegments.push(segment);
1714
+ } else {
1715
+ break;
1716
+ }
1717
+ }
1718
+ if (commonSegments.length === 0) {
1719
+ return normalized[0];
1720
+ }
1721
+ if (commonSegments.length === 1 && /^[a-zA-Z]:$/.test(commonSegments[0])) {
1722
+ return normalized[0];
1723
+ }
1724
+ if (commonSegments.length === 1 && commonSegments[0] === "") {
1725
+ return normalized[0];
1726
+ }
1727
+ return commonSegments.join(import_path4.default.sep);
1728
+ }
1729
+ function toRelativePath(absolutePath, workspaceRoot) {
1730
+ if (!absolutePath || !workspaceRoot) {
1731
+ return absolutePath;
1732
+ }
1733
+ let normalized = safeRealpath(absolutePath);
1734
+ let normalizedRoot = safeRealpath(workspaceRoot);
1735
+ while (normalizedRoot.length > 1 && normalizedRoot.endsWith(import_path4.default.sep)) {
1736
+ normalizedRoot = normalizedRoot.slice(0, -1);
1737
+ }
1738
+ if (normalized === normalizedRoot) {
1739
+ return ".";
1740
+ }
1741
+ if (normalized.startsWith(normalizedRoot + import_path4.default.sep)) {
1742
+ return import_path4.default.relative(normalizedRoot, normalized);
1743
+ }
1744
+ return absolutePath;
1745
+ }
1680
1746
  var import_path4, import_fs3;
1681
1747
  var init_path_validation = __esm({
1682
1748
  "src/utils/path-validation.js"() {
@@ -37304,21 +37370,24 @@ var init_zod = __esm({
37304
37370
  // src/tools/edit.js
37305
37371
  function isPathAllowed(filePath, allowedFolders) {
37306
37372
  if (!allowedFolders || allowedFolders.length === 0) {
37307
- const resolvedPath3 = (0, import_path5.resolve)(filePath);
37308
- const cwd = (0, import_path5.resolve)(process.cwd());
37373
+ const resolvedPath3 = safeRealpath(filePath);
37374
+ const cwd = safeRealpath(process.cwd());
37309
37375
  return resolvedPath3 === cwd || resolvedPath3.startsWith(cwd + import_path5.sep);
37310
37376
  }
37311
- const resolvedPath2 = (0, import_path5.resolve)(filePath);
37377
+ const resolvedPath2 = safeRealpath(filePath);
37312
37378
  return allowedFolders.some((folder) => {
37313
- const allowedPath = (0, import_path5.resolve)(folder);
37379
+ const allowedPath = safeRealpath(folder);
37314
37380
  return resolvedPath2 === allowedPath || resolvedPath2.startsWith(allowedPath + import_path5.sep);
37315
37381
  });
37316
37382
  }
37317
37383
  function parseFileToolOptions(options = {}) {
37384
+ const allowedFolders = options.allowedFolders || [];
37318
37385
  return {
37319
37386
  debug: options.debug || false,
37320
- allowedFolders: options.allowedFolders || [],
37321
- cwd: options.cwd
37387
+ allowedFolders,
37388
+ cwd: options.cwd,
37389
+ // Consistent fallback chain: workspaceRoot > cwd > allowedFolders[0] > process.cwd()
37390
+ workspaceRoot: options.workspaceRoot || options.cwd || allowedFolders.length > 0 && allowedFolders[0] || process.cwd()
37322
37391
  };
37323
37392
  }
37324
37393
  var import_ai, import_fs4, import_path5, import_fs5, editTool, createTool, editSchema, createSchema, editDescription, createDescription, editToolDefinition, createToolDefinition;
@@ -37329,8 +37398,9 @@ var init_edit = __esm({
37329
37398
  import_fs4 = require("fs");
37330
37399
  import_path5 = require("path");
37331
37400
  import_fs5 = require("fs");
37401
+ init_path_validation();
37332
37402
  editTool = (options = {}) => {
37333
- const { debug, allowedFolders, cwd } = parseFileToolOptions(options);
37403
+ const { debug, allowedFolders, cwd, workspaceRoot } = parseFileToolOptions(options);
37334
37404
  return (0, import_ai.tool)({
37335
37405
  name: "edit",
37336
37406
  description: `Edit files using exact string replacement (Claude Code style).
@@ -37386,7 +37456,8 @@ Important:
37386
37456
  console.error(`[Edit] Attempting to edit file: ${resolvedPath2}`);
37387
37457
  }
37388
37458
  if (!isPathAllowed(resolvedPath2, allowedFolders)) {
37389
- return `Error editing file: Permission denied - ${file_path} is outside allowed directories`;
37459
+ const relativePath = toRelativePath(resolvedPath2, workspaceRoot);
37460
+ return `Error editing file: Permission denied - ${relativePath} is outside allowed directories`;
37390
37461
  }
37391
37462
  if (!(0, import_fs5.existsSync)(resolvedPath2)) {
37392
37463
  return `Error editing file: File not found - ${file_path}`;
@@ -37422,7 +37493,7 @@ Important:
37422
37493
  });
37423
37494
  };
37424
37495
  createTool = (options = {}) => {
37425
- const { debug, allowedFolders, cwd } = parseFileToolOptions(options);
37496
+ const { debug, allowedFolders, cwd, workspaceRoot } = parseFileToolOptions(options);
37426
37497
  return (0, import_ai.tool)({
37427
37498
  name: "create",
37428
37499
  description: `Create new files with specified content.
@@ -37470,7 +37541,8 @@ Important:
37470
37541
  console.error(`[Create] Attempting to create file: ${resolvedPath2}`);
37471
37542
  }
37472
37543
  if (!isPathAllowed(resolvedPath2, allowedFolders)) {
37473
- return `Error creating file: Permission denied - ${file_path} is outside allowed directories`;
37544
+ const relativePath = toRelativePath(resolvedPath2, workspaceRoot);
37545
+ return `Error creating file: Permission denied - ${relativePath} is outside allowed directories`;
37474
37546
  }
37475
37547
  if ((0, import_fs5.existsSync)(resolvedPath2) && !overwrite) {
37476
37548
  return `Error creating file: File already exists - ${file_path}. Use overwrite: true to replace it.`;
@@ -39321,11 +39393,12 @@ function createTools(configOptions) {
39321
39393
  return tools2;
39322
39394
  }
39323
39395
  function parseXmlToolCallWithThinking(xmlString, validTools) {
39324
- const { cleanedXmlString, recoveryResult } = processXmlWithThinkingAndRecovery(xmlString, validTools);
39396
+ const { cleanedXmlString, recoveryResult, thinkingContent } = processXmlWithThinkingAndRecovery(xmlString, validTools);
39325
39397
  if (recoveryResult) {
39326
- return recoveryResult;
39398
+ return { ...recoveryResult, thinkingContent };
39327
39399
  }
39328
- return parseXmlToolCall(cleanedXmlString, validTools);
39400
+ const toolCall = parseXmlToolCall(cleanedXmlString, validTools);
39401
+ return toolCall ? { ...toolCall, thinkingContent } : null;
39329
39402
  }
39330
39403
  var import_crypto2, implementToolDefinition, listFilesToolDefinition, searchFilesToolDefinition, listSkillsToolDefinition, useSkillToolDefinition, readImageToolDefinition;
39331
39404
  var init_tools = __esm({
@@ -43308,7 +43381,7 @@ var init_esm3 = __esm({
43308
43381
  });
43309
43382
 
43310
43383
  // node_modules/path-scurry/dist/esm/index.js
43311
- var import_node_path, import_node_url, import_fs6, actualFS, import_promises, realpathSync, defaultFS, fsFromOption, uncDriveRegexp, uncToDrive, eitherSep, UNKNOWN, IFIFO, IFCHR, IFDIR, IFBLK, IFREG, IFLNK, IFSOCK, IFMT, IFMT_UNKNOWN, READDIR_CALLED, LSTAT_CALLED, ENOTDIR, ENOENT, ENOREADLINK, ENOREALPATH, ENOCHILD, TYPEMASK, entToType, normalizeCache, normalize, normalizeNocaseCache, normalizeNocase, ResolveCache, ChildrenCache, setAsCwd, PathBase, PathWin32, PathPosix, PathScurryBase, PathScurryWin32, PathScurryPosix, PathScurryDarwin, Path, PathScurry;
43384
+ var import_node_path, import_node_url, import_fs6, actualFS, import_promises, realpathSync2, defaultFS, fsFromOption, uncDriveRegexp, uncToDrive, eitherSep, UNKNOWN, IFIFO, IFCHR, IFDIR, IFBLK, IFREG, IFLNK, IFSOCK, IFMT, IFMT_UNKNOWN, READDIR_CALLED, LSTAT_CALLED, ENOTDIR, ENOENT, ENOREADLINK, ENOREALPATH, ENOCHILD, TYPEMASK, entToType, normalizeCache, normalize, normalizeNocaseCache, normalizeNocase, ResolveCache, ChildrenCache, setAsCwd, PathBase, PathWin32, PathPosix, PathScurryBase, PathScurryWin32, PathScurryPosix, PathScurryDarwin, Path, PathScurry;
43312
43385
  var init_esm4 = __esm({
43313
43386
  "node_modules/path-scurry/dist/esm/index.js"() {
43314
43387
  init_esm2();
@@ -43318,13 +43391,13 @@ var init_esm4 = __esm({
43318
43391
  actualFS = __toESM(require("node:fs"), 1);
43319
43392
  import_promises = require("node:fs/promises");
43320
43393
  init_esm3();
43321
- realpathSync = import_fs6.realpathSync.native;
43394
+ realpathSync2 = import_fs6.realpathSync.native;
43322
43395
  defaultFS = {
43323
43396
  lstatSync: import_fs6.lstatSync,
43324
43397
  readdir: import_fs6.readdir,
43325
43398
  readdirSync: import_fs6.readdirSync,
43326
43399
  readlinkSync: import_fs6.readlinkSync,
43327
- realpathSync,
43400
+ realpathSync: realpathSync2,
43328
43401
  promises: {
43329
43402
  lstat: import_promises.lstat,
43330
43403
  readdir: import_promises.readdir,
@@ -85596,25 +85669,27 @@ function parseXmlMcpToolCall(xmlString, mcpToolNames = []) {
85596
85669
  function parseHybridXmlToolCall(xmlString, nativeTools = [], mcpBridge = null) {
85597
85670
  const nativeResult = parseNativeXmlToolWithThinking(xmlString, nativeTools);
85598
85671
  if (nativeResult) {
85599
- return { ...nativeResult, type: "native" };
85672
+ const { thinkingContent, ...rest } = nativeResult;
85673
+ return { ...rest, type: "native", thinkingContent };
85600
85674
  }
85601
85675
  if (mcpBridge) {
85602
85676
  const mcpResult = parseXmlMcpToolCall(xmlString, mcpBridge.getToolNames());
85603
85677
  if (mcpResult) {
85604
- return { ...mcpResult, type: "mcp" };
85678
+ const { thinkingContent } = processXmlWithThinkingAndRecovery(xmlString, []);
85679
+ return { ...mcpResult, type: "mcp", thinkingContent };
85605
85680
  }
85606
85681
  }
85607
85682
  return null;
85608
85683
  }
85609
85684
  function parseNativeXmlToolWithThinking(xmlString, validTools) {
85610
- const { cleanedXmlString, recoveryResult } = processXmlWithThinkingAndRecovery(xmlString, validTools);
85685
+ const { cleanedXmlString, recoveryResult, thinkingContent } = processXmlWithThinkingAndRecovery(xmlString, validTools);
85611
85686
  if (recoveryResult) {
85612
- return recoveryResult;
85687
+ return { ...recoveryResult, thinkingContent };
85613
85688
  }
85614
85689
  for (const toolName of validTools) {
85615
85690
  const result = parseNativeXmlTool(cleanedXmlString, toolName);
85616
85691
  if (result) {
85617
- return result;
85692
+ return { ...result, thinkingContent };
85618
85693
  }
85619
85694
  }
85620
85695
  return null;
@@ -95869,6 +95944,7 @@ var init_ProbeAgent = __esm({
95869
95944
  init_FallbackManager();
95870
95945
  init_contextCompactor();
95871
95946
  init_error_types();
95947
+ init_path_validation();
95872
95948
  init_outputTruncator();
95873
95949
  init_delegate();
95874
95950
  init_tasks();
@@ -95986,7 +96062,8 @@ var init_ProbeAgent = __esm({
95986
96062
  } else {
95987
96063
  this.allowedFolders = [process.cwd()];
95988
96064
  }
95989
- this.cwd = options.cwd || null;
96065
+ this.workspaceRoot = getCommonPrefix(this.allowedFolders);
96066
+ this.cwd = options.cwd || this.workspaceRoot;
95990
96067
  this.clientApiProvider = options.provider || null;
95991
96068
  this.clientApiModel = options.model || null;
95992
96069
  this.clientApiKey = null;
@@ -95998,6 +96075,8 @@ var init_ProbeAgent = __esm({
95998
96075
  console.log(`[DEBUG] Maximum tool iterations configured: ${MAX_TOOL_ITERATIONS}`);
95999
96076
  console.log(`[DEBUG] Allow Edit (implement tool): ${this.allowEdit}`);
96000
96077
  console.log(`[DEBUG] Search delegation enabled: ${this.searchDelegate}`);
96078
+ console.log(`[DEBUG] Workspace root: ${this.workspaceRoot}`);
96079
+ console.log(`[DEBUG] Working directory (cwd): ${this.cwd}`);
96001
96080
  }
96002
96081
  this.initializeTools();
96003
96082
  this.history = [];
@@ -96075,6 +96154,181 @@ var init_ProbeAgent = __esm({
96075
96154
  _filterMcpTools(mcpToolNames) {
96076
96155
  return mcpToolNames.filter((toolName) => this._isMcpToolAllowed(toolName));
96077
96156
  }
96157
+ /**
96158
+ * Check if tracer is AppTracer (expects sessionId as first param) vs SimpleAppTracer
96159
+ * @returns {boolean} - True if tracer is AppTracer style (requires sessionId)
96160
+ * @private
96161
+ */
96162
+ _isAppTracerStyle() {
96163
+ return this.tracer && typeof this.tracer.sessionSpans !== "undefined";
96164
+ }
96165
+ /**
96166
+ * Record an error classification event for telemetry
96167
+ * Provides unified error recording across all error types
96168
+ * @param {string} errorType - Error type (wrapped_tool, unrecognized_tool, no_tool_call, circuit_breaker)
96169
+ * @param {string} message - Error message
96170
+ * @param {Object} context - Additional context data
96171
+ * @param {number} iteration - Current iteration number
96172
+ * @private
96173
+ */
96174
+ _recordErrorTelemetry(errorType, message, context, iteration) {
96175
+ if (!this.tracer) return;
96176
+ if (this._isAppTracerStyle() && typeof this.tracer.recordErrorClassification === "function") {
96177
+ this.tracer.recordErrorClassification(this.sessionId, iteration, errorType, {
96178
+ message,
96179
+ context
96180
+ });
96181
+ } else if (typeof this.tracer.recordErrorEvent === "function") {
96182
+ this.tracer.recordErrorEvent(errorType, {
96183
+ message,
96184
+ context: { ...context, iteration }
96185
+ });
96186
+ } else {
96187
+ this.tracer.addEvent(`error.${errorType}`, {
96188
+ "error.type": errorType,
96189
+ "error.message": message,
96190
+ "error.recoverable": errorType !== "circuit_breaker",
96191
+ "error.context": JSON.stringify(context).substring(0, 1e3),
96192
+ "iteration": iteration
96193
+ });
96194
+ }
96195
+ }
96196
+ /**
96197
+ * Record AI thinking content for telemetry
96198
+ * @param {string} thinkingContent - The thinking content
96199
+ * @param {number} iteration - Current iteration number
96200
+ * @private
96201
+ */
96202
+ _recordThinkingTelemetry(thinkingContent, iteration) {
96203
+ if (!this.tracer || !thinkingContent) return;
96204
+ if (this._isAppTracerStyle() && typeof this.tracer.recordThinkingContent === "function") {
96205
+ this.tracer.recordThinkingContent(this.sessionId, iteration, thinkingContent);
96206
+ } else if (typeof this.tracer.recordThinkingContent === "function") {
96207
+ this.tracer.recordThinkingContent(thinkingContent, { iteration });
96208
+ } else {
96209
+ this.tracer.addEvent("ai.thinking", {
96210
+ "ai.thinking.content": thinkingContent.substring(0, 5e4),
96211
+ "ai.thinking.length": thinkingContent.length,
96212
+ "iteration": iteration
96213
+ });
96214
+ }
96215
+ }
96216
+ /**
96217
+ * Record AI tool decision for telemetry
96218
+ * @param {string} toolName - The tool name
96219
+ * @param {Object} params - Tool parameters
96220
+ * @param {number} responseLength - Length of AI response
96221
+ * @param {number} iteration - Current iteration number
96222
+ * @private
96223
+ */
96224
+ _recordToolDecisionTelemetry(toolName, params, responseLength, iteration) {
96225
+ if (!this.tracer) return;
96226
+ if (this._isAppTracerStyle() && typeof this.tracer.recordAIToolDecision === "function") {
96227
+ this.tracer.recordAIToolDecision(this.sessionId, iteration, toolName, params);
96228
+ } else if (typeof this.tracer.recordToolDecision === "function") {
96229
+ this.tracer.recordToolDecision(toolName, params, {
96230
+ iteration,
96231
+ "ai.tool_decision.raw_response_length": responseLength
96232
+ });
96233
+ } else {
96234
+ this.tracer.addEvent("ai.tool_decision", {
96235
+ "ai.tool_decision.name": toolName,
96236
+ "ai.tool_decision.params": JSON.stringify(params || {}).substring(0, 2e3),
96237
+ "ai.tool_decision.raw_response_length": responseLength,
96238
+ "iteration": iteration
96239
+ });
96240
+ }
96241
+ }
96242
+ /**
96243
+ * Record tool result for telemetry
96244
+ * @param {string} toolName - The tool name
96245
+ * @param {string|Object} result - Tool result
96246
+ * @param {boolean} success - Whether tool succeeded
96247
+ * @param {number} durationMs - Execution duration in milliseconds
96248
+ * @param {number} iteration - Current iteration number
96249
+ * @private
96250
+ */
96251
+ _recordToolResultTelemetry(toolName, result, success, durationMs, iteration) {
96252
+ if (!this.tracer) return;
96253
+ if (this._isAppTracerStyle() && typeof this.tracer.recordToolResult === "function") {
96254
+ this.tracer.recordToolResult(this.sessionId, iteration, toolName, result, success, durationMs);
96255
+ } else if (typeof this.tracer.recordToolResult === "function") {
96256
+ this.tracer.recordToolResult(toolName, result, success, durationMs, { iteration });
96257
+ } else {
96258
+ const resultStr = typeof result === "string" ? result : JSON.stringify(result || "");
96259
+ this.tracer.addEvent("tool.result", {
96260
+ "tool.name": toolName,
96261
+ "tool.result": resultStr.substring(0, 1e4),
96262
+ "tool.result.length": resultStr.length,
96263
+ "tool.duration_ms": durationMs,
96264
+ "tool.success": success,
96265
+ "iteration": iteration
96266
+ });
96267
+ }
96268
+ }
96269
+ /**
96270
+ * Record MCP tool lifecycle event for telemetry
96271
+ * @param {string} phase - 'start' or 'end'
96272
+ * @param {string} toolName - MCP tool name
96273
+ * @param {Object} params - Tool parameters (for start) or null (for end)
96274
+ * @param {number} iteration - Current iteration number
96275
+ * @param {Object} [endData] - Additional data for end phase (result, success, durationMs, error)
96276
+ * @private
96277
+ */
96278
+ _recordMcpToolTelemetry(phase, toolName, params, iteration, endData = null) {
96279
+ if (!this.tracer) return;
96280
+ if (phase === "start") {
96281
+ if (this._isAppTracerStyle() && typeof this.tracer.recordMcpToolStart === "function") {
96282
+ this.tracer.recordMcpToolStart(this.sessionId, iteration, toolName, "mcp", params);
96283
+ } else if (typeof this.tracer.recordMcpToolStart === "function") {
96284
+ this.tracer.recordMcpToolStart(toolName, "mcp", params, { iteration });
96285
+ } else {
96286
+ this.tracer.addEvent("mcp.tool.start", {
96287
+ "mcp.tool.name": toolName,
96288
+ "mcp.tool.server": "mcp",
96289
+ "mcp.tool.params": JSON.stringify(params || {}).substring(0, 2e3),
96290
+ "iteration": iteration
96291
+ });
96292
+ }
96293
+ } else if (phase === "end" && endData) {
96294
+ const { result, success, durationMs, error: error2 } = endData;
96295
+ if (this._isAppTracerStyle() && typeof this.tracer.recordMcpToolEnd === "function") {
96296
+ this.tracer.recordMcpToolEnd(this.sessionId, iteration, toolName, "mcp", result, success, durationMs, error2);
96297
+ } else if (typeof this.tracer.recordMcpToolEnd === "function") {
96298
+ this.tracer.recordMcpToolEnd(toolName, "mcp", result, success, durationMs, error2, { iteration });
96299
+ } else {
96300
+ const resultStr = typeof result === "string" ? result : JSON.stringify(result || "");
96301
+ this.tracer.addEvent("mcp.tool.end", {
96302
+ "mcp.tool.name": toolName,
96303
+ "mcp.tool.server": "mcp",
96304
+ "mcp.tool.result": resultStr.substring(0, 1e4),
96305
+ "mcp.tool.result.length": resultStr.length,
96306
+ "mcp.tool.duration_ms": durationMs,
96307
+ "mcp.tool.success": success,
96308
+ "mcp.tool.error": error2,
96309
+ "iteration": iteration
96310
+ });
96311
+ }
96312
+ }
96313
+ }
96314
+ /**
96315
+ * Record iteration lifecycle event for telemetry
96316
+ * @param {string} phase - 'end' (start is already handled elsewhere)
96317
+ * @param {number} iteration - Current iteration number
96318
+ * @param {Object} data - Additional iteration data
96319
+ * @private
96320
+ */
96321
+ _recordIterationTelemetry(phase, iteration, data2 = {}) {
96322
+ if (!this.tracer) return;
96323
+ if (typeof this.tracer.recordIterationEvent === "function") {
96324
+ this.tracer.recordIterationEvent(phase, iteration, data2);
96325
+ } else {
96326
+ this.tracer.addEvent(`iteration.${phase}`, {
96327
+ "iteration": iteration,
96328
+ ...data2
96329
+ });
96330
+ }
96331
+ }
96078
96332
  /**
96079
96333
  * Initialize the agent asynchronously (must be called after constructor)
96080
96334
  * This method initializes MCP and merges MCP tools into the tool list, and loads history from storage
@@ -96170,8 +96424,9 @@ var init_ProbeAgent = __esm({
96170
96424
  const configOptions = {
96171
96425
  sessionId: this.sessionId,
96172
96426
  debug: this.debug,
96173
- // Use explicit cwd if set, otherwise fall back to first allowed folder
96174
- cwd: this.cwd || (this.allowedFolders.length > 0 ? this.allowedFolders[0] : process.cwd()),
96427
+ // Use cwd (which defaults to workspaceRoot in constructor)
96428
+ cwd: this.cwd,
96429
+ workspaceRoot: this.workspaceRoot,
96175
96430
  allowedFolders: this.allowedFolders,
96176
96431
  outline: this.outline,
96177
96432
  searchDelegate: this.searchDelegate,
@@ -96858,16 +97113,16 @@ var init_ProbeAgent = __esm({
96858
97113
  let absolutePath;
96859
97114
  let isPathAllowed2 = false;
96860
97115
  if ((0, import_path13.isAbsolute)(imagePath)) {
96861
- absolutePath = (0, import_path13.normalize)((0, import_path13.resolve)(imagePath));
97116
+ absolutePath = safeRealpath((0, import_path13.resolve)(imagePath));
96862
97117
  isPathAllowed2 = allowedDirs.some((dir) => {
96863
- const normalizedDir = (0, import_path13.normalize)((0, import_path13.resolve)(dir));
96864
- return absolutePath === normalizedDir || absolutePath.startsWith(normalizedDir + import_path13.sep);
97118
+ const resolvedDir = safeRealpath(dir);
97119
+ return absolutePath === resolvedDir || absolutePath.startsWith(resolvedDir + import_path13.sep);
96865
97120
  });
96866
97121
  } else {
96867
97122
  for (const dir of allowedDirs) {
96868
- const normalizedDir = (0, import_path13.normalize)((0, import_path13.resolve)(dir));
96869
- const resolvedPath2 = (0, import_path13.normalize)((0, import_path13.resolve)(dir, imagePath));
96870
- if (resolvedPath2 === normalizedDir || resolvedPath2.startsWith(normalizedDir + import_path13.sep)) {
97123
+ const resolvedDir = safeRealpath(dir);
97124
+ const resolvedPath2 = safeRealpath((0, import_path13.resolve)(dir, imagePath));
97125
+ if (resolvedPath2 === resolvedDir || resolvedPath2.startsWith(resolvedDir + import_path13.sep)) {
96871
97126
  absolutePath = resolvedPath2;
96872
97127
  isPathAllowed2 = true;
96873
97128
  break;
@@ -97050,7 +97305,7 @@ var init_ProbeAgent = __esm({
97050
97305
  if (this._architectureContextLoaded) {
97051
97306
  return this.architectureContext;
97052
97307
  }
97053
- const rootDirectory = this.allowedFolders.length > 0 ? this.allowedFolders[0] : process.cwd();
97308
+ const rootDirectory = this.workspaceRoot || (this.allowedFolders.length > 0 ? this.allowedFolders[0] : process.cwd());
97054
97309
  const configuredName = typeof this.architectureFileName === "string" ? this.architectureFileName.trim() : "";
97055
97310
  const hasConfiguredName = !!configuredName;
97056
97311
  let guidanceCandidates = [];
@@ -97187,6 +97442,9 @@ ${this.architectureContext.content}
97187
97442
  `;
97188
97443
  }
97189
97444
  _getSkillsRepoRoot() {
97445
+ if (this.workspaceRoot) {
97446
+ return (0, import_path13.resolve)(this.workspaceRoot);
97447
+ }
97190
97448
  if (this.allowedFolders && this.allowedFolders.length > 0) {
97191
97449
  return (0, import_path13.resolve)(this.allowedFolders[0]);
97192
97450
  }
@@ -97254,7 +97512,7 @@ Workspace: ${this.allowedFolders.join(", ")}`;
97254
97512
 
97255
97513
  # Repository Structure
97256
97514
  `;
97257
- systemPrompt += `You are working with a repository located at: ${this.allowedFolders[0]}
97515
+ systemPrompt += `You are working with a repository located at: ${this.workspaceRoot}
97258
97516
 
97259
97517
  `;
97260
97518
  systemPrompt += `Here's an overview of the repository structure (showing up to 100 most relevant files):
@@ -97307,7 +97565,7 @@ Workspace: ${this.allowedFolders.join(", ")}`;
97307
97565
 
97308
97566
  # Repository Structure
97309
97567
  `;
97310
- systemPrompt += `You are working with a repository located at: ${this.allowedFolders[0]}
97568
+ systemPrompt += `You are working with a repository located at: ${this.workspaceRoot}
97311
97569
 
97312
97570
  `;
97313
97571
  systemPrompt += `Here's an overview of the repository structure (showing up to 100 most relevant files):
@@ -97606,21 +97864,34 @@ For MCP tools, use JSON format within the params tag, e.g.:
97606
97864
  `;
97607
97865
  }
97608
97866
  }
97609
- const searchDirectory = this.allowedFolders.length > 0 ? this.allowedFolders[0] : process.cwd();
97867
+ const searchDirectory = this.workspaceRoot;
97610
97868
  if (this.debug) {
97611
- console.log(`[DEBUG] Generating file list for base directory: ${searchDirectory}...`);
97869
+ console.log(`[DEBUG] Generating file list for workspace root: ${searchDirectory}...`);
97870
+ }
97871
+ const relativeWorkspaces = this.allowedFolders.map((f5) => {
97872
+ const rel = toRelativePath(f5, this.workspaceRoot);
97873
+ if (rel && rel !== "." && !rel.startsWith(".") && !rel.startsWith("/")) {
97874
+ return "./" + rel;
97875
+ }
97876
+ return rel;
97877
+ }).filter((f5) => f5 && f5 !== ".");
97878
+ let workspaceDesc;
97879
+ if (relativeWorkspaces.length === 0) {
97880
+ workspaceDesc = ". (current directory)";
97881
+ } else {
97882
+ workspaceDesc = relativeWorkspaces.join(", ");
97612
97883
  }
97613
97884
  try {
97614
97885
  const files = await listFilesByLevel({
97615
97886
  directory: searchDirectory,
97616
97887
  maxFiles: 100,
97617
97888
  respectGitignore: !process.env.PROBE_NO_GITIGNORE || process.env.PROBE_NO_GITIGNORE === "",
97618
- cwd: process.cwd()
97889
+ cwd: this.workspaceRoot
97619
97890
  });
97620
97891
  systemMessage += `
97621
97892
  # Repository Structure
97622
97893
 
97623
- You are working with a repository located at: ${searchDirectory}
97894
+ You are working with a workspace. Available paths: ${workspaceDesc}
97624
97895
 
97625
97896
  Here's an overview of the repository structure (showing up to 100 most relevant files):
97626
97897
 
@@ -97636,15 +97907,22 @@ ${files}
97636
97907
  systemMessage += `
97637
97908
  # Repository Structure
97638
97909
 
97639
- You are working with a repository located at: ${searchDirectory}
97910
+ You are working with a workspace. Available paths: ${workspaceDesc}
97640
97911
 
97641
97912
  `;
97642
97913
  }
97643
97914
  await this.loadArchitectureContext();
97644
97915
  systemMessage += this.getArchitectureSection();
97645
97916
  if (this.allowedFolders.length > 0) {
97917
+ const relativeAllowed = this.allowedFolders.map((f5) => {
97918
+ const rel = toRelativePath(f5, this.workspaceRoot);
97919
+ if (rel && rel !== "." && !rel.startsWith(".") && !rel.startsWith("/")) {
97920
+ return "./" + rel;
97921
+ }
97922
+ return rel;
97923
+ });
97646
97924
  systemMessage += `
97647
- **Important**: For security reasons, you can only search within these allowed folders: ${this.allowedFolders.join(", ")}
97925
+ **Important**: For security reasons, you can only access these paths: ${relativeAllowed.join(", ")}
97648
97926
 
97649
97927
  `;
97650
97928
  }
@@ -98029,8 +98307,12 @@ You are working with a repository located at: ${searchDirectory}
98029
98307
  }
98030
98308
  const nativeTools = validTools;
98031
98309
  const parsedTool = this.mcpBridge && !options._disableTools ? parseHybridXmlToolCall(assistantResponseContent, nativeTools, this.mcpBridge) : parseXmlToolCallWithThinking(assistantResponseContent, validTools);
98310
+ if (parsedTool?.thinkingContent) {
98311
+ this._recordThinkingTelemetry(parsedTool.thinkingContent, currentIteration);
98312
+ }
98032
98313
  if (parsedTool) {
98033
98314
  const { toolName, params } = parsedTool;
98315
+ this._recordToolDecisionTelemetry(toolName, params, assistantResponseContent.length, currentIteration);
98034
98316
  if (this.debug) console.log(`[DEBUG] Parsed tool call: ${toolName} with params:`, params);
98035
98317
  if (toolName === "attempt_completion") {
98036
98318
  completionAttempted = true;
@@ -98107,6 +98389,8 @@ You are working with a repository located at: ${searchDirectory}
98107
98389
  } else {
98108
98390
  const { type } = parsedTool;
98109
98391
  if (type === "mcp" && this.mcpBridge && this.mcpBridge.isMcpTool(toolName)) {
98392
+ const mcpStartTime = Date.now();
98393
+ this._recordMcpToolTelemetry("start", toolName, params, currentIteration);
98110
98394
  try {
98111
98395
  if (this.debug) {
98112
98396
  console.error(`
@@ -98136,6 +98420,13 @@ You are working with a repository located at: ${searchDirectory}
98136
98420
  } catch (truncateError) {
98137
98421
  console.error(`[WARN] Tool output truncation failed: ${truncateError.message}`);
98138
98422
  }
98423
+ const mcpDurationMs = Date.now() - mcpStartTime;
98424
+ this._recordMcpToolTelemetry("end", toolName, null, currentIteration, {
98425
+ result: toolResultContent,
98426
+ success: true,
98427
+ durationMs: mcpDurationMs,
98428
+ error: null
98429
+ });
98139
98430
  if (this.debug) {
98140
98431
  const preview = toolResultContent.length > 500 ? toolResultContent.substring(0, 500) + "..." : toolResultContent;
98141
98432
  console.error(`[DEBUG] ========================================`);
@@ -98145,10 +98436,18 @@ You are working with a repository located at: ${searchDirectory}
98145
98436
  console.error(`[DEBUG] ========================================
98146
98437
  `);
98147
98438
  }
98439
+ currentMessages.push({ role: "assistant", content: assistantResponseContent });
98148
98440
  currentMessages.push({ role: "user", content: `<tool_result>
98149
98441
  ${toolResultContent}
98150
98442
  </tool_result>` });
98151
98443
  } catch (error2) {
98444
+ const mcpDurationMs = Date.now() - mcpStartTime;
98445
+ this._recordMcpToolTelemetry("end", toolName, null, currentIteration, {
98446
+ result: null,
98447
+ success: false,
98448
+ durationMs: mcpDurationMs,
98449
+ error: error2.message
98450
+ });
98152
98451
  console.error(`Error executing MCP tool ${toolName}:`, error2);
98153
98452
  if (this.debug) {
98154
98453
  console.error(`[DEBUG] ========================================`);
@@ -98158,17 +98457,18 @@ ${toolResultContent}
98158
98457
  `);
98159
98458
  }
98160
98459
  const errorXml = formatErrorForAI(error2);
98460
+ currentMessages.push({ role: "assistant", content: assistantResponseContent });
98161
98461
  currentMessages.push({ role: "user", content: `<tool_result>
98162
98462
  ${errorXml}
98163
98463
  </tool_result>` });
98164
98464
  }
98165
98465
  } else if (this.toolImplementations[toolName]) {
98166
98466
  try {
98167
- let resolvedWorkingDirectory = this.cwd || this.allowedFolders && this.allowedFolders[0] || process.cwd();
98467
+ let resolvedWorkingDirectory = this.workspaceRoot || this.cwd || this.allowedFolders && this.allowedFolders[0] || process.cwd();
98168
98468
  if (params.workingDirectory) {
98169
- const requestedDir = (0, import_path13.isAbsolute)(params.workingDirectory) ? (0, import_path13.resolve)(params.workingDirectory) : (0, import_path13.resolve)(resolvedWorkingDirectory, params.workingDirectory);
98469
+ const requestedDir = safeRealpath((0, import_path13.isAbsolute)(params.workingDirectory) ? (0, import_path13.resolve)(params.workingDirectory) : (0, import_path13.resolve)(resolvedWorkingDirectory, params.workingDirectory));
98170
98470
  const isWithinAllowed = !this.allowedFolders || this.allowedFolders.length === 0 || this.allowedFolders.some((folder) => {
98171
- const resolvedFolder = (0, import_path13.resolve)(folder);
98471
+ const resolvedFolder = safeRealpath(folder);
98172
98472
  return requestedDir === resolvedFolder || requestedDir.startsWith(resolvedFolder + import_path13.sep);
98173
98473
  });
98174
98474
  if (isWithinAllowed) {
@@ -98240,6 +98540,7 @@ ${errorXml}
98240
98540
  return await this.toolImplementations[toolName].execute(toolParams);
98241
98541
  };
98242
98542
  let toolResult;
98543
+ const toolStartTime = Date.now();
98243
98544
  try {
98244
98545
  if (this.tracer) {
98245
98546
  toolResult = await this.tracer.withSpan("tool.call", executeToolCall, {
@@ -98250,6 +98551,8 @@ ${errorXml}
98250
98551
  } else {
98251
98552
  toolResult = await executeToolCall();
98252
98553
  }
98554
+ const toolDurationMs = Date.now() - toolStartTime;
98555
+ this._recordToolResultTelemetry(toolName, toolResult, true, toolDurationMs, currentIteration);
98253
98556
  if (this.debug) {
98254
98557
  const resultPreview = typeof toolResult === "string" ? toolResult.length > 500 ? toolResult.substring(0, 500) + "..." : toolResult : toolResult ? JSON.stringify(toolResult, null, 2).substring(0, 500) + "..." : "No Result";
98255
98558
  console.error(`[DEBUG] ========================================`);
@@ -98306,6 +98609,20 @@ ${toolResultContent}
98306
98609
  role: "user",
98307
98610
  content: toolResultMessage
98308
98611
  });
98612
+ if (this.tracer) {
98613
+ if (typeof this.tracer.recordConversationTurn === "function") {
98614
+ this.tracer.recordConversationTurn("assistant", assistantResponseContent, {
98615
+ iteration: currentIteration,
98616
+ has_tool_call: true,
98617
+ tool_name: toolName
98618
+ });
98619
+ this.tracer.recordConversationTurn("tool_result", toolResultContent, {
98620
+ iteration: currentIteration,
98621
+ tool_name: toolName,
98622
+ tool_success: true
98623
+ });
98624
+ }
98625
+ }
98309
98626
  if (this.debug) {
98310
98627
  console.log(`[DEBUG] Tool ${toolName} executed successfully. Result length: ${typeof toolResult === "string" ? toolResult.length : JSON.stringify(toolResult).length}`);
98311
98628
  }
@@ -98376,6 +98693,7 @@ ${errorXml}
98376
98693
  if (this.debug) {
98377
98694
  console.log(`[DEBUG] Detected wrapped tool '${wrappedToolName}' in assistant response - wrong XML format.`);
98378
98695
  }
98696
+ this._recordErrorTelemetry("wrapped_tool", "Tool call wrapped in markdown", { toolName: wrappedToolName }, currentIteration);
98379
98697
  const toolError = new ParameterError(
98380
98698
  `Tool '${wrappedToolName}' found but in WRONG FORMAT - do not wrap tools in other XML tags.`,
98381
98699
  {
@@ -98401,6 +98719,7 @@ ${formatErrorForAI(toolError)}
98401
98719
  if (this.debug) {
98402
98720
  console.log(`[DEBUG] Detected unrecognized tool '${unrecognizedTool}' in assistant response.`);
98403
98721
  }
98722
+ this._recordErrorTelemetry("unrecognized_tool", `Unknown tool: ${unrecognizedTool}`, { toolName: unrecognizedTool, validTools }, currentIteration);
98404
98723
  const toolError = new ParameterError(`Tool '${unrecognizedTool}' is not available in this context.`, {
98405
98724
  suggestion: `Available tools: ${validTools.join(", ")}. Please use one of these tools instead.`
98406
98725
  });
@@ -98408,6 +98727,7 @@ ${formatErrorForAI(toolError)}
98408
98727
  ${formatErrorForAI(toolError)}
98409
98728
  </tool_result>`;
98410
98729
  } else {
98730
+ this._recordErrorTelemetry("no_tool_call", "AI response did not contain tool call", { responsePreview: assistantResponseContent.substring(0, 500) }, currentIteration);
98411
98731
  if (currentIteration >= maxIterations) {
98412
98732
  let cleanedResponse = assistantResponseContent;
98413
98733
  cleanedResponse = cleanedResponse.replace(/<thinking>[\s\S]*?<\/thinking>/gi, "").trim();
@@ -98483,6 +98803,7 @@ Note: <attempt_complete></attempt_complete> reuses your PREVIOUS assistant messa
98483
98803
  sameFormatErrorCount++;
98484
98804
  if (sameFormatErrorCount >= MAX_REPEATED_FORMAT_ERRORS) {
98485
98805
  const errorDesc = isWrapped ? "wrapped tool format" : unrecognizedTool;
98806
+ this._recordErrorTelemetry("circuit_breaker", "Format error limit exceeded", { formatErrorCount: sameFormatErrorCount, errorCategory }, currentIteration);
98486
98807
  console.error(`[ERROR] Format error category '${errorCategory}' repeated ${sameFormatErrorCount} times. Breaking loop early to prevent infinite iteration.`);
98487
98808
  finalResult = `Error: Unable to complete request. The AI model repeatedly used incorrect tool call format (${errorDesc}). Please try rephrasing your question or using a different model.`;
98488
98809
  break;
@@ -98496,6 +98817,10 @@ Note: <attempt_complete></attempt_complete> reuses your PREVIOUS assistant messa
98496
98817
  sameFormatErrorCount = 0;
98497
98818
  }
98498
98819
  }
98820
+ this._recordIterationTelemetry("end", currentIteration, {
98821
+ "iteration.completed": completionAttempted,
98822
+ "iteration.message_count": currentMessages.length
98823
+ });
98499
98824
  if (currentMessages.length > MAX_HISTORY_MESSAGES) {
98500
98825
  const messagesBefore = currentMessages.length;
98501
98826
  const systemMsg = currentMessages[0];
@@ -98612,7 +98937,7 @@ Convert your previous response content into actual JSON data that follows this s
98612
98937
  }
98613
98938
  const mermaidValidation = await validateAndFixMermaidResponse(finalResult, {
98614
98939
  debug: this.debug,
98615
- path: this.allowedFolders[0],
98940
+ path: this.workspaceRoot || this.allowedFolders[0],
98616
98941
  provider: this.clientApiProvider,
98617
98942
  model: this.model,
98618
98943
  tracer: this.tracer
@@ -98685,7 +99010,7 @@ Convert your previous response content into actual JSON data that follows this s
98685
99010
  }
98686
99011
  const { JsonFixingAgent: JsonFixingAgent2 } = await Promise.resolve().then(() => (init_schemaUtils(), schemaUtils_exports));
98687
99012
  const jsonFixer = new JsonFixingAgent2({
98688
- path: this.allowedFolders[0],
99013
+ path: this.workspaceRoot || this.allowedFolders[0],
98689
99014
  provider: this.clientApiProvider,
98690
99015
  model: this.model,
98691
99016
  debug: this.debug,
@@ -98754,7 +99079,7 @@ Convert your previous response content into actual JSON data that follows this s
98754
99079
  }
98755
99080
  const mermaidValidation = await validateAndFixMermaidResponse(finalResult, {
98756
99081
  debug: this.debug,
98757
- path: this.allowedFolders[0],
99082
+ path: this.workspaceRoot || this.allowedFolders[0],
98758
99083
  provider: this.clientApiProvider,
98759
99084
  model: this.model,
98760
99085
  tracer: this.tracer
@@ -98886,7 +99211,7 @@ Convert your previous response content into actual JSON data that follows this s
98886
99211
  }
98887
99212
  const finalMermaidValidation = await validateAndFixMermaidResponse(finalResult, {
98888
99213
  debug: this.debug,
98889
- path: this.allowedFolders[0],
99214
+ path: this.workspaceRoot || this.allowedFolders[0],
98890
99215
  provider: this.clientApiProvider,
98891
99216
  model: this.model,
98892
99217
  tracer: this.tracer
@@ -99036,8 +99361,7 @@ Convert your previous response content into actual JSON data that follows this s
99036
99361
  allowEdit: this.allowEdit,
99037
99362
  enableDelegate: this.enableDelegate,
99038
99363
  architectureFileName: this.architectureFileName,
99039
- path: this.allowedFolders[0],
99040
- // Use first allowed folder as primary path
99364
+ // Pass allowedFolders which will recompute workspaceRoot correctly
99041
99365
  allowedFolders: [...this.allowedFolders],
99042
99366
  cwd: this.cwd,
99043
99367
  // Preserve explicit working directory
@@ -100000,6 +100324,7 @@ async function analyzeAll(options) {
100000
100324
  sessionId,
100001
100325
  debug = false,
100002
100326
  cwd,
100327
+ workspaceRoot,
100003
100328
  allowedFolders,
100004
100329
  provider,
100005
100330
  model,
@@ -100012,10 +100337,11 @@ async function analyzeAll(options) {
100012
100337
  if (!question) {
100013
100338
  throw new Error('The "question" parameter is required.');
100014
100339
  }
100340
+ const effectiveWorkspaceRoot = workspaceRoot || cwd || allowedFolders?.[0] || path9;
100015
100341
  const delegateOptions = {
100016
100342
  debug,
100017
100343
  sessionId,
100018
- path: allowedFolders?.[0] || cwd || path9,
100344
+ path: effectiveWorkspaceRoot,
100019
100345
  allowedFolders,
100020
100346
  provider,
100021
100347
  model,
@@ -100477,7 +100803,7 @@ var init_vercel = __esm({
100477
100803
  });
100478
100804
  };
100479
100805
  delegateTool = (options = {}) => {
100480
- const { debug = false, timeout = 300, cwd, allowedFolders, enableBash = false, bashConfig, architectureFileName, enableMcp = false, mcpConfig = null, mcpConfigPath = null, delegationManager = null } = options;
100806
+ const { debug = false, timeout = 300, cwd, allowedFolders, workspaceRoot, enableBash = false, bashConfig, architectureFileName, enableMcp = false, mcpConfig = null, mcpConfigPath = null, delegationManager = null } = options;
100481
100807
  return (0, import_ai4.tool)({
100482
100808
  name: "delegate",
100483
100809
  description: delegateDescription,
@@ -100510,8 +100836,8 @@ var init_vercel = __esm({
100510
100836
  if (searchDelegate !== void 0 && typeof searchDelegate !== "boolean") {
100511
100837
  throw new TypeError("searchDelegate must be a boolean if provided");
100512
100838
  }
100513
- const workspaceRoot = allowedFolders && allowedFolders[0];
100514
- const effectivePath = path9 || workspaceRoot || cwd;
100839
+ const effectiveWorkspaceRoot = workspaceRoot || allowedFolders && allowedFolders[0];
100840
+ const effectivePath = path9 || effectiveWorkspaceRoot || cwd;
100515
100841
  if (debug) {
100516
100842
  console.error(`Executing delegate with task: "${task.substring(0, 100)}${task.length > 100 ? "..." : ""}"`);
100517
100843
  if (parentSessionId) {
@@ -100548,7 +100874,7 @@ var init_vercel = __esm({
100548
100874
  });
100549
100875
  };
100550
100876
  analyzeAllTool = (options = {}) => {
100551
- const { sessionId, debug = false, delegationManager = null } = options;
100877
+ const { sessionId, debug = false, delegationManager = null, workspaceRoot } = options;
100552
100878
  return (0, import_ai4.tool)({
100553
100879
  name: "analyze_all",
100554
100880
  description: analyzeAllDescription,
@@ -100567,12 +100893,14 @@ var init_vercel = __esm({
100567
100893
  console.error(`[analyze_all] Question: ${question}`);
100568
100894
  console.error(`[analyze_all] Path: ${searchPath}`);
100569
100895
  }
100896
+ const effectiveWorkspaceRoot = workspaceRoot || options.cwd || options.allowedFolders && options.allowedFolders[0];
100570
100897
  const result = await analyzeAll({
100571
100898
  question,
100572
100899
  path: searchPath,
100573
100900
  sessionId,
100574
100901
  debug,
100575
100902
  cwd: options.cwd,
100903
+ workspaceRoot: effectiveWorkspaceRoot,
100576
100904
  allowedFolders: options.allowedFolders,
100577
100905
  provider: options.provider,
100578
100906
  model: options.model,
@@ -102049,14 +102377,17 @@ var init_bash = __esm({
102049
102377
  import_path15 = require("path");
102050
102378
  init_bashPermissions();
102051
102379
  init_bashExecutor();
102380
+ init_path_validation();
102052
102381
  bashTool = (options = {}) => {
102053
102382
  const {
102054
102383
  bashConfig = {},
102055
102384
  debug = false,
102056
102385
  cwd,
102057
102386
  allowedFolders = [],
102387
+ workspaceRoot: providedWorkspaceRoot,
102058
102388
  tracer = null
102059
102389
  } = options;
102390
+ const workspaceRoot = providedWorkspaceRoot || cwd || allowedFolders.length > 0 && allowedFolders[0] || process.cwd();
102060
102391
  const permissionChecker = new BashPermissionChecker({
102061
102392
  allow: bashConfig.allow,
102062
102393
  deny: bashConfig.deny,
@@ -102072,6 +102403,9 @@ var init_bash = __esm({
102072
102403
  if (cwd) {
102073
102404
  return cwd;
102074
102405
  }
102406
+ if (workspaceRoot) {
102407
+ return workspaceRoot;
102408
+ }
102075
102409
  if (allowedFolders && allowedFolders.length > 0) {
102076
102410
  return allowedFolders[0];
102077
102411
  }
@@ -102159,13 +102493,15 @@ For code exploration, try these safe alternatives:
102159
102493
  const defaultDir = getDefaultWorkingDirectory();
102160
102494
  const workingDir = workingDirectory ? (0, import_path15.isAbsolute)(workingDirectory) ? (0, import_path15.resolve)(workingDirectory) : (0, import_path15.resolve)(defaultDir, workingDirectory) : defaultDir;
102161
102495
  if (allowedFolders && allowedFolders.length > 0) {
102162
- const resolvedWorkingDir = (0, import_path15.resolve)(workingDir);
102496
+ const resolvedWorkingDir = safeRealpath(workingDir);
102163
102497
  const isAllowed = allowedFolders.some((folder) => {
102164
- const resolvedFolder = (0, import_path15.resolve)(folder);
102498
+ const resolvedFolder = safeRealpath(folder);
102165
102499
  return resolvedWorkingDir === resolvedFolder || resolvedWorkingDir.startsWith(resolvedFolder + import_path15.sep);
102166
102500
  });
102167
102501
  if (!isAllowed) {
102168
- return `Error: Working directory "${workingDir}" is not within allowed folders: ${allowedFolders.join(", ")}`;
102502
+ const relativeDir = toRelativePath(workingDir, workspaceRoot);
102503
+ const relativeAllowed = allowedFolders.map((f5) => toRelativePath(f5, workspaceRoot));
102504
+ return `Error: Working directory "${relativeDir}" is not within allowed folders: ${relativeAllowed.join(", ")}`;
102169
102505
  }
102170
102506
  }
102171
102507
  const executionOptions = {
@@ -102836,6 +103172,183 @@ var init_simpleTelemetry = __esm({
102836
103172
  console.log("[Attributes]", attributes);
102837
103173
  }
102838
103174
  }
103175
+ /**
103176
+ * Hash content for deduplication/comparison purposes
103177
+ * @param {string} content - The content to hash
103178
+ * @returns {string} - Hex string hash
103179
+ */
103180
+ hashContent(content) {
103181
+ let hash = 0;
103182
+ const len = Math.min(content.length, 1e3);
103183
+ for (let i5 = 0; i5 < len; i5++) {
103184
+ hash = (hash << 5) - hash + content.charCodeAt(i5);
103185
+ hash |= 0;
103186
+ }
103187
+ return hash.toString(16);
103188
+ }
103189
+ /**
103190
+ * Record a conversation turn (assistant response or tool result)
103191
+ * @param {string} role - The role (assistant, tool_result)
103192
+ * @param {string} content - The turn content
103193
+ * @param {Object} metadata - Additional metadata
103194
+ */
103195
+ recordConversationTurn(role, content, metadata = {}) {
103196
+ if (!this.isEnabled()) return;
103197
+ this.addEvent(`conversation.turn.${role}`, {
103198
+ "session.id": this.sessionId,
103199
+ "conversation.role": role,
103200
+ "conversation.content": content.substring(0, 1e4),
103201
+ "conversation.content.length": content.length,
103202
+ "conversation.content.hash": this.hashContent(content),
103203
+ ...metadata
103204
+ });
103205
+ }
103206
+ /**
103207
+ * Record error events with classification
103208
+ * @param {string} errorType - The type of error (wrapped_tool, unrecognized_tool, no_tool_call, circuit_breaker, etc.)
103209
+ * @param {Object} errorDetails - Error details including message, stack, context
103210
+ */
103211
+ recordErrorEvent(errorType, errorDetails = {}) {
103212
+ if (!this.isEnabled()) return;
103213
+ this.addEvent(`error.${errorType}`, {
103214
+ "session.id": this.sessionId,
103215
+ "error.type": errorType,
103216
+ "error.message": errorDetails.message?.substring(0, 1e3) || null,
103217
+ "error.stack": errorDetails.stack?.substring(0, 2e3) || null,
103218
+ "error.recoverable": errorDetails.recoverable ?? true,
103219
+ "error.context": JSON.stringify(errorDetails.context || {}).substring(0, 1e3),
103220
+ ...Object.fromEntries(
103221
+ Object.entries(errorDetails).filter(([k5]) => !["message", "stack", "context", "recoverable"].includes(k5)).map(([k5, v5]) => [`error.${k5}`, v5])
103222
+ )
103223
+ });
103224
+ }
103225
+ /**
103226
+ * Record AI thinking/reasoning content
103227
+ * @param {string} thinkingContent - The thinking content from AI response
103228
+ * @param {Object} metadata - Additional metadata
103229
+ */
103230
+ recordThinkingContent(thinkingContent, metadata = {}) {
103231
+ if (!this.isEnabled() || !thinkingContent) return;
103232
+ this.addEvent("ai.thinking", {
103233
+ "session.id": this.sessionId,
103234
+ "ai.thinking.content": thinkingContent.substring(0, 5e4),
103235
+ "ai.thinking.length": thinkingContent.length,
103236
+ "ai.thinking.hash": this.hashContent(thinkingContent),
103237
+ ...metadata
103238
+ });
103239
+ }
103240
+ /**
103241
+ * Record AI tool call decision
103242
+ * @param {string} toolName - The tool name AI decided to call
103243
+ * @param {Object} params - The parameters AI provided
103244
+ * @param {Object} metadata - Additional metadata
103245
+ */
103246
+ recordToolDecision(toolName, params, metadata = {}) {
103247
+ if (!this.isEnabled()) return;
103248
+ this.addEvent("ai.tool_decision", {
103249
+ "session.id": this.sessionId,
103250
+ "ai.tool_decision.name": toolName,
103251
+ "ai.tool_decision.params": JSON.stringify(params || {}).substring(0, 2e3),
103252
+ ...metadata
103253
+ });
103254
+ }
103255
+ /**
103256
+ * Record tool result after execution
103257
+ * @param {string} toolName - The tool that was executed
103258
+ * @param {string|Object} result - The tool result
103259
+ * @param {boolean} success - Whether the tool succeeded
103260
+ * @param {number} durationMs - Execution duration in milliseconds
103261
+ * @param {Object} metadata - Additional metadata
103262
+ */
103263
+ recordToolResult(toolName, result, success, durationMs, metadata = {}) {
103264
+ if (!this.isEnabled()) return;
103265
+ const resultStr = typeof result === "string" ? result : JSON.stringify(result);
103266
+ this.addEvent("tool.result", {
103267
+ "session.id": this.sessionId,
103268
+ "tool.name": toolName,
103269
+ "tool.result": resultStr.substring(0, 1e4),
103270
+ "tool.result.length": resultStr.length,
103271
+ "tool.result.hash": this.hashContent(resultStr),
103272
+ "tool.duration_ms": durationMs,
103273
+ "tool.success": success,
103274
+ ...metadata
103275
+ });
103276
+ }
103277
+ /**
103278
+ * Record MCP tool execution start
103279
+ * @param {string} toolName - MCP tool name
103280
+ * @param {string} serverName - MCP server name
103281
+ * @param {Object} params - Tool parameters
103282
+ * @param {Object} metadata - Additional metadata
103283
+ */
103284
+ recordMcpToolStart(toolName, serverName, params, metadata = {}) {
103285
+ if (!this.isEnabled()) return;
103286
+ this.addEvent("mcp.tool.start", {
103287
+ "session.id": this.sessionId,
103288
+ "mcp.tool.name": toolName,
103289
+ "mcp.tool.server": serverName || "unknown",
103290
+ "mcp.tool.params": JSON.stringify(params || {}).substring(0, 2e3),
103291
+ ...metadata
103292
+ });
103293
+ }
103294
+ /**
103295
+ * Record MCP tool execution end
103296
+ * @param {string} toolName - MCP tool name
103297
+ * @param {string} serverName - MCP server name
103298
+ * @param {string|Object} result - Tool result
103299
+ * @param {boolean} success - Whether succeeded
103300
+ * @param {number} durationMs - Execution duration
103301
+ * @param {string} errorMessage - Error message if failed
103302
+ * @param {Object} metadata - Additional metadata
103303
+ */
103304
+ recordMcpToolEnd(toolName, serverName, result, success, durationMs, errorMessage = null, metadata = {}) {
103305
+ if (!this.isEnabled()) return;
103306
+ const resultStr = typeof result === "string" ? result : JSON.stringify(result || "");
103307
+ this.addEvent("mcp.tool.end", {
103308
+ "session.id": this.sessionId,
103309
+ "mcp.tool.name": toolName,
103310
+ "mcp.tool.server": serverName || "unknown",
103311
+ "mcp.tool.result": resultStr.substring(0, 1e4),
103312
+ "mcp.tool.result.length": resultStr.length,
103313
+ "mcp.tool.duration_ms": durationMs,
103314
+ "mcp.tool.success": success,
103315
+ "mcp.tool.error": errorMessage,
103316
+ ...metadata
103317
+ });
103318
+ }
103319
+ /**
103320
+ * Record iteration lifecycle event
103321
+ * @param {string} eventType - start or end
103322
+ * @param {number} iteration - Iteration number
103323
+ * @param {Object} data - Additional data
103324
+ */
103325
+ recordIterationEvent(eventType, iteration, data2 = {}) {
103326
+ if (!this.isEnabled()) return;
103327
+ this.addEvent(`iteration.${eventType}`, {
103328
+ "session.id": this.sessionId,
103329
+ "iteration": iteration,
103330
+ ...data2
103331
+ });
103332
+ }
103333
+ /**
103334
+ * Record per-turn token breakdown
103335
+ * @param {number} iteration - Iteration number
103336
+ * @param {Object} tokenData - Token metrics
103337
+ */
103338
+ recordTokenTurn(iteration, tokenData = {}) {
103339
+ if (!this.isEnabled()) return;
103340
+ this.addEvent("tokens.turn", {
103341
+ "session.id": this.sessionId,
103342
+ "iteration": iteration,
103343
+ "tokens.input": tokenData.inputTokens || 0,
103344
+ "tokens.output": tokenData.outputTokens || 0,
103345
+ "tokens.total": (tokenData.inputTokens || 0) + (tokenData.outputTokens || 0),
103346
+ "tokens.cache_read": tokenData.cacheReadTokens || 0,
103347
+ "tokens.cache_write": tokenData.cacheWriteTokens || 0,
103348
+ "tokens.context_used": tokenData.contextTokens || 0,
103349
+ "tokens.context_remaining": tokenData.maxContextTokens ? tokenData.maxContextTokens - (tokenData.contextTokens || 0) : null
103350
+ });
103351
+ }
102839
103352
  async withSpan(spanName, fn, attributes = {}) {
102840
103353
  if (!this.isEnabled()) {
102841
103354
  return fn();