@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
package/dist/hitl/hitlManager.js
CHANGED
|
@@ -7,12 +7,23 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { EventEmitter } from "events";
|
|
9
9
|
import { randomUUID } from "crypto";
|
|
10
|
-
import { HITLTimeoutError, HITLConfigurationError } from "./hitlErrors.js";
|
|
10
|
+
import { HITLCancelledError, HITLTimeoutError, HITLConfigurationError, } from "./hitlErrors.js";
|
|
11
11
|
import { logger } from "../utils/logger.js";
|
|
12
12
|
// Default configuration constants
|
|
13
13
|
const DEFAULT_TIMEOUT = 30000; // 30 seconds
|
|
14
14
|
// Shared with NeuroLink's HITL init logs so they report the policy applied here
|
|
15
15
|
export const DEFAULT_ALLOW_MODIFICATION = false;
|
|
16
|
+
/** The abort reason as text for `hitl:cancelled`, whatever the caller passed. */
|
|
17
|
+
export function describeAbortReason(signal) {
|
|
18
|
+
const reason = signal.reason;
|
|
19
|
+
if (typeof reason === "string" && reason.length > 0) {
|
|
20
|
+
return reason;
|
|
21
|
+
}
|
|
22
|
+
if (reason instanceof Error && reason.message) {
|
|
23
|
+
return reason.message;
|
|
24
|
+
}
|
|
25
|
+
return "Tool call was aborted";
|
|
26
|
+
}
|
|
16
27
|
/**
|
|
17
28
|
* HITLManager - Central orchestrator for Human-in-the-Loop safety mechanisms
|
|
18
29
|
*
|
|
@@ -27,6 +38,8 @@ export const DEFAULT_ALLOW_MODIFICATION = false;
|
|
|
27
38
|
export class HITLManager extends EventEmitter {
|
|
28
39
|
config;
|
|
29
40
|
pendingConfirmations = new Map();
|
|
41
|
+
/** hitl:cancelled deliveries held back while that ID's request emit runs. */
|
|
42
|
+
requestsEmitting = new Map();
|
|
30
43
|
statistics = {
|
|
31
44
|
totalRequests: 0,
|
|
32
45
|
pendingRequests: 0,
|
|
@@ -118,15 +131,30 @@ export class HITLManager extends EventEmitter {
|
|
|
118
131
|
return false;
|
|
119
132
|
}
|
|
120
133
|
/**
|
|
121
|
-
* Request confirmation for a tool execution
|
|
134
|
+
* Request confirmation for a tool execution.
|
|
135
|
+
*
|
|
136
|
+
* Aborting `context.signal` withdraws the request (see `cancelConfirmation`);
|
|
137
|
+
* a signal that is already aborted raises no card at all.
|
|
122
138
|
*/
|
|
123
139
|
async requestConfirmation(toolName, arguments_, context) {
|
|
140
|
+
const signal = context?.signal;
|
|
141
|
+
if (signal?.aborted) {
|
|
142
|
+
throw new HITLCancelledError(`Confirmation cancelled before it was requested for tool: ${toolName}`, undefined, describeAbortReason(signal));
|
|
143
|
+
}
|
|
124
144
|
const confirmationId = this.generateConfirmationId();
|
|
125
145
|
const startTime = Date.now();
|
|
126
146
|
// Update statistics
|
|
127
147
|
this.statistics.totalRequests++;
|
|
128
148
|
this.statistics.pendingRequests++;
|
|
129
149
|
return new Promise((resolve, reject) => {
|
|
150
|
+
const onAbort = () => {
|
|
151
|
+
if (signal) {
|
|
152
|
+
this.cancelConfirmation(confirmationId, describeAbortReason(signal));
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
// Every way the request settles detaches the listener, so a signal
|
|
156
|
+
// that aborts after the answer cancels nothing.
|
|
157
|
+
const detach = () => signal?.removeEventListener("abort", onAbort);
|
|
130
158
|
// Set up timeout
|
|
131
159
|
const timeoutHandle = setTimeout(() => {
|
|
132
160
|
this.handleTimeout(confirmationId);
|
|
@@ -138,10 +166,19 @@ export class HITLManager extends EventEmitter {
|
|
|
138
166
|
arguments: arguments_,
|
|
139
167
|
timestamp: startTime,
|
|
140
168
|
timeoutHandle,
|
|
141
|
-
resolve
|
|
142
|
-
|
|
169
|
+
resolve: (result) => {
|
|
170
|
+
detach();
|
|
171
|
+
resolve(result);
|
|
172
|
+
},
|
|
173
|
+
reject: (error) => {
|
|
174
|
+
detach();
|
|
175
|
+
reject(error);
|
|
176
|
+
},
|
|
143
177
|
};
|
|
144
178
|
this.pendingConfirmations.set(confirmationId, request);
|
|
179
|
+
// Attached before the card is emitted: a listener may answer, or the
|
|
180
|
+
// caller may abort, synchronously inside the emit below.
|
|
181
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
145
182
|
// Create confirmation request event
|
|
146
183
|
const requestEvent = {
|
|
147
184
|
type: "hitl:confirmation-request",
|
|
@@ -161,8 +198,19 @@ export class HITLManager extends EventEmitter {
|
|
|
161
198
|
allowModification: this.config.allowArgumentModification ?? DEFAULT_ALLOW_MODIFICATION,
|
|
162
199
|
},
|
|
163
200
|
};
|
|
164
|
-
// Emit confirmation request event
|
|
165
|
-
|
|
201
|
+
// Emit confirmation request event. An abort raised inside a listener
|
|
202
|
+
// defers its hitl:cancelled until every request listener has run.
|
|
203
|
+
this.requestsEmitting.set(confirmationId, []);
|
|
204
|
+
try {
|
|
205
|
+
this.emit("hitl:confirmation-request", requestEvent);
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
const deferred = this.requestsEmitting.get(confirmationId) ?? [];
|
|
209
|
+
this.requestsEmitting.delete(confirmationId);
|
|
210
|
+
for (const deliver of deferred) {
|
|
211
|
+
deliver();
|
|
212
|
+
}
|
|
213
|
+
}
|
|
166
214
|
// Log audit trail if enabled
|
|
167
215
|
if (this.config.auditLogging) {
|
|
168
216
|
this.logAuditEvent("confirmation-requested", {
|
|
@@ -297,6 +345,66 @@ export class HITLManager extends EventEmitter {
|
|
|
297
345
|
request.reject(new HITLTimeoutError(`Confirmation timeout for tool: ${request.toolName}`, confirmationId, this.config.timeout ?? DEFAULT_TIMEOUT));
|
|
298
346
|
}
|
|
299
347
|
}
|
|
348
|
+
/**
|
|
349
|
+
* Withdraw a pending confirmation because the call that asked was aborted.
|
|
350
|
+
*
|
|
351
|
+
* Clears the timer, forgets the entry (so a later answer for this ID runs
|
|
352
|
+
* nothing), rejects the waiting call with `HITLCancelledError` and emits
|
|
353
|
+
* `hitl:cancelled` so the approval UI can retire the card.
|
|
354
|
+
*
|
|
355
|
+
* @returns false when nothing was pending under this ID
|
|
356
|
+
*/
|
|
357
|
+
cancelConfirmation(confirmationId, reason = "Confirmation cancelled") {
|
|
358
|
+
const request = this.pendingConfirmations.get(confirmationId);
|
|
359
|
+
if (!request) {
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
362
|
+
clearTimeout(request.timeoutHandle);
|
|
363
|
+
this.pendingConfirmations.delete(confirmationId);
|
|
364
|
+
this.statistics.pendingRequests--;
|
|
365
|
+
if (this.config.auditLogging) {
|
|
366
|
+
this.logAuditEvent("confirmation-cancelled", {
|
|
367
|
+
confirmationId,
|
|
368
|
+
toolName: request.toolName,
|
|
369
|
+
reason,
|
|
370
|
+
arguments: request.arguments,
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
// Reject before emitting: a throwing listener must not leave the call
|
|
374
|
+
// waiting, and this often runs inside an AbortSignal listener, where a
|
|
375
|
+
// throw would surface as an uncaught exception.
|
|
376
|
+
request.reject(new HITLCancelledError(`Confirmation cancelled for tool: ${request.toolName}`, confirmationId, reason));
|
|
377
|
+
this.deliverCancelled(confirmationId, request.toolName, reason);
|
|
378
|
+
return true;
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Emit `hitl:cancelled`, or hold it until the request emit for this ID has
|
|
382
|
+
* finished so no listener sees the cancel before the card.
|
|
383
|
+
*/
|
|
384
|
+
deliverCancelled(confirmationId, toolName, reason) {
|
|
385
|
+
const deliver = () => {
|
|
386
|
+
const cancelledEvent = {
|
|
387
|
+
type: "hitl:cancelled",
|
|
388
|
+
payload: { confirmationId, toolName, reason },
|
|
389
|
+
};
|
|
390
|
+
try {
|
|
391
|
+
this.emit("hitl:cancelled", cancelledEvent);
|
|
392
|
+
}
|
|
393
|
+
catch (error) {
|
|
394
|
+
logger.warn("[HITL] A hitl:cancelled listener threw", {
|
|
395
|
+
confirmationId,
|
|
396
|
+
error: error instanceof Error ? error.message : String(error),
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
const held = this.requestsEmitting.get(confirmationId);
|
|
401
|
+
if (held) {
|
|
402
|
+
held.push(deliver);
|
|
403
|
+
}
|
|
404
|
+
else {
|
|
405
|
+
deliver();
|
|
406
|
+
}
|
|
407
|
+
}
|
|
300
408
|
/**
|
|
301
409
|
* Set up event handlers for processing responses
|
|
302
410
|
*/
|
|
@@ -410,8 +518,18 @@ export class HITLManager extends EventEmitter {
|
|
|
410
518
|
...data,
|
|
411
519
|
};
|
|
412
520
|
logger.info(`[HITL Audit] ${eventType}:`, auditLog);
|
|
413
|
-
// Emit audit event for external logging systems
|
|
414
|
-
|
|
521
|
+
// Emit audit event for external logging systems. Every caller logs before
|
|
522
|
+
// it settles the waiting call, often inside a timer or an AbortSignal
|
|
523
|
+
// listener, so a throwing listener must not reach it.
|
|
524
|
+
try {
|
|
525
|
+
this.emit("hitl:audit", auditLog);
|
|
526
|
+
}
|
|
527
|
+
catch (error) {
|
|
528
|
+
logger.warn("[HITL] A hitl:audit listener threw", {
|
|
529
|
+
eventType,
|
|
530
|
+
error: error instanceof Error ? error.message : String(error),
|
|
531
|
+
});
|
|
532
|
+
}
|
|
415
533
|
}
|
|
416
534
|
/**
|
|
417
535
|
* Get current HITL usage statistics
|
|
@@ -447,17 +565,17 @@ export class HITLManager extends EventEmitter {
|
|
|
447
565
|
* Clean up resources and reject pending confirmations
|
|
448
566
|
*/
|
|
449
567
|
cleanup() {
|
|
450
|
-
|
|
451
|
-
|
|
568
|
+
const clearedConfirmations = this.pendingConfirmations.size;
|
|
569
|
+
const pending = [...this.pendingConfirmations];
|
|
570
|
+
this.pendingConfirmations.clear();
|
|
571
|
+
this.statistics.pendingRequests = 0;
|
|
572
|
+
for (const [confirmationId, request] of pending) {
|
|
452
573
|
clearTimeout(request.timeoutHandle);
|
|
453
574
|
request.reject(new Error(`HITL cleanup: confirmation ${confirmationId} cancelled`));
|
|
575
|
+
this.deliverCancelled(confirmationId, request.toolName, "HITL manager cleanup");
|
|
454
576
|
}
|
|
455
|
-
this.pendingConfirmations.clear();
|
|
456
|
-
this.statistics.pendingRequests = 0;
|
|
457
577
|
if (this.config.auditLogging) {
|
|
458
|
-
this.logAuditEvent("manager-cleanup", {
|
|
459
|
-
clearedConfirmations: this.pendingConfirmations.size,
|
|
460
|
-
});
|
|
578
|
+
this.logAuditEvent("manager-cleanup", { clearedConfirmations });
|
|
461
579
|
}
|
|
462
580
|
}
|
|
463
581
|
/**
|
package/dist/hitl/index.d.ts
CHANGED
|
@@ -4,4 +4,4 @@
|
|
|
4
4
|
* Simple barrel export for HITL components.
|
|
5
5
|
*/
|
|
6
6
|
export { HITLManager } from "./hitlManager.js";
|
|
7
|
-
export { HITLError, HITLUserRejectedError, HITLTimeoutError, HITLConfigurationError, } from "./hitlErrors.js";
|
|
7
|
+
export { HITLError, HITLUserRejectedError, HITLTimeoutError, HITLCancelledError, HITLConfigurationError, } from "./hitlErrors.js";
|
package/dist/hitl/index.js
CHANGED
|
@@ -6,4 +6,4 @@
|
|
|
6
6
|
// Core HITL Manager
|
|
7
7
|
export { HITLManager } from "./hitlManager.js";
|
|
8
8
|
// Error Classes
|
|
9
|
-
export { HITLError, HITLUserRejectedError, HITLTimeoutError, HITLConfigurationError, } from "./hitlErrors.js";
|
|
9
|
+
export { HITLError, HITLUserRejectedError, HITLTimeoutError, HITLCancelledError, HITLConfigurationError, } from "./hitlErrors.js";
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one HITL confirmation step every tool-execution path shares.
|
|
3
|
+
*
|
|
4
|
+
* `NeuroLink.executeTool` runs it once per call, before the circuit breaker,
|
|
5
|
+
* the retry loop and the attempt timeout, and records the decision on the
|
|
6
|
+
* call's `HITLExecutionState`. The tool registry and the external server
|
|
7
|
+
* manager run the same step inline only for a caller that arrives with no
|
|
8
|
+
* recorded decision, so a gated call is never asked twice.
|
|
9
|
+
*/
|
|
10
|
+
import type { Span } from "@opentelemetry/api";
|
|
11
|
+
import type { HITLConfirmationContext, HITLExecutionState, HITLManager, HITLOutcomeAction, PauseDeadline } from "../types/index.js";
|
|
12
|
+
/**
|
|
13
|
+
* A fresh state for one tool call. `triggered` is kept for callers that read
|
|
14
|
+
* it and is only ever true once a human approved the call.
|
|
15
|
+
*/
|
|
16
|
+
export declare function createHITLExecutionState(): HITLExecutionState;
|
|
17
|
+
/**
|
|
18
|
+
* Whether `hitl` confirms every call to the built-in tool `toolName`, whether
|
|
19
|
+
* or not its rule matches the name: true for the built-ins that change the
|
|
20
|
+
* machine unless the host set `hitl.confirmBuiltinTools: false`.
|
|
21
|
+
*/
|
|
22
|
+
export declare function builtInToolAlwaysConfirmed(hitl: HITLManager, toolName: string): boolean;
|
|
23
|
+
/** Mark `result` as a HITL refusal and return it. */
|
|
24
|
+
export declare function markRefusalResult<T extends object>(result: T): T;
|
|
25
|
+
/** Whether `result` was marked as a HITL refusal (`markRefusalResult`). */
|
|
26
|
+
export declare function isRefusalResult(result: unknown): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Whether the call's recorded decision refused it. The result of such a call
|
|
29
|
+
* is a refusal, and a refusal must never be cached: the next identical call
|
|
30
|
+
* has to raise a fresh card.
|
|
31
|
+
*/
|
|
32
|
+
export declare function hitlStateRefused(state: HITLExecutionState | undefined): boolean;
|
|
33
|
+
/**
|
|
34
|
+
* The confirmation step for one tool call, shared by `NeuroLink.executeTool`'s
|
|
35
|
+
* gate, the tool registry and the external server manager.
|
|
36
|
+
*
|
|
37
|
+
* - A state that already records a decision is not asked again: `approved`
|
|
38
|
+
* and `not-required` run with the arguments they were decided for, any
|
|
39
|
+
* refusal is refused. A state reused with other arguments is decided again.
|
|
40
|
+
* - With HITL off, the call runs and nothing is recorded.
|
|
41
|
+
* - Otherwise the human is asked (when the tool needs it) and the decision is
|
|
42
|
+
* written to `state` after the wait, never before it.
|
|
43
|
+
*
|
|
44
|
+
* `report` lets the caller log the ask and the decision with its own logger
|
|
45
|
+
* and puts `tool.hitl_*` events and `tool.hitl.decision` on its span;
|
|
46
|
+
* `subject` names the tool kind in the messages (default "Tool");
|
|
47
|
+
* `pauseDeadline` pauses the caller's outer deadlines while the human decides;
|
|
48
|
+
* `alwaysConfirm` asks even when the rule does not match the tool (see
|
|
49
|
+
* `builtInToolAlwaysConfirmed`).
|
|
50
|
+
*/
|
|
51
|
+
export declare function resolveToolCallConfirmation(hitl: HITLManager | undefined, toolName: string, args: unknown, state: HITLExecutionState | undefined, context: HITLConfirmationContext, report?: {
|
|
52
|
+
log?: (message: string) => void;
|
|
53
|
+
span?: Span;
|
|
54
|
+
subject?: string;
|
|
55
|
+
pauseDeadline?: PauseDeadline;
|
|
56
|
+
alwaysConfirm?: boolean;
|
|
57
|
+
}): Promise<HITLOutcomeAction>;
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one HITL confirmation step every tool-execution path shares.
|
|
3
|
+
*
|
|
4
|
+
* `NeuroLink.executeTool` runs it once per call, before the circuit breaker,
|
|
5
|
+
* the retry loop and the attempt timeout, and records the decision on the
|
|
6
|
+
* call's `HITLExecutionState`. The tool registry and the external server
|
|
7
|
+
* manager run the same step inline only for a caller that arrives with no
|
|
8
|
+
* recorded decision, so a gated call is never asked twice.
|
|
9
|
+
*/
|
|
10
|
+
import { isDeepStrictEqual } from "node:util";
|
|
11
|
+
import { HITLCancelledError, HITLError, HITLTimeoutError, HITLUserRejectedError, } from "./hitlErrors.js";
|
|
12
|
+
import { describeAbortReason } from "./hitlManager.js";
|
|
13
|
+
/**
|
|
14
|
+
* The tool and arguments a state's recorded `approved` or `not-required`
|
|
15
|
+
* decision was made for. The decision covers that tool with those arguments
|
|
16
|
+
* only: a caller that reuses the state for another tool or with other
|
|
17
|
+
* arguments is asked again.
|
|
18
|
+
*/
|
|
19
|
+
const decidedArguments = new WeakMap();
|
|
20
|
+
/**
|
|
21
|
+
* The states `createHITLExecutionState` made, each for one `executeTool`
|
|
22
|
+
* call. Their decision is bound to the arguments object itself: one approval
|
|
23
|
+
* covers every attempt of that call, even when a tool or middleware changes
|
|
24
|
+
* the object between attempts. Any other state is the caller's, and its
|
|
25
|
+
* decision is bound to a copy taken when it was made.
|
|
26
|
+
*/
|
|
27
|
+
const callStates = new WeakSet();
|
|
28
|
+
/** Stands in for decided arguments that could not be copied; nothing equals it. */
|
|
29
|
+
const UNCOPYABLE_ARGUMENTS = Symbol("uncopyable decided arguments");
|
|
30
|
+
/**
|
|
31
|
+
* A fresh state for one tool call. `triggered` is kept for callers that read
|
|
32
|
+
* it and is only ever true once a human approved the call.
|
|
33
|
+
*/
|
|
34
|
+
export function createHITLExecutionState() {
|
|
35
|
+
const state = {
|
|
36
|
+
get triggered() {
|
|
37
|
+
return state.decision === "approved";
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
callStates.add(state);
|
|
41
|
+
return state;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Record what `state`'s decision was made for: the arguments object for a
|
|
45
|
+
* call's own state, a copy of it for a caller's, so that changing the
|
|
46
|
+
* object in place afterwards is a change. Arguments that cannot be copied
|
|
47
|
+
* (a function value, for example) never match again: the caller is asked.
|
|
48
|
+
*/
|
|
49
|
+
function bindDecidedArguments(state, toolName, args) {
|
|
50
|
+
if (callStates.has(state)) {
|
|
51
|
+
decidedArguments.set(state, { toolName, args });
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
decidedArguments.set(state, { toolName, args: structuredClone(args) });
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
decidedArguments.set(state, { toolName, args: UNCOPYABLE_ARGUMENTS });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** A copy of `args` that later changes to the original cannot reach. */
|
|
62
|
+
function snapshotArguments(args) {
|
|
63
|
+
try {
|
|
64
|
+
return structuredClone(args);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return args;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Built-in tools that change the machine. While HITL is enabled they require
|
|
72
|
+
* confirmation on every call, whatever `dangerousActions` lists, unless the
|
|
73
|
+
* host sets `hitl.confirmBuiltinTools: false`. The other built-ins (clock,
|
|
74
|
+
* arithmetic, reads, directory listings, CSV analysis, web search) are gated
|
|
75
|
+
* by `dangerousActions` keywords and `customRules` like every other tool.
|
|
76
|
+
*/
|
|
77
|
+
const HITL_ALWAYS_CONFIRM_BUILT_IN_TOOLS = new Set([
|
|
78
|
+
"writeFile",
|
|
79
|
+
"executeBashCommand",
|
|
80
|
+
]);
|
|
81
|
+
/**
|
|
82
|
+
* Whether `hitl` confirms every call to the built-in tool `toolName`, whether
|
|
83
|
+
* or not its rule matches the name: true for the built-ins that change the
|
|
84
|
+
* machine unless the host set `hitl.confirmBuiltinTools: false`.
|
|
85
|
+
*/
|
|
86
|
+
export function builtInToolAlwaysConfirmed(hitl, toolName) {
|
|
87
|
+
return (HITL_ALWAYS_CONFIRM_BUILT_IN_TOOLS.has(toolName) &&
|
|
88
|
+
hitl.getConfig().confirmBuiltinTools !== false);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Tool results that carry a HITL refusal. A cache of tool results must not
|
|
92
|
+
* keep one, the per-turn one of the Gemini loops (`DedupExecuteMap`)
|
|
93
|
+
* included: the identical call has to raise a fresh card.
|
|
94
|
+
*/
|
|
95
|
+
const refusalResults = new WeakSet();
|
|
96
|
+
/** Mark `result` as a HITL refusal and return it. */
|
|
97
|
+
export function markRefusalResult(result) {
|
|
98
|
+
refusalResults.add(result);
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
/** Whether `result` was marked as a HITL refusal (`markRefusalResult`). */
|
|
102
|
+
export function isRefusalResult(result) {
|
|
103
|
+
return (typeof result === "object" && result !== null && refusalResults.has(result));
|
|
104
|
+
}
|
|
105
|
+
/** Whether a recorded decision lets the tool run. */
|
|
106
|
+
function hitlDecisionAllowsExecution(decision) {
|
|
107
|
+
return decision === "approved" || decision === "not-required";
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Whether the call's recorded decision refused it. The result of such a call
|
|
111
|
+
* is a refusal, and a refusal must never be cached: the next identical call
|
|
112
|
+
* has to raise a fresh card.
|
|
113
|
+
*/
|
|
114
|
+
export function hitlStateRefused(state) {
|
|
115
|
+
return (state?.decision !== undefined &&
|
|
116
|
+
!hitlDecisionAllowsExecution(state.decision));
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* A promise that rejects with `HITLCancelledError` once `signal` has aborted,
|
|
120
|
+
* so a manager that ignores the signal cannot keep the call waiting. It
|
|
121
|
+
* rejects one macrotask after the abort: a manager that honours the signal,
|
|
122
|
+
* as the shipped one does, has rejected by then, and its own cancellation is
|
|
123
|
+
* what the call reports. `detach` drops the listener once the wait settles.
|
|
124
|
+
*/
|
|
125
|
+
function rejectOnAbort(signal, toolName) {
|
|
126
|
+
let timer;
|
|
127
|
+
let onAbort;
|
|
128
|
+
const promise = new Promise((_resolve, reject) => {
|
|
129
|
+
onAbort = () => {
|
|
130
|
+
timer = setTimeout(() => reject(new HITLCancelledError(`Confirmation cancelled for tool: ${toolName}`, undefined, describeAbortReason(signal))), 0);
|
|
131
|
+
};
|
|
132
|
+
if (signal.aborted) {
|
|
133
|
+
onAbort();
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
return {
|
|
140
|
+
promise,
|
|
141
|
+
detach: () => {
|
|
142
|
+
if (onAbort) {
|
|
143
|
+
signal.removeEventListener("abort", onAbort);
|
|
144
|
+
}
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Ask the human whether `toolName` may run with `args`, and say what they
|
|
151
|
+
* decided. Never throws: a timed-out card is `timeout`, any other failure of
|
|
152
|
+
* the wait (an abort, a manager cleanup) is `cancelled`, and an approval that
|
|
153
|
+
* arrives after `context.signal` aborted is `cancelled` too, because the call
|
|
154
|
+
* that asked has already been told it did not run. An abort ends the wait
|
|
155
|
+
* even when the manager ignores the signal; such a manager keeps its card,
|
|
156
|
+
* and a later answer to it runs nothing.
|
|
157
|
+
*
|
|
158
|
+
* `options.pauseDeadline` stops the caller's outer deadlines for the wait
|
|
159
|
+
* only (a model loop's per-tool bound), and every outcome resumes them with
|
|
160
|
+
* the time that was left. `options.alwaysConfirm` asks even when the rule
|
|
161
|
+
* does not match.
|
|
162
|
+
*/
|
|
163
|
+
async function confirmWithHitl(hitl, toolName, args, context, onRequest, options = {}) {
|
|
164
|
+
if (!options.alwaysConfirm && !hitl.requiresConfirmation(toolName, args)) {
|
|
165
|
+
return { decision: "not-required", args };
|
|
166
|
+
}
|
|
167
|
+
onRequest();
|
|
168
|
+
// The human reviews, and the tool runs with, this snapshot: the caller's
|
|
169
|
+
// object (or a manager) changing it during the wait cannot change what was
|
|
170
|
+
// approved. Arguments that cannot be copied are presented as they are.
|
|
171
|
+
const presented = snapshotArguments(args);
|
|
172
|
+
let result;
|
|
173
|
+
const resume = options.pauseDeadline?.();
|
|
174
|
+
const abort = context.signal
|
|
175
|
+
? rejectOnAbort(context.signal, toolName)
|
|
176
|
+
: undefined;
|
|
177
|
+
try {
|
|
178
|
+
const answer = hitl.requestConfirmation(toolName, presented, context);
|
|
179
|
+
result = abort ? await Promise.race([answer, abort.promise]) : await answer;
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
return {
|
|
183
|
+
decision: error instanceof HITLTimeoutError ? "timeout" : "cancelled",
|
|
184
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
finally {
|
|
188
|
+
abort?.detach();
|
|
189
|
+
resume?.();
|
|
190
|
+
}
|
|
191
|
+
if (!result.approved) {
|
|
192
|
+
return { decision: "denied", reason: result.reason };
|
|
193
|
+
}
|
|
194
|
+
if (context.signal?.aborted) {
|
|
195
|
+
return {
|
|
196
|
+
decision: "cancelled",
|
|
197
|
+
error: new HITLCancelledError("Tool call was cancelled before it ran"),
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
return { decision: "approved", args: result.modifiedArguments ?? presented };
|
|
201
|
+
}
|
|
202
|
+
/** What an outcome means for the call; the refusal texts live only here. */
|
|
203
|
+
function outcomeAction(outcome, toolName, subject) {
|
|
204
|
+
switch (outcome.decision) {
|
|
205
|
+
case "approved":
|
|
206
|
+
case "not-required":
|
|
207
|
+
return { run: true, args: outcome.args };
|
|
208
|
+
case "denied":
|
|
209
|
+
return {
|
|
210
|
+
run: false,
|
|
211
|
+
error: new HITLUserRejectedError(`${subject} execution rejected by user: ${outcome.reason || "No reason provided"}`, toolName, outcome.reason),
|
|
212
|
+
};
|
|
213
|
+
case "timeout":
|
|
214
|
+
return { run: false, error: outcome.error };
|
|
215
|
+
case "cancelled":
|
|
216
|
+
return {
|
|
217
|
+
run: false,
|
|
218
|
+
error: outcome.error instanceof HITLError
|
|
219
|
+
? outcome.error
|
|
220
|
+
: new Error(`HITL confirmation failed: ${outcome.error.message}`, {
|
|
221
|
+
cause: outcome.error,
|
|
222
|
+
}),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The confirmation step for one tool call, shared by `NeuroLink.executeTool`'s
|
|
228
|
+
* gate, the tool registry and the external server manager.
|
|
229
|
+
*
|
|
230
|
+
* - A state that already records a decision is not asked again: `approved`
|
|
231
|
+
* and `not-required` run with the arguments they were decided for, any
|
|
232
|
+
* refusal is refused. A state reused with other arguments is decided again.
|
|
233
|
+
* - With HITL off, the call runs and nothing is recorded.
|
|
234
|
+
* - Otherwise the human is asked (when the tool needs it) and the decision is
|
|
235
|
+
* written to `state` after the wait, never before it.
|
|
236
|
+
*
|
|
237
|
+
* `report` lets the caller log the ask and the decision with its own logger
|
|
238
|
+
* and puts `tool.hitl_*` events and `tool.hitl.decision` on its span;
|
|
239
|
+
* `subject` names the tool kind in the messages (default "Tool");
|
|
240
|
+
* `pauseDeadline` pauses the caller's outer deadlines while the human decides;
|
|
241
|
+
* `alwaysConfirm` asks even when the rule does not match the tool (see
|
|
242
|
+
* `builtInToolAlwaysConfirmed`).
|
|
243
|
+
*/
|
|
244
|
+
export async function resolveToolCallConfirmation(hitl, toolName, args, state, context, report = {}) {
|
|
245
|
+
const subject = report.subject ?? "Tool";
|
|
246
|
+
const recorded = state?.decision;
|
|
247
|
+
if (recorded !== undefined) {
|
|
248
|
+
if (!hitlDecisionAllowsExecution(recorded)) {
|
|
249
|
+
return {
|
|
250
|
+
run: false,
|
|
251
|
+
error: new HITLCancelledError(`${subject} '${toolName}' was refused by its confirmation (${recorded})`),
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
if (!state || !decidedArguments.has(state)) {
|
|
255
|
+
return { run: true, args };
|
|
256
|
+
}
|
|
257
|
+
const decided = decidedArguments.get(state);
|
|
258
|
+
if (decided?.toolName === toolName &&
|
|
259
|
+
isDeepStrictEqual(decided.args, args)) {
|
|
260
|
+
return { run: true, args };
|
|
261
|
+
}
|
|
262
|
+
// Decided for another tool or other arguments: this call has not been,
|
|
263
|
+
// so decide again.
|
|
264
|
+
}
|
|
265
|
+
if (!hitl?.isEnabled()) {
|
|
266
|
+
return { run: true, args };
|
|
267
|
+
}
|
|
268
|
+
const outcome = await confirmWithHitl(hitl, toolName, args, context, () => {
|
|
269
|
+
report.log?.(`${subject} '${toolName}' requires HITL confirmation`);
|
|
270
|
+
report.span?.addEvent("tool.hitl_requested");
|
|
271
|
+
}, {
|
|
272
|
+
pauseDeadline: report.pauseDeadline,
|
|
273
|
+
alwaysConfirm: report.alwaysConfirm,
|
|
274
|
+
});
|
|
275
|
+
if (state) {
|
|
276
|
+
state.decision = outcome.decision;
|
|
277
|
+
if (outcome.decision === "approved" ||
|
|
278
|
+
outcome.decision === "not-required") {
|
|
279
|
+
bindDecidedArguments(state, toolName, outcome.args);
|
|
280
|
+
}
|
|
281
|
+
else {
|
|
282
|
+
decidedArguments.delete(state);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
report.span?.setAttribute("tool.hitl.decision", outcome.decision);
|
|
286
|
+
if (outcome.decision === "approved") {
|
|
287
|
+
report.span?.addEvent("tool.hitl_approved");
|
|
288
|
+
}
|
|
289
|
+
else if (outcome.decision === "denied") {
|
|
290
|
+
report.span?.addEvent("tool.hitl_rejected");
|
|
291
|
+
}
|
|
292
|
+
if (outcome.decision !== "not-required") {
|
|
293
|
+
report.log?.(`${subject} '${toolName}' HITL decision: ${outcome.decision}`);
|
|
294
|
+
}
|
|
295
|
+
return outcomeAction(outcome, toolName, subject);
|
|
296
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -507,5 +507,5 @@ export { TripwireEvaluator, createDefaultTripwireEvaluator, commonTripwires, } f
|
|
|
507
507
|
export { Agent } from "./agent/agent.js";
|
|
508
508
|
export { AgentNetwork } from "./agent/agentNetwork.js";
|
|
509
509
|
export { TERMINAL_AGENT_PROMPT_V1, TERMINAL_AGENT_PROMPT_V2, TERMINAL_AGENT_PROMPT_VERSION, } from "./agent/prompts/terminalAgentPrompt.js";
|
|
510
|
-
export { AgentCoordinator, TaskDistributor, MessageBus, NetworkOrchestrator, NetworkTopology, TopologyBuilder, } from "./agent/index.js";
|
|
510
|
+
export { AgentCoordinator, TaskDistributor, MessageBus, NetworkOrchestrator, NetworkTopology, TopologyBuilder, buildMechanicalDigest, } from "./agent/index.js";
|
|
511
511
|
export { createLocalUsageReader, getLocalUsageDescriptors, getRegisteredLocalUsageCliIds, readAllLocalUsage, registerLocalUsageReader, } from "./localUsage/index.js";
|
package/dist/index.js
CHANGED
|
@@ -820,7 +820,10 @@ AgentCoordinator, TaskDistributor,
|
|
|
820
820
|
// Communication
|
|
821
821
|
MessageBus,
|
|
822
822
|
// Orchestration
|
|
823
|
-
NetworkOrchestrator, NetworkTopology, TopologyBuilder,
|
|
823
|
+
NetworkOrchestrator, NetworkTopology, TopologyBuilder,
|
|
824
|
+
// Isolated sub-agent runs: the bounded summary of a run's tool executions
|
|
825
|
+
// that a host shows its model when the run produced no text of its own
|
|
826
|
+
buildMechanicalDigest, } from "./agent/index.js";
|
|
824
827
|
// ============================================================================
|
|
825
828
|
// Local usage exports
|
|
826
829
|
// ============================================================================
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { EventEmitter } from "events";
|
|
10
10
|
import { ToolDiscoveryService } from "./toolDiscoveryService.js";
|
|
11
|
-
import type { HITLManager, JsonObject, ServerLoadResult, ExternalMCPServerInstance, ExternalMCPServerHealth, ExternalMCPConfigValidation, ExternalMCPOperationResult, ExternalMCPManagerConfig, ExternalMCPToolInfo, MCPServerInfo } from "../types/index.js";
|
|
11
|
+
import type { HITLExecutionState, HITLManager, JsonObject, ServerLoadResult, ExternalMCPServerInstance, ExternalMCPServerHealth, ExternalMCPConfigValidation, ExternalMCPOperationResult, ExternalMCPManagerConfig, ExternalMCPToolInfo, MCPServerInfo, PauseDeadline } from "../types/index.js";
|
|
12
12
|
export declare class ExternalServerManager extends EventEmitter {
|
|
13
13
|
private servers;
|
|
14
14
|
private config;
|
|
@@ -28,6 +28,13 @@ export declare class ExternalServerManager extends EventEmitter {
|
|
|
28
28
|
private toolDiscovery;
|
|
29
29
|
private enableMainRegistryIntegration;
|
|
30
30
|
private hitlManager?;
|
|
31
|
+
/**
|
|
32
|
+
* Where to find a manager when none was set with `setHITLManager`: the
|
|
33
|
+
* owning instance's tool registry, so an instance with no HITL of its own
|
|
34
|
+
* on a shared registry (a worker) confirms its external tools with the
|
|
35
|
+
* registry's manager, as it does its registered tools.
|
|
36
|
+
*/
|
|
37
|
+
private fallbackHITLManager?;
|
|
31
38
|
constructor(config?: ExternalMCPManagerConfig, options?: {
|
|
32
39
|
enableMainRegistryIntegration?: boolean;
|
|
33
40
|
});
|
|
@@ -43,7 +50,15 @@ export declare class ExternalServerManager extends EventEmitter {
|
|
|
43
50
|
*/
|
|
44
51
|
setHITLManager(hitlManager?: HITLManager): void;
|
|
45
52
|
/**
|
|
46
|
-
*
|
|
53
|
+
* Set where to find a HITL manager when none was set with
|
|
54
|
+
* `setHITLManager`, resolved per call. NeuroLink points it at its tool
|
|
55
|
+
* registry's manager, so an instance with no HITL of its own on a shared
|
|
56
|
+
* registry confirms its external tools with that manager.
|
|
57
|
+
*/
|
|
58
|
+
setFallbackHITLManager(resolve?: () => HITLManager | undefined): void;
|
|
59
|
+
/**
|
|
60
|
+
* Get the HITL manager external tool calls are confirmed with: the one set
|
|
61
|
+
* with `setHITLManager` when it is enabled, else the fallback's.
|
|
47
62
|
*/
|
|
48
63
|
getHITLManager(): HITLManager | undefined;
|
|
49
64
|
/**
|
|
@@ -234,7 +249,23 @@ export declare class ExternalServerManager extends EventEmitter {
|
|
|
234
249
|
*/
|
|
235
250
|
executeTool(serverId: string, toolName: string, parameters: JsonObject, options?: {
|
|
236
251
|
timeout?: number;
|
|
252
|
+
/** The call's HITL state; a recorded decision skips the inline check */
|
|
253
|
+
hitlState?: HITLExecutionState;
|
|
254
|
+
/**
|
|
255
|
+
* Aborting it withdraws a pending inline confirmation; once it has
|
|
256
|
+
* fired, the call is not sent to the server.
|
|
257
|
+
*/
|
|
258
|
+
signal?: AbortSignal;
|
|
259
|
+
/** Pauses the caller's deadline while an inline confirmation waits */
|
|
260
|
+
pauseDeadline?: PauseDeadline;
|
|
237
261
|
}): Promise<unknown>;
|
|
262
|
+
/**
|
|
263
|
+
* The external manager's inline HITL check, for a caller that arrives
|
|
264
|
+
* without a recorded decision (`executeExternalMCPTool` and the AI-SDK
|
|
265
|
+
* conversion path). Throws when the call must not run; otherwise returns
|
|
266
|
+
* the parameters to run with.
|
|
267
|
+
*/
|
|
268
|
+
private confirmExternalToolCall;
|
|
238
269
|
/**
|
|
239
270
|
* Get all tools from all servers
|
|
240
271
|
*/
|