@juspay/neurolink 13.12.0 → 13.12.2

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 (64) hide show
  1. package/CHANGELOG.md +5 -3
  2. package/dist/agent/agentToolRegistrar.js +3 -1
  3. package/dist/auth/middleware/AuthMiddleware.d.ts +1 -1
  4. package/dist/browser/neurolink.min.js +467 -467
  5. package/dist/context/fileSummarizationService.js +2 -0
  6. package/dist/core/baseProvider.d.ts +2 -2
  7. package/dist/core/loopEngine.js +20 -8
  8. package/dist/core/modules/ToolsManager.d.ts +11 -33
  9. package/dist/core/modules/ToolsManager.js +71 -99
  10. package/dist/core/modules/Utilities.js +6 -1
  11. package/dist/core/toolExecutionGuards.js +79 -11
  12. package/dist/evaluation/ragasEvaluator.js +2 -0
  13. package/dist/evaluation/scorers/llm/baseLLMScorer.js +2 -0
  14. package/dist/hitl/hitlErrors.d.ts +8 -0
  15. package/dist/hitl/hitlErrors.js +12 -0
  16. package/dist/hitl/hitlManager.d.ts +25 -7
  17. package/dist/hitl/hitlManager.js +133 -15
  18. package/dist/hitl/index.d.ts +1 -1
  19. package/dist/hitl/index.js +1 -1
  20. package/dist/hitl/toolCallConfirmation.d.ts +57 -0
  21. package/dist/hitl/toolCallConfirmation.js +296 -0
  22. package/dist/index.d.ts +1 -1
  23. package/dist/index.js +4 -1
  24. package/dist/mcp/externalServerManager.d.ts +33 -2
  25. package/dist/mcp/externalServerManager.js +68 -52
  26. package/dist/mcp/toolDiscoveryService.js +8 -1
  27. package/dist/mcp/toolRegistry.d.ts +20 -0
  28. package/dist/mcp/toolRegistry.js +68 -58
  29. package/dist/middleware/utils/guardrailsUtils.js +2 -0
  30. package/dist/neurolink.d.ts +114 -2
  31. package/dist/neurolink.js +492 -71
  32. package/dist/providers/amazonBedrock/client.js +23 -4
  33. package/dist/providers/amazonSagemaker.d.ts +1 -1
  34. package/dist/providers/anthropic/client.js +5 -1
  35. package/dist/providers/catalog/schema.d.ts +1 -1
  36. package/dist/providers/googleNativeGemini3/utils.js +5 -1
  37. package/dist/providers/openaiChatCompletionsBase.js +21 -3
  38. package/dist/providers/sagemaker/language-model.d.ts +2 -2
  39. package/dist/proxy/otelLogSink.d.ts +1 -1
  40. package/dist/rag/metadata/metadataExtractor.js +2 -0
  41. package/dist/rag/pipeline/RAGPipeline.js +4 -0
  42. package/dist/rag/pipeline/contextAssembly.d.ts +1 -0
  43. package/dist/rag/pipeline/contextAssembly.js +2 -0
  44. package/dist/rag/reranker/reranker.js +4 -0
  45. package/dist/server/utils/validation.d.ts +28 -28
  46. package/dist/types/hitl.d.ts +100 -8
  47. package/dist/types/mcp.d.ts +5 -0
  48. package/dist/types/providers.d.ts +23 -2
  49. package/dist/types/tools.d.ts +34 -9
  50. package/dist/utils/async/index.d.ts +2 -1
  51. package/dist/utils/async/index.js +2 -1
  52. package/dist/utils/async/pausableDeadline.d.ts +28 -0
  53. package/dist/utils/async/pausableDeadline.js +88 -0
  54. package/dist/utils/async/withTimeout.d.ts +5 -0
  55. package/dist/utils/async/withTimeout.js +23 -0
  56. package/dist/utils/errorHandling.d.ts +32 -1
  57. package/dist/utils/errorHandling.js +70 -18
  58. package/dist/utils/providerUtils.js +5 -1
  59. package/dist/workflow/config.d.ts +7 -7
  60. package/dist/workflow/core/ensembleExecutor.js +2 -0
  61. package/dist/workflow/core/judgeScorer.js +2 -0
  62. package/dist/workflow/core/responseConditioner.js +2 -0
  63. package/docs-site/static/search-index.json +8 -6
  64. package/package.json +18 -11
package/dist/neurolink.js CHANGED
@@ -53,6 +53,9 @@ import { FileReferenceRegistry } from "./files/fileReferenceRegistry.js";
53
53
  import { resolveAttachmentPolicy } from "./utils/attachmentPolicy.js";
54
54
  import { createFileTools } from "./files/fileTools.js";
55
55
  import { HITLManager, DEFAULT_ALLOW_MODIFICATION } from "./hitl/hitlManager.js";
56
+ import { builtInToolAlwaysConfirmed, createHITLExecutionState, hitlStateRefused, isRefusalResult, markRefusalResult, resolveToolCallConfirmation, } from "./hitl/toolCallConfirmation.js";
57
+ import { HITLError } from "./hitl/hitlErrors.js";
58
+ import { getAuthContext as getAmbientAuthContext } from "./auth/authContext.js";
56
59
  import { ToolCallBatcher } from "./mcp/batching/index.js";
57
60
  // MCP Enhancement modules - wired into core execution path
58
61
  import { ToolResultCache } from "./mcp/caching/index.js";
@@ -85,6 +88,8 @@ import { endSpanWhenDropped, withSpan } from "./telemetry/withSpan.js";
85
88
  import { getActiveTraceContext } from "./telemetry/traceContext.js";
86
89
  import { calculateCost } from "./utils/pricing.js";
87
90
  import { createToolExecutionId } from "./utils/toolExecutionId.js";
91
+ import { TimeoutError, abortSignalOf } from "./utils/async/index.js";
92
+ import { composeAbortSignalsScoped } from "./utils/timeout.js";
88
93
  import { acquireTelemetry, ensureTelemetry, flushOpenTelemetry, getLangfuseHealthStatus, isOpenTelemetryInitialized, releaseTelemetry, setLangfuseContext, traceMetadataFromContext, } from "./services/server/ai/observability/instrumentation.js";
89
94
  import { clearChecklistState, createChecklistTools, getChecklistState, resolveChecklistSessionId, } from "./agent/taskChecklist.js";
90
95
  import { cancelDelegates as cancelBackgroundDelegates, collectDelegates as collectBackgroundDelegates, configureDelegation, createDelegationTools, spawnDelegate as spawnBackgroundDelegate, } from "./agent/backgroundDelegation.js";
@@ -99,7 +104,7 @@ import { toolSpanName } from "./telemetry/observationNames.js";
99
104
  import { isNestedOperation, tracers } from "./telemetry/tracers.js";
100
105
  import { getConversationMessages, storeConversationTurn, } from "./utils/conversationMemory.js";
101
106
  // Enhanced error handling imports
102
- import { CircuitBreaker, ERROR_CODES, ErrorFactory, isAbortError, isRetriableError, logStructuredError, NeuroLinkError, withRetry, withTimeout, } from "./utils/errorHandling.js";
107
+ import { CircuitBreaker, ERROR_CODES, ErrorFactory, isAbortError, isCancelledByCaller, isRetriableError, logStructuredError, NeuroLinkError, throwIfSignalAborted, withRetry, withTimeout, } from "./utils/errorHandling.js";
103
108
  import { hasLifecycleErrorFired, markLifecycleErrorFired, markLifecycleStreamCallbacksOwnedByBaseProvider, } from "./utils/lifecycleCallbacks.js";
104
109
  import { interleaveTTSStream } from "./utils/ttsStream.js";
105
110
  import { resolveLifecycleTimeoutMs } from "./utils/lifecycleTimeout.js";
@@ -1083,7 +1088,9 @@ export class NeuroLink {
1083
1088
  logger.debug("[NeuroLink] Memory condensation skipped: the host instance has been shut down");
1084
1089
  throw new Error("Memory condenser released: the host NeuroLink instance has been shut down");
1085
1090
  }
1086
- return condenser.generate(options);
1091
+ // Condensation writes text; the condenser is given no tools,
1092
+ // whatever options its caller passes.
1093
+ return condenser.generate({ ...options, disableTools: true });
1087
1094
  },
1088
1095
  };
1089
1096
  }
@@ -1407,6 +1414,10 @@ export class NeuroLink {
1407
1414
  this.initializeProviderRegistry(constructorId, constructorStartTime, constructorHrTimeStart);
1408
1415
  this.initializeConversationMemory(config, constructorId, constructorStartTime, constructorHrTimeStart);
1409
1416
  this.initializeExternalServerManager(constructorId, constructorStartTime, constructorHrTimeStart);
1417
+ // With no HITL of its own, this instance's external tools are confirmed
1418
+ // by the manager its tool registry holds (a host's, for a worker on a
1419
+ // shared registry), as its registered tools are.
1420
+ this.externalServerManager?.setFallbackHITLManager(() => this.toolRegistry.getHITLManager());
1410
1421
  this.initializeHITL(config, constructorId, constructorStartTime, constructorHrTimeStart);
1411
1422
  this.initializeMCPEnhancements(config);
1412
1423
  this.registerFileTools();
@@ -1681,11 +1692,15 @@ export class NeuroLink {
1681
1692
  });
1682
1693
  // Wire batcher to execute tools via the internal execution path (bypass batcher itself)
1683
1694
  this.mcpToolBatcher.setToolExecutor(async (tool, args) => {
1695
+ // A state of its own per call, so the safe-tool retry inside
1696
+ // executeToolInternal reuses the first answer instead of asking again.
1697
+ // A tool registered with no retries gets no safe-tool retry either.
1684
1698
  return this.executeToolInternal(tool, args, {
1685
1699
  timeout: TOOL_TIMEOUTS.EXECUTION_DEFAULT_MS,
1686
- maxRetries: RETRY_ATTEMPTS.DEFAULT,
1700
+ maxRetries: this.toolRegistry.getToolInfo(tool)?.tool?.maxRetries ??
1701
+ RETRY_ATTEMPTS.DEFAULT,
1687
1702
  retryDelayMs: RETRY_DELAYS.BASE_MS,
1688
- });
1703
+ }, createHITLExecutionState());
1689
1704
  });
1690
1705
  logger.debug("[NeuroLink] MCP tool call batcher initialized");
1691
1706
  }
@@ -1953,14 +1968,18 @@ export class NeuroLink {
1953
1968
  allowMutations: this.skillsConfig?.allowMutations === true,
1954
1969
  });
1955
1970
  for (const [toolName, toolDef] of Object.entries(canonicalTools)) {
1956
- this.registerTool(toolName, {
1971
+ const definition = {
1957
1972
  name: toolName,
1958
1973
  description: toolDef.description ?? toolName,
1959
1974
  // Zod schema — registerTool() detects isZodSchema and preserves it
1960
1975
  // so ToolsManager gives the LLM full parameter types.
1961
1976
  inputSchema: toolDef.inputSchema,
1962
1977
  execute: async (params) => withTimeout(toolDef.execute(params, { toolCallId: "skill-tool", messages: [] }), TOOL_TIMEOUTS.EXECUTION_DEFAULT_MS, ErrorFactory.toolTimeout(toolName, TOOL_TIMEOUTS.EXECUTION_DEFAULT_MS)),
1963
- });
1978
+ };
1979
+ // Never retried: an attempt that times out keeps running in the
1980
+ // background, so a retry would run the skill again, and a skill write
1981
+ // would apply twice.
1982
+ this.registerTool(toolName, definition, { maxRetries: 0 });
1964
1983
  }
1965
1984
  logger.info(`[NeuroLink] Registered ${Object.keys(canonicalTools).length} skill tools`, { allowMutations: this.skillsConfig?.allowMutations === true });
1966
1985
  }
@@ -2424,6 +2443,14 @@ Current user's request: ${currentInput}`;
2424
2443
  });
2425
2444
  this.emitter.emit("hitl:timeout", event);
2426
2445
  });
2446
+ // Forward withdrawn confirmations so the approval UI can retire the card
2447
+ this.hitlManager.on("hitl:cancelled", (event) => {
2448
+ logger.debug("Forwarding HITL cancelled event", {
2449
+ confirmationId: event.payload?.confirmationId,
2450
+ toolName: event.payload?.toolName,
2451
+ });
2452
+ this.emitter.emit("hitl:cancelled", event);
2453
+ });
2427
2454
  // Listen for confirmation responses from main emitter and forward to HITL manager
2428
2455
  this.emitter.on("hitl:confirmation-response", (event) => {
2429
2456
  const typedEvent = event;
@@ -6633,9 +6660,7 @@ Current user's request: ${currentInput}`;
6633
6660
  this.emitter.emit("message", `${providerName} provider initialized successfully`);
6634
6661
  provider.setupToolExecutor({
6635
6662
  customTools: this.getCustomTools(),
6636
- executeTool: (toolName, params) => this.executeTool(toolName, params, {
6637
- disableToolCache: options.disableToolCache,
6638
- }),
6663
+ executeTool: this.providerToolExecutor(options.disableToolCache),
6639
6664
  }, functionTag);
6640
6665
  logger.debug("[Observability] User input to LLM", {
6641
6666
  requestId,
@@ -6856,9 +6881,7 @@ Current user's request: ${currentInput}`;
6856
6881
  // Enable tool execution for direct provider generation using BaseProvider method
6857
6882
  provider.setupToolExecutor({
6858
6883
  customTools: this.getCustomTools(),
6859
- executeTool: (toolName, params) => this.executeTool(toolName, params, {
6860
- disableToolCache: options.disableToolCache,
6861
- }),
6884
+ executeTool: this.providerToolExecutor(options.disableToolCache),
6862
6885
  }, functionTag);
6863
6886
  provider.setFileToolRootPolicy?.(this.fileToolRootsFor(options));
6864
6887
  const result = await provider.generate({
@@ -6946,9 +6969,7 @@ Current user's request: ${currentInput}`;
6946
6969
  poolProvider.setTraceContext(this._metricsTraceContext);
6947
6970
  poolProvider.setupToolExecutor({
6948
6971
  customTools: this.getCustomTools(),
6949
- executeTool: (toolName, params) => this.executeTool(toolName, params, {
6950
- disableToolCache: options.disableToolCache,
6951
- }),
6972
+ executeTool: this.providerToolExecutor(options.disableToolCache),
6952
6973
  }, functionTag);
6953
6974
  poolProvider.setFileToolRootPolicy?.(this.fileToolRootsFor(options));
6954
6975
  const poolResult = await poolProvider.generate({
@@ -9371,13 +9392,13 @@ Current user's request: ${currentInput}`;
9371
9392
  reason: errorMsg,
9372
9393
  });
9373
9394
  try {
9374
- const fallbackProvider = await AIProviderFactory.createProvider(fallbackRoute.provider, fallbackRoute.model, true, undefined, undefined, this.resolveCredentials(enhancedOptions.credentials));
9395
+ // Built with this instance, like the primary provider, so the
9396
+ // fallback's tools are confirmed by this instance's rule.
9397
+ const fallbackProvider = await AIProviderFactory.createProvider(fallbackRoute.provider, fallbackRoute.model, true, this, undefined, this.resolveCredentials(enhancedOptions.credentials));
9375
9398
  // Ensure fallback provider can execute tools
9376
9399
  fallbackProvider.setupToolExecutor({
9377
9400
  customTools: this.getCustomTools(),
9378
- executeTool: (toolName, params) => this.executeTool(toolName, params, {
9379
- disableToolCache: enhancedOptions.disableToolCache,
9380
- }),
9401
+ executeTool: this.providerToolExecutor(enhancedOptions.disableToolCache),
9381
9402
  }, "NeuroLink.fallbackStream");
9382
9403
  // Prefer the caller-supplied / compacted conversation messages that were
9383
9404
  // threaded through options. Only fall back to memory when no explicit
@@ -9636,9 +9657,7 @@ Current user's request: ${currentInput}`;
9636
9657
  // Enable tool execution for the provider using BaseProvider method
9637
9658
  provider.setupToolExecutor({
9638
9659
  customTools: this.getCustomTools(),
9639
- executeTool: (toolName, params) => this.executeTool(toolName, params, {
9640
- disableToolCache: options.disableToolCache,
9641
- }),
9660
+ executeTool: this.providerToolExecutor(options.disableToolCache),
9642
9661
  }, "NeuroLink.createMCPStream");
9643
9662
  // 🔧 FIX: Get available tools and create tool-aware system prompt
9644
9663
  // Use SAME pattern as tryMCPGeneration (generate mode)
@@ -9915,9 +9934,7 @@ Current user's request: ${currentInput}`;
9915
9934
  poolStreamProvider.setTraceContext(this._metricsTraceContext);
9916
9935
  poolStreamProvider.setupToolExecutor({
9917
9936
  customTools: this.getCustomTools(),
9918
- executeTool: (toolName, params) => this.executeTool(toolName, params, {
9919
- disableToolCache: options.disableToolCache,
9920
- }),
9937
+ executeTool: this.providerToolExecutor(options.disableToolCache),
9921
9938
  }, "NeuroLink.createMCPStream");
9922
9939
  poolStreamProvider.setFileToolRootPolicy?.(this.fileToolRootsFor(options));
9923
9940
  const poolStreamResult = await poolStreamProvider.stream({
@@ -10168,7 +10185,15 @@ Current user's request: ${currentInput}`;
10168
10185
  const originalPrompt = options.input.text;
10169
10186
  const responseTime = Date.now() - startTime;
10170
10187
  const providerName = await getBestProvider(options.provider);
10171
- const provider = await AIProviderFactory.createProvider(providerName, options.model, true, undefined, undefined, this.resolveCredentials(options.credentials));
10188
+ // Built with this instance, like the primary provider, so the
10189
+ // fallback's tools are confirmed by this instance's rule. It follows the
10190
+ // call's tool options as the primary does: no tools when the call
10191
+ // disabled them, and the call's tool filters, signal and cache choice.
10192
+ const provider = await AIProviderFactory.createProvider(providerName, options.model, !options.disableTools, this, undefined, this.resolveCredentials(options.credentials));
10193
+ provider.setupToolExecutor({
10194
+ customTools: this.getCustomTools(),
10195
+ executeTool: this.providerToolExecutor(options.disableToolCache),
10196
+ }, "NeuroLink.handleStreamError");
10172
10197
  provider.setFileToolRootPolicy?.(this.fileToolRootsFor(options));
10173
10198
  const fallbackStreamResult = await provider.stream({
10174
10199
  input: { text: options.input.text },
@@ -10176,6 +10201,27 @@ Current user's request: ${currentInput}`;
10176
10201
  temperature: options.temperature,
10177
10202
  maxTokens: options.maxTokens,
10178
10203
  conversationMessages: options.conversationMessages,
10204
+ ...(options.disableTools !== undefined && {
10205
+ disableTools: options.disableTools,
10206
+ }),
10207
+ ...(options.tools && { tools: options.tools }),
10208
+ ...(options.toolFilter && { toolFilter: options.toolFilter }),
10209
+ ...(options.excludeTools && { excludeTools: options.excludeTools }),
10210
+ ...(options.enabledToolNames && {
10211
+ enabledToolNames: options.enabledToolNames,
10212
+ }),
10213
+ ...(options.abortSignal && { abortSignal: options.abortSignal }),
10214
+ ...(options.disableToolCache !== undefined && {
10215
+ disableToolCache: options.disableToolCache,
10216
+ }),
10217
+ ...(options.maxSteps !== undefined && { maxSteps: options.maxSteps }),
10218
+ ...(options.toolTimeoutMs !== undefined && {
10219
+ toolTimeoutMs: options.toolTimeoutMs,
10220
+ }),
10221
+ ...(options.turnTimeoutMs !== undefined && {
10222
+ turnTimeoutMs: options.turnTimeoutMs,
10223
+ }),
10224
+ ...(options.timeout !== undefined && { timeout: options.timeout }),
10179
10225
  });
10180
10226
  // Create a wrapper around the fallback stream that accumulates content
10181
10227
  let fallbackAccumulatedContent = "";
@@ -11266,6 +11312,15 @@ Current user's request: ${currentInput}`;
11266
11312
  getAutoDiscoveredServerInfos() {
11267
11313
  return this.autoDiscoveredServerInfos;
11268
11314
  }
11315
+ /**
11316
+ * The `executeTool` a provider's tool loop calls (via `setupToolExecutor`)
11317
+ * for a registered tool. It forwards what the loop passes for the call,
11318
+ * above all its signal (the turn's abort or the loop's per-tool deadline),
11319
+ * so the call's confirmation, its attempts and the tool see a cancellation.
11320
+ */
11321
+ providerToolExecutor(disableToolCache) {
11322
+ return (toolName, params, callOptions) => this.executeTool(toolName, params, { ...callOptions, disableToolCache });
11323
+ }
11269
11324
  /**
11270
11325
  * Execute a specific tool by name with robust error handling
11271
11326
  * Supports both custom tools and MCP server tools with timeout, retry, and circuit breaker patterns
@@ -11275,7 +11330,20 @@ Current user's request: ${currentInput}`;
11275
11330
  * @returns Tool execution result
11276
11331
  */
11277
11332
  async executeTool(toolName, params = {}, options) {
11278
- if (this.mcpToolBatcher && !options?.bypassBatcher) {
11333
+ // A call that needs a human's confirmation is never batched: the gate in
11334
+ // runPreparedToolExecution must ask before any timer (a batch has its
11335
+ // own), before the result cache, and with the caller's abortSignal. Nor
11336
+ // is a call that carries a signal: only this path takes it to the
11337
+ // confirmation, the attempts and the tool. Nor is an agent tool's: only
11338
+ // this path's attempt signal stops its worker run when the call ends.
11339
+ // Nor is a call made with no retries: the batch drops the call's
11340
+ // options, and only this path keeps it to one run.
11341
+ if (this.mcpToolBatcher &&
11342
+ !options?.bypassBatcher &&
11343
+ options?.maxRetries !== 0 &&
11344
+ !(options?.abortSignal ?? abortSignalOf(options?.authContext)) &&
11345
+ !this.toolRegistry.isToolUnbatchable(toolName) &&
11346
+ !this.callNeedsConfirmation(toolName, params)) {
11279
11347
  return this.mcpToolBatcher.execute(toolName, params);
11280
11348
  }
11281
11349
  const executionContext = this.createToolExecutionContext(toolName, params, options);
@@ -11314,7 +11382,7 @@ Current user's request: ${currentInput}`;
11314
11382
  toolType,
11315
11383
  inputSize: inputStr.length,
11316
11384
  options,
11317
- hitlState: { triggered: false },
11385
+ hitlState: createHITLExecutionState(),
11318
11386
  };
11319
11387
  }
11320
11388
  async executeToolWithSpan(toolName, params, options, executionContext, toolSpan) {
@@ -11409,6 +11477,10 @@ Current user's request: ${currentInput}`;
11409
11477
  retryDelayMs,
11410
11478
  authContext: options?.authContext,
11411
11479
  disableToolCache: options?.disableToolCache,
11480
+ // A caller that passes its signal only in authContext (the channel
11481
+ // registerAgentTool reads) gets the same cancellation.
11482
+ abortSignal: options?.abortSignal ?? abortSignalOf(options?.authContext),
11483
+ pauseDeadline: options?.pauseDeadline,
11412
11484
  };
11413
11485
  const { MemoryManager } = await import("./utils/performance.js");
11414
11486
  const startMemory = MemoryManager.getMemoryUsageMB();
@@ -11445,9 +11517,38 @@ Current user's request: ${currentInput}`;
11445
11517
  async runPreparedToolExecution(toolName, params, prepared, executionContext, toolSpan) {
11446
11518
  let toolRetryCount = 0;
11447
11519
  try {
11520
+ // A call cancelled before it starts throws, gated or not, instead of
11521
+ // coming back as a refusal.
11522
+ throwIfSignalAborted(prepared.finalOptions.abortSignal);
11523
+ // An open breaker refuses the call before it asks the human: an
11524
+ // approval could not be acted on. Non-mutating, so the half-open probe
11525
+ // is still taken by the execute below.
11526
+ prepared.circuitBreaker.assertAvailable();
11527
+ // Before the breaker, the retry loop and the attempt timeout: waiting
11528
+ // for a human can neither time an attempt out nor be retried, and only
11529
+ // an approved call reaches executeToolInternal.
11530
+ const gate = await this.gateToolCall(toolName, params, {
11531
+ state: executionContext.hitlState,
11532
+ serverId: executionContext.externalTool?.serverId ??
11533
+ this.toolRegistry.getToolInfo(toolName)?.tool?.serverId,
11534
+ external: executionContext.externalTool !== undefined,
11535
+ authContext: prepared.finalOptions.authContext,
11536
+ span: toolSpan,
11537
+ }, {
11538
+ abortSignal: prepared.finalOptions.abortSignal,
11539
+ pauseDeadline: prepared.finalOptions.pauseDeadline,
11540
+ });
11541
+ if ("refused" in gate) {
11542
+ return this.handleRefusedToolExecution(toolName, gate.refused, prepared, executionContext, toolSpan);
11543
+ }
11544
+ const approvedParams = gate.params;
11545
+ const { abortSignal } = prepared.finalOptions;
11546
+ // Cancelled before the first attempt: nothing runs, and the breaker is
11547
+ // not entered (a cancellation says nothing about the tool's health).
11548
+ throwIfSignalAborted(abortSignal);
11448
11549
  mcpLogger.debug(`[${executionContext.functionTag}] Executing tool: ${toolName}`, {
11449
11550
  toolName,
11450
- params,
11551
+ params: approvedParams,
11451
11552
  options: prepared.finalOptions,
11452
11553
  circuitBreakerState: prepared.circuitBreaker.getState(),
11453
11554
  });
@@ -11456,9 +11557,18 @@ Current user's request: ${currentInput}`;
11456
11557
  const budgetStart = Date.now();
11457
11558
  const deadline = budgetStart + totalTimeout;
11458
11559
  let attemptNumber = 0;
11459
- const result = await prepared.circuitBreaker.execute(async () => {
11560
+ // Kept out of the breaker once the call is under way: the abort that
11561
+ // stops a retry from starting, and any outcome after a caller's cancel
11562
+ // (a failure is not counted, and a result does not reset the count).
11563
+ // A failure after the call's own per-tool deadline fired still counts:
11564
+ // the deadline is evidence about the tool.
11565
+ const isCancellation = (error) => abortSignal?.aborted === true &&
11566
+ (isAbortError(error) || isCancelledByCaller(abortSignal));
11567
+ const runAttempts = async () => {
11460
11568
  return withRetry(async () => {
11461
11569
  attemptNumber++;
11570
+ // Cancelled during the retry delay: no further attempt starts.
11571
+ throwIfSignalAborted(abortSignal);
11462
11572
  const remaining = deadline - Date.now();
11463
11573
  if (remaining <= 0) {
11464
11574
  throw ErrorFactory.toolTimeout(toolName, totalTimeout, undefined, {
@@ -11474,19 +11584,44 @@ Current user's request: ${currentInput}`;
11474
11584
  // retries alone would not: the last attempt could start just under
11475
11585
  // the deadline and still run a full attempt timeout past it.
11476
11586
  const attemptTimeout = Math.min(prepared.finalOptions.timeout, remaining);
11477
- return withTimeout(this.executeToolInternal(toolName, params, prepared.finalOptions, executionContext.hitlState), attemptTimeout, ErrorFactory.toolTimeout(toolName, attemptTimeout, undefined, {
11587
+ // Each attempt runs under a signal of its own, linked to the
11588
+ // call's, that is aborted with a TimeoutError when the attempt
11589
+ // times out. An attempt the timer gives up on is thereby stopped,
11590
+ // not left running: a confirmation it is waiting on is withdrawn,
11591
+ // and the work it started is cancelled. The breaker still reads
11592
+ // only the call's signal (isCancellation), so a timed-out attempt
11593
+ // counts as before.
11594
+ const attemptTimeoutError = ErrorFactory.toolTimeout(toolName, attemptTimeout, undefined, {
11478
11595
  attempt: attemptNumber,
11479
11596
  maxAttempts,
11480
11597
  attemptTimeoutMs: prepared.finalOptions.timeout,
11481
11598
  totalTimeoutMs: totalTimeout,
11482
11599
  elapsedMs: Date.now() - budgetStart,
11483
- }));
11600
+ });
11601
+ const attempt = this.attemptSignals(abortSignal, prepared.finalOptions.authContext);
11602
+ try {
11603
+ return await withTimeout(this.executeToolInternal(toolName, approvedParams, {
11604
+ ...prepared.finalOptions,
11605
+ abortSignal: attempt.callSignal,
11606
+ toolAbortSignal: attempt.toolSignal,
11607
+ }, executionContext.hitlState), attemptTimeout, attemptTimeoutError);
11608
+ }
11609
+ catch (error) {
11610
+ if (error === attemptTimeoutError) {
11611
+ attempt.abort(new TimeoutError(`Tool "${toolName}" attempt timed out after ${attemptTimeout}ms`, attemptTimeout));
11612
+ }
11613
+ throw error;
11614
+ }
11615
+ finally {
11616
+ attempt.dispose();
11617
+ }
11484
11618
  }, {
11485
11619
  maxAttempts,
11486
11620
  delayMs: prepared.finalOptions.retryDelayMs,
11487
11621
  // Stop when there is not enough budget left for the retry delay
11488
11622
  // plus any real work after it.
11489
- isRetriable: (error) => Date.now() + prepared.finalOptions.retryDelayMs < deadline &&
11623
+ isRetriable: (error) => !abortSignal?.aborted &&
11624
+ Date.now() + prepared.finalOptions.retryDelayMs < deadline &&
11490
11625
  isRetriableError(error),
11491
11626
  onRetry: (attempt, error) => {
11492
11627
  toolRetryCount = attempt;
@@ -11497,6 +11632,9 @@ Current user's request: ${currentInput}`;
11497
11632
  });
11498
11633
  },
11499
11634
  });
11635
+ };
11636
+ const result = await prepared.circuitBreaker.execute(runAttempts, {
11637
+ isCancellation,
11500
11638
  });
11501
11639
  toolSpan.setAttribute("tool.retry_count", toolRetryCount);
11502
11640
  return await this.handleSuccessfulToolExecution(toolName, result, prepared, executionContext, toolSpan);
@@ -11507,6 +11645,169 @@ Current user's request: ${currentInput}`;
11507
11645
  return this.handleFailedToolExecution(toolName, params, error, prepared, executionContext, toolSpan);
11508
11646
  }
11509
11647
  }
11648
+ /**
11649
+ * Confirm a tool call with the human, once, before any attempt timer, retry
11650
+ * or circuit breaker the call is subject to starts. The decision is written
11651
+ * to `ctx.state`, which every attempt carries down to the registry and the
11652
+ * external server manager, so neither asks again. An approved (or
11653
+ * not-required) call gets the parameters to run with, the approver's edits
11654
+ * included; any other decision gets the registry's `{ success: false }`
11655
+ * result, which `executeTool` returns without retrying.
11656
+ */
11657
+ async gateToolCall(toolName, params, ctx, options) {
11658
+ const hitl = this.confirmationManagerFor(ctx.external);
11659
+ // HITL off everywhere this call can reach: nothing to confirm, and no
11660
+ // decision is recorded.
11661
+ if (!hitl?.isEnabled()) {
11662
+ return { params };
11663
+ }
11664
+ // The identity the registry's inline check reports on the card.
11665
+ const identity = {
11666
+ ...this.toolExecutionContext,
11667
+ ...ctx.authContext,
11668
+ };
11669
+ const sessionId = typeof identity.sessionId === "string" ? identity.sessionId : undefined;
11670
+ const userId = typeof identity.userId === "string"
11671
+ ? identity.userId
11672
+ : getAmbientAuthContext()?.user?.id;
11673
+ const startedAt = Date.now();
11674
+ const action = await resolveToolCallConfirmation(hitl, toolName, params, ctx.state, {
11675
+ serverId: ctx.serverId,
11676
+ sessionId: sessionId ?? crypto.randomUUID(),
11677
+ userId,
11678
+ signal: options.abortSignal,
11679
+ }, { span: ctx.span, pauseDeadline: options.pauseDeadline });
11680
+ if (action.run) {
11681
+ return { params: action.args };
11682
+ }
11683
+ return {
11684
+ refused: {
11685
+ success: false,
11686
+ data: null,
11687
+ error: action.error.message,
11688
+ usage: { executionTime: Date.now() - startedAt },
11689
+ metadata: { toolName, sessionId },
11690
+ },
11691
+ };
11692
+ }
11693
+ /**
11694
+ * The HITL manager that confirms a call before any timer starts.
11695
+ *
11696
+ * The one the call's inline check would ask, when it is enabled: the tool
11697
+ * registry's for a registered or built-in tool, the external manager's for
11698
+ * an external MCP tool. That is the manager these calls have always been
11699
+ * confirmed with, and asking it here, before the attempt timer and the
11700
+ * retries, records the decision so the inline check skips it. Otherwise
11701
+ * this instance's own, when it has an enabled one.
11702
+ *
11703
+ * An instance with HITL installs its manager on its registry and its
11704
+ * external manager, so the two usually agree. They differ when another
11705
+ * manager was installed on the registry: with `setHITLManager`, or by a
11706
+ * worker with HITL of its own on a shared registry, which takes it over.
11707
+ * A worker built on a host's registry (`createWorkerInstance`, and so
11708
+ * `runIsolatedAgent`, `registerAgentTool` and `delegate_task`) with no HITL
11709
+ * of its own is confirmed by the registry's manager, the host's unless
11710
+ * another took it over, and the card reaches that manager owner's emitter.
11711
+ */
11712
+ confirmationManagerFor(external) {
11713
+ const inlineManager = external
11714
+ ? this.externalServerManager.getHITLManager()
11715
+ : this.toolRegistry.getHITLManager();
11716
+ if (inlineManager?.isEnabled()) {
11717
+ return inlineManager;
11718
+ }
11719
+ return this.hitlManager?.isEnabled() ? this.hitlManager : inlineManager;
11720
+ }
11721
+ /**
11722
+ * Confirm one call to a built-in tool that a model loop runs directly (the
11723
+ * file, time and math tools a provider hands the model, which never pass
11724
+ * through `executeTool`). It is the same confirmation step `executeTool`
11725
+ * runs for a registered tool, before the tool's body: the same manager, the
11726
+ * same rule (`requiresConfirmation` on the tool's name and arguments), the
11727
+ * same outcomes, and the call's signal and the loop's deadline pause. The
11728
+ * built-ins that change the machine (`writeFile`, `executeBashCommand`) are
11729
+ * also asked when the rule does not match, unless the host set
11730
+ * `hitl.confirmBuiltinTools: false`.
11731
+ *
11732
+ * Returns `{ run: true, args }` (the approved, possibly modified,
11733
+ * arguments) or `{ run: false, error }` for a refusal. A tool that needs no
11734
+ * confirmation, or HITL off, runs unchanged and nothing is asked.
11735
+ */
11736
+ // Not `@internal`: the provider tool manager calls it through the
11737
+ // `NeuroLink` type, and stripInternal would drop it from the shipped
11738
+ // declarations that manager compiles against.
11739
+ async confirmBuiltInToolCall(toolName, args, options = {}) {
11740
+ const hitl = this.confirmationManagerFor(false);
11741
+ if (!hitl?.isEnabled()) {
11742
+ return { run: true, args };
11743
+ }
11744
+ const identity = { ...this.toolExecutionContext };
11745
+ const sessionId = typeof identity.sessionId === "string" ? identity.sessionId : undefined;
11746
+ const userId = typeof identity.userId === "string"
11747
+ ? identity.userId
11748
+ : getAmbientAuthContext()?.user?.id;
11749
+ return resolveToolCallConfirmation(hitl, toolName, args, undefined, {
11750
+ // The serverId a built-in tool's card has always carried.
11751
+ serverId: "direct",
11752
+ sessionId: sessionId ?? crypto.randomUUID(),
11753
+ userId,
11754
+ signal: options.abortSignal,
11755
+ }, {
11756
+ log: (message) => mcpLogger.info(`[NeuroLink] ${message}`),
11757
+ subject: "Built-in tool",
11758
+ pauseDeadline: options.pauseDeadline,
11759
+ alwaysConfirm: builtInToolAlwaysConfirmed(hitl, toolName),
11760
+ });
11761
+ }
11762
+ /**
11763
+ * Whether the gate would ask a human about this call, for a registered or
11764
+ * an external tool. Each distinct manager is asked once; the registry and
11765
+ * the external manager usually share the host's.
11766
+ */
11767
+ callNeedsConfirmation(toolName, params) {
11768
+ const managers = new Set([
11769
+ this.confirmationManagerFor(false),
11770
+ this.confirmationManagerFor(true),
11771
+ ]);
11772
+ for (const manager of managers) {
11773
+ if (manager?.requiresConfirmation(toolName, params)) {
11774
+ return true;
11775
+ }
11776
+ }
11777
+ return false;
11778
+ }
11779
+ /**
11780
+ * Bookkeeping for a call its confirmation refused: `tool:end` with
11781
+ * `success: false`, the span marked as an error and a failed execution
11782
+ * counted. No circuit-breaker failure is recorded (a human's answer says
11783
+ * nothing about the tool's health), and nothing ran.
11784
+ */
11785
+ handleRefusedToolExecution(toolName, refused, prepared, executionContext, toolSpan) {
11786
+ const executionTime = Date.now() - executionContext.executionStartTime;
11787
+ const decision = executionContext.hitlState.decision;
11788
+ const message = typeof refused.error === "string" ? refused.error : "Tool call refused";
11789
+ const category = decision === "timeout"
11790
+ ? ErrorCategory.TIMEOUT
11791
+ : decision === "cancelled"
11792
+ ? ErrorCategory.ABORT
11793
+ : ErrorCategory.PERMISSION;
11794
+ prepared.metrics.failedExecutions++;
11795
+ prepared.metrics.errorCategories[category] =
11796
+ (prepared.metrics.errorCategories[category] || 0) + 1;
11797
+ mcpLogger.info(`[${executionContext.functionTag}] Tool call refused by its HITL confirmation: ${toolName}`, { toolName, decision, executionTime });
11798
+ const error = new Error(message);
11799
+ // Gate on listenerCount — see handleGenerateTextInternalFailure for the
11800
+ // rationale (Node EventEmitter rethrows on no listener).
11801
+ if (this.emitter.listenerCount("error") > 0) {
11802
+ this.emitter.emit("error", error);
11803
+ }
11804
+ this.emitToolEndEvent(toolName, executionContext.executionStartTime, false, refused, error, executionContext.executionId);
11805
+ toolSpan.setAttribute("tool.retry_count", 0);
11806
+ toolSpan.setAttribute("tool.result.status", "refused");
11807
+ toolSpan.setAttribute("tool.duration_ms", executionTime);
11808
+ toolSpan.setStatus({ code: SpanStatusCode.ERROR, message });
11809
+ return markRefusalResult(refused);
11810
+ }
11510
11811
  async handleSuccessfulToolExecution(toolName, result, prepared, executionContext, toolSpan) {
11511
11812
  const executionTime = Date.now() - executionContext.executionStartTime;
11512
11813
  prepared.metrics.successfulExecutions++;
@@ -11553,6 +11854,11 @@ Current user's request: ${currentInput}`;
11553
11854
  try {
11554
11855
  await prepared.circuitBreaker.execute(async () => {
11555
11856
  throw new Error(`Tool ${toolName} returned isError:true`);
11857
+ },
11858
+ // A tool that stopped because its caller cancelled is not unwell; one
11859
+ // its per-tool deadline stopped may be, and is counted.
11860
+ {
11861
+ isCancellation: () => isCancelledByCaller(prepared.finalOptions.abortSignal),
11556
11862
  });
11557
11863
  }
11558
11864
  catch {
@@ -11717,8 +12023,9 @@ Current user's request: ${currentInput}`;
11717
12023
  return undefined;
11718
12024
  }
11719
12025
  }
11720
- async executeToolInternal(toolName, params, options, HITLState) {
12026
+ async executeToolInternal(toolName, params, options, hitlState) {
11721
12027
  const functionTag = "NeuroLink.executeToolInternal";
12028
+ const { abortSignal } = options;
11722
12029
  // === MCP ENHANCEMENT: Infer annotations for cache/retry decisions ===
11723
12030
  const toolAnnotations = this.getToolAnnotationsForExecution(toolName);
11724
12031
  const isCacheEnabled = this.mcpToolResultCache &&
@@ -11824,7 +12131,7 @@ Current user's request: ${currentInput}`;
11824
12131
  if (externalTool && externalTool.isAvailable) {
11825
12132
  try {
11826
12133
  mcpLogger.debug(`[${functionTag}] Executing external MCP tool: ${toolName} from ${externalTool.serverId}`);
11827
- const result = await this.externalServerManager.executeTool(externalTool.serverId, toolName, params, { timeout: options.timeout });
12134
+ const result = await this.externalServerManager.executeTool(externalTool.serverId, toolName, params, { timeout: options.timeout, hitlState, signal: abortSignal });
11828
12135
  logger.debug(`[${functionTag}] External MCP tool execution successful:`, {
11829
12136
  toolName,
11830
12137
  serverId: externalTool.serverId,
@@ -11833,25 +12140,12 @@ Current user's request: ${currentInput}`;
11833
12140
  return result;
11834
12141
  }
11835
12142
  catch (error) {
11836
- logger.error(`[${functionTag}] External MCP tool execution failed:`, {
11837
- toolName,
11838
- serverId: externalTool.serverId,
11839
- error: error instanceof Error ? error.message : String(error),
11840
- });
11841
- throw ErrorFactory.toolExecutionFailed(toolName, error instanceof Error ? error : new Error(String(error)), externalTool.serverId);
12143
+ throw this.externalToolFailure(functionTag, toolName, externalTool.serverId, error);
11842
12144
  }
11843
12145
  }
11844
12146
  // Execute via tool registry (custom/built-in tools)
11845
12147
  try {
11846
- const storedContext = this.toolExecutionContext || {};
11847
- const passedAuthContext = options.authContext || {};
11848
- // This instance's roots, on the private channel (overwrites the caller's).
11849
- const context = bindFileToolRoots({ ...storedContext, ...passedAuthContext, hitlState: HITLState }, this.resolveFileToolRoots(undefined));
11850
- logger.debug(`[Using merged context for unified registry tool:`, {
11851
- toolName,
11852
- storedContextKeys: Object.keys(storedContext),
11853
- finalContextKeys: Object.keys(context),
11854
- });
12148
+ const context = this.registryToolContext(toolName, options, hitlState);
11855
12149
  const result = (await this.toolRegistry.executeTool(toolName, params, context));
11856
12150
  // Check if result indicates a failure and emit error event
11857
12151
  if (result &&
@@ -11885,7 +12179,15 @@ Current user's request: ${currentInput}`;
11885
12179
  try {
11886
12180
  const result = await executeWithMiddleware(executeCore);
11887
12181
  // === MCP ENHANCEMENT: Cache store (after successful execution) ===
11888
- if (isCacheEnabled && toolResultCache && result !== undefined) {
12182
+ // Never a refusal: the identical call must raise a new card. Never a
12183
+ // result produced after the call's signal fired: a tool that stopped on
12184
+ // it returned an early or partial value the next call must not get.
12185
+ if (isCacheEnabled &&
12186
+ toolResultCache &&
12187
+ result !== undefined &&
12188
+ !hitlStateRefused(hitlState) &&
12189
+ !isRefusalResult(result) &&
12190
+ !abortSignal?.aborted) {
11889
12191
  toolResultCache.cacheResult(toolName, cacheParams, result);
11890
12192
  logger.debug(`[${functionTag}] Cached result for tool: ${toolName}`);
11891
12193
  }
@@ -11893,23 +12195,18 @@ Current user's request: ${currentInput}`;
11893
12195
  }
11894
12196
  catch (error) {
11895
12197
  // === MCP ENHANCEMENT: Retry safe tools on failure ===
11896
- const toolStubForRetry = toolAnnotations
11897
- ? {
11898
- name: toolName,
11899
- description: "",
11900
- annotations: toolAnnotations,
11901
- execute: async () => ({}),
11902
- }
11903
- : undefined;
11904
- if (toolStubForRetry &&
11905
- isSafeToRetry(toolStubForRetry) &&
11906
- error instanceof Error &&
11907
- isRetriableError(error)) {
12198
+ if (this.maySafelyRetryOnce(toolName, toolAnnotations, options.maxRetries, abortSignal, error)) {
11908
12199
  logger.debug(`[${functionTag}] Tool ${toolName} is safe to retry, attempting once more`);
11909
12200
  try {
11910
12201
  const retryResult = await executeWithMiddleware(executeCore);
11911
- // Cache the retry result
11912
- if (isCacheEnabled && toolResultCache && retryResult !== undefined) {
12202
+ // Cache the retry result (never a refusal or a result produced
12203
+ // after the abort, as above)
12204
+ if (isCacheEnabled &&
12205
+ toolResultCache &&
12206
+ retryResult !== undefined &&
12207
+ !hitlStateRefused(hitlState) &&
12208
+ !isRefusalResult(retryResult) &&
12209
+ !abortSignal?.aborted) {
11913
12210
  toolResultCache.cacheResult(toolName, cacheParams, retryResult);
11914
12211
  }
11915
12212
  return retryResult;
@@ -11921,6 +12218,103 @@ Current user's request: ${currentInput}`;
11921
12218
  throw error;
11922
12219
  }
11923
12220
  }
12221
+ /**
12222
+ * Whether a failed call gets executeToolInternal's one extra run: a tool
12223
+ * whose annotations say it is safe to retry, a call that may be retried at
12224
+ * all (a tool with no retries runs once per call, as its registration
12225
+ * says), not cancelled, and a retriable error.
12226
+ */
12227
+ maySafelyRetryOnce(toolName, toolAnnotations, maxRetries, abortSignal, error) {
12228
+ if (!toolAnnotations || maxRetries === 0 || abortSignal?.aborted) {
12229
+ return false;
12230
+ }
12231
+ const toolStub = {
12232
+ name: toolName,
12233
+ description: "",
12234
+ annotations: toolAnnotations,
12235
+ execute: async () => ({}),
12236
+ };
12237
+ return (isSafeToRetry(toolStub) &&
12238
+ error instanceof Error &&
12239
+ isRetriableError(error));
12240
+ }
12241
+ /**
12242
+ * What an external tool call's failure surfaces as from executeToolInternal.
12243
+ * A call its caller cancelled stays the abort it is and is logged at info
12244
+ * (an outcome, not a fault); any other failure is logged and wrapped.
12245
+ */
12246
+ externalToolFailure(functionTag, toolName, serverId, error) {
12247
+ const cause = error instanceof Error ? error : new Error(String(error));
12248
+ if (isAbortError(error)) {
12249
+ logger.info(`[${functionTag}] External MCP tool call cancelled: ${toolName}`);
12250
+ return cause;
12251
+ }
12252
+ logger.error(`[${functionTag}] External MCP tool execution failed:`, {
12253
+ toolName,
12254
+ serverId,
12255
+ error: cause.message,
12256
+ });
12257
+ return ErrorFactory.toolExecutionFailed(toolName, cause, serverId);
12258
+ }
12259
+ /**
12260
+ * The signals one attempt of an `executeTool` call runs under, each linked
12261
+ * to an attempt controller that `abort()` fires when the attempt times out.
12262
+ *
12263
+ * - `callSignal`: the call's own signal plus the attempt's. It is the
12264
+ * attempt's `abortSignal` (the external manager's `signal`, the cache and
12265
+ * safe-retry guards).
12266
+ * - `toolSignal`: the signal the tool's context would otherwise carry (its
12267
+ * `authContext`'s, else the call's, else the one set with
12268
+ * `setToolContext()`) plus the attempt's. Precedence is unchanged; the
12269
+ * tool sees its usual signal, linked to the attempt's timer too.
12270
+ */
12271
+ attemptSignals(callSignal, authContext) {
12272
+ const attemptAbort = new AbortController();
12273
+ const call = composeAbortSignalsScoped(callSignal, attemptAbort.signal);
12274
+ const toolSource = abortSignalOf(authContext) ??
12275
+ callSignal ??
12276
+ abortSignalOf(this.toolExecutionContext);
12277
+ const tool = toolSource === callSignal
12278
+ ? call
12279
+ : composeAbortSignalsScoped(toolSource, attemptAbort.signal);
12280
+ return {
12281
+ callSignal: call.signal,
12282
+ toolSignal: tool.signal,
12283
+ abort: (reason) => {
12284
+ if (!attemptAbort.signal.aborted) {
12285
+ attemptAbort.abort(reason);
12286
+ }
12287
+ },
12288
+ dispose: () => {
12289
+ call.dispose();
12290
+ tool.dispose();
12291
+ },
12292
+ };
12293
+ }
12294
+ /**
12295
+ * The context a registry tool executes with: this instance's tool context
12296
+ * (`setToolContext`), then the call's `abortSignal` (it replaces a stored
12297
+ * one), then the caller's `authContext` (which wins), plus the call's HITL
12298
+ * state and, on its private channel, this instance's file-tool roots.
12299
+ */
12300
+ registryToolContext(toolName, options, hitlState) {
12301
+ const storedContext = this.toolExecutionContext || {};
12302
+ const context = bindFileToolRoots({
12303
+ ...storedContext,
12304
+ ...(options.abortSignal && { abortSignal: options.abortSignal }),
12305
+ ...options.authContext,
12306
+ ...(options.toolAbortSignal && {
12307
+ abortSignal: options.toolAbortSignal,
12308
+ }),
12309
+ hitlState,
12310
+ }, this.resolveFileToolRoots(undefined));
12311
+ logger.debug(`[Using merged context for unified registry tool:`, {
12312
+ toolName,
12313
+ storedContextKeys: Object.keys(storedContext),
12314
+ finalContextKeys: Object.keys(context),
12315
+ });
12316
+ return context;
12317
+ }
11924
12318
  /**
11925
12319
  * Get tool annotations for execution decisions (cache, retry).
11926
12320
  * Checks cached tool list first, falls back to inference from tool name.
@@ -13436,7 +13830,12 @@ Current user's request: ${currentInput}`;
13436
13830
  * @param serverId - ID of the server
13437
13831
  * @param toolName - Name of the tool
13438
13832
  * @param parameters - Tool parameters
13439
- * @param options - Execution options
13833
+ * @param options - Execution options. Aborting `abortSignal` withdraws the
13834
+ * call's pending confirmation; a call whose signal has already fired is
13835
+ * never sent to the server and rejects with an abort error, except that
13836
+ * a result already in the tool-result cache for this call is returned
13837
+ * first. `pauseDeadline` pauses the caller's deadline while that
13838
+ * confirmation waits.
13440
13839
  * @returns Tool execution result
13441
13840
  */
13442
13841
  async executeExternalMCPTool(serverId, requestedToolName, parameters, options) {
@@ -13487,7 +13886,11 @@ Current user's request: ${currentInput}`;
13487
13886
  return cached;
13488
13887
  }
13489
13888
  }
13490
- const result = await this.externalServerManager.executeTool(serverId, toolName, parameters, options);
13889
+ const result = await this.externalServerManager.executeTool(serverId, toolName, parameters, options && {
13890
+ timeout: options.timeout,
13891
+ signal: options.abortSignal,
13892
+ pauseDeadline: options.pauseDeadline,
13893
+ });
13491
13894
  // BZ-664: Store result in cache after successful execution.
13492
13895
  // Only cache SUCCESSFUL results. Caching an error result (isError:true /
13493
13896
  // success:false — e.g. an upstream 403/timeout surfaced as a tool error)
@@ -13514,7 +13917,17 @@ Current user's request: ${currentInput}`;
13514
13917
  return result;
13515
13918
  }
13516
13919
  catch (error) {
13517
- mcpLogger.error(`[NeuroLink] External MCP tool execution failed: ${toolName}`, error);
13920
+ if (error instanceof HITLError) {
13921
+ // A human's "no" (or a withdrawn card) is an outcome, not a fault.
13922
+ mcpLogger.info(`[NeuroLink] External MCP tool refused by its HITL confirmation: ${toolName}`);
13923
+ }
13924
+ else if (isAbortError(error) ||
13925
+ options?.abortSignal?.aborted === true) {
13926
+ mcpLogger.info(`[NeuroLink] External MCP tool call cancelled by its caller: ${toolName}`);
13927
+ }
13928
+ else {
13929
+ mcpLogger.error(`[NeuroLink] External MCP tool execution failed: ${toolName}`, error);
13930
+ }
13518
13931
  throw error;
13519
13932
  }
13520
13933
  }
@@ -13900,10 +14313,10 @@ Current user's request: ${currentInput}`;
13900
14313
  // The AI provider will handle parameters dynamically based on the tool description
13901
14314
  const toolDefinition = {
13902
14315
  description: tool.description,
13903
- execute: async (params) => {
14316
+ execute: async (params, execOptions) => {
13904
14317
  try {
13905
14318
  mcpLogger.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${tool.name}`, { params });
13906
- const result = await this.externalServerManager.executeTool(tool.serverId, tool.name, params, { timeout: 30000 });
14319
+ const result = await this.externalServerManager.executeTool(tool.serverId, tool.name, params, { timeout: 30000, signal: abortSignalOf(execOptions) });
13907
14320
  mcpLogger.debug(`[NeuroLink] External MCP tool execution result: ${tool.name}`, {
13908
14321
  success: !!result,
13909
14322
  hasData: !!(result &&
@@ -15453,6 +15866,9 @@ Current user's request: ${currentInput}`;
15453
15866
  const { registerAgentTool } = await import("./agent/agentToolRegistrar.js");
15454
15867
  const registered = registerAgentTool(this, definition, options);
15455
15868
  this.hasAgentTools = true;
15869
+ // Marked on the registry, so every instance that shares it, including
15870
+ // workers created before or after this call, never batches the tool.
15871
+ this.toolRegistry.setToolUnbatchable(registered.name, true);
15456
15872
  return registered;
15457
15873
  }
15458
15874
  /**
@@ -15543,7 +15959,12 @@ Current user's request: ${currentInput}`;
15543
15959
  // Never cacheable: `delegate_task` starts a new worker every call and
15544
15960
  // `collect_results` claims each outcome exactly once. A cached result
15545
15961
  // would spawn nothing and hand the same worker back twice.
15546
- this.registerTool(toolName, toolDef, { cacheable: false });
15962
+ // `delegate_task` is never retried either: once its spawn went through,
15963
+ // a retry after any later failure starts a second worker for the same
15964
+ // task.
15965
+ this.registerTool(toolName, toolDef, toolName === "delegate_task"
15966
+ ? { cacheable: false, maxRetries: 0 }
15967
+ : { cacheable: false });
15547
15968
  }
15548
15969
  this.hasBackgroundDelegationTools = true;
15549
15970
  logger.info(`[NeuroLink] Registered ${Object.keys(tools).length} background delegation tools`);