@juspay/neurolink 13.13.3 → 13.13.5
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.
- package/CHANGELOG.md +2 -2
- package/dist/browser/neurolink.min.js +413 -413
- package/dist/core/toolRouting.js +4 -3
- package/dist/core/toolRoutingDecision.d.ts +10 -0
- package/dist/core/toolRoutingDecision.js +13 -0
- package/dist/hitl/hitlManager.js +1 -0
- package/dist/hitl/toolCallConfirmation.d.ts +8 -0
- package/dist/hitl/toolCallConfirmation.js +12 -0
- package/dist/mcp/batching/requestBatcher.d.ts +1 -1
- package/dist/mcp/batching/requestBatcher.js +8 -4
- package/dist/mcp/toolRegistry.js +9 -4
- package/dist/neurolink.d.ts +7 -0
- package/dist/neurolink.js +156 -10
- package/dist/providers/systemOneDecision.js +33 -6
- package/dist/proxy/proxyFetch.js +21 -2
- package/dist/types/decision.d.ts +14 -0
- package/dist/types/hitl.d.ts +8 -0
- package/dist/types/mcp.d.ts +3 -1
- package/docs-site/static/search-index.json +3 -3
- package/package.json +2 -2
package/dist/core/toolRouting.js
CHANGED
|
@@ -38,7 +38,7 @@ import { z } from "zod";
|
|
|
38
38
|
import { logger } from "../utils/logger.js";
|
|
39
39
|
import { withTimeout } from "../utils/async/index.js";
|
|
40
40
|
import { selectRelevantToolNames } from "./toolRoutingEmbedding.js";
|
|
41
|
-
import { selectServersByDecision } from "./toolRoutingDecision.js";
|
|
41
|
+
import { selectServersByDecision, ToolRoutingDecisionTimeoutError, } from "./toolRoutingDecision.js";
|
|
42
42
|
const routerOutputSchema = z.object({
|
|
43
43
|
servers: z.array(z.string()),
|
|
44
44
|
});
|
|
@@ -498,8 +498,9 @@ export async function resolveToolRoutingExclusions(params) {
|
|
|
498
498
|
return excludedToolNames;
|
|
499
499
|
}
|
|
500
500
|
catch (error) {
|
|
501
|
-
const isTimeout = error instanceof
|
|
502
|
-
error
|
|
501
|
+
const isTimeout = error instanceof ToolRoutingDecisionTimeoutError ||
|
|
502
|
+
(error instanceof Error &&
|
|
503
|
+
error.message.includes("Tool routing router call exceeded"));
|
|
503
504
|
const outcome = isTimeout
|
|
504
505
|
? "failed-open-timeout"
|
|
505
506
|
: "failed-open-error";
|
|
@@ -22,6 +22,16 @@
|
|
|
22
22
|
* @module core/toolRoutingDecision
|
|
23
23
|
*/
|
|
24
24
|
import type { DecisionCallerFn, ToolRoutingCatalogEntry, ToolRoutingDecisionOutcome } from "../types/index.js";
|
|
25
|
+
/**
|
|
26
|
+
* Thrown by a host-bound `decideFn` when a configured decision provider did
|
|
27
|
+
* not answer inside `toolRouting.timeoutMs`. It is distinct from `null`
|
|
28
|
+
* ("no provider", which falls back to the generative router): after a timeout
|
|
29
|
+
* the router must add no exclusions, or a slow decision model would hand the
|
|
30
|
+
* turn to a second, unbounded model that can still drop tools.
|
|
31
|
+
*/
|
|
32
|
+
export declare class ToolRoutingDecisionTimeoutError extends Error {
|
|
33
|
+
constructor(timeoutMs: number);
|
|
34
|
+
}
|
|
25
35
|
/**
|
|
26
36
|
* Ask one yes/no question per routable server and return the servers to keep.
|
|
27
37
|
*
|
|
@@ -23,6 +23,19 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { decisionKey, gateDecisionBoolean } from "../utils/decisionAnswers.js";
|
|
25
25
|
import { logger } from "../utils/logger.js";
|
|
26
|
+
/**
|
|
27
|
+
* Thrown by a host-bound `decideFn` when a configured decision provider did
|
|
28
|
+
* not answer inside `toolRouting.timeoutMs`. It is distinct from `null`
|
|
29
|
+
* ("no provider", which falls back to the generative router): after a timeout
|
|
30
|
+
* the router must add no exclusions, or a slow decision model would hand the
|
|
31
|
+
* turn to a second, unbounded model that can still drop tools.
|
|
32
|
+
*/
|
|
33
|
+
export class ToolRoutingDecisionTimeoutError extends Error {
|
|
34
|
+
constructor(timeoutMs) {
|
|
35
|
+
super(`Tool routing decision exceeded ${timeoutMs}ms`);
|
|
36
|
+
this.name = "ToolRoutingDecisionTimeoutError";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
26
39
|
/** Namespace for the per-server questions in the batch. */
|
|
27
40
|
const SERVER_NAMESPACE = "server";
|
|
28
41
|
/**
|
package/dist/hitl/hitlManager.js
CHANGED
|
@@ -71,6 +71,7 @@ export class HITLManager extends EventEmitter {
|
|
|
71
71
|
auditLogging: config.auditLogging ?? false, // Default: false
|
|
72
72
|
customRules: config.customRules ?? [], // Default: empty array
|
|
73
73
|
confirmBuiltinTools: config.confirmBuiltinTools ?? true, // Default: true (built-in write/bash tools prompt)
|
|
74
|
+
confirmDirectToolCalls: config.confirmDirectToolCalls ?? false, // Default: false (direct executeTool calls keep their existing behaviour)
|
|
74
75
|
};
|
|
75
76
|
if (!configWithDefaults.enabled) {
|
|
76
77
|
return configWithDefaults; // If disabled, don't validate other fields
|
|
@@ -20,6 +20,14 @@ export declare function createHITLExecutionState(): HITLExecutionState;
|
|
|
20
20
|
* machine unless the host set `hitl.confirmBuiltinTools: false`.
|
|
21
21
|
*/
|
|
22
22
|
export declare function builtInToolAlwaysConfirmed(hitl: HITLManager, toolName: string): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* `builtInToolAlwaysConfirmed` for a direct call to a tool resolved from the
|
|
25
|
+
* registry. It is opt-in (`hitl.confirmDirectToolCalls: true`) because direct
|
|
26
|
+
* callers were never prompted for these tools. Only a tool registered by
|
|
27
|
+
* NeuroLink itself (server `direct`) is a built-in, so a custom or external
|
|
28
|
+
* tool that reuses the name `writeFile` is not swept in.
|
|
29
|
+
*/
|
|
30
|
+
export declare function registeredToolAlwaysConfirmed(hitl: HITLManager, toolName: string, serverId: string | undefined): boolean;
|
|
23
31
|
/** Mark `result` as a HITL refusal and return it. */
|
|
24
32
|
export declare function markRefusalResult<T extends object>(result: T): T;
|
|
25
33
|
/** Whether `result` was marked as a HITL refusal (`markRefusalResult`). */
|
|
@@ -87,6 +87,18 @@ export function builtInToolAlwaysConfirmed(hitl, toolName) {
|
|
|
87
87
|
return (HITL_ALWAYS_CONFIRM_BUILT_IN_TOOLS.has(toolName) &&
|
|
88
88
|
hitl.getConfig().confirmBuiltinTools !== false);
|
|
89
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* `builtInToolAlwaysConfirmed` for a direct call to a tool resolved from the
|
|
92
|
+
* registry. It is opt-in (`hitl.confirmDirectToolCalls: true`) because direct
|
|
93
|
+
* callers were never prompted for these tools. Only a tool registered by
|
|
94
|
+
* NeuroLink itself (server `direct`) is a built-in, so a custom or external
|
|
95
|
+
* tool that reuses the name `writeFile` is not swept in.
|
|
96
|
+
*/
|
|
97
|
+
export function registeredToolAlwaysConfirmed(hitl, toolName, serverId) {
|
|
98
|
+
return (hitl.getConfig().confirmDirectToolCalls === true &&
|
|
99
|
+
serverId === "direct" &&
|
|
100
|
+
builtInToolAlwaysConfirmed(hitl, toolName));
|
|
101
|
+
}
|
|
90
102
|
/**
|
|
91
103
|
* Tool results that carry a HITL refusal. A cache of tool results must not
|
|
92
104
|
* keep one, the per-turn one of the Gemini loops (`DedupExecuteMap`)
|
|
@@ -98,7 +98,7 @@ export declare class ToolCallBatcher {
|
|
|
98
98
|
/**
|
|
99
99
|
* Set the tool executor function
|
|
100
100
|
*/
|
|
101
|
-
setToolExecutor(executor: (tool: string, args: unknown, serverId?: string) => Promise<unknown>): void;
|
|
101
|
+
setToolExecutor(executor: (tool: string, args: unknown, serverId?: string, signal?: AbortSignal) => Promise<unknown>): void;
|
|
102
102
|
/**
|
|
103
103
|
* Execute a tool call (will be batched automatically)
|
|
104
104
|
*/
|
|
@@ -238,15 +238,19 @@ export class RequestBatcher extends EventEmitter {
|
|
|
238
238
|
});
|
|
239
239
|
}
|
|
240
240
|
// Execute the batch with a timeout to prevent indefinite hangs
|
|
241
|
+
const batchAbort = new AbortController();
|
|
241
242
|
const executorPromise = this.executor(batchRequests.map((r) => ({
|
|
242
243
|
tool: r.tool,
|
|
243
244
|
args: r.args,
|
|
244
245
|
serverId: r.serverId,
|
|
245
|
-
})));
|
|
246
|
+
})), batchAbort.signal);
|
|
246
247
|
const timeoutMs = Math.max(5000, Number(process.env.MCP_TOOL_TIMEOUT) || 60000);
|
|
247
248
|
let timeoutHandle;
|
|
248
249
|
const timeoutPromise = new Promise((_, reject) => {
|
|
249
|
-
timeoutHandle = setTimeout(() =>
|
|
250
|
+
timeoutHandle = setTimeout(() => {
|
|
251
|
+
batchAbort.abort();
|
|
252
|
+
reject(ErrorFactory.toolTimeout("batchExecution", timeoutMs));
|
|
253
|
+
}, timeoutMs);
|
|
250
254
|
});
|
|
251
255
|
// Suppress unhandled rejection if executorPromise rejects after timeout wins
|
|
252
256
|
void executorPromise.catch((_e) => {
|
|
@@ -394,7 +398,7 @@ export class ToolCallBatcher {
|
|
|
394
398
|
...config,
|
|
395
399
|
});
|
|
396
400
|
// Set up internal executor that calls individual tool executions
|
|
397
|
-
this.batcher.setExecutor(async (requests) => {
|
|
401
|
+
this.batcher.setExecutor(async (requests, signal) => {
|
|
398
402
|
if (!this.toolExecutor) {
|
|
399
403
|
throw ErrorFactory.missingConfiguration("toolExecutor", {
|
|
400
404
|
hint: "Call setToolExecutor() before executing tool calls",
|
|
@@ -403,7 +407,7 @@ export class ToolCallBatcher {
|
|
|
403
407
|
const executor = this.toolExecutor;
|
|
404
408
|
const results = await Promise.all(requests.map(async (req) => {
|
|
405
409
|
try {
|
|
406
|
-
const result = await executor(req.tool, req.args, req.serverId);
|
|
410
|
+
const result = await executor(req.tool, req.args, req.serverId, signal);
|
|
407
411
|
return { success: true, result };
|
|
408
412
|
}
|
|
409
413
|
catch (error) {
|
package/dist/mcp/toolRegistry.js
CHANGED
|
@@ -13,7 +13,7 @@ import { detectCategory, createMCPServerInfo } from "../utils/mcpDefaults.js";
|
|
|
13
13
|
import { FlexibleToolValidator } from "./flexibleToolValidator.js";
|
|
14
14
|
import { ErrorFactory, isAbortError, throwIfSignalAborted, } from "../utils/errorHandling.js";
|
|
15
15
|
import { HITLError } from "../hitl/hitlErrors.js";
|
|
16
|
-
import { isRefusalResult, markRefusalResult, resolveToolCallConfirmation, } from "../hitl/toolCallConfirmation.js";
|
|
16
|
+
import { isRefusalResult, markRefusalResult, registeredToolAlwaysConfirmed, resolveToolCallConfirmation, } from "../hitl/toolCallConfirmation.js";
|
|
17
17
|
import { withSpan, tracers, ATTR } from "../telemetry/index.js";
|
|
18
18
|
import { SpanStatusCode } from "@opentelemetry/api";
|
|
19
19
|
import { getAuthContext } from "../auth/authContext.js";
|
|
@@ -364,7 +364,7 @@ export class MCPToolRegistry extends MCPRegistry {
|
|
|
364
364
|
// HITL Safety Check. A call that NeuroLink.executeTool already gated
|
|
365
365
|
// arrives with its decision recorded and is never asked again; a
|
|
366
366
|
// direct caller without one is asked here.
|
|
367
|
-
const finalArgs = await this.confirmToolCall(toolName, args, tool.serverId, execContext, span);
|
|
367
|
+
const finalArgs = await this.confirmToolCall(toolName, args, tool.serverId, execContext, span, tool.name);
|
|
368
368
|
// A call cancelled during its confirmation must not start.
|
|
369
369
|
throwIfSignalAborted(execContext.abortSignal);
|
|
370
370
|
// Execute the actual tool (with potentially modified arguments)
|
|
@@ -560,13 +560,18 @@ export class MCPToolRegistry extends MCPRegistry {
|
|
|
560
560
|
* must not run, which `executeTool` reports as `{ success: false }`;
|
|
561
561
|
* otherwise returns the arguments to run with.
|
|
562
562
|
*/
|
|
563
|
-
async confirmToolCall(toolName, args, serverId, execContext, span) {
|
|
563
|
+
async confirmToolCall(toolName, args, serverId, execContext, span, canonicalName) {
|
|
564
564
|
const action = await resolveToolCallConfirmation(this.hitlManager, toolName, args, execContext.hitlState, {
|
|
565
565
|
serverId,
|
|
566
566
|
sessionId: execContext.sessionId,
|
|
567
567
|
userId: execContext.userId,
|
|
568
568
|
signal: execContext.abortSignal,
|
|
569
|
-
}, {
|
|
569
|
+
}, {
|
|
570
|
+
log: (message) => registryLogger.info(message),
|
|
571
|
+
span,
|
|
572
|
+
alwaysConfirm: this.hitlManager !== undefined &&
|
|
573
|
+
registeredToolAlwaysConfirmed(this.hitlManager, canonicalName, serverId),
|
|
574
|
+
});
|
|
570
575
|
if (!action.run) {
|
|
571
576
|
throw action.error;
|
|
572
577
|
}
|
package/dist/neurolink.d.ts
CHANGED
|
@@ -1983,6 +1983,13 @@ export declare class NeuroLink {
|
|
|
1983
1983
|
* the external manager usually share the host's.
|
|
1984
1984
|
*/
|
|
1985
1985
|
private callNeedsConfirmation;
|
|
1986
|
+
/**
|
|
1987
|
+
* Whether a direct `executeTool` call to `toolName` resolves to a built-in
|
|
1988
|
+
* the host asked to have confirmed on every call (`confirmBuiltinTools`),
|
|
1989
|
+
* the same rule a model's call to it is held to. Opt-in through
|
|
1990
|
+
* `confirmDirectToolCalls`, so existing direct callers are not prompted.
|
|
1991
|
+
*/
|
|
1992
|
+
private isRegisteredBuiltInGated;
|
|
1986
1993
|
/**
|
|
1987
1994
|
* Bookkeeping for a call its confirmation refused: `tool:end` with
|
|
1988
1995
|
* `success: false`, the span marked as an error and a failed execution
|
package/dist/neurolink.js
CHANGED
|
@@ -37,6 +37,7 @@ import { SYSTEM_LIMITS, DEFAULT_TOOL_ROUTING_TIMEOUT_MS, JEV_ROUTING_AUDIT_PROVI
|
|
|
37
37
|
import { ConversationMemoryManager } from "./core/conversationMemoryManager.js";
|
|
38
38
|
import { buildToolRoutingCatalog, buildRoutingQueryFromHistory, resolveToolRoutingExclusions, } from "./core/toolRouting.js";
|
|
39
39
|
import { ToolRoutingCache } from "./core/toolRoutingCache.js";
|
|
40
|
+
import { ToolRoutingDecisionTimeoutError } from "./core/toolRoutingDecision.js";
|
|
40
41
|
import { DEFAULT_RECENT_TURNS, KnowledgeGroundingEngine, } from "./knowledge/index.js";
|
|
41
42
|
import { AnthropicThreadStore } from "./providers/anthropic/threads.js";
|
|
42
43
|
import { AIProviderFactory } from "./core/factory.js";
|
|
@@ -53,7 +54,7 @@ import { FileReferenceRegistry } from "./files/fileReferenceRegistry.js";
|
|
|
53
54
|
import { resolveAttachmentPolicy } from "./utils/attachmentPolicy.js";
|
|
54
55
|
import { createFileTools } from "./files/fileTools.js";
|
|
55
56
|
import { HITLManager, DEFAULT_ALLOW_MODIFICATION } from "./hitl/hitlManager.js";
|
|
56
|
-
import { builtInToolAlwaysConfirmed, createHITLExecutionState, hitlStateRefused, isRefusalResult, markRefusalResult, resolveToolCallConfirmation, } from "./hitl/toolCallConfirmation.js";
|
|
57
|
+
import { builtInToolAlwaysConfirmed, createHITLExecutionState, hitlStateRefused, isRefusalResult, markRefusalResult, registeredToolAlwaysConfirmed, resolveToolCallConfirmation, } from "./hitl/toolCallConfirmation.js";
|
|
57
58
|
import { HITLError } from "./hitl/hitlErrors.js";
|
|
58
59
|
import { getAuthContext as getAmbientAuthContext } from "./auth/authContext.js";
|
|
59
60
|
import { ToolCallBatcher } from "./mcp/batching/index.js";
|
|
@@ -1711,7 +1712,10 @@ export class NeuroLink {
|
|
|
1711
1712
|
maxWaitMs: mcpConfig.batcher.maxWaitMs ?? 100,
|
|
1712
1713
|
});
|
|
1713
1714
|
// Wire batcher to execute tools via the internal execution path (bypass batcher itself)
|
|
1714
|
-
this.mcpToolBatcher.setToolExecutor(async (tool, args) => {
|
|
1715
|
+
this.mcpToolBatcher.setToolExecutor(async (tool, args, _serverId, batchSignal) => {
|
|
1716
|
+
// The batch's timeout aborts the call, so a confirmation card that
|
|
1717
|
+
// opened inside the batch (the setting changed after the call was
|
|
1718
|
+
// enqueued) is withdrawn and a late approval cannot run the call.
|
|
1715
1719
|
// A state of its own per call, so the safe-tool retry inside
|
|
1716
1720
|
// executeToolInternal reuses the first answer instead of asking again.
|
|
1717
1721
|
// A tool registered with no retries gets no safe-tool retry either.
|
|
@@ -1720,6 +1724,7 @@ export class NeuroLink {
|
|
|
1720
1724
|
maxRetries: this.toolRegistry.getToolInfo(tool)?.tool?.maxRetries ??
|
|
1721
1725
|
RETRY_ATTEMPTS.DEFAULT,
|
|
1722
1726
|
retryDelayMs: RETRY_DELAYS.BASE_MS,
|
|
1727
|
+
...(batchSignal ? { abortSignal: batchSignal } : {}),
|
|
1723
1728
|
}, createHITLExecutionState());
|
|
1724
1729
|
});
|
|
1725
1730
|
logger.debug("[NeuroLink] MCP tool call batcher initialized");
|
|
@@ -8185,7 +8190,112 @@ Current user's request: ${currentInput}`;
|
|
|
8185
8190
|
if (auditEnabled) {
|
|
8186
8191
|
auditInput = buildJevRoutingAuditInput(decisionOptions.state);
|
|
8187
8192
|
}
|
|
8188
|
-
|
|
8193
|
+
// One deadline for the whole provider call (every retry and
|
|
8194
|
+
// backoff included), enforced by aborting the in-flight request
|
|
8195
|
+
// and by not waiting for a wrapper that ignores the signal.
|
|
8196
|
+
// siteDecide starts it right before provider dispatch, so a slow
|
|
8197
|
+
// host `extendQuestions` hook keeps its own budget. A fraction
|
|
8198
|
+
// is floored to whole ms (AbortSignal.timeout rejects one) so
|
|
8199
|
+
// the ceiling is never extended. Unset, or a value that is not
|
|
8200
|
+
// a usable bound (<= 0, NaN, Infinity), keeps the provider's
|
|
8201
|
+
// own state-scaled default untouched.
|
|
8202
|
+
const configured = routingConfig.timeoutMs;
|
|
8203
|
+
const boundMs = typeof configured === "number" &&
|
|
8204
|
+
Number.isFinite(configured) &&
|
|
8205
|
+
configured > 0
|
|
8206
|
+
? // Node's timers treat anything above 2^31-1 ms as 1 ms.
|
|
8207
|
+
Math.min(2_147_483_647, Math.max(1, Math.floor(configured)))
|
|
8208
|
+
: undefined;
|
|
8209
|
+
// Whether the provider's own call had already hit the deadline
|
|
8210
|
+
// when it returned; a slow host observer afterwards is not a
|
|
8211
|
+
// provider timeout.
|
|
8212
|
+
let deadlineHitAtReturn;
|
|
8213
|
+
let deadline;
|
|
8214
|
+
let onDeadlineStarted = () => { };
|
|
8215
|
+
const deadlineStarted = new Promise((resolve) => {
|
|
8216
|
+
onDeadlineStarted = resolve;
|
|
8217
|
+
});
|
|
8218
|
+
const decision = this.siteDecide(decisionOptions, {
|
|
8219
|
+
...this.decisionSiteContext(options, sessionId || undefined),
|
|
8220
|
+
providerTimeoutMs: boundMs,
|
|
8221
|
+
onProviderDeadline: (signal) => {
|
|
8222
|
+
deadline = signal;
|
|
8223
|
+
onDeadlineStarted(signal);
|
|
8224
|
+
},
|
|
8225
|
+
onProviderReturned: () => {
|
|
8226
|
+
deadlineHitAtReturn = deadline?.aborted === true;
|
|
8227
|
+
},
|
|
8228
|
+
});
|
|
8229
|
+
const DECISION_DEADLINE = Symbol("decisionDeadline");
|
|
8230
|
+
let result;
|
|
8231
|
+
if (boundMs === undefined) {
|
|
8232
|
+
result = await decision;
|
|
8233
|
+
}
|
|
8234
|
+
else {
|
|
8235
|
+
// A host override of decide() may ignore the signal and never
|
|
8236
|
+
// settle: the deadline itself ends the wait, and whatever the
|
|
8237
|
+
// wrapped call returns later is dropped.
|
|
8238
|
+
decision.catch(() => undefined);
|
|
8239
|
+
const expired = deadlineStarted.then((signal) => new Promise((resolve) => {
|
|
8240
|
+
// Only the provider call is bounded: once it returned,
|
|
8241
|
+
// a slow host observer is not a provider timeout.
|
|
8242
|
+
const fire = () => {
|
|
8243
|
+
if (deadlineHitAtReturn === undefined) {
|
|
8244
|
+
resolve(DECISION_DEADLINE);
|
|
8245
|
+
}
|
|
8246
|
+
};
|
|
8247
|
+
if (signal.aborted) {
|
|
8248
|
+
fire();
|
|
8249
|
+
return;
|
|
8250
|
+
}
|
|
8251
|
+
signal.addEventListener("abort", fire, { once: true });
|
|
8252
|
+
}));
|
|
8253
|
+
// The caller's own cancellation is raced separately, so an
|
|
8254
|
+
// unresponsive decide() cannot hold a cancelled turn until the
|
|
8255
|
+
// deadline. A late answer is dropped, never applied.
|
|
8256
|
+
const callerSignal = options.abortSignal;
|
|
8257
|
+
const CALLER_ABORTED = Symbol("callerAborted");
|
|
8258
|
+
let removeAbortListener = () => { };
|
|
8259
|
+
const cancelled = new Promise((resolve) => {
|
|
8260
|
+
if (callerSignal === undefined) {
|
|
8261
|
+
return;
|
|
8262
|
+
}
|
|
8263
|
+
if (callerSignal.aborted) {
|
|
8264
|
+
resolve(CALLER_ABORTED);
|
|
8265
|
+
return;
|
|
8266
|
+
}
|
|
8267
|
+
const onAbort = () => resolve(CALLER_ABORTED);
|
|
8268
|
+
callerSignal.addEventListener("abort", onAbort, {
|
|
8269
|
+
once: true,
|
|
8270
|
+
});
|
|
8271
|
+
removeAbortListener = () => callerSignal.removeEventListener("abort", onAbort);
|
|
8272
|
+
});
|
|
8273
|
+
let winner;
|
|
8274
|
+
try {
|
|
8275
|
+
winner = await Promise.race([decision, expired, cancelled]);
|
|
8276
|
+
}
|
|
8277
|
+
finally {
|
|
8278
|
+
removeAbortListener();
|
|
8279
|
+
}
|
|
8280
|
+
if (winner === CALLER_ABORTED) {
|
|
8281
|
+
throw new DOMException("The operation was aborted", "AbortError");
|
|
8282
|
+
}
|
|
8283
|
+
if (winner === DECISION_DEADLINE) {
|
|
8284
|
+
if (callerSignal?.aborted) {
|
|
8285
|
+
throw new DOMException("The operation was aborted", "AbortError");
|
|
8286
|
+
}
|
|
8287
|
+
throw new ToolRoutingDecisionTimeoutError(boundMs);
|
|
8288
|
+
}
|
|
8289
|
+
result = winner;
|
|
8290
|
+
}
|
|
8291
|
+
// A late or aborted answer is never applied. A missed deadline
|
|
8292
|
+
// means a provider was configured and too slow, unlike the
|
|
8293
|
+
// no-provider null that falls back to the generative router.
|
|
8294
|
+
if ((deadlineHitAtReturn ?? deadline?.aborted) &&
|
|
8295
|
+
boundMs !== undefined &&
|
|
8296
|
+
!options.abortSignal?.aborted) {
|
|
8297
|
+
throw new ToolRoutingDecisionTimeoutError(boundMs);
|
|
8298
|
+
}
|
|
8189
8299
|
if (auditInput !== null && result !== null) {
|
|
8190
8300
|
try {
|
|
8191
8301
|
if (result.provider === JEV_ROUTING_AUDIT_PROVIDER) {
|
|
@@ -11771,7 +11881,11 @@ Current user's request: ${currentInput}`;
|
|
|
11771
11881
|
sessionId: sessionId ?? crypto.randomUUID(),
|
|
11772
11882
|
userId,
|
|
11773
11883
|
signal: options.abortSignal,
|
|
11774
|
-
}, {
|
|
11884
|
+
}, {
|
|
11885
|
+
span: ctx.span,
|
|
11886
|
+
pauseDeadline: options.pauseDeadline,
|
|
11887
|
+
alwaysConfirm: !ctx.external && this.isRegisteredBuiltInGated(hitl, toolName),
|
|
11888
|
+
});
|
|
11775
11889
|
if (action.run) {
|
|
11776
11890
|
return { params: action.args };
|
|
11777
11891
|
}
|
|
@@ -11860,8 +11974,9 @@ Current user's request: ${currentInput}`;
|
|
|
11860
11974
|
* the external manager usually share the host's.
|
|
11861
11975
|
*/
|
|
11862
11976
|
callNeedsConfirmation(toolName, params) {
|
|
11977
|
+
const registryManager = this.confirmationManagerFor(false);
|
|
11863
11978
|
const managers = new Set([
|
|
11864
|
-
|
|
11979
|
+
registryManager,
|
|
11865
11980
|
this.confirmationManagerFor(true),
|
|
11866
11981
|
]);
|
|
11867
11982
|
for (const manager of managers) {
|
|
@@ -11869,7 +11984,19 @@ Current user's request: ${currentInput}`;
|
|
|
11869
11984
|
return true;
|
|
11870
11985
|
}
|
|
11871
11986
|
}
|
|
11872
|
-
return
|
|
11987
|
+
return (registryManager?.isEnabled() === true &&
|
|
11988
|
+
this.isRegisteredBuiltInGated(registryManager, toolName));
|
|
11989
|
+
}
|
|
11990
|
+
/**
|
|
11991
|
+
* Whether a direct `executeTool` call to `toolName` resolves to a built-in
|
|
11992
|
+
* the host asked to have confirmed on every call (`confirmBuiltinTools`),
|
|
11993
|
+
* the same rule a model's call to it is held to. Opt-in through
|
|
11994
|
+
* `confirmDirectToolCalls`, so existing direct callers are not prompted.
|
|
11995
|
+
*/
|
|
11996
|
+
isRegisteredBuiltInGated(hitl, toolName) {
|
|
11997
|
+
const tool = this.toolRegistry.getToolInfo(toolName)?.tool;
|
|
11998
|
+
return (tool !== undefined &&
|
|
11999
|
+
registeredToolAlwaysConfirmed(hitl, tool.name, tool.serverId));
|
|
11873
12000
|
}
|
|
11874
12001
|
/**
|
|
11875
12002
|
* Bookkeeping for a call its confirmation refused: `tool:end` with
|
|
@@ -14780,16 +14907,35 @@ Current user's request: ${currentInput}`;
|
|
|
14780
14907
|
sessionId: outer?.sessionId ?? request.sessionId,
|
|
14781
14908
|
requestId: outer?.requestId ?? request.requestId,
|
|
14782
14909
|
};
|
|
14910
|
+
let providerDeadline;
|
|
14911
|
+
const runWire = async (wireRequest) => {
|
|
14912
|
+
// Started here, not at the caller, so host hooks that ran first spend
|
|
14913
|
+
// their own budget; shared by every wire call this siteDecide makes.
|
|
14914
|
+
if (outer?.providerTimeoutMs !== undefined && !providerDeadline) {
|
|
14915
|
+
providerDeadline = AbortSignal.timeout(outer.providerTimeoutMs);
|
|
14916
|
+
outer.onProviderDeadline?.(providerDeadline);
|
|
14917
|
+
}
|
|
14918
|
+
const wireResult = await this.tryRunDecide(providerDeadline
|
|
14919
|
+
? {
|
|
14920
|
+
...wireRequest,
|
|
14921
|
+
signal: wireRequest.signal
|
|
14922
|
+
? AbortSignal.any([wireRequest.signal, providerDeadline])
|
|
14923
|
+
: providerDeadline,
|
|
14924
|
+
}
|
|
14925
|
+
: wireRequest);
|
|
14926
|
+
outer?.onProviderReturned?.();
|
|
14927
|
+
return wireResult;
|
|
14928
|
+
};
|
|
14783
14929
|
const site = merged.site;
|
|
14784
14930
|
if (!site) {
|
|
14785
|
-
return
|
|
14931
|
+
return runWire(merged);
|
|
14786
14932
|
}
|
|
14787
14933
|
// No host hook or event without a decision provider: a hook must not sit
|
|
14788
14934
|
// on the request path of a tenant that has no decision model to reach, and
|
|
14789
14935
|
// an event for a call that could never be made would only mislead. The
|
|
14790
14936
|
// plain call still runs, so the WARNING observation it records is kept.
|
|
14791
14937
|
if (!this.resolveDecisionProviderName(merged.provider, merged.credentials)) {
|
|
14792
|
-
return
|
|
14938
|
+
return runWire(merged);
|
|
14793
14939
|
}
|
|
14794
14940
|
// Wire id → the host's own id, so answers can be handed back under the
|
|
14795
14941
|
// ids the host used, and NeuroLink's consumers never see a host id. A Map,
|
|
@@ -14899,7 +15045,7 @@ Current user's request: ${currentInput}`;
|
|
|
14899
15045
|
this.emitDecisionEvent("decision:before", beforeEvent);
|
|
14900
15046
|
}
|
|
14901
15047
|
const startedAt = Date.now();
|
|
14902
|
-
const result = await
|
|
15048
|
+
const result = await runWire({ ...merged, questions });
|
|
14903
15049
|
obtained = result;
|
|
14904
15050
|
// Null-prototype maps: a host id such as `__proto__` or `constructor`
|
|
14905
15051
|
// must land as an own key, not fall into the prototype and vanish.
|
|
@@ -14961,7 +15107,7 @@ Current user's request: ${currentInput}`;
|
|
|
14961
15107
|
? "deciding with NeuroLink's own questions"
|
|
14962
15108
|
: "handing the consumer the answers already obtained"}`, { error: error instanceof Error ? error.message : String(error) });
|
|
14963
15109
|
if (obtained === undefined) {
|
|
14964
|
-
return
|
|
15110
|
+
return runWire(merged);
|
|
14965
15111
|
}
|
|
14966
15112
|
return obtained ? stripHostAnswers(obtained, hostIdByWireId) : null;
|
|
14967
15113
|
}
|
|
@@ -82,9 +82,8 @@ function isRedirectRefusal(error) {
|
|
|
82
82
|
/**
|
|
83
83
|
* Rejects with the signal's reason when it aborts, so a caller tearing a turn
|
|
84
84
|
* down is not held, nor its process kept alive, for the length of a vendor's
|
|
85
|
-
* Retry-After wait. The
|
|
86
|
-
*
|
|
87
|
-
* already handling that error.
|
|
85
|
+
* Retry-After wait. The transport-error backoff passes the request signal
|
|
86
|
+
* too and turns a rejection into a non-retryable error.
|
|
88
87
|
*/
|
|
89
88
|
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
90
89
|
if (signal?.aborted) {
|
|
@@ -316,7 +315,16 @@ export class SystemOneDecisionProvider extends BaseProvider {
|
|
|
316
315
|
const requestId = this.readRequestId(response.headers);
|
|
317
316
|
const upstreamMs = Number(response.headers.get("x-envoy-upstream-service-time")) ||
|
|
318
317
|
undefined;
|
|
319
|
-
const payload = await response
|
|
318
|
+
const payload = await response
|
|
319
|
+
.json()
|
|
320
|
+
.catch((error) => {
|
|
321
|
+
// A deadline or abort that cuts the body read short is a timeout,
|
|
322
|
+
// not a response without answers; the catch below classifies it.
|
|
323
|
+
if (signal.aborted) {
|
|
324
|
+
throw error;
|
|
325
|
+
}
|
|
326
|
+
return null;
|
|
327
|
+
});
|
|
320
328
|
if (!response.ok) {
|
|
321
329
|
lastError = this.parseDecisionError(response.status, payload, requestId);
|
|
322
330
|
if (lastError.kind === "authentication") {
|
|
@@ -401,9 +409,13 @@ export class SystemOneDecisionProvider extends BaseProvider {
|
|
|
401
409
|
// turn is already being torn down.
|
|
402
410
|
const aborted = request.signal?.aborted === true;
|
|
403
411
|
const isTimeout = error instanceof Error && error.name === "TimeoutError";
|
|
412
|
+
// The caller's deadline is an AbortSignal.timeout, so its reason is a
|
|
413
|
+
// TimeoutError; a cancellation is not, and stays a network failure.
|
|
414
|
+
const reason = request.signal?.reason;
|
|
415
|
+
const deadlineHit = aborted && reason instanceof Error && reason.name === "TimeoutError";
|
|
404
416
|
const redirected = isRedirectRefusal(error);
|
|
405
417
|
lastError = {
|
|
406
|
-
kind:
|
|
418
|
+
kind: deadlineHit || (!aborted && isTimeout) ? "timeout" : "network",
|
|
407
419
|
// `fetch` words a refused redirect as "fetch failed", which says
|
|
408
420
|
// nothing about why, and asking again meets the same answer. The
|
|
409
421
|
// address it points at is the server's to choose, so it is not quoted.
|
|
@@ -415,7 +427,22 @@ export class SystemOneDecisionProvider extends BaseProvider {
|
|
|
415
427
|
if (!lastError.retryable || attempt === this.maxRetries) {
|
|
416
428
|
throw this.decisionError(lastError);
|
|
417
429
|
}
|
|
418
|
-
|
|
430
|
+
try {
|
|
431
|
+
await sleep(2 ** attempt * 250 + Math.random() * 250, request.signal);
|
|
432
|
+
}
|
|
433
|
+
catch (sleepError) {
|
|
434
|
+
// The caller's deadline or abort landed during the backoff. Record
|
|
435
|
+
// that, not the earlier network error, so the span matches what the
|
|
436
|
+
// caller sees; a deadline stays a timeout, a cancellation does not.
|
|
437
|
+
const deadlineHit = sleepError instanceof Error && sleepError.name === "TimeoutError";
|
|
438
|
+
throw this.decisionError({
|
|
439
|
+
kind: deadlineHit ? "timeout" : "network",
|
|
440
|
+
message: redactCredentials(redactUrlsInText(sleepError instanceof Error
|
|
441
|
+
? sleepError.message
|
|
442
|
+
: `${label} request was cancelled.`), this.decisionApiKey()),
|
|
443
|
+
retryable: false,
|
|
444
|
+
});
|
|
445
|
+
}
|
|
419
446
|
}
|
|
420
447
|
}
|
|
421
448
|
throw this.decisionError(lastError ?? {
|
package/dist/proxy/proxyFetch.js
CHANGED
|
@@ -116,6 +116,13 @@ export function isTransientNetworkError(error) {
|
|
|
116
116
|
*/
|
|
117
117
|
async function fetchWithRetry(url, init, maxRetries = 3, baseDelay = 500) {
|
|
118
118
|
const hostname = extractHostname(url);
|
|
119
|
+
// The signal fetch itself observes: an explicit init.signal (null included)
|
|
120
|
+
// overrides the one carried by a Request.
|
|
121
|
+
const effectiveSignal = init?.signal !== undefined
|
|
122
|
+
? init.signal
|
|
123
|
+
: url instanceof Request
|
|
124
|
+
? url.signal
|
|
125
|
+
: undefined;
|
|
119
126
|
return fetchTracer.startActiveSpan("http.fetchWithRetry", async (span) => {
|
|
120
127
|
span.setAttribute("http.request.max_retries", maxRetries);
|
|
121
128
|
span.setAttribute("http.request.hostname", hostname);
|
|
@@ -136,7 +143,10 @@ async function fetchWithRetry(url, init, maxRetries = 3, baseDelay = 500) {
|
|
|
136
143
|
catch (error) {
|
|
137
144
|
const isRetryable = isTransientNetworkError(error);
|
|
138
145
|
const err = error;
|
|
139
|
-
|
|
146
|
+
// A caller whose signal has fired is done waiting; retrying (and
|
|
147
|
+
// backing off) past it would outlive its deadline.
|
|
148
|
+
const callerGaveUp = effectiveSignal?.aborted === true;
|
|
149
|
+
if (!isRetryable || attempt === maxRetries || callerGaveUp) {
|
|
140
150
|
// Final failure — record on span and rethrow
|
|
141
151
|
span.setAttribute("http.request.total_attempts", totalAttempts);
|
|
142
152
|
span.setStatus({
|
|
@@ -154,7 +164,16 @@ async function fetchWithRetry(url, init, maxRetries = 3, baseDelay = 500) {
|
|
|
154
164
|
"retry.error": (err?.code || err?.message || String(error)).slice(0, 256),
|
|
155
165
|
});
|
|
156
166
|
logger.debug(`[fetchWithRetry] Transient error (${err?.code || err?.message}), retrying in ${delay}ms (attempt ${attempt + 1}/${maxRetries})`);
|
|
157
|
-
await new Promise((
|
|
167
|
+
await new Promise((resolve) => {
|
|
168
|
+
const timer = setTimeout(done, delay);
|
|
169
|
+
const signal = effectiveSignal ?? undefined;
|
|
170
|
+
function done() {
|
|
171
|
+
clearTimeout(timer);
|
|
172
|
+
signal?.removeEventListener("abort", done);
|
|
173
|
+
resolve();
|
|
174
|
+
}
|
|
175
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
176
|
+
});
|
|
158
177
|
}
|
|
159
178
|
}
|
|
160
179
|
throw new Error("fetchWithRetry exhausted"); // unreachable
|
package/dist/types/decision.d.ts
CHANGED
|
@@ -476,6 +476,20 @@ export type DecisionSiteContext = {
|
|
|
476
476
|
signal?: AbortSignal;
|
|
477
477
|
sessionId?: string;
|
|
478
478
|
requestId?: string;
|
|
479
|
+
/**
|
|
480
|
+
* Called each time the wire call returns, before any host hook runs, so the
|
|
481
|
+
* caller can tell whether the provider itself met a deadline apart from the
|
|
482
|
+
* time a host observer then spent.
|
|
483
|
+
*/
|
|
484
|
+
onProviderReturned?: () => void;
|
|
485
|
+
/**
|
|
486
|
+
* A deadline, in whole milliseconds, for the provider call alone. It starts
|
|
487
|
+
* right before the first wire dispatch (after any host `extendQuestions`
|
|
488
|
+
* hook) and is shared by every attempt and backoff of this call.
|
|
489
|
+
*/
|
|
490
|
+
providerTimeoutMs?: number;
|
|
491
|
+
/** Receives the deadline signal when it starts. */
|
|
492
|
+
onProviderDeadline?: (signal: AbortSignal) => void;
|
|
479
493
|
};
|
|
480
494
|
/** What a site call adds to its decision span beyond the request itself. */
|
|
481
495
|
export type DecisionSiteAttributes = {
|
package/dist/types/hitl.d.ts
CHANGED
|
@@ -36,6 +36,14 @@ export type HITLConfig = {
|
|
|
36
36
|
* only, as every other tool is.
|
|
37
37
|
*/
|
|
38
38
|
confirmBuiltinTools?: boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Whether `confirmBuiltinTools` also applies to a direct
|
|
41
|
+
* `neurolink.executeTool("writeFile", ...)` call, which the host's own code
|
|
42
|
+
* makes rather than a model (default: false, so existing callers are not
|
|
43
|
+
* prompted). Applies only while `enabled` and `confirmBuiltinTools` are
|
|
44
|
+
* `true`; `dangerousActions` and `customRules` match direct calls either way.
|
|
45
|
+
*/
|
|
46
|
+
confirmDirectToolCalls?: boolean;
|
|
39
47
|
};
|
|
40
48
|
/**
|
|
41
49
|
* Custom rule for advanced HITL scenarios
|
package/dist/types/mcp.d.ts
CHANGED
|
@@ -1988,7 +1988,9 @@ export type BatchExecutor<T> = (requests: Array<{
|
|
|
1988
1988
|
tool: string;
|
|
1989
1989
|
args: unknown;
|
|
1990
1990
|
serverId?: string;
|
|
1991
|
-
}
|
|
1991
|
+
}>,
|
|
1992
|
+
/** Aborted when the batch times out, so a call still waiting can be withdrawn. */
|
|
1993
|
+
signal?: AbortSignal) => Promise<Array<{
|
|
1992
1994
|
success: boolean;
|
|
1993
1995
|
result?: T;
|
|
1994
1996
|
error?: Error;
|