@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
@@ -12,6 +12,7 @@ import { bedrockChunksToV3Stream, bedrockConversationFromV3Prompt, bedrockV3Stre
12
12
  import { AuthenticationError, ProviderError, RateLimitError, } from "../../types/index.js";
13
13
  import { classifyProviderError } from "../../utils/errorClassifier.js";
14
14
  import { isAbortError, withTimeout } from "../../utils/errorHandling.js";
15
+ import { abortSignalOf, pauseDeadlineOf } from "../../utils/async/index.js";
15
16
  import { ImageProcessor } from "../../utils/imageProcessor.js";
16
17
  import { logger } from "../../utils/logger.js";
17
18
  import { resolveSamplingParams } from "../../models/modelRegistry.js";
@@ -599,7 +600,7 @@ export class AmazonBedrockProvider extends BaseProvider {
599
600
  * all. The turn's full merged tool set is resolved once by the caller and
600
601
  * handed down.
601
602
  */
602
- async executeSingleTool(tools, toolName, args, _toolUseId) {
603
+ async executeSingleTool(tools, toolName, args, _toolUseId, context) {
603
604
  return bedrockTracer.startActiveSpan("bedrock.tool.execute", {
604
605
  kind: SpanKind.CLIENT,
605
606
  attributes: { "tool.name": toolName },
@@ -636,7 +637,7 @@ export class AmazonBedrockProvider extends BaseProvider {
636
637
  toolArgs[key] = value;
637
638
  }
638
639
  }
639
- const result = await tool.execute(toolArgs);
640
+ const result = await tool.execute(toolArgs, context);
640
641
  logger.debug(`[AmazonBedrockProvider] Tool execution result:`, {
641
642
  toolName,
642
643
  result,
@@ -724,7 +725,19 @@ export class AmazonBedrockProvider extends BaseProvider {
724
725
  const engineTools = {};
725
726
  for (const name of Object.keys(tools)) {
726
727
  engineTools[name] = {
727
- execute: (args) => this.executeSingleTool(tools, name, args),
728
+ // The engine's signal for the call (the turn's abort or its per-tool
729
+ // deadline) goes down to the tool with it, and so does the pause a
730
+ // confirmation puts on that deadline.
731
+ execute: (args, opts) => {
732
+ const abortSignal = abortSignalOf(opts);
733
+ const pauseDeadline = pauseDeadlineOf(opts);
734
+ return this.executeSingleTool(tools, name, args, undefined, abortSignal || pauseDeadline
735
+ ? {
736
+ ...(abortSignal && { abortSignal }),
737
+ ...(pauseDeadline && { pauseDeadline }),
738
+ }
739
+ : undefined);
740
+ },
728
741
  };
729
742
  }
730
743
  return engineTools;
@@ -740,11 +753,17 @@ export class AmazonBedrockProvider extends BaseProvider {
740
753
  result[name] = {
741
754
  description: tool.description,
742
755
  parameters: extractedParams,
743
- execute: async (params) => {
756
+ execute: async (params, context) => {
744
757
  if ("execute" in tool && tool.execute) {
745
758
  const result = await tool.execute(params, {
746
759
  toolCallId: `tool_${Date.now()}`,
747
760
  messages: [],
761
+ ...(context?.abortSignal
762
+ ? { abortSignal: context.abortSignal }
763
+ : {}),
764
+ ...(context?.pauseDeadline
765
+ ? { pauseDeadline: context.pauseDeadline }
766
+ : {}),
748
767
  });
749
768
  return {
750
769
  success: true,
@@ -34,7 +34,7 @@ import { resolveToolExecutionRecords, toolCallsFromSummaries, } from "../../core
34
34
  import { transformToolExecutions } from "../../utils/transformationUtils.js";
35
35
  import { createAnthropicConfig, getProviderModel, validateApiKey, } from "../../utils/providerConfig.js";
36
36
  import { composeAbortSignals, composeAbortSignalsScoped, createTimeoutController, mergeAbortSignals, TimeoutError, } from "../../utils/timeout.js";
37
- import { raceWithAbort } from "../../utils/async/index.js";
37
+ import { pauseDeadlineOf, raceWithAbort } from "../../utils/async/index.js";
38
38
  import { normalizeResolvedToolChoice, resolveToolChoice, } from "../../utils/toolChoice.js";
39
39
  import { NoOutputGeneratedError } from "../../utils/generationErrors.js";
40
40
  import { buildNoOutputSentinel, stampNoOutputSpan, } from "../../utils/noOutputSentinel.js";
@@ -2303,9 +2303,13 @@ export class AnthropicProvider extends BaseProvider {
2303
2303
  engineTools[name] = {
2304
2304
  execute: async (args, opts) => {
2305
2305
  const ctx = opts;
2306
+ // The engine's pause for its per-tool deadline goes down too, so
2307
+ // a confirmation the call waits on does not spend that bound.
2308
+ const pauseDeadline = pauseDeadlineOf(opts);
2306
2309
  return execute(args, {
2307
2310
  toolCallId: ctx.toolCallId ?? "",
2308
2311
  ...(ctx.abortSignal ? { abortSignal: ctx.abortSignal } : {}),
2312
+ ...(pauseDeadline ? { pauseDeadline } : {}),
2309
2313
  messages: [],
2310
2314
  });
2311
2315
  },
@@ -16,6 +16,7 @@ import { needsAudioTranscode, toProviderCompatibleAudio, } from "../../adapters/
16
16
  import { canDeliverVideoNatively } from "../../adapters/videoFormatSupport.js";
17
17
  import { logger } from "../../utils/logger.js";
18
18
  import { guardToolExecutor } from "../../core/toolExecutionGuards.js";
19
+ import { isRefusalResult } from "../../hitl/toolCallConfirmation.js";
19
20
  import { resolveSamplingParams } from "../../models/modelRegistry.js";
20
21
  import { convertZodToJsonSchema, ensureNestedSchemaTypes, inlineJsonSchema, isZodSchema, } from "../../utils/schemaConversion.js";
21
22
  import { createNativeThinkingConfig } from "../../utils/thinkingConfig.js";
@@ -61,7 +62,10 @@ export class DedupExecuteMap extends Map {
61
62
  return resultCache.get(key);
62
63
  }
63
64
  const result = await execute(args, options);
64
- resultCache.set(key, result);
65
+ // A HITL refusal is never reused: the identical call asks again.
66
+ if (!isRefusalResult(result)) {
67
+ resultCache.set(key, result);
68
+ }
65
69
  return result;
66
70
  };
67
71
  return wrapped;
@@ -2178,6 +2178,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2178
2178
  toolExecutionSummaries,
2179
2179
  options,
2180
2180
  stepIndex: step,
2181
+ abortSignal,
2181
2182
  }));
2182
2183
  const executed = toolExecutionSummaries.slice(-stepResult.toolCalls.size);
2183
2184
  stepRecords.push(toPrepareStepRecord({
@@ -2389,7 +2390,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2389
2390
  });
2390
2391
  }
2391
2392
  async executeToolBatch(args) {
2392
- const { stepResult, conversation, toolsRecord, toolNameFromWire, toolsUsed, toolExecutionSummaries, options, stepIndex, } = args;
2393
+ const { stepResult, conversation, toolsRecord, toolNameFromWire, toolsUsed, toolExecutionSummaries, options, stepIndex, abortSignal, } = args;
2393
2394
  const toolCallsForMessage = [];
2394
2395
  for (const [, t] of stepResult.toolCalls) {
2395
2396
  toolCallsForMessage.push({
@@ -2406,7 +2407,17 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2406
2407
  ? { reasoning_content: stepResult.reasoning }
2407
2408
  : {}),
2408
2409
  });
2410
+ let executedCount = 0;
2409
2411
  for (const [, t] of stepResult.toolCalls) {
2412
+ // Honour an abort BETWEEN tool executions, as the loop engine does: a
2413
+ // tool that ignores its signal would otherwise still be started after
2414
+ // the turn was cancelled. The batch stops here so the results of the
2415
+ // tools that did run are still stored; the abort check after the
2416
+ // storage ends the turn the way the next step's request would have.
2417
+ if (abortSignal?.aborted) {
2418
+ break;
2419
+ }
2420
+ executedCount += 1;
2410
2421
  const startedAt = new Date();
2411
2422
  const parsed = parseToolInput(t.argsBuffered);
2412
2423
  let output;
@@ -2441,7 +2452,11 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2441
2452
  }
2442
2453
  else {
2443
2454
  try {
2444
- output = await toolDef.execute(input, {});
2455
+ output = await toolDef.execute(input, {
2456
+ toolCallId: t.id,
2457
+ messages: [],
2458
+ ...(abortSignal ? { abortSignal } : {}),
2459
+ });
2445
2460
  }
2446
2461
  catch (err) {
2447
2462
  errorMsg = err instanceof Error ? err.message : String(err);
@@ -2466,7 +2481,7 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2466
2481
  content: stringifyToolOutput(output),
2467
2482
  });
2468
2483
  }
2469
- const justExecuted = toolExecutionSummaries.slice(-stepResult.toolCalls.size);
2484
+ const justExecuted = executedCount > 0 ? toolExecutionSummaries.slice(-executedCount) : [];
2470
2485
  // No `tool:end` here: the executor already emitted start/end with the
2471
2486
  // real duration, and a second emission per result doubled every
2472
2487
  // consumer's count.
@@ -2496,6 +2511,9 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2496
2511
  error: err instanceof Error ? err.message : String(err),
2497
2512
  });
2498
2513
  }
2514
+ // An abort during the batch's last tool: the turn ends with it even when
2515
+ // no step follows to make a request that would throw it.
2516
+ abortSignal?.throwIfAborted();
2499
2517
  }
2500
2518
  /**
2501
2519
  * Default implementation hits `${baseURL}/models`. Subclasses with a
@@ -263,6 +263,8 @@ Return the extracted data as JSON.`;
263
263
  prompt,
264
264
  maxTokens: config.maxTokens || 500,
265
265
  temperature: config.temperature || 0.3,
266
+ // Extracted metadata is text; the extractor is given no tools.
267
+ disableTools: true,
266
268
  });
267
269
  return result?.content || "";
268
270
  }
@@ -765,6 +765,8 @@ export class RAGPipeline {
765
765
  systemPrompt: "You are an image captioning assistant. Provide concise, descriptive captions.",
766
766
  input: { text: "", images: [dataUri] },
767
767
  maxTokens: 100,
768
+ // A caption is text; the captioner is given no tools.
769
+ disableTools: true,
768
770
  }), DEFAULT_TIMEOUT_MS, "Image captioning timed out");
769
771
  return result?.content || "Image";
770
772
  }
@@ -851,6 +853,8 @@ Cite sources when possible using [Source N] format.`;
851
853
  systemPrompt,
852
854
  temperature: temperature ?? this.config.generationModel?.temperature ?? 0.7,
853
855
  maxTokens: this.config.generationModel?.maxTokens ?? 1000,
856
+ // The answer is written from the retrieved context; no tools.
857
+ disableTools: true,
854
858
  }), DEFAULT_TIMEOUT_MS * 2, "Answer generation timed out");
855
859
  return result?.content || "";
856
860
  }
@@ -66,6 +66,7 @@ export declare function summarizeContext(context: string, maxLength?: number, pr
66
66
  prompt: string;
67
67
  maxTokens: number;
68
68
  temperature: number;
69
+ disableTools?: boolean;
69
70
  }) => Promise<{
70
71
  content?: string;
71
72
  } | null>;
@@ -208,6 +208,8 @@ export async function summarizeContext(context, maxLength = 500, provider) {
208
208
  prompt: `Summarize the following context in no more than ${maxLength} words, preserving the key information:\n\n${context}\n\nSummary:`,
209
209
  maxTokens: Math.ceil(maxLength * 1.5),
210
210
  temperature: 0.3,
211
+ // A summary is text; the summarizing model is given no tools.
212
+ disableTools: true,
211
213
  });
212
214
  return result?.content?.trim() || truncateText(context, maxLength * 4);
213
215
  }
@@ -125,6 +125,8 @@ Score:`;
125
125
  prompt,
126
126
  maxTokens: 10,
127
127
  temperature: 0,
128
+ // A relevance score is text; the reranker is given no tools.
129
+ disableTools: true,
128
130
  });
129
131
  const scoreText = result?.content?.trim() || "0";
130
132
  const score = parseFloat(scoreText);
@@ -194,6 +196,8 @@ Respond with only the scores, one per line, in order:`;
194
196
  prompt,
195
197
  maxTokens: 50,
196
198
  temperature: 0,
199
+ // Relevance scores are text; the reranker is given no tools.
200
+ disableTools: true,
197
201
  });
198
202
  // Parse scores from response
199
203
  const scoreLines = (result?.content || "")
@@ -160,6 +160,22 @@ export type ConfirmationTimeoutEvent = {
160
160
  timeout: number;
161
161
  };
162
162
  };
163
+ /**
164
+ * Event payload for a withdrawn confirmation
165
+ * Emitted when the call that asked was aborted before anyone answered, so the
166
+ * approval UI can retire the card: a later answer to it runs nothing.
167
+ */
168
+ export type ConfirmationCancelledEvent = {
169
+ type: "hitl:cancelled";
170
+ payload: {
171
+ /** Confirmation ID that was withdrawn */
172
+ confirmationId: string;
173
+ /** Tool name whose confirmation was withdrawn */
174
+ toolName: string;
175
+ /** Why it was withdrawn: the abort reason, when the caller gave one */
176
+ reason: string;
177
+ };
178
+ };
163
179
  /**
164
180
  * HITL audit log entry
165
181
  * Used for compliance and debugging purposes
@@ -168,7 +184,7 @@ export type HITLAuditLog = {
168
184
  /** ISO timestamp of the event */
169
185
  timestamp: string;
170
186
  /** Type of HITL event */
171
- eventType: "confirmation-requested" | "confirmation-approved" | "confirmation-rejected" | "confirmation-timeout" | "confirmation-auto-approved";
187
+ eventType: "confirmation-requested" | "confirmation-approved" | "confirmation-rejected" | "confirmation-timeout" | "confirmation-auto-approved" | "confirmation-cancelled";
172
188
  /** Tool that was involved */
173
189
  toolName: string;
174
190
  /** User who made the decision (if applicable) */
@@ -214,12 +230,19 @@ export type HITLManager = {
214
230
  isEnabled(): boolean;
215
231
  /** Check if a tool requires confirmation based on configuration */
216
232
  requiresConfirmation(toolName: string, args?: unknown): boolean;
217
- /** Request confirmation for a tool execution */
218
- requestConfirmation(toolName: string, arguments_: unknown, context?: {
219
- serverId?: string;
220
- sessionId?: string;
221
- userId?: string;
222
- }): Promise<ConfirmationResult>;
233
+ /**
234
+ * Request confirmation for a tool execution; aborting `context.signal`
235
+ * withdraws it. The call that asked stops waiting on that abort even when
236
+ * an implementation ignores the signal: its card then stays until it is
237
+ * answered, and the answer runs nothing.
238
+ */
239
+ requestConfirmation(toolName: string, arguments_: unknown, context?: HITLConfirmationContext): Promise<ConfirmationResult>;
240
+ /**
241
+ * Withdraw a pending confirmation; false when nothing was pending under this
242
+ * ID. Optional so existing implementations of this type still compile; the
243
+ * shipped HITLManager has it.
244
+ */
245
+ cancelConfirmation?(confirmationId: string, reason?: string): boolean;
223
246
  /** Process user response to confirmation request */
224
247
  processUserResponse(confirmationId: string, response: {
225
248
  approved: boolean;
@@ -244,6 +267,75 @@ export type HITLManager = {
244
267
  on(event: string, listener: (...args: unknown[]) => void): HITLManager;
245
268
  emit(event: string, ...args: unknown[]): boolean;
246
269
  };
270
+ /**
271
+ * What the human-in-the-loop step decided for one tool call. Only `approved`
272
+ * and `not-required` let the tool run.
273
+ */
274
+ export type HITLDecision = "approved" | "denied" | "timeout" | "cancelled" | "not-required";
275
+ /**
276
+ * Per-call HITL state, shared by every attempt of one `executeTool` call.
277
+ *
278
+ * The confirmation step writes `decision` once it has decided (after the
279
+ * human answered, or the wait ended), never before; an attempt that arrives
280
+ * with the decision for its arguments is not asked again. A state whose `decision` is still undefined has not been
281
+ * confirmed. An approval (or a `not-required` decision) covers the arguments
282
+ * it was made for. A state you pass yourself is compared with a copy of
283
+ * those arguments taken when the decision was made: reused with other
284
+ * arguments, or with the same object changed in place since, it is decided
285
+ * again and `decision` is overwritten; arguments that cannot be copied (a
286
+ * function value, for example) are always decided again. A `decision` you
287
+ * write yourself, rather than the confirmation step, is used as it is. The
288
+ * state `executeTool` makes for its own call is bound to the arguments
289
+ * object itself, so one approval covers every attempt of that call.
290
+ */
247
291
  export type HITLExecutionState = {
248
- triggered: boolean;
292
+ /** Recorded after the confirmation step; undefined until then */
293
+ decision?: HITLDecision;
294
+ /**
295
+ * Read-only alias of `decision === "approved"`, kept for callers that read
296
+ * it. Never true before the human approved. A plain object passed by a
297
+ * caller does not carry it; read `decision` instead.
298
+ */
299
+ readonly triggered?: boolean;
300
+ };
301
+ /** Where, and for whom, a confirmation is requested */
302
+ export type HITLConfirmationContext = {
303
+ /** MCP server ID (if this is an external tool) */
304
+ serverId?: string;
305
+ /** User session identifier */
306
+ sessionId?: string;
307
+ /** User identifier */
308
+ userId?: string;
309
+ /** Aborting it withdraws the pending confirmation (`hitl:cancelled`) */
310
+ signal?: AbortSignal;
311
+ };
312
+ /**
313
+ * Result of the shared confirmation step: the arguments to run with, or why
314
+ * the call must not run.
315
+ */
316
+ export type HITLConfirmationOutcome = {
317
+ decision: "approved" | "not-required";
318
+ /** The approver's modified arguments, else the requested ones */
319
+ args: unknown;
320
+ } | {
321
+ decision: "denied";
322
+ /** The approver's reason, if one was given */
323
+ reason?: string;
324
+ } | {
325
+ decision: "timeout" | "cancelled";
326
+ /** HITLTimeoutError, HITLCancelledError, or whatever ended the wait */
327
+ error: Error;
328
+ };
329
+ /**
330
+ * What the confirmation step means for one tool call, the same on every
331
+ * execution path: run with these arguments, or refuse with this error.
332
+ */
333
+ export type HITLOutcomeAction = {
334
+ run: true;
335
+ /** The approver's modified arguments, else the requested ones */
336
+ args: unknown;
337
+ } | {
338
+ run: false;
339
+ /** Why the call must not run; its message is the refusal text */
340
+ error: Error;
249
341
  };
@@ -492,6 +492,11 @@ export type ExternalToolExecutionOptions = {
492
492
  validateInput?: boolean;
493
493
  /** Whether to validate output */
494
494
  validateOutput?: boolean;
495
+ /**
496
+ * Aborting it cancels the in-flight MCP request: the SDK rejects the call
497
+ * and sends `notifications/cancelled` to the server.
498
+ */
499
+ signal?: AbortSignal;
495
500
  };
496
501
  /**
497
502
  * Tool validation result
@@ -14,7 +14,7 @@ import type { StreamOptions, StreamResult } from "./stream.js";
14
14
  import type { ProviderError, ProviderErrorRule } from "./errors.js";
15
15
  import type { ExternalMCPToolInfo } from "./externalMcp.js";
16
16
  import type { ClaudeSubscriptionTier, AnthropicAuthMethod, AnthropicAuthConfig, SubscriptionInfo, OAuthToken } from "./subscription.js";
17
- import type { Tool } from "./tools.js";
17
+ import type { PauseDeadline, Tool } from "./tools.js";
18
18
  export type { LanguageModel, EmbeddingModel, ImageModel, GenerateTextResult, StepResult, ToolCallRepairFunction, PrepareStepFunction, PrepareStepResult, FinishReason, LanguageModelUsage, LanguageModelRequestMetadata, LanguageModelResponseMetadata, } from "./aiCompat.js";
19
19
  export type { ClaudeSubscriptionTier, AnthropicAuthMethod, AnthropicAuthConfig, SubscriptionInfo, } from "./subscription.js";
20
20
  /**
@@ -1168,6 +1168,27 @@ export type OpenAICompatCatalogEntry = {
1168
1168
  * needs — lets call sites pass a minimal object without the full catalog
1169
1169
  * entry (e.g. in tests, or a future non-catalog caller). */
1170
1170
  export type OpenAICompatConfigInput = Pick<OpenAICompatCatalogEntry, "providerName" | "apiKeyEnvVar" | "baseURLEnvVar" | "defaultBaseURL" | "computedBaseURL" | "configOptions">;
1171
+ /**
1172
+ * What a provider's tool loop passes to the `executeTool` handed to
1173
+ * `setupToolExecutor`, for one model tool call.
1174
+ */
1175
+ export type ProviderToolExecutorOptions = {
1176
+ /** Attempt timeout set when the tool was registered */
1177
+ timeout?: number;
1178
+ /** Retries set when the tool was registered */
1179
+ maxRetries?: number;
1180
+ /**
1181
+ * The loop's signal for this call: the turn's abort, or the loop's
1182
+ * per-tool deadline. `NeuroLink.executeTool` takes it to the call's
1183
+ * confirmation, its attempts and the tool's execution context.
1184
+ */
1185
+ abortSignal?: AbortSignal;
1186
+ /**
1187
+ * Pauses the loop's deadlines for this call. `NeuroLink.executeTool`'s
1188
+ * confirmation gate calls it around the wait for a human.
1189
+ */
1190
+ pauseDeadline?: PauseDeadline;
1191
+ };
1171
1192
  /**
1172
1193
  * AI Provider type with flexible parameter support
1173
1194
  */
@@ -1197,7 +1218,7 @@ export type AIProvider = {
1197
1218
  decide?(request: DecisionRequest): Promise<DecisionResult>;
1198
1219
  setupToolExecutor(sdk: {
1199
1220
  customTools: Map<string, unknown>;
1200
- executeTool: (toolName: string, params: unknown) => Promise<unknown>;
1221
+ executeTool: (toolName: string, params: unknown, options?: ProviderToolExecutorOptions) => Promise<unknown>;
1201
1222
  }, functionTag: string): void;
1202
1223
  /**
1203
1224
  * Propagate trace context from NeuroLink SDK for parent-child span hierarchy.
@@ -51,6 +51,8 @@ export type ExecutionContext<T = StandardRecord> = {
51
51
  maxRetries?: number;
52
52
  startTime?: number;
53
53
  hitlState?: HITLExecutionState;
54
+ /** The caller's cancellation signal (`executeTool`'s `abortSignal` option) */
55
+ abortSignal?: AbortSignal;
54
56
  };
55
57
  /**
56
58
  * Cache configuration options
@@ -155,26 +157,30 @@ export type ToolExecutionOptions = {
155
157
  * Options for tool registration via registerTool()
156
158
  *
157
159
  * These options configure per-tool execution behavior. When not provided,
158
- * the SDK's global defaults are used (30s timeout, 2 retries), preserving
159
- * backward compatibility with existing production systems.
160
+ * `executeTool` uses the SDK's defaults: a 120 s timeout per attempt and 3
161
+ * retries (up to 4 attempts), 1 s apart. A per-call `executeTool` option
162
+ * overrides the registered value.
160
163
  *
161
164
  * @example
162
165
  * // Register with custom timeout and no retries
163
166
  * sdk.registerTool("myTool", tool, { timeout: 5000, maxRetries: 0 });
164
167
  *
165
- * // Register with defaults (same as before — no behavior change)
168
+ * // Register with the defaults
166
169
  * sdk.registerTool("myTool", tool);
167
170
  */
168
171
  export type ToolRegistrationOptions = {
169
- /** Per-tool execution timeout in milliseconds. Only applied when explicitly set.
170
- * When omitted, the SDK's global default (30s) is used. */
172
+ /** Timeout for one attempt, in milliseconds. Only applied when explicitly
173
+ * set. When omitted, the SDK's default (120 s) is used. */
171
174
  timeout?: number;
172
- /** Maximum retry attempts on failure. Only applied when explicitly set.
173
- * When omitted, the SDK's global default (2 retries) is used.
174
- * Set to 0 to disable retries for this tool. */
175
+ /** Maximum retries after a failed attempt. Only applied when explicitly set.
176
+ * When omitted, the SDK's default (3 retries, so up to 4 attempts) is used.
177
+ * Set to 0 to disable retries for this tool, as you should for a tool
178
+ * whose effect must not happen twice. */
175
179
  maxRetries?: number;
176
180
  /** Ceiling on the whole execution across every attempt and the delays
177
- * between them. When omitted, `timeout * (maxRetries + 1)` is used. */
181
+ * between them. When omitted,
182
+ * `timeout * (maxRetries + 1) + retryDelayMs * maxRetries` is used, the
183
+ * retry delay being 1 s unless the call sets `retryDelayMs`. */
178
184
  totalTimeoutMs?: number;
179
185
  /**
180
186
  * Whether this tool's result may be served from the tool-result cache
@@ -223,6 +229,21 @@ export type ToolExecutionMetadata = {
223
229
  version?: string;
224
230
  [key: string]: JsonValue | undefined;
225
231
  };
232
+ /**
233
+ * Pauses the deadlines a model loop put around one tool call, for as long as
234
+ * the call waits for something outside the tool (a human confirmation).
235
+ * Returns the function that resumes them with the time that was left.
236
+ */
237
+ export type PauseDeadline = () => () => void;
238
+ /**
239
+ * A deadline that can be paused (`pause()` returns the resume function) and
240
+ * ended for good (`clear()`: a later resume re-arms nothing and the deadline
241
+ * never fires).
242
+ */
243
+ export type PausableDeadline = {
244
+ pause: PauseDeadline;
245
+ clear: () => void;
246
+ };
226
247
  /**
227
248
  * Tool execution context
228
249
  */
@@ -231,6 +252,10 @@ export type ToolContext = {
231
252
  userId?: string;
232
253
  aiProvider?: string;
233
254
  metadata?: ToolExecutionMetadata;
255
+ /** The loop's signal for this call (its turn abort or per-tool deadline) */
256
+ abortSignal?: AbortSignal;
257
+ /** Pauses the loop's deadlines for this call while it waits for a human */
258
+ pauseDeadline?: PauseDeadline;
234
259
  };
235
260
  /**
236
261
  * SDK-specific tool context with additional fields for SDK usage
@@ -19,5 +19,6 @@
19
19
  * ```
20
20
  */
21
21
  export { delay, sleep } from "./delay.js";
22
+ export { createPausableDeadline, pauseDeadlineOf } from "./pausableDeadline.js";
22
23
  export { calculateBackoff, createRetry, DEFAULT_RETRY_OPTIONS, RetryExhaustedError, retry, } from "./retry.js";
23
- export { TimeoutError, raceWithAbort, withTimeout, withTimeoutFn, } from "./withTimeout.js";
24
+ export { TimeoutError, abortSignalOf, raceWithAbort, withTimeout, withTimeoutFn, } from "./withTimeout.js";
@@ -19,5 +19,6 @@
19
19
  * ```
20
20
  */
21
21
  export { delay, sleep } from "./delay.js";
22
+ export { createPausableDeadline, pauseDeadlineOf } from "./pausableDeadline.js";
22
23
  export { calculateBackoff, createRetry, DEFAULT_RETRY_OPTIONS, RetryExhaustedError, retry, } from "./retry.js";
23
- export { TimeoutError, raceWithAbort, withTimeout, withTimeoutFn, } from "./withTimeout.js";
24
+ export { TimeoutError, abortSignalOf, raceWithAbort, withTimeout, withTimeoutFn, } from "./withTimeout.js";
@@ -0,0 +1,28 @@
1
+ /**
2
+ * A deadline a tool call can pause while it waits for a human.
3
+ *
4
+ * A model loop bounds each tool call. A call that needs a confirmation spends
5
+ * part of that bound waiting for a person, which says nothing about the tool,
6
+ * so the confirmation pauses the bound and resumes it afterwards with the time
7
+ * that was left, never a fresh one.
8
+ */
9
+ import type { PauseDeadline, PausableDeadline } from "../../types/index.js";
10
+ /**
11
+ * Arms a deadline of `ms` that calls `onExpire` once when it runs out.
12
+ *
13
+ * - `pause()` stops the clock and returns the resume function. Paused time is
14
+ * not spent: resuming re-arms the timer with what was left. Pauses nest; the
15
+ * clock runs again only once every pause has resumed, and each resume
16
+ * function acts once.
17
+ * - `clear()` ends the deadline for good: `onExpire` never runs, and a resume
18
+ * that arrives later re-arms nothing.
19
+ *
20
+ * The timer is deliberately not unref'd: while a call is in flight it may be
21
+ * the only thing that will end a wedged tool.
22
+ */
23
+ export declare function createPausableDeadline(ms: number, onExpire: () => void): PausableDeadline;
24
+ /**
25
+ * The `pauseDeadline` in a tool's execute options (the second argument a
26
+ * model loop passes), or undefined when there is none.
27
+ */
28
+ export declare function pauseDeadlineOf(execOptions: unknown): PauseDeadline | undefined;
@@ -0,0 +1,88 @@
1
+ /**
2
+ * A deadline a tool call can pause while it waits for a human.
3
+ *
4
+ * A model loop bounds each tool call. A call that needs a confirmation spends
5
+ * part of that bound waiting for a person, which says nothing about the tool,
6
+ * so the confirmation pauses the bound and resumes it afterwards with the time
7
+ * that was left, never a fresh one.
8
+ */
9
+ /**
10
+ * Arms a deadline of `ms` that calls `onExpire` once when it runs out.
11
+ *
12
+ * - `pause()` stops the clock and returns the resume function. Paused time is
13
+ * not spent: resuming re-arms the timer with what was left. Pauses nest; the
14
+ * clock runs again only once every pause has resumed, and each resume
15
+ * function acts once.
16
+ * - `clear()` ends the deadline for good: `onExpire` never runs, and a resume
17
+ * that arrives later re-arms nothing.
18
+ *
19
+ * The timer is deliberately not unref'd: while a call is in flight it may be
20
+ * the only thing that will end a wedged tool.
21
+ */
22
+ export function createPausableDeadline(ms, onExpire) {
23
+ let remaining = ms;
24
+ let armedAt = 0;
25
+ let timer;
26
+ let pauses = 0;
27
+ let ended = false;
28
+ const arm = () => {
29
+ armedAt = Date.now();
30
+ timer = setTimeout(() => {
31
+ timer = undefined;
32
+ ended = true;
33
+ onExpire();
34
+ }, Math.max(0, remaining));
35
+ };
36
+ const pause = () => {
37
+ if (ended) {
38
+ return () => undefined;
39
+ }
40
+ if (pauses === 0) {
41
+ clearTimeout(timer);
42
+ timer = undefined;
43
+ remaining -= Date.now() - armedAt;
44
+ }
45
+ pauses++;
46
+ let resumed = false;
47
+ return () => {
48
+ if (resumed) {
49
+ return;
50
+ }
51
+ resumed = true;
52
+ pauses--;
53
+ if (pauses === 0 && !ended) {
54
+ arm();
55
+ }
56
+ };
57
+ };
58
+ arm();
59
+ return {
60
+ pause,
61
+ clear: () => {
62
+ ended = true;
63
+ clearTimeout(timer);
64
+ timer = undefined;
65
+ },
66
+ };
67
+ }
68
+ /**
69
+ * The `pauseDeadline` in a tool's execute options (the second argument a
70
+ * model loop passes), or undefined when there is none.
71
+ */
72
+ export function pauseDeadlineOf(execOptions) {
73
+ if (typeof execOptions !== "object" ||
74
+ execOptions === null ||
75
+ !("pauseDeadline" in execOptions)) {
76
+ return undefined;
77
+ }
78
+ const { pauseDeadline } = execOptions;
79
+ if (typeof pauseDeadline !== "function") {
80
+ return undefined;
81
+ }
82
+ // Called through a wrapper, so whatever it returns, the caller gets a
83
+ // resume function it can always call.
84
+ return () => {
85
+ const resume = pauseDeadline();
86
+ return typeof resume === "function" ? () => void resume() : () => undefined;
87
+ };
88
+ }