@juspay/neurolink 13.12.1 → 13.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -5
- package/dist/agent/agentToolRegistrar.js +3 -1
- package/dist/browser/neurolink.min.js +467 -467
- package/dist/context/fileSummarizationService.js +2 -0
- package/dist/core/baseProvider.d.ts +2 -2
- package/dist/core/loopEngine.js +20 -8
- package/dist/core/modules/ToolsManager.d.ts +11 -33
- package/dist/core/modules/ToolsManager.js +71 -99
- package/dist/core/modules/Utilities.js +6 -1
- package/dist/core/toolExecutionGuards.js +79 -11
- package/dist/evaluation/ragasEvaluator.js +2 -0
- package/dist/evaluation/scorers/llm/baseLLMScorer.js +2 -0
- package/dist/hitl/hitlErrors.d.ts +8 -0
- package/dist/hitl/hitlErrors.js +12 -0
- package/dist/hitl/hitlManager.d.ts +25 -7
- package/dist/hitl/hitlManager.js +133 -15
- package/dist/hitl/index.d.ts +1 -1
- package/dist/hitl/index.js +1 -1
- package/dist/hitl/toolCallConfirmation.d.ts +57 -0
- package/dist/hitl/toolCallConfirmation.js +296 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4 -1
- package/dist/mcp/externalServerManager.d.ts +33 -2
- package/dist/mcp/externalServerManager.js +68 -52
- package/dist/mcp/toolDiscoveryService.js +8 -1
- package/dist/mcp/toolRegistry.d.ts +20 -0
- package/dist/mcp/toolRegistry.js +68 -58
- package/dist/middleware/utils/guardrailsUtils.js +2 -0
- package/dist/neurolink.d.ts +114 -2
- package/dist/neurolink.js +492 -71
- package/dist/providers/amazonBedrock/client.js +23 -4
- package/dist/providers/anthropic/client.js +5 -1
- package/dist/providers/googleNativeGemini3/utils.js +5 -1
- package/dist/providers/openaiChatCompletionsBase.js +21 -3
- package/dist/rag/metadata/metadataExtractor.js +2 -0
- package/dist/rag/pipeline/RAGPipeline.js +4 -0
- package/dist/rag/pipeline/contextAssembly.d.ts +1 -0
- package/dist/rag/pipeline/contextAssembly.js +2 -0
- package/dist/rag/reranker/reranker.js +4 -0
- package/dist/types/hitl.d.ts +100 -8
- package/dist/types/mcp.d.ts +5 -0
- package/dist/types/providers.d.ts +23 -2
- package/dist/types/tools.d.ts +34 -9
- package/dist/utils/async/index.d.ts +2 -1
- package/dist/utils/async/index.js +2 -1
- package/dist/utils/async/pausableDeadline.d.ts +28 -0
- package/dist/utils/async/pausableDeadline.js +88 -0
- package/dist/utils/async/withTimeout.d.ts +5 -0
- package/dist/utils/async/withTimeout.js +23 -0
- package/dist/utils/errorHandling.d.ts +32 -1
- package/dist/utils/errorHandling.js +70 -18
- package/dist/utils/providerUtils.js +5 -1
- package/dist/workflow/core/ensembleExecutor.js +2 -0
- package/dist/workflow/core/judgeScorer.js +2 -0
- package/dist/workflow/core/responseConditioner.js +2 -0
- package/docs-site/static/search-index.json +8 -6
- package/package.json +5 -1
|
@@ -223,6 +223,8 @@ export class FileSummarizationService {
|
|
|
223
223
|
input: { text: prompt },
|
|
224
224
|
provider: this.provider,
|
|
225
225
|
model: this.model,
|
|
226
|
+
// A summary is text; the summarizer is given no tools.
|
|
227
|
+
disableTools: true,
|
|
226
228
|
});
|
|
227
229
|
const summaryText = typeof result === "string" ? result : (result?.content ?? "");
|
|
228
230
|
const summaryTokens = estimateTokens(summaryText, budgetParams.provider);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AIProviderName } from "../constants/enums.js";
|
|
2
2
|
import type { EvaluationData } from "../index.js";
|
|
3
3
|
import type { NeuroLink } from "../neurolink.js";
|
|
4
|
-
import type { FileToolRootPolicy, UnknownRecord, MiddlewareFactoryOptions, StreamOptions, StreamResult, AIProvider, AnalyticsData, EnhancedGenerateResult, TextGenerationOptions, TextGenerationResult, ValidationSchema, EmbedInput, DecisionRequest, DecisionResult, MemoryToolCallRecord, MemoryToolResultRecord, ToolExecutionSummaryInternal } from "../types/index.js";
|
|
4
|
+
import type { FileToolRootPolicy, UnknownRecord, MiddlewareFactoryOptions, StreamOptions, StreamResult, AIProvider, AnalyticsData, EnhancedGenerateResult, TextGenerationOptions, TextGenerationResult, ValidationSchema, EmbedInput, DecisionRequest, DecisionResult, MemoryToolCallRecord, MemoryToolResultRecord, ProviderToolExecutorOptions, ToolExecutionSummaryInternal } from "../types/index.js";
|
|
5
5
|
import { TelemetryHandler } from "./modules/TelemetryHandler.js";
|
|
6
6
|
import { ToolsManager } from "./modules/ToolsManager.js";
|
|
7
7
|
import type { LanguageModel, ModelMessage, RawUsageObject, Tool, ToolCallRepairFunction, ToolSet } from "../types/index.js";
|
|
@@ -783,7 +783,7 @@ export declare abstract class BaseProvider implements AIProvider {
|
|
|
783
783
|
*/
|
|
784
784
|
setupToolExecutor(sdk: {
|
|
785
785
|
customTools: Map<string, unknown>;
|
|
786
|
-
executeTool: (toolName: string, params: unknown) => Promise<unknown>;
|
|
786
|
+
executeTool: (toolName: string, params: unknown, options?: ProviderToolExecutorOptions) => Promise<unknown>;
|
|
787
787
|
}, functionTag: string): void;
|
|
788
788
|
/**
|
|
789
789
|
* Normalize text generation options - delegated to Utilities
|
package/dist/core/loopEngine.js
CHANGED
|
@@ -3,6 +3,7 @@ import { observeGeneration } from "../telemetry/observation.js";
|
|
|
3
3
|
import { StepSpans, withGeneration } from "../telemetry/withSpan.js";
|
|
4
4
|
import { logger } from "../utils/logger.js";
|
|
5
5
|
import { withProviderRetry } from "../utils/providerRetry.js";
|
|
6
|
+
import { TimeoutError, createPausableDeadline } from "../utils/async/index.js";
|
|
6
7
|
import { resolveToolTimeoutMs } from "./constants.js";
|
|
7
8
|
/**
|
|
8
9
|
* Marks a step error that occurred AFTER at least one chunk had already
|
|
@@ -78,25 +79,36 @@ async function executeToolCall(params) {
|
|
|
78
79
|
// thing that will ever end a wedged one, so it must be able to hold the
|
|
79
80
|
// event loop open long enough to fire. `finally` clears it the instant the
|
|
80
81
|
// call settles, so it never outlives its tool.
|
|
81
|
-
|
|
82
|
+
//
|
|
83
|
+
// The call can pause it (`pauseDeadline`) while it waits for a human
|
|
84
|
+
// confirmation: that wait says nothing about the tool, and resuming keeps
|
|
85
|
+
// the time that was left. It aborts with a TimeoutError, as the guard's
|
|
86
|
+
// deadline does, which is how the circuit breaker tells a deadline from a
|
|
87
|
+
// caller's cancel (isCancelledByCaller).
|
|
88
|
+
let rejectDeadline = () => undefined;
|
|
82
89
|
const deadline = new Promise((_, reject) => {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
90
|
+
rejectDeadline = reject;
|
|
91
|
+
});
|
|
92
|
+
const clock = createPausableDeadline(toolTimeoutMs, () => {
|
|
93
|
+
const error = new TimeoutError(`Tool "${name}" execution timed out after ${toolTimeoutMs}ms`, toolTimeoutMs);
|
|
94
|
+
toolAbort.abort(error);
|
|
95
|
+
rejectDeadline(error);
|
|
88
96
|
});
|
|
89
97
|
try {
|
|
90
98
|
// `Promise.race` subscribes to both, so a tool that eventually rejects
|
|
91
99
|
// after its deadline has already been reported cannot resurface as an
|
|
92
100
|
// unhandled rejection and kill the consumer's process.
|
|
93
101
|
return await Promise.race([
|
|
94
|
-
Promise.resolve(execute(args, {
|
|
102
|
+
Promise.resolve(execute(args, {
|
|
103
|
+
toolCallId,
|
|
104
|
+
abortSignal: toolAbort.signal,
|
|
105
|
+
pauseDeadline: clock.pause,
|
|
106
|
+
})),
|
|
95
107
|
deadline,
|
|
96
108
|
]);
|
|
97
109
|
}
|
|
98
110
|
finally {
|
|
99
|
-
|
|
111
|
+
clock.clear();
|
|
100
112
|
turnSignal.removeEventListener("abort", onTurnAbort);
|
|
101
113
|
}
|
|
102
114
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AIProviderName, ToolUtilities } from "../../types/index.js";
|
|
1
|
+
import type { AIProviderName, ProviderToolExecutorOptions, ToolUtilities } from "../../types/index.js";
|
|
2
2
|
import type { NeuroLink } from "../../neurolink.js";
|
|
3
3
|
import type { Tool } from "../../types/index.js";
|
|
4
4
|
/**
|
|
@@ -25,7 +25,7 @@ export declare class ToolsManager {
|
|
|
25
25
|
private readonly utilities?;
|
|
26
26
|
protected mcpTools?: Record<string, Tool>;
|
|
27
27
|
protected customTools?: Map<string, unknown>;
|
|
28
|
-
protected toolExecutor?: (toolName: string, params: unknown, options?:
|
|
28
|
+
protected toolExecutor?: (toolName: string, params: unknown, options?: ProviderToolExecutorOptions) => Promise<unknown>;
|
|
29
29
|
protected sessionId?: string;
|
|
30
30
|
protected userId?: string;
|
|
31
31
|
private readonly eventWrappedExecutes;
|
|
@@ -40,36 +40,6 @@ export declare class ToolsManager {
|
|
|
40
40
|
* every tool uncancellable (deadline overshoot / ghost executions).
|
|
41
41
|
*/
|
|
42
42
|
private wrapExecuteWithTruncation;
|
|
43
|
-
/**
|
|
44
|
-
* The HITL manager of the owning NeuroLink instance, when one is configured.
|
|
45
|
-
* It lives on the tool registry (`setHITLManager`), which is also where the
|
|
46
|
-
* registered-tool execution path reads it, so the two paths cannot disagree.
|
|
47
|
-
*/
|
|
48
|
-
private resolveHITLManager;
|
|
49
|
-
/**
|
|
50
|
-
* Whether a built-in tool call must be confirmed by a human first.
|
|
51
|
-
*
|
|
52
|
-
* Same rule as `MCPToolRegistry.executeTool` applies to registered tools —
|
|
53
|
-
* `dangerousActions` keywords and `customRules` — plus the built-in tools
|
|
54
|
-
* that change the machine (`HITL_ALWAYS_CONFIRM_DIRECT_TOOLS`), which are
|
|
55
|
-
* confirmed on every call unless `hitl.confirmBuiltinTools` is `false`.
|
|
56
|
-
*/
|
|
57
|
-
private directToolNeedsConfirmation;
|
|
58
|
-
/**
|
|
59
|
-
* Gate a built-in (direct) tool's execute behind the instance's HITL
|
|
60
|
-
* manager, with the semantics of the registry path: a denial throws
|
|
61
|
-
* `HITLUserRejectedError` (the loop reports it to the model as a failed
|
|
62
|
-
* call), a timeout propagates the manager's `HITLTimeoutError` (or the
|
|
63
|
-
* auto-approval it is configured for), and user-modified arguments replace
|
|
64
|
-
* the model's. Without HITL the execute runs untouched.
|
|
65
|
-
*
|
|
66
|
-
* Direct tools reach the model through `getAllTools()` and are executed by
|
|
67
|
-
* the provider loops directly, never through `MCPToolRegistry.executeTool`
|
|
68
|
-
* — so before this wrapper the registry's HITL check never saw them, and
|
|
69
|
-
* `writeFile` / `executeBashCommand` ran unconfirmed while the bash tool's
|
|
70
|
-
* own description promised otherwise.
|
|
71
|
-
*/
|
|
72
|
-
private wrapExecuteWithHITL;
|
|
73
43
|
/**
|
|
74
44
|
* Byte budget for BZ-666 truncation. Reads the instance-level
|
|
75
45
|
* `tools.outputTruncationMaxBytes` config (see `ToolConfig` /
|
|
@@ -166,7 +136,7 @@ export declare class ToolsManager {
|
|
|
166
136
|
*/
|
|
167
137
|
setupToolExecutor(sdk: {
|
|
168
138
|
customTools: Map<string, unknown>;
|
|
169
|
-
executeTool: (toolName: string, params: unknown) => Promise<unknown>;
|
|
139
|
+
executeTool: (toolName: string, params: unknown, options?: ProviderToolExecutorOptions) => Promise<unknown>;
|
|
170
140
|
}, functionTag: string): void;
|
|
171
141
|
/**
|
|
172
142
|
* Get all available tools - direct tools are ALWAYS available
|
|
@@ -191,6 +161,14 @@ export declare class ToolsManager {
|
|
|
191
161
|
* Get custom tools
|
|
192
162
|
*/
|
|
193
163
|
getCustomTools(): Map<string, unknown> | undefined;
|
|
164
|
+
/**
|
|
165
|
+
* A built-in tool the loop runs directly is confirmed before its body runs,
|
|
166
|
+
* by the same step `executeTool` uses for a registered tool (see
|
|
167
|
+
* `NeuroLink.confirmBuiltInToolCall`). Approval runs the body once with the
|
|
168
|
+
* approved arguments; a refusal returns the refusal and runs nothing. With
|
|
169
|
+
* HITL off the body runs unchanged.
|
|
170
|
+
*/
|
|
171
|
+
private wrapExecuteWithConfirmation;
|
|
194
172
|
/**
|
|
195
173
|
* Process direct tools with event emission wrapping
|
|
196
174
|
*/
|
|
@@ -8,7 +8,9 @@ import { getKeyCount } from "../../utils/transformationUtils.js";
|
|
|
8
8
|
import { extractIsErrorText } from "../../utils/toolResultStatus.js";
|
|
9
9
|
import { createToolExecutionId } from "../../utils/toolExecutionId.js";
|
|
10
10
|
import { convertJsonSchemaToZod, stripUnsafeRegexPatterns, } from "../../utils/schemaConversion.js";
|
|
11
|
-
import {
|
|
11
|
+
import { abortSignalOf, pauseDeadlineOf } from "../../utils/async/index.js";
|
|
12
|
+
import { isAbortError } from "../../utils/errorHandling.js";
|
|
13
|
+
import { markRefusalResult } from "../../hitl/toolCallConfirmation.js";
|
|
12
14
|
import { generateToolOutputPreview, DEFAULT_MAX_PREVIEW_BYTES, RETRIEVE_CONTEXT_TOOL_NAME, } from "../../context/toolOutputLimits.js";
|
|
13
15
|
/**
|
|
14
16
|
* Own property stamped on a tool object whose `execute` already emits
|
|
@@ -32,19 +34,6 @@ function makeToolAbortError() {
|
|
|
32
34
|
e.name = "AbortError";
|
|
33
35
|
return e;
|
|
34
36
|
}
|
|
35
|
-
/**
|
|
36
|
-
* Built-in tools that change the machine. While HITL is enabled they require
|
|
37
|
-
* confirmation on every call, whatever `dangerousActions` lists, unless the
|
|
38
|
-
* host sets `hitl.confirmBuiltinTools: false`. The other built-ins (clock,
|
|
39
|
-
* arithmetic, reads, directory listings, CSV analysis, web search) are gated
|
|
40
|
-
* by `dangerousActions` keywords and `customRules` like every other tool.
|
|
41
|
-
*/
|
|
42
|
-
const HITL_ALWAYS_CONFIRM_DIRECT_TOOLS = new Set([
|
|
43
|
-
"writeFile",
|
|
44
|
-
"executeBashCommand",
|
|
45
|
-
]);
|
|
46
|
-
/** serverId the registry uses for the built-in tools; reused in HITL requests. */
|
|
47
|
-
const DIRECT_TOOL_SERVER_ID = "direct";
|
|
48
37
|
/** Tool names a provider accepts: 1-64 characters from this set. */
|
|
49
38
|
const TOOL_NAME_SAFE_CHARS = /[^A-Za-z0-9_-]/g;
|
|
50
39
|
const MAX_TOOL_NAME_LENGTH = 64;
|
|
@@ -264,82 +253,17 @@ export class ToolsManager {
|
|
|
264
253
|
const signal = execOptions
|
|
265
254
|
?.abortSignal;
|
|
266
255
|
const inner = originalExecute(params, execOptions);
|
|
267
|
-
// Inner executes that
|
|
268
|
-
//
|
|
269
|
-
// promptly on abort via the
|
|
270
|
-
//
|
|
256
|
+
// Inner executes that do not stop on the signal (a tool that ignores
|
|
257
|
+
// it; an external MCP call already sent, since the signal is not
|
|
258
|
+
// plumbed to the transport yet) still return promptly on abort via the
|
|
259
|
+
// race; the loop's isAbortError handling treats the rejection as a
|
|
260
|
+
// cancellation, not a tool failure.
|
|
271
261
|
const result = signal && typeof signal.addEventListener === "function"
|
|
272
262
|
? await raceWithAbortSignal(inner, signal)
|
|
273
263
|
: await inner;
|
|
274
264
|
return this.truncateToolResult(toolName, result);
|
|
275
265
|
};
|
|
276
266
|
}
|
|
277
|
-
/**
|
|
278
|
-
* The HITL manager of the owning NeuroLink instance, when one is configured.
|
|
279
|
-
* It lives on the tool registry (`setHITLManager`), which is also where the
|
|
280
|
-
* registered-tool execution path reads it, so the two paths cannot disagree.
|
|
281
|
-
*/
|
|
282
|
-
resolveHITLManager() {
|
|
283
|
-
const registry = this.neurolink?.getToolRegistry?.();
|
|
284
|
-
const manager = registry && typeof registry.getHITLManager === "function"
|
|
285
|
-
? registry.getHITLManager()
|
|
286
|
-
: undefined;
|
|
287
|
-
return manager && manager.isEnabled() ? manager : undefined;
|
|
288
|
-
}
|
|
289
|
-
/**
|
|
290
|
-
* Whether a built-in tool call must be confirmed by a human first.
|
|
291
|
-
*
|
|
292
|
-
* Same rule as `MCPToolRegistry.executeTool` applies to registered tools —
|
|
293
|
-
* `dangerousActions` keywords and `customRules` — plus the built-in tools
|
|
294
|
-
* that change the machine (`HITL_ALWAYS_CONFIRM_DIRECT_TOOLS`), which are
|
|
295
|
-
* confirmed on every call unless `hitl.confirmBuiltinTools` is `false`.
|
|
296
|
-
*/
|
|
297
|
-
directToolNeedsConfirmation(manager, toolName, params) {
|
|
298
|
-
if (manager.requiresConfirmation(toolName, params)) {
|
|
299
|
-
return true;
|
|
300
|
-
}
|
|
301
|
-
if (!HITL_ALWAYS_CONFIRM_DIRECT_TOOLS.has(toolName)) {
|
|
302
|
-
return false;
|
|
303
|
-
}
|
|
304
|
-
const confirmBuiltins = manager.getConfig().confirmBuiltinTools;
|
|
305
|
-
return confirmBuiltins !== false;
|
|
306
|
-
}
|
|
307
|
-
/**
|
|
308
|
-
* Gate a built-in (direct) tool's execute behind the instance's HITL
|
|
309
|
-
* manager, with the semantics of the registry path: a denial throws
|
|
310
|
-
* `HITLUserRejectedError` (the loop reports it to the model as a failed
|
|
311
|
-
* call), a timeout propagates the manager's `HITLTimeoutError` (or the
|
|
312
|
-
* auto-approval it is configured for), and user-modified arguments replace
|
|
313
|
-
* the model's. Without HITL the execute runs untouched.
|
|
314
|
-
*
|
|
315
|
-
* Direct tools reach the model through `getAllTools()` and are executed by
|
|
316
|
-
* the provider loops directly, never through `MCPToolRegistry.executeTool`
|
|
317
|
-
* — so before this wrapper the registry's HITL check never saw them, and
|
|
318
|
-
* `writeFile` / `executeBashCommand` ran unconfirmed while the bash tool's
|
|
319
|
-
* own description promised otherwise.
|
|
320
|
-
*/
|
|
321
|
-
wrapExecuteWithHITL(toolName, execute) {
|
|
322
|
-
return async (params, execOptions) => {
|
|
323
|
-
const manager = this.resolveHITLManager();
|
|
324
|
-
if (!manager ||
|
|
325
|
-
!this.directToolNeedsConfirmation(manager, toolName, params)) {
|
|
326
|
-
return execute(params, execOptions);
|
|
327
|
-
}
|
|
328
|
-
logger.info(`Built-in tool '${toolName}' requires HITL confirmation`);
|
|
329
|
-
const confirmation = await manager.requestConfirmation(toolName, params, {
|
|
330
|
-
serverId: DIRECT_TOOL_SERVER_ID,
|
|
331
|
-
sessionId: this.sessionId,
|
|
332
|
-
userId: this.userId,
|
|
333
|
-
});
|
|
334
|
-
if (!confirmation.approved) {
|
|
335
|
-
throw new HITLUserRejectedError(`Tool execution rejected by user: ${confirmation.reason || "No reason provided"}`, toolName, confirmation.reason);
|
|
336
|
-
}
|
|
337
|
-
const finalParams = confirmation.modifiedArguments !== undefined
|
|
338
|
-
? confirmation.modifiedArguments
|
|
339
|
-
: params;
|
|
340
|
-
return execute(finalParams, execOptions);
|
|
341
|
-
};
|
|
342
|
-
}
|
|
343
267
|
/**
|
|
344
268
|
* Byte budget for BZ-666 truncation. Reads the instance-level
|
|
345
269
|
* `tools.outputTruncationMaxBytes` config (see `ToolConfig` /
|
|
@@ -831,6 +755,34 @@ export class ToolsManager {
|
|
|
831
755
|
getCustomTools() {
|
|
832
756
|
return this.customTools;
|
|
833
757
|
}
|
|
758
|
+
/**
|
|
759
|
+
* A built-in tool the loop runs directly is confirmed before its body runs,
|
|
760
|
+
* by the same step `executeTool` uses for a registered tool (see
|
|
761
|
+
* `NeuroLink.confirmBuiltInToolCall`). Approval runs the body once with the
|
|
762
|
+
* approved arguments; a refusal returns the refusal and runs nothing. With
|
|
763
|
+
* HITL off the body runs unchanged.
|
|
764
|
+
*/
|
|
765
|
+
wrapExecuteWithConfirmation(toolName, execute) {
|
|
766
|
+
const neurolink = this.neurolink;
|
|
767
|
+
if (typeof neurolink?.confirmBuiltInToolCall !== "function") {
|
|
768
|
+
return execute;
|
|
769
|
+
}
|
|
770
|
+
return async (params, execOptions) => {
|
|
771
|
+
const abortSignal = abortSignalOf(execOptions);
|
|
772
|
+
const pauseDeadline = pauseDeadlineOf(execOptions);
|
|
773
|
+
const action = await neurolink.confirmBuiltInToolCall(toolName, params, {
|
|
774
|
+
...(abortSignal && { abortSignal }),
|
|
775
|
+
...(pauseDeadline && { pauseDeadline }),
|
|
776
|
+
});
|
|
777
|
+
if (!action.run) {
|
|
778
|
+
return markRefusalResult({
|
|
779
|
+
success: false,
|
|
780
|
+
error: action.error.message,
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
return execute(action.args, execOptions);
|
|
784
|
+
};
|
|
785
|
+
}
|
|
834
786
|
/**
|
|
835
787
|
* Process direct tools with event emission wrapping
|
|
836
788
|
*/
|
|
@@ -848,7 +800,7 @@ export class ToolsManager {
|
|
|
848
800
|
// Create a new tool with wrapped execute function (BZ-666/BZ-664 guards applied).
|
|
849
801
|
// HITL sits INSIDE the truncation wrapper so a pending confirmation is
|
|
850
802
|
// raced against the loop's abort signal like any other tool wait.
|
|
851
|
-
const guardedExecute = this.wrapExecuteWithTruncation(toolName, this.
|
|
803
|
+
const guardedExecute = this.wrapExecuteWithTruncation(toolName, this.wrapExecuteWithConfirmation(toolName, originalExecute));
|
|
852
804
|
tools[toolName] = markEventWrapped({
|
|
853
805
|
...directTool,
|
|
854
806
|
execute: this.wrapExecuteWithEvents(toolName, guardedExecute),
|
|
@@ -990,7 +942,7 @@ export class ToolsManager {
|
|
|
990
942
|
return markEventWrapped(createAISDKTool({
|
|
991
943
|
description: toolInfo.description || `Tool ${toolName}`,
|
|
992
944
|
inputSchema: finalSchema, // AI SDK v6 uses inputSchema (not parameters)
|
|
993
|
-
execute: async (params) => {
|
|
945
|
+
execute: async (params, execOptions) => {
|
|
994
946
|
const customToolSpan = tracers.sdk.startSpan("tools.execute_custom", {
|
|
995
947
|
attributes: {
|
|
996
948
|
"tool.name": toolName,
|
|
@@ -1012,17 +964,22 @@ export class ToolsManager {
|
|
|
1012
964
|
// but we also forward them to toolExecutor for MCP-level handling.
|
|
1013
965
|
const toolTimeoutMs = toolInfo.timeoutMs;
|
|
1014
966
|
const toolMaxRetries = toolInfo.maxRetries;
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
}
|
|
1025
|
-
|
|
967
|
+
// The loop's signal for this call (its turn abort or per-tool
|
|
968
|
+
// deadline) goes down with it, so the call's confirmation,
|
|
969
|
+
// its attempts and the tool itself see the cancellation; so
|
|
970
|
+
// does the pause the confirmation puts on that deadline.
|
|
971
|
+
const abortSignal = abortSignalOf(execOptions);
|
|
972
|
+
const pauseDeadline = pauseDeadlineOf(execOptions);
|
|
973
|
+
const result = await this.toolExecutor(toolName, params, {
|
|
974
|
+
...(toolTimeoutMs !== undefined && {
|
|
975
|
+
timeout: toolTimeoutMs,
|
|
976
|
+
}),
|
|
977
|
+
...(toolMaxRetries !== undefined && {
|
|
978
|
+
maxRetries: toolMaxRetries,
|
|
979
|
+
}),
|
|
980
|
+
...(abortSignal && { abortSignal }),
|
|
981
|
+
...(pauseDeadline && { pauseDeadline }),
|
|
982
|
+
});
|
|
1026
983
|
const convertedResult = this.utilities?.convertToolResult
|
|
1027
984
|
? await this.utilities.convertToolResult(result)
|
|
1028
985
|
: result;
|
|
@@ -1177,10 +1134,20 @@ export class ToolsManager {
|
|
|
1177
1134
|
: z.object({});
|
|
1178
1135
|
}
|
|
1179
1136
|
// BZ-666/BZ-664: Wrap the raw MCP execute with guards before event wrapping
|
|
1180
|
-
const rawExecute = async (params) => {
|
|
1137
|
+
const rawExecute = async (params, execOptions) => {
|
|
1181
1138
|
if (this.neurolink &&
|
|
1182
1139
|
typeof this.neurolink.executeExternalMCPTool === "function") {
|
|
1183
|
-
|
|
1140
|
+
// The loop's signal withdraws the call's pending confirmation, and
|
|
1141
|
+
// a call it already cancelled is never sent to the server; the
|
|
1142
|
+
// loop's deadline pauses while that confirmation waits.
|
|
1143
|
+
const abortSignal = abortSignalOf(execOptions);
|
|
1144
|
+
const pauseDeadline = pauseDeadlineOf(execOptions);
|
|
1145
|
+
return this.neurolink.executeExternalMCPTool(tool.serverId || "unknown", tool.name, params, abortSignal || pauseDeadline
|
|
1146
|
+
? {
|
|
1147
|
+
...(abortSignal && { abortSignal }),
|
|
1148
|
+
...(pauseDeadline && { pauseDeadline }),
|
|
1149
|
+
}
|
|
1150
|
+
: undefined);
|
|
1184
1151
|
}
|
|
1185
1152
|
throw new Error(`Cannot execute external MCP tool: NeuroLink executeExternalMCPTool not available`);
|
|
1186
1153
|
};
|
|
@@ -1190,6 +1157,11 @@ export class ToolsManager {
|
|
|
1190
1157
|
return await guardedExecute(params, execOptions);
|
|
1191
1158
|
}
|
|
1192
1159
|
catch (mcpError) {
|
|
1160
|
+
if (isAbortError(mcpError)) {
|
|
1161
|
+
// The loop cancelled the call: an outcome, not a fault.
|
|
1162
|
+
logger.info(`External MCP tool call cancelled: ${tool.name}`);
|
|
1163
|
+
throw mcpError;
|
|
1164
|
+
}
|
|
1193
1165
|
logger.error(`External MCP tool failed: ${tool.name}`, {
|
|
1194
1166
|
serverId: tool.serverId,
|
|
1195
1167
|
error: mcpError instanceof Error ? mcpError.message : String(mcpError),
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import { z } from "zod";
|
|
20
20
|
import { logger } from "../../utils/logger.js";
|
|
21
|
+
import { isRefusalResult, markRefusalResult, } from "../../hitl/toolCallConfirmation.js";
|
|
21
22
|
import { getSafeMaxTokens } from "../../utils/tokenLimits.js";
|
|
22
23
|
import { TimeoutError, getDefaultTimeout, parseTimeout, } from "../../utils/timeout.js";
|
|
23
24
|
import { validateStreamOptions as validateStreamOpts, validateTextGenerationOptions, ValidationError, createValidationSummary, } from "../../utils/parameterValidation.js";
|
|
@@ -221,7 +222,7 @@ export class Utilities {
|
|
|
221
222
|
// Log the error for debugging but don't throw
|
|
222
223
|
logger.warn(`Tool execution failed: ${errorMsg}`);
|
|
223
224
|
// Return error as structured data that can be processed by the AI
|
|
224
|
-
|
|
225
|
+
const converted = {
|
|
225
226
|
isError: true,
|
|
226
227
|
error: errorMsg,
|
|
227
228
|
content: [
|
|
@@ -231,6 +232,10 @@ export class Utilities {
|
|
|
231
232
|
},
|
|
232
233
|
],
|
|
233
234
|
};
|
|
235
|
+
// A refusal stays one, so no result cache keeps it.
|
|
236
|
+
return isRefusalResult(result)
|
|
237
|
+
? markRefusalResult(converted)
|
|
238
|
+
: converted;
|
|
234
239
|
}
|
|
235
240
|
}
|
|
236
241
|
return result;
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
* Nothing in here is provider-specific: it takes an executor and a guards
|
|
12
12
|
* object and returns a wrapped executor.
|
|
13
13
|
*/
|
|
14
|
-
import { raceWithAbort,
|
|
14
|
+
import { TimeoutError, abortSignalOf, createPausableDeadline, pauseDeadlineOf, raceWithAbort, } from "../utils/async/index.js";
|
|
15
|
+
import { isNonNullObject } from "../utils/typeUtils.js";
|
|
15
16
|
/**
|
|
16
17
|
* Everything a native provider loop wraps around a tool call that the shared
|
|
17
18
|
* engine does not do itself.
|
|
@@ -29,20 +30,19 @@ import { raceWithAbort, withTimeout } from "../utils/async/index.js";
|
|
|
29
30
|
*/
|
|
30
31
|
export function guardToolExecutor(name, execute, guards) {
|
|
31
32
|
return async (args, opts) => {
|
|
32
|
-
const call = () => Promise.resolve(execute(args, opts));
|
|
33
33
|
guards.onProgress?.();
|
|
34
34
|
try {
|
|
35
|
-
const raced = guards.abortSignal
|
|
36
|
-
? raceWithAbort(call(), guards.abortSignal)
|
|
37
|
-
: call();
|
|
38
35
|
// `== null` catches both an omitted bound and an explicit `null` — a
|
|
39
36
|
// caller that asked for unbounded tool execution. Testing only for
|
|
40
|
-
// `undefined` would
|
|
41
|
-
//
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
37
|
+
// `undefined` would arm a timer with no delay, which fires the deadline
|
|
38
|
+
// immediately.
|
|
39
|
+
if (guards.toolTimeoutMs === undefined || guards.toolTimeoutMs === null) {
|
|
40
|
+
const call = Promise.resolve(execute(args, opts));
|
|
41
|
+
return await (guards.abortSignal
|
|
42
|
+
? raceWithAbort(call, guards.abortSignal)
|
|
43
|
+
: call);
|
|
44
|
+
}
|
|
45
|
+
return await runUnderDeadline(name, execute, args, opts, guards, guards.toolTimeoutMs);
|
|
46
46
|
}
|
|
47
47
|
finally {
|
|
48
48
|
// In `finally`, not after a successful await: a tool that times out or
|
|
@@ -52,3 +52,71 @@ export function guardToolExecutor(name, execute, guards) {
|
|
|
52
52
|
}
|
|
53
53
|
};
|
|
54
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* One guarded call under the per-tool deadline. The call runs with a signal of
|
|
57
|
+
* its own, chained to the loop's (`opts.abortSignal`, `guards.abortSignal`),
|
|
58
|
+
* and the deadline aborts it at the moment it rejects: one timer does both, so
|
|
59
|
+
* the tool, its confirmation and `executeTool`'s attempts stop when the model
|
|
60
|
+
* is told the call timed out, and nothing runs after that. This is what the
|
|
61
|
+
* loop engine's `executeToolCall` already does with its own deadline.
|
|
62
|
+
*
|
|
63
|
+
* The call can pause the deadline (`pauseDeadline`) while it waits for a
|
|
64
|
+
* human confirmation, and resuming keeps the time that was left. The pause
|
|
65
|
+
* chains to the loop's own (`opts.pauseDeadline`): where a guard sits inside
|
|
66
|
+
* the loop engine, as on the Vertex and AI Studio Gemini paths, both bounds
|
|
67
|
+
* stop for the wait.
|
|
68
|
+
*/
|
|
69
|
+
async function runUnderDeadline(name, execute, args, opts, guards, timeoutMs) {
|
|
70
|
+
const toolAbort = new AbortController();
|
|
71
|
+
const upstream = new Set([abortSignalOf(opts), guards.abortSignal].filter((signal) => signal !== undefined));
|
|
72
|
+
const detach = [];
|
|
73
|
+
for (const signal of upstream) {
|
|
74
|
+
if (signal.aborted) {
|
|
75
|
+
toolAbort.abort(signal.reason);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const onAbort = () => toolAbort.abort(signal.reason);
|
|
79
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
80
|
+
detach.push(() => signal.removeEventListener("abort", onAbort));
|
|
81
|
+
}
|
|
82
|
+
// Armed before the call starts, so its pause is in the options the call
|
|
83
|
+
// receives.
|
|
84
|
+
let rejectDeadline = () => undefined;
|
|
85
|
+
const deadline = new Promise((_, reject) => {
|
|
86
|
+
rejectDeadline = reject;
|
|
87
|
+
});
|
|
88
|
+
const clock = createPausableDeadline(timeoutMs, () => {
|
|
89
|
+
const error = new TimeoutError(`Tool "${name}" execution timed out after ${timeoutMs}ms`, timeoutMs);
|
|
90
|
+
toolAbort.abort(error);
|
|
91
|
+
rejectDeadline(error);
|
|
92
|
+
});
|
|
93
|
+
const outerPause = pauseDeadlineOf(opts);
|
|
94
|
+
const pauseDeadline = () => {
|
|
95
|
+
const resumeOwn = clock.pause();
|
|
96
|
+
const resumeOuter = outerPause?.();
|
|
97
|
+
return () => {
|
|
98
|
+
resumeOuter?.();
|
|
99
|
+
resumeOwn();
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
const callOpts = {
|
|
103
|
+
...(isNonNullObject(opts) ? opts : {}),
|
|
104
|
+
abortSignal: toolAbort.signal,
|
|
105
|
+
pauseDeadline,
|
|
106
|
+
};
|
|
107
|
+
try {
|
|
108
|
+
const call = Promise.resolve(execute(args, callOpts));
|
|
109
|
+
const raced = guards.abortSignal
|
|
110
|
+
? raceWithAbort(call, guards.abortSignal)
|
|
111
|
+
: call;
|
|
112
|
+
// `Promise.race` subscribes to both, so a call that rejects after the
|
|
113
|
+
// deadline already won cannot surface as an unhandled rejection.
|
|
114
|
+
return await Promise.race([raced, deadline]);
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
clock.clear();
|
|
118
|
+
for (const off of detach) {
|
|
119
|
+
off();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -55,6 +55,8 @@ export class RAGASEvaluator {
|
|
|
55
55
|
const provider = await AIProviderFactory.createProvider(this.providerName, this.evaluationModel);
|
|
56
56
|
const result = await provider.generate({
|
|
57
57
|
input: { text: prompt },
|
|
58
|
+
// The evaluator scores text; it is given no tools.
|
|
59
|
+
disableTools: true,
|
|
58
60
|
});
|
|
59
61
|
if (!result) {
|
|
60
62
|
throw new Error("Evaluation generation failed to return a result.");
|
|
@@ -126,6 +126,8 @@ export class BaseLLMScorer extends BaseScorer {
|
|
|
126
126
|
prompt,
|
|
127
127
|
temperature: this._llmConfig.temperature ?? 0.1,
|
|
128
128
|
maxTokens: 2000,
|
|
129
|
+
// A scorer rates text; it is given no tools.
|
|
130
|
+
disableTools: true,
|
|
129
131
|
}), timeout, `${this.metadata.id}-llm-call`));
|
|
130
132
|
if (!result) {
|
|
131
133
|
throw new Error("Provider returned no result");
|
|
@@ -30,6 +30,14 @@ export declare class HITLTimeoutError extends HITLError {
|
|
|
30
30
|
readonly timeout: number;
|
|
31
31
|
constructor(message: string, confirmationId: string, timeout: number);
|
|
32
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Thrown when a confirmation is withdrawn before it could let the tool run:
|
|
35
|
+
* the call that asked was aborted, so a later answer must run nothing.
|
|
36
|
+
*/
|
|
37
|
+
export declare class HITLCancelledError extends HITLError {
|
|
38
|
+
readonly reason?: string | undefined;
|
|
39
|
+
constructor(message: string, confirmationId?: string, reason?: string | undefined);
|
|
40
|
+
}
|
|
33
41
|
/**
|
|
34
42
|
* Thrown when HITL configuration is invalid or missing required properties
|
|
35
43
|
*/
|
package/dist/hitl/hitlErrors.js
CHANGED
|
@@ -43,6 +43,18 @@ export class HITLTimeoutError extends HITLError {
|
|
|
43
43
|
this.name = "HITLTimeoutError";
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* Thrown when a confirmation is withdrawn before it could let the tool run:
|
|
48
|
+
* the call that asked was aborted, so a later answer must run nothing.
|
|
49
|
+
*/
|
|
50
|
+
export class HITLCancelledError extends HITLError {
|
|
51
|
+
reason;
|
|
52
|
+
constructor(message, confirmationId, reason) {
|
|
53
|
+
super(message, confirmationId);
|
|
54
|
+
this.reason = reason;
|
|
55
|
+
this.name = "HITLCancelledError";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
46
58
|
/**
|
|
47
59
|
* Thrown when HITL configuration is invalid or missing required properties
|
|
48
60
|
*/
|
|
@@ -6,8 +6,10 @@
|
|
|
6
6
|
* for enterprise-grade AI safety.
|
|
7
7
|
*/
|
|
8
8
|
import { EventEmitter } from "events";
|
|
9
|
-
import type { HITLConfig, ConfirmationResult, HITLStatistics } from "../types/index.js";
|
|
9
|
+
import type { HITLConfig, ConfirmationResult, HITLConfirmationContext, HITLStatistics } from "../types/index.js";
|
|
10
10
|
export declare const DEFAULT_ALLOW_MODIFICATION = false;
|
|
11
|
+
/** The abort reason as text for `hitl:cancelled`, whatever the caller passed. */
|
|
12
|
+
export declare function describeAbortReason(signal: AbortSignal): string;
|
|
11
13
|
/**
|
|
12
14
|
* HITLManager - Central orchestrator for Human-in-the-Loop safety mechanisms
|
|
13
15
|
*
|
|
@@ -22,6 +24,8 @@ export declare const DEFAULT_ALLOW_MODIFICATION = false;
|
|
|
22
24
|
export declare class HITLManager extends EventEmitter {
|
|
23
25
|
private config;
|
|
24
26
|
private pendingConfirmations;
|
|
27
|
+
/** hitl:cancelled deliveries held back while that ID's request emit runs. */
|
|
28
|
+
private requestsEmitting;
|
|
25
29
|
private statistics;
|
|
26
30
|
constructor(config: HITLConfig);
|
|
27
31
|
/**
|
|
@@ -33,13 +37,12 @@ export declare class HITLManager extends EventEmitter {
|
|
|
33
37
|
*/
|
|
34
38
|
requiresConfirmation(toolName: string, args?: unknown): boolean;
|
|
35
39
|
/**
|
|
36
|
-
* Request confirmation for a tool execution
|
|
40
|
+
* Request confirmation for a tool execution.
|
|
41
|
+
*
|
|
42
|
+
* Aborting `context.signal` withdraws the request (see `cancelConfirmation`);
|
|
43
|
+
* a signal that is already aborted raises no card at all.
|
|
37
44
|
*/
|
|
38
|
-
requestConfirmation(toolName: string, arguments_: unknown, context?:
|
|
39
|
-
serverId?: string;
|
|
40
|
-
sessionId?: string;
|
|
41
|
-
userId?: string;
|
|
42
|
-
}): Promise<ConfirmationResult>;
|
|
45
|
+
requestConfirmation(toolName: string, arguments_: unknown, context?: HITLConfirmationContext): Promise<ConfirmationResult>;
|
|
43
46
|
/**
|
|
44
47
|
* Process user response to confirmation request
|
|
45
48
|
*/
|
|
@@ -54,6 +57,21 @@ export declare class HITLManager extends EventEmitter {
|
|
|
54
57
|
* Handle confirmation timeout
|
|
55
58
|
*/
|
|
56
59
|
private handleTimeout;
|
|
60
|
+
/**
|
|
61
|
+
* Withdraw a pending confirmation because the call that asked was aborted.
|
|
62
|
+
*
|
|
63
|
+
* Clears the timer, forgets the entry (so a later answer for this ID runs
|
|
64
|
+
* nothing), rejects the waiting call with `HITLCancelledError` and emits
|
|
65
|
+
* `hitl:cancelled` so the approval UI can retire the card.
|
|
66
|
+
*
|
|
67
|
+
* @returns false when nothing was pending under this ID
|
|
68
|
+
*/
|
|
69
|
+
cancelConfirmation(confirmationId: string, reason?: string): boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Emit `hitl:cancelled`, or hold it until the request emit for this ID has
|
|
72
|
+
* finished so no listener sees the cancel before the card.
|
|
73
|
+
*/
|
|
74
|
+
private deliverCancelled;
|
|
57
75
|
/**
|
|
58
76
|
* Set up event handlers for processing responses
|
|
59
77
|
*/
|