@juspay/neurolink 13.12.1 → 13.12.3

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 (59) hide show
  1. package/CHANGELOG.md +2 -5
  2. package/dist/agent/agentToolRegistrar.js +3 -1
  3. package/dist/browser/neurolink.min.js +467 -467
  4. package/dist/context/fileSummarizationService.js +2 -0
  5. package/dist/core/baseProvider.d.ts +2 -2
  6. package/dist/core/loopEngine.js +20 -8
  7. package/dist/core/modules/ToolsManager.d.ts +11 -33
  8. package/dist/core/modules/ToolsManager.js +71 -99
  9. package/dist/core/modules/Utilities.js +6 -1
  10. package/dist/core/toolExecutionGuards.js +79 -11
  11. package/dist/evaluation/ragasEvaluator.js +2 -0
  12. package/dist/evaluation/scorers/llm/baseLLMScorer.js +2 -0
  13. package/dist/hitl/hitlErrors.d.ts +8 -0
  14. package/dist/hitl/hitlErrors.js +12 -0
  15. package/dist/hitl/hitlManager.d.ts +25 -7
  16. package/dist/hitl/hitlManager.js +133 -15
  17. package/dist/hitl/index.d.ts +1 -1
  18. package/dist/hitl/index.js +1 -1
  19. package/dist/hitl/toolCallConfirmation.d.ts +57 -0
  20. package/dist/hitl/toolCallConfirmation.js +296 -0
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +4 -1
  23. package/dist/mcp/externalServerManager.d.ts +33 -2
  24. package/dist/mcp/externalServerManager.js +68 -52
  25. package/dist/mcp/mcpCircuitBreaker.d.ts +9 -2
  26. package/dist/mcp/mcpCircuitBreaker.js +9 -1
  27. package/dist/mcp/toolDiscoveryService.js +11 -2
  28. package/dist/mcp/toolRegistry.d.ts +20 -0
  29. package/dist/mcp/toolRegistry.js +68 -58
  30. package/dist/middleware/utils/guardrailsUtils.js +2 -0
  31. package/dist/neurolink.d.ts +114 -2
  32. package/dist/neurolink.js +492 -71
  33. package/dist/providers/amazonBedrock/client.js +23 -4
  34. package/dist/providers/anthropic/client.js +5 -1
  35. package/dist/providers/googleNativeGemini3/utils.js +5 -1
  36. package/dist/providers/openaiChatCompletionsBase.js +21 -3
  37. package/dist/rag/metadata/metadataExtractor.js +2 -0
  38. package/dist/rag/pipeline/RAGPipeline.js +4 -0
  39. package/dist/rag/pipeline/contextAssembly.d.ts +1 -0
  40. package/dist/rag/pipeline/contextAssembly.js +2 -0
  41. package/dist/rag/reranker/reranker.js +4 -0
  42. package/dist/types/hitl.d.ts +100 -8
  43. package/dist/types/mcp.d.ts +5 -0
  44. package/dist/types/providers.d.ts +23 -2
  45. package/dist/types/tools.d.ts +34 -9
  46. package/dist/utils/async/index.d.ts +2 -1
  47. package/dist/utils/async/index.js +2 -1
  48. package/dist/utils/async/pausableDeadline.d.ts +28 -0
  49. package/dist/utils/async/pausableDeadline.js +88 -0
  50. package/dist/utils/async/withTimeout.d.ts +5 -0
  51. package/dist/utils/async/withTimeout.js +23 -0
  52. package/dist/utils/errorHandling.d.ts +32 -1
  53. package/dist/utils/errorHandling.js +70 -18
  54. package/dist/utils/providerUtils.js +5 -1
  55. package/dist/workflow/core/ensembleExecutor.js +2 -0
  56. package/dist/workflow/core/judgeScorer.js +2 -0
  57. package/dist/workflow/core/responseConditioner.js +2 -0
  58. package/docs-site/static/search-index.json +8 -6
  59. package/package.json +5 -1
@@ -11,7 +11,9 @@ import { mcpLogger } from "../utils/logger.js";
11
11
  import { MCPClientFactory, terminateLiveStdioServers, } from "./mcpClientFactory.js";
12
12
  import { ToolDiscoveryService } from "./toolDiscoveryService.js";
13
13
  import { toolRegistry } from "./toolRegistry.js";
14
- import { HITLUserRejectedError, HITLTimeoutError } from "../hitl/hitlErrors.js";
14
+ import { HITLError } from "../hitl/hitlErrors.js";
15
+ import { resolveToolCallConfirmation } from "../hitl/toolCallConfirmation.js";
16
+ import { throwIfSignalAborted } from "../utils/errorHandling.js";
15
17
  import { detectCategory } from "../utils/mcpDefaults.js";
16
18
  import { isObject, isNonNullObject } from "../utils/typeUtils.js";
17
19
  import { recordMCPToolCall } from "../telemetry/aiMetrics.js";
@@ -545,6 +547,13 @@ export class ExternalServerManager extends EventEmitter {
545
547
  toolDiscovery;
546
548
  enableMainRegistryIntegration;
547
549
  hitlManager; // Optional HITL manager for safety mechanisms
550
+ /**
551
+ * Where to find a manager when none was set with `setHITLManager`: the
552
+ * owning instance's tool registry, so an instance with no HITL of its own
553
+ * on a shared registry (a worker) confirms its external tools with the
554
+ * registry's manager, as it does its registered tools.
555
+ */
556
+ fallbackHITLManager;
548
557
  constructor(config = {}, options = {}) {
549
558
  super();
550
559
  // Set defaults for configuration
@@ -609,10 +618,23 @@ export class ExternalServerManager extends EventEmitter {
609
618
  }
610
619
  }
611
620
  /**
612
- * Get current HITL manager
621
+ * Set where to find a HITL manager when none was set with
622
+ * `setHITLManager`, resolved per call. NeuroLink points it at its tool
623
+ * registry's manager, so an instance with no HITL of its own on a shared
624
+ * registry confirms its external tools with that manager.
625
+ */
626
+ setFallbackHITLManager(resolve) {
627
+ this.fallbackHITLManager = resolve;
628
+ }
629
+ /**
630
+ * Get the HITL manager external tool calls are confirmed with: the one set
631
+ * with `setHITLManager` when it is enabled, else the fallback's.
613
632
  */
614
633
  getHITLManager() {
615
- return this.hitlManager;
634
+ if (this.hitlManager?.isEnabled()) {
635
+ return this.hitlManager;
636
+ }
637
+ return this.fallbackHITLManager?.() ?? this.hitlManager;
616
638
  }
617
639
  /**
618
640
  * Resolve the human-readable server name for an event payload.
@@ -2004,54 +2026,17 @@ export class ExternalServerManager extends EventEmitter {
2004
2026
  if (blockedTools.includes(toolName)) {
2005
2027
  throw new Error(`Tool '${toolName}' is blocked on server '${serverId}' by configuration`);
2006
2028
  }
2029
+ // A call its caller already cancelled raises no card and is never sent.
2030
+ throwIfSignalAborted(options?.signal);
2007
2031
  const startTime = Date.now();
2008
2032
  try {
2009
- // HITL Safety Check: Request confirmation if required
2010
- let finalParameters = parameters;
2011
- if (this.hitlManager && this.hitlManager.isEnabled()) {
2012
- const requiresConfirmation = this.hitlManager.requiresConfirmation(toolName, parameters);
2013
- if (requiresConfirmation) {
2014
- mcpLogger.info(`[ExternalServerManager] External tool '${toolName}' on server '${serverId}' requires HITL confirmation`);
2015
- try {
2016
- const confirmationResult = await this.hitlManager.requestConfirmation(toolName, parameters, {
2017
- serverId: serverId,
2018
- sessionId: `external-${serverId}-${Date.now()}`,
2019
- userId: undefined, // External tools don't have user context by default
2020
- });
2021
- if (!confirmationResult.approved) {
2022
- // User rejected the tool execution
2023
- throw new HITLUserRejectedError(`External tool execution rejected by user: ${confirmationResult.reason || "No reason provided"}`, toolName, confirmationResult.reason);
2024
- }
2025
- // User approved - use modified arguments if provided
2026
- if (confirmationResult.modifiedArguments !== undefined) {
2027
- finalParameters =
2028
- confirmationResult.modifiedArguments;
2029
- mcpLogger.info(`[ExternalServerManager] External tool '${toolName}' arguments modified by user`);
2030
- }
2031
- mcpLogger.info(`[ExternalServerManager] External tool '${toolName}' approved for execution (response time: ${confirmationResult.responseTime}ms)`);
2032
- }
2033
- catch (error) {
2034
- if (error instanceof HITLTimeoutError) {
2035
- // Timeout occurred - user didn't respond in time
2036
- mcpLogger.warn(`[ExternalServerManager] External tool '${toolName}' execution timed out waiting for user confirmation`);
2037
- throw error;
2038
- }
2039
- else if (error instanceof HITLUserRejectedError) {
2040
- // User explicitly rejected
2041
- mcpLogger.info(`[ExternalServerManager] External tool '${toolName}' execution rejected by user`);
2042
- throw error;
2043
- }
2044
- else {
2045
- // Other HITL error (configuration, system error, etc.)
2046
- mcpLogger.error(`[ExternalServerManager] HITL confirmation failed for external tool '${toolName}':`, error);
2047
- throw new Error(`HITL confirmation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
2048
- }
2049
- }
2050
- }
2051
- else {
2052
- mcpLogger.debug(`[ExternalServerManager] External tool '${toolName}' does not require HITL confirmation`);
2053
- }
2054
- }
2033
+ // HITL Safety Check. A call that NeuroLink.executeTool already gated
2034
+ // carries its decision (and the approved parameters) and is not asked
2035
+ // again; a direct caller without one is asked here, before the
2036
+ // discovery service starts its timer.
2037
+ const finalParameters = await this.confirmExternalToolCall(serverId, toolName, parameters, options);
2038
+ // Cancelled while the decision was being made: nothing is sent.
2039
+ throwIfSignalAborted(options?.signal);
2055
2040
  // Execute tool through discovery service (with potentially modified parameters)
2056
2041
  this.trackToolCall(serverId, 1);
2057
2042
  let result;
@@ -2060,6 +2045,7 @@ export class ExternalServerManager extends EventEmitter {
2060
2045
  timeout: options?.timeout ||
2061
2046
  instance.config.timeout ||
2062
2047
  this.config.defaultTimeout,
2048
+ signal: options?.signal,
2063
2049
  });
2064
2050
  }
2065
2051
  finally {
@@ -2098,9 +2084,17 @@ export class ExternalServerManager extends EventEmitter {
2098
2084
  }
2099
2085
  }
2100
2086
  catch (error) {
2101
- instance.metrics.totalErrors++;
2102
- recordMCPToolCall(toolName, Date.now() - startTime, false);
2103
- mcpLogger.error(`[ExternalServerManager] Tool execution failed: ${toolName} on ${serverId}`, error);
2087
+ if (error instanceof HITLError || options?.signal?.aborted === true) {
2088
+ // A human's "no" (a withdrawn card) or the caller's own cancellation
2089
+ // is an outcome, not a fault, and the server never received the
2090
+ // call: no server error is counted.
2091
+ mcpLogger.info(`[ExternalServerManager] External tool '${toolName}' on ${serverId} refused or cancelled before it ran: ${error instanceof Error ? error.message : String(error)}`);
2092
+ }
2093
+ else {
2094
+ instance.metrics.totalErrors++;
2095
+ recordMCPToolCall(toolName, Date.now() - startTime, false);
2096
+ mcpLogger.error(`[ExternalServerManager] Tool execution failed: ${toolName} on ${serverId}`, error);
2097
+ }
2104
2098
  // The SDK rejects with its connection-closed error when the server is
2105
2099
  // gone. Without this transition the instance stayed "connected" and
2106
2100
  // every later call failed the same way with no restart ever scheduled.
@@ -2110,6 +2104,28 @@ export class ExternalServerManager extends EventEmitter {
2110
2104
  throw error;
2111
2105
  }
2112
2106
  }
2107
+ /**
2108
+ * The external manager's inline HITL check, for a caller that arrives
2109
+ * without a recorded decision (`executeExternalMCPTool` and the AI-SDK
2110
+ * conversion path). Throws when the call must not run; otherwise returns
2111
+ * the parameters to run with.
2112
+ */
2113
+ async confirmExternalToolCall(serverId, toolName, parameters, options) {
2114
+ const action = await resolveToolCallConfirmation(this.getHITLManager(), toolName, parameters, options?.hitlState, {
2115
+ serverId,
2116
+ sessionId: `external-${serverId}-${Date.now()}`,
2117
+ userId: undefined, // External tools don't have user context by default
2118
+ signal: options?.signal,
2119
+ }, {
2120
+ log: (message) => mcpLogger.info(`[ExternalServerManager] ${message}`),
2121
+ subject: "External tool",
2122
+ pauseDeadline: options?.pauseDeadline,
2123
+ });
2124
+ if (!action.run) {
2125
+ throw action.error;
2126
+ }
2127
+ return action.args;
2128
+ }
2113
2129
  /**
2114
2130
  * Get all tools from all servers
2115
2131
  */
@@ -35,8 +35,15 @@ export declare class MCPCircuitBreaker extends EventEmitter {
35
35
  * the call is still counted as a normal, non-throwing success from the
36
36
  * `Promise.race` below, so this callback is what tells `execute()`
37
37
  * otherwise. Callers that never call it see no behavior change.
38
- */
39
- execute<T>(operation: (recordResolvedFailure: (reason?: string) => void) => Promise<T>): Promise<T>;
38
+ *
39
+ * `options.isCancelled` is consulted when `operation` throws: if it returns
40
+ * true the caller withdrew the request (e.g. an aborted signal), which says
41
+ * nothing about the downstream's health, so the error is rethrown without
42
+ * being recorded as a failure.
43
+ */
44
+ execute<T>(operation: (recordResolvedFailure: (reason?: string) => void) => Promise<T>, options?: {
45
+ isCancelled?: () => boolean;
46
+ }): Promise<T>;
40
47
  /**
41
48
  * Shared bookkeeping for a failed outcome — a thrown error, or a resolved
42
49
  * result the caller flagged via `recordResolvedFailure`. Records the call
@@ -67,8 +67,13 @@ export class MCPCircuitBreaker extends EventEmitter {
67
67
  * the call is still counted as a normal, non-throwing success from the
68
68
  * `Promise.race` below, so this callback is what tells `execute()`
69
69
  * otherwise. Callers that never call it see no behavior change.
70
+ *
71
+ * `options.isCancelled` is consulted when `operation` throws: if it returns
72
+ * true the caller withdrew the request (e.g. an aborted signal), which says
73
+ * nothing about the downstream's health, so the error is rethrown without
74
+ * being recorded as a failure.
70
75
  */
71
- async execute(operation) {
76
+ async execute(operation, options) {
72
77
  const startTime = Date.now();
73
78
  try {
74
79
  // Check if circuit is open
@@ -144,6 +149,9 @@ export class MCPCircuitBreaker extends EventEmitter {
144
149
  return result;
145
150
  }
146
151
  catch (error) {
152
+ if (options?.isCancelled?.()) {
153
+ throw error;
154
+ }
147
155
  // Record failed call
148
156
  const duration = Date.now() - startTime;
149
157
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -485,7 +485,10 @@ export class ToolDiscoveryService extends EventEmitter {
485
485
  const callResult = await withTimeout(client.callTool({
486
486
  name: toolName,
487
487
  arguments: effectiveParameters,
488
- }, undefined, { timeout: effectiveTimeout }), timeout, new Error(`Tool execution timeout: ${toolName}`));
488
+ }, undefined, {
489
+ timeout: effectiveTimeout,
490
+ ...(options.signal && { signal: options.signal }),
491
+ }), timeout, new Error(`Tool execution timeout: ${toolName}`));
489
492
  // Curator P0-1/P0-2: the MCP client does NOT throw on protocol
490
493
  // errors — it returns { isError: true, content: [...] }. Detect
491
494
  // that pattern so the span status reflects reality.
@@ -543,7 +546,9 @@ export class ToolDiscoveryService extends EventEmitter {
543
546
  callSpan.end();
544
547
  }
545
548
  });
546
- });
549
+ },
550
+ // A caller-cancelled call says nothing about the tool's health.
551
+ { isCancelled: () => options.signal?.aborted === true });
547
552
  const duration = Date.now() - startTime;
548
553
  // Update tool statistics. A resolved isError result is a failed call
549
554
  // for completion telemetry purposes even though the wrapper below
@@ -578,6 +583,10 @@ export class ToolDiscoveryService extends EventEmitter {
578
583
  // Update tool statistics
579
584
  const toolKey = this.createToolKey(serverId, toolName);
580
585
  this.updateToolStats(toolKey, false, duration);
586
+ // The caller cancelled the request: report that, not a tool failure.
587
+ if (options.signal?.aborted) {
588
+ throw error;
589
+ }
581
590
  // Circuit breaker open errors: return a structured isError result with
582
591
  // actionable details so AI models understand the tool is temporarily
583
592
  // unavailable and should NOT retry until the cooldown expires.
@@ -10,6 +10,12 @@ export declare class MCPToolRegistry extends MCPRegistry {
10
10
  private toolExecutionStats;
11
11
  private builtInServerInfos;
12
12
  private hitlManager?;
13
+ /**
14
+ * Tools that must never go through a request batcher (agent tools). Kept
15
+ * on the registry, beside the tools themselves, so every NeuroLink
16
+ * instance that shares this registry sees the same mark.
17
+ */
18
+ private unbatchableTools;
13
19
  private fileToolRootResolver;
14
20
  constructor();
15
21
  /**
@@ -21,6 +27,13 @@ export declare class MCPToolRegistry extends MCPRegistry {
21
27
  * Get current HITL manager
22
28
  */
23
29
  getHITLManager(): HITLManager | undefined;
30
+ /**
31
+ * Mark a tool as never batched, or clear the mark. Agent tools are marked
32
+ * when they are registered.
33
+ */
34
+ setToolUnbatchable(toolName: string, unbatchable: boolean): void;
35
+ /** Whether a tool must never go through a request batcher. */
36
+ isToolUnbatchable(toolName: string): boolean;
24
37
  /**
25
38
  * Resolve file-tool roots for built-in tools executed on this registry
26
39
  * without a per-call policy. Set by the NeuroLink instance that created it.
@@ -80,6 +93,13 @@ export declare class MCPToolRegistry extends MCPRegistry {
80
93
  }): Promise<ToolInfo[]>;
81
94
  private resolveToolExecutionTarget;
82
95
  private createExecutionContext;
96
+ /**
97
+ * The registry's inline HITL check, for a caller that arrives without a
98
+ * recorded decision (a direct `executeTool` caller). Throws when the call
99
+ * must not run, which `executeTool` reports as `{ success: false }`;
100
+ * otherwise returns the arguments to run with.
101
+ */
102
+ private confirmToolCall;
83
103
  /**
84
104
  * Get tool information with server details
85
105
  */
@@ -11,8 +11,9 @@ import { boundFileToolRoots, resolveFileToolRootPolicy, } from "../utils/fileToo
11
11
  import { convertZodToJsonSchema } from "../utils/schemaConversion.js";
12
12
  import { detectCategory, createMCPServerInfo } from "../utils/mcpDefaults.js";
13
13
  import { FlexibleToolValidator } from "./flexibleToolValidator.js";
14
- import { ErrorFactory } from "../utils/errorHandling.js";
15
- import { HITLUserRejectedError, HITLTimeoutError } from "../hitl/hitlErrors.js";
14
+ import { ErrorFactory, isAbortError, throwIfSignalAborted, } from "../utils/errorHandling.js";
15
+ import { HITLError } from "../hitl/hitlErrors.js";
16
+ import { isRefusalResult, markRefusalResult, resolveToolCallConfirmation, } from "../hitl/toolCallConfirmation.js";
16
17
  import { withSpan, tracers, ATTR } from "../telemetry/index.js";
17
18
  import { SpanStatusCode } from "@opentelemetry/api";
18
19
  import { getAuthContext } from "../auth/authContext.js";
@@ -22,6 +23,12 @@ export class MCPToolRegistry extends MCPRegistry {
22
23
  toolExecutionStats = new Map();
23
24
  builtInServerInfos = []; // DIRECT storage for MCPServerInfo
24
25
  hitlManager; // Optional HITL manager for safety mechanisms
26
+ /**
27
+ * Tools that must never go through a request batcher (agent tools). Kept
28
+ * on the registry, beside the tools themselves, so every NeuroLink
29
+ * instance that shares this registry sees the same mark.
30
+ */
31
+ unbatchableTools = new Set();
25
32
  // The owning NeuroLink's file-tool roots, for callers (HTTP tool routes, CLI)
26
33
  // that execute built-in tools on this registry without a bound policy.
27
34
  fileToolRootResolver = () => resolveFileToolRootPolicy({});
@@ -50,6 +57,22 @@ export class MCPToolRegistry extends MCPRegistry {
50
57
  getHITLManager() {
51
58
  return this.hitlManager;
52
59
  }
60
+ /**
61
+ * Mark a tool as never batched, or clear the mark. Agent tools are marked
62
+ * when they are registered.
63
+ */
64
+ setToolUnbatchable(toolName, unbatchable) {
65
+ if (unbatchable) {
66
+ this.unbatchableTools.add(toolName);
67
+ }
68
+ else {
69
+ this.unbatchableTools.delete(toolName);
70
+ }
71
+ }
72
+ /** Whether a tool must never go through a request batcher. */
73
+ isToolUnbatchable(toolName) {
74
+ return this.unbatchableTools.has(toolName);
75
+ }
53
76
  /**
54
77
  * Resolve file-tool roots for built-in tools executed on this registry
55
78
  * without a per-call policy. Set by the NeuroLink instance that created it.
@@ -338,60 +361,12 @@ export class MCPToolRegistry extends MCPRegistry {
338
361
  }
339
362
  span.setAttribute("tool.arguments_present", args !== undefined);
340
363
  span.setAttribute("tool.arguments_size", argsStr.length);
341
- // HITL Safety Check: Request confirmation if required
342
- let finalArgs = args;
343
- const HITLState = context?.hitlState;
344
- if (!HITLState?.triggered &&
345
- this.hitlManager &&
346
- this.hitlManager.isEnabled()) {
347
- const requiresConfirmation = this.hitlManager.requiresConfirmation(toolName, args);
348
- if (requiresConfirmation) {
349
- registryLogger.info(`Tool '${toolName}' requires HITL confirmation`);
350
- span.addEvent("tool.hitl_requested");
351
- try {
352
- if (HITLState) {
353
- HITLState.triggered = true;
354
- }
355
- const confirmationResult = await this.hitlManager.requestConfirmation(toolName, args, {
356
- serverId: tool.serverId,
357
- sessionId: execContext.sessionId,
358
- userId: execContext.userId,
359
- });
360
- if (!confirmationResult.approved) {
361
- // User rejected the tool execution
362
- span.addEvent("tool.hitl_rejected");
363
- throw new HITLUserRejectedError(`Tool execution rejected by user: ${confirmationResult.reason || "No reason provided"}`, toolName, confirmationResult.reason);
364
- }
365
- span.addEvent("tool.hitl_approved");
366
- // User approved - use modified arguments if provided
367
- if (confirmationResult.modifiedArguments !== undefined) {
368
- finalArgs = confirmationResult.modifiedArguments;
369
- registryLogger.info(`Tool '${toolName}' arguments modified by user`);
370
- }
371
- registryLogger.info(`Tool '${toolName}' approved for execution (response time: ${confirmationResult.responseTime}ms)`);
372
- }
373
- catch (error) {
374
- if (error instanceof HITLTimeoutError) {
375
- // Timeout occurred - user didn't respond in time
376
- registryLogger.warn(`Tool '${toolName}' execution timed out waiting for user confirmation`);
377
- throw error;
378
- }
379
- else if (error instanceof HITLUserRejectedError) {
380
- // User explicitly rejected
381
- registryLogger.info(`Tool '${toolName}' execution rejected by user`);
382
- throw error;
383
- }
384
- else {
385
- // Other HITL error (configuration, system error, etc.)
386
- registryLogger.error(`HITL confirmation failed for tool '${toolName}':`, error);
387
- throw new Error(`HITL confirmation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
388
- }
389
- }
390
- }
391
- else {
392
- registryLogger.debug(`Tool '${toolName}' does not require HITL confirmation`);
393
- }
394
- }
364
+ // HITL Safety Check. A call that NeuroLink.executeTool already gated
365
+ // arrives with its decision recorded and is never asked again; a
366
+ // direct caller without one is asked here.
367
+ const finalArgs = await this.confirmToolCall(toolName, args, tool.serverId, execContext, span);
368
+ // A call cancelled during its confirmation must not start.
369
+ throwIfSignalAborted(execContext.abortSignal);
395
370
  // Execute the actual tool (with potentially modified arguments)
396
371
  registryLogger.debug(`Executing tool '${toolName}' with args:`, finalArgs);
397
372
  const toolResult = await toolImpl.execute(finalArgs, execContext);
@@ -418,6 +393,10 @@ export class MCPToolRegistry extends MCPRegistry {
418
393
  executionTime: Date.now() - startTime,
419
394
  },
420
395
  };
396
+ // A tool that returns another call's refusal returns a refusal.
397
+ if (isRefusalResult(toolResult)) {
398
+ markRefusalResult(result);
399
+ }
421
400
  }
422
401
  else {
423
402
  // Result is a raw value, wrap it in ToolResult format
@@ -452,7 +431,17 @@ export class MCPToolRegistry extends MCPRegistry {
452
431
  return result;
453
432
  }
454
433
  catch (error) {
455
- registryLogger.error(`Tool execution failed: ${toolName}`, error);
434
+ if (error instanceof HITLError) {
435
+ // A human's "no" (or a withdrawn card) is an outcome, not a fault.
436
+ registryLogger.info(`Tool '${toolName}' refused by its HITL confirmation: ${error.message}`);
437
+ }
438
+ else if (isAbortError(error)) {
439
+ // So is a call its caller cancelled.
440
+ registryLogger.info(`Tool '${toolName}' stopped by its signal`);
441
+ }
442
+ else {
443
+ registryLogger.error(`Tool execution failed: ${toolName}`, error);
444
+ }
456
445
  // Record failure on span
457
446
  span.setAttribute("tool.success", false);
458
447
  // Rethrow precondition errors (tool not found, not executable)
@@ -483,7 +472,9 @@ export class MCPToolRegistry extends MCPRegistry {
483
472
  sessionId: context?.sessionId,
484
473
  },
485
474
  };
486
- return errorResult;
475
+ return (error instanceof HITLError
476
+ ? markRefusalResult(errorResult)
477
+ : errorResult);
487
478
  }
488
479
  });
489
480
  }
@@ -563,6 +554,24 @@ export class MCPToolRegistry extends MCPRegistry {
563
554
  userId: context?.userId ?? authUserId,
564
555
  };
565
556
  }
557
+ /**
558
+ * The registry's inline HITL check, for a caller that arrives without a
559
+ * recorded decision (a direct `executeTool` caller). Throws when the call
560
+ * must not run, which `executeTool` reports as `{ success: false }`;
561
+ * otherwise returns the arguments to run with.
562
+ */
563
+ async confirmToolCall(toolName, args, serverId, execContext, span) {
564
+ const action = await resolveToolCallConfirmation(this.hitlManager, toolName, args, execContext.hitlState, {
565
+ serverId,
566
+ sessionId: execContext.sessionId,
567
+ userId: execContext.userId,
568
+ signal: execContext.abortSignal,
569
+ }, { log: (message) => registryLogger.info(message), span });
570
+ if (!action.run) {
571
+ throw action.error;
572
+ }
573
+ return action.args;
574
+ }
566
575
  /**
567
576
  * Get tool information with server details
568
577
  */
@@ -770,6 +779,7 @@ export class MCPToolRegistry extends MCPRegistry {
770
779
  this.tools.delete(toolId);
771
780
  this.toolImplementations.delete(toolId); // Fix memory leak
772
781
  this.toolExecutionStats.delete(toolId); // Fix memory leak
782
+ this.unbatchableTools.delete(toolId);
773
783
  removedTools.push(toolId);
774
784
  }
775
785
  }
@@ -124,6 +124,8 @@ export async function performPrecallEvaluation(config, userInput) {
124
124
  const prompt = evaluationPrompt.replace("{USER_INPUT}", userInput);
125
125
  const result = await provider.generate({
126
126
  input: { text: prompt },
127
+ // The evaluator only classifies the input; it is given no tools.
128
+ disableTools: true,
127
129
  });
128
130
  if (!result || !result.content) {
129
131
  throw new Error("Evaluation generation failed to return a result.");
@@ -1,5 +1,5 @@
1
1
  import type { DecisionCallerOptions, DecisionLimitsQuery, DecisionLimitsReading, DecisionOptions, DecisionResult, AgentDefinition, AgentNetworkConfig, AgentRunOptions, AgentRunOutcome, AgentToolRegistrationOptions, IsolatedAgentDefinition, NetworkExecutionInput, NetworkExecutionOptions, NetworkExecutionResult, NetworkStreamChunk, WorkerInstanceOptions } from "./types/index.js";
2
- import type { CompactionConfig, CompactionResult, ArtifactStore, SpanData, ExporterStatus, ObservabilityConfig, MetricsSummary, MCPToolAnnotations, TraceView, AuthenticatedContext, AuthProvider, JsonObject, NeuroLinkEvents, TypedEventEmitter, MCPEnhancementsConfig, NeuroLinkAuthConfig, NeurolinkConstructorConfig, ChatMessage, ConversationSeedMessage, ConversationSeedOptions, RecordConversationTurnOptions, RecordConversationTurnResult, ExternalMCPOperationResult, ExternalMCPServerInstance, ExternalMCPServerHealth, ExternalMCPToolInfo, GenerateOptions, GenerateResult, ProviderStatus, TextGenerationOptions, TextGenerationResult, MCPExecutableTool, MCPServerInfo, MCPStatus, StreamOptions, StreamResult, ToolExecutionContext, ToolExecutionSummary, ToolInfo, ToolRegistrationOptions, BatchOperationResult, StreamGenerationEndContext, ToolRoutingServerDescriptor, ToolDedupConfig, ToolConfig, KnowledgeEngineStatus, ChecklistState, ArtifactPageRequest, BankArtifactOptions, BankedArtifactRef, DelegateCollectRequest, DelegateCollectResult, DelegateHandle, DelegateRegistrationOptions, DelegateSpawnOptions, BackgroundCommandHandle, BackgroundCommandOptions, BackgroundCommandOutputPage, BackgroundCommandPageRequest, BackgroundCommandPolicy, BackgroundCommandStatus, GitToolResult, GitToolsetOptions } from "./types/index.js";
2
+ import type { CompactionConfig, CompactionResult, ArtifactStore, SpanData, ExporterStatus, ObservabilityConfig, MetricsSummary, MCPToolAnnotations, TraceView, AuthenticatedContext, AuthProvider, JsonObject, NeuroLinkEvents, TypedEventEmitter, MCPEnhancementsConfig, NeuroLinkAuthConfig, NeurolinkConstructorConfig, ChatMessage, ConversationSeedMessage, ConversationSeedOptions, RecordConversationTurnOptions, RecordConversationTurnResult, ExternalMCPOperationResult, ExternalMCPServerInstance, ExternalMCPServerHealth, ExternalMCPToolInfo, GenerateOptions, GenerateResult, PauseDeadline, ProviderStatus, TextGenerationOptions, TextGenerationResult, MCPExecutableTool, MCPServerInfo, MCPStatus, StreamOptions, StreamResult, ToolExecutionContext, ToolExecutionSummary, ToolInfo, ToolRegistrationOptions, BatchOperationResult, StreamGenerationEndContext, ToolRoutingServerDescriptor, ToolDedupConfig, ToolConfig, KnowledgeEngineStatus, ChecklistState, ArtifactPageRequest, BankArtifactOptions, BankedArtifactRef, DelegateCollectRequest, DelegateCollectResult, DelegateHandle, DelegateRegistrationOptions, DelegateSpawnOptions, BackgroundCommandHandle, BackgroundCommandOptions, BackgroundCommandOutputPage, BackgroundCommandPageRequest, BackgroundCommandPolicy, BackgroundCommandStatus, GitToolResult, GitToolsetOptions } from "./types/index.js";
3
3
  import { ConversationMemoryManager } from "./core/conversationMemoryManager.js";
4
4
  import { AnthropicThreadStore } from "./providers/anthropic/threads.js";
5
5
  import type { RedisConversationMemoryManager } from "./core/redisConversationMemoryManager.js";
@@ -1881,6 +1881,13 @@ export declare class NeuroLink {
1881
1881
  * @returns Array of MCPServerInfo
1882
1882
  */
1883
1883
  getAutoDiscoveredServerInfos(): MCPServerInfo[];
1884
+ /**
1885
+ * The `executeTool` a provider's tool loop calls (via `setupToolExecutor`)
1886
+ * for a registered tool. It forwards what the loop passes for the call,
1887
+ * above all its signal (the turn's abort or the loop's per-tool deadline),
1888
+ * so the call's confirmation, its attempts and the tool see a cancellation.
1889
+ */
1890
+ private providerToolExecutor;
1884
1891
  /**
1885
1892
  * Execute a specific tool by name with robust error handling
1886
1893
  * Supports both custom tools and MCP server tools with timeout, retry, and circuit breaker patterns
@@ -1904,6 +1911,28 @@ export declare class NeuroLink {
1904
1911
  disableToolCache?: boolean;
1905
1912
  /** Bypass the request batcher for this call */
1906
1913
  bypassBatcher?: boolean;
1914
+ /**
1915
+ * The caller's cancellation signal. Aborting it while the call waits
1916
+ * for a human confirmation withdraws the card (`hitl:cancelled`) and
1917
+ * runs nothing. Once it has fired, no attempt starts: a call cancelled
1918
+ * before it starts rejects with an abort error, gated or not (a gated
1919
+ * one raises no card), and an abort between attempts stops the
1920
+ * retries. A
1921
+ * registered tool also receives it as `abortSignal` in its execution
1922
+ * context, in place of any signal set with `setToolContext()`; one
1923
+ * passed in `authContext` still wins, and is used for all of the above
1924
+ * when this option is absent. A result produced after it fired is
1925
+ * never cached, and a call that passes it is never batched.
1926
+ */
1927
+ abortSignal?: AbortSignal;
1928
+ /**
1929
+ * Pauses the caller's own deadline for this call (a model loop's
1930
+ * per-tool bound) while the call waits for a human confirmation, and
1931
+ * returns the function that resumes it. The gate calls it around the
1932
+ * wait only, and every outcome resumes it, with the time that was left.
1933
+ * Provider tool loops pass it; a direct caller rarely needs it.
1934
+ */
1935
+ pauseDeadline?: PauseDeadline;
1907
1936
  authContext?: {
1908
1937
  userId?: string;
1909
1938
  sessionId?: string;
@@ -1915,6 +1944,49 @@ export declare class NeuroLink {
1915
1944
  private executeToolWithSpan;
1916
1945
  private prepareToolExecutionState;
1917
1946
  private runPreparedToolExecution;
1947
+ /**
1948
+ * Confirm a tool call with the human, once, before any attempt timer, retry
1949
+ * or circuit breaker the call is subject to starts. The decision is written
1950
+ * to `ctx.state`, which every attempt carries down to the registry and the
1951
+ * external server manager, so neither asks again. An approved (or
1952
+ * not-required) call gets the parameters to run with, the approver's edits
1953
+ * included; any other decision gets the registry's `{ success: false }`
1954
+ * result, which `executeTool` returns without retrying.
1955
+ */
1956
+ private gateToolCall;
1957
+ /**
1958
+ * The HITL manager that confirms a call before any timer starts.
1959
+ *
1960
+ * The one the call's inline check would ask, when it is enabled: the tool
1961
+ * registry's for a registered or built-in tool, the external manager's for
1962
+ * an external MCP tool. That is the manager these calls have always been
1963
+ * confirmed with, and asking it here, before the attempt timer and the
1964
+ * retries, records the decision so the inline check skips it. Otherwise
1965
+ * this instance's own, when it has an enabled one.
1966
+ *
1967
+ * An instance with HITL installs its manager on its registry and its
1968
+ * external manager, so the two usually agree. They differ when another
1969
+ * manager was installed on the registry: with `setHITLManager`, or by a
1970
+ * worker with HITL of its own on a shared registry, which takes it over.
1971
+ * A worker built on a host's registry (`createWorkerInstance`, and so
1972
+ * `runIsolatedAgent`, `registerAgentTool` and `delegate_task`) with no HITL
1973
+ * of its own is confirmed by the registry's manager, the host's unless
1974
+ * another took it over, and the card reaches that manager owner's emitter.
1975
+ */
1976
+ private confirmationManagerFor;
1977
+ /**
1978
+ * Whether the gate would ask a human about this call, for a registered or
1979
+ * an external tool. Each distinct manager is asked once; the registry and
1980
+ * the external manager usually share the host's.
1981
+ */
1982
+ private callNeedsConfirmation;
1983
+ /**
1984
+ * Bookkeeping for a call its confirmation refused: `tool:end` with
1985
+ * `success: false`, the span marked as an error and a failed execution
1986
+ * counted. No circuit-breaker failure is recorded (a human's answer says
1987
+ * nothing about the tool's health), and nothing ran.
1988
+ */
1989
+ private handleRefusedToolExecution;
1918
1990
  private handleSuccessfulToolExecution;
1919
1991
  private handleFailedToolExecution;
1920
1992
  /**
@@ -1926,6 +1998,39 @@ export declare class NeuroLink {
1926
1998
  */
1927
1999
  private toolCacheRepeatKey;
1928
2000
  private executeToolInternal;
2001
+ /**
2002
+ * Whether a failed call gets executeToolInternal's one extra run: a tool
2003
+ * whose annotations say it is safe to retry, a call that may be retried at
2004
+ * all (a tool with no retries runs once per call, as its registration
2005
+ * says), not cancelled, and a retriable error.
2006
+ */
2007
+ private maySafelyRetryOnce;
2008
+ /**
2009
+ * What an external tool call's failure surfaces as from executeToolInternal.
2010
+ * A call its caller cancelled stays the abort it is and is logged at info
2011
+ * (an outcome, not a fault); any other failure is logged and wrapped.
2012
+ */
2013
+ private externalToolFailure;
2014
+ /**
2015
+ * The signals one attempt of an `executeTool` call runs under, each linked
2016
+ * to an attempt controller that `abort()` fires when the attempt times out.
2017
+ *
2018
+ * - `callSignal`: the call's own signal plus the attempt's. It is the
2019
+ * attempt's `abortSignal` (the external manager's `signal`, the cache and
2020
+ * safe-retry guards).
2021
+ * - `toolSignal`: the signal the tool's context would otherwise carry (its
2022
+ * `authContext`'s, else the call's, else the one set with
2023
+ * `setToolContext()`) plus the attempt's. Precedence is unchanged; the
2024
+ * tool sees its usual signal, linked to the attempt's timer too.
2025
+ */
2026
+ private attemptSignals;
2027
+ /**
2028
+ * The context a registry tool executes with: this instance's tool context
2029
+ * (`setToolContext`), then the call's `abortSignal` (it replaces a stored
2030
+ * one), then the caller's `authContext` (which wins), plus the call's HITL
2031
+ * state and, on its private channel, this instance's file-tool roots.
2032
+ */
2033
+ private registryToolContext;
1929
2034
  /**
1930
2035
  * Get tool annotations for execution decisions (cache, retry).
1931
2036
  * Checks cached tool list first, falls back to inference from tool name.
@@ -2320,11 +2425,18 @@ export declare class NeuroLink {
2320
2425
  * @param serverId - ID of the server
2321
2426
  * @param toolName - Name of the tool
2322
2427
  * @param parameters - Tool parameters
2323
- * @param options - Execution options
2428
+ * @param options - Execution options. Aborting `abortSignal` withdraws the
2429
+ * call's pending confirmation; a call whose signal has already fired is
2430
+ * never sent to the server and rejects with an abort error, except that
2431
+ * a result already in the tool-result cache for this call is returned
2432
+ * first. `pauseDeadline` pauses the caller's deadline while that
2433
+ * confirmation waits.
2324
2434
  * @returns Tool execution result
2325
2435
  */
2326
2436
  executeExternalMCPTool(serverId: string, requestedToolName: string, parameters: JsonObject, options?: {
2327
2437
  timeout?: number;
2438
+ abortSignal?: AbortSignal;
2439
+ pauseDeadline?: PauseDeadline;
2328
2440
  }): Promise<unknown>;
2329
2441
  /**
2330
2442
  * Resolve a tool name for a direct external MCP execution