@juspay/neurolink 13.12.0 → 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 +5 -3
- package/dist/agent/agentToolRegistrar.js +3 -1
- package/dist/auth/middleware/AuthMiddleware.d.ts +1 -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/amazonSagemaker.d.ts +1 -1
- package/dist/providers/anthropic/client.js +5 -1
- package/dist/providers/catalog/schema.d.ts +1 -1
- package/dist/providers/googleNativeGemini3/utils.js +5 -1
- package/dist/providers/openaiChatCompletionsBase.js +21 -3
- package/dist/providers/sagemaker/language-model.d.ts +2 -2
- package/dist/proxy/otelLogSink.d.ts +1 -1
- 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/server/utils/validation.d.ts +28 -28
- 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/config.d.ts +7 -7
- 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 +18 -11
package/dist/types/hitl.d.ts
CHANGED
|
@@ -160,6 +160,22 @@ export type ConfirmationTimeoutEvent = {
|
|
|
160
160
|
timeout: number;
|
|
161
161
|
};
|
|
162
162
|
};
|
|
163
|
+
/**
|
|
164
|
+
* Event payload for a withdrawn confirmation
|
|
165
|
+
* Emitted when the call that asked was aborted before anyone answered, so the
|
|
166
|
+
* approval UI can retire the card: a later answer to it runs nothing.
|
|
167
|
+
*/
|
|
168
|
+
export type ConfirmationCancelledEvent = {
|
|
169
|
+
type: "hitl:cancelled";
|
|
170
|
+
payload: {
|
|
171
|
+
/** Confirmation ID that was withdrawn */
|
|
172
|
+
confirmationId: string;
|
|
173
|
+
/** Tool name whose confirmation was withdrawn */
|
|
174
|
+
toolName: string;
|
|
175
|
+
/** Why it was withdrawn: the abort reason, when the caller gave one */
|
|
176
|
+
reason: string;
|
|
177
|
+
};
|
|
178
|
+
};
|
|
163
179
|
/**
|
|
164
180
|
* HITL audit log entry
|
|
165
181
|
* Used for compliance and debugging purposes
|
|
@@ -168,7 +184,7 @@ export type HITLAuditLog = {
|
|
|
168
184
|
/** ISO timestamp of the event */
|
|
169
185
|
timestamp: string;
|
|
170
186
|
/** Type of HITL event */
|
|
171
|
-
eventType: "confirmation-requested" | "confirmation-approved" | "confirmation-rejected" | "confirmation-timeout" | "confirmation-auto-approved";
|
|
187
|
+
eventType: "confirmation-requested" | "confirmation-approved" | "confirmation-rejected" | "confirmation-timeout" | "confirmation-auto-approved" | "confirmation-cancelled";
|
|
172
188
|
/** Tool that was involved */
|
|
173
189
|
toolName: string;
|
|
174
190
|
/** User who made the decision (if applicable) */
|
|
@@ -214,12 +230,19 @@ export type HITLManager = {
|
|
|
214
230
|
isEnabled(): boolean;
|
|
215
231
|
/** Check if a tool requires confirmation based on configuration */
|
|
216
232
|
requiresConfirmation(toolName: string, args?: unknown): boolean;
|
|
217
|
-
/**
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
233
|
+
/**
|
|
234
|
+
* Request confirmation for a tool execution; aborting `context.signal`
|
|
235
|
+
* withdraws it. The call that asked stops waiting on that abort even when
|
|
236
|
+
* an implementation ignores the signal: its card then stays until it is
|
|
237
|
+
* answered, and the answer runs nothing.
|
|
238
|
+
*/
|
|
239
|
+
requestConfirmation(toolName: string, arguments_: unknown, context?: HITLConfirmationContext): Promise<ConfirmationResult>;
|
|
240
|
+
/**
|
|
241
|
+
* Withdraw a pending confirmation; false when nothing was pending under this
|
|
242
|
+
* ID. Optional so existing implementations of this type still compile; the
|
|
243
|
+
* shipped HITLManager has it.
|
|
244
|
+
*/
|
|
245
|
+
cancelConfirmation?(confirmationId: string, reason?: string): boolean;
|
|
223
246
|
/** Process user response to confirmation request */
|
|
224
247
|
processUserResponse(confirmationId: string, response: {
|
|
225
248
|
approved: boolean;
|
|
@@ -244,6 +267,75 @@ export type HITLManager = {
|
|
|
244
267
|
on(event: string, listener: (...args: unknown[]) => void): HITLManager;
|
|
245
268
|
emit(event: string, ...args: unknown[]): boolean;
|
|
246
269
|
};
|
|
270
|
+
/**
|
|
271
|
+
* What the human-in-the-loop step decided for one tool call. Only `approved`
|
|
272
|
+
* and `not-required` let the tool run.
|
|
273
|
+
*/
|
|
274
|
+
export type HITLDecision = "approved" | "denied" | "timeout" | "cancelled" | "not-required";
|
|
275
|
+
/**
|
|
276
|
+
* Per-call HITL state, shared by every attempt of one `executeTool` call.
|
|
277
|
+
*
|
|
278
|
+
* The confirmation step writes `decision` once it has decided (after the
|
|
279
|
+
* human answered, or the wait ended), never before; an attempt that arrives
|
|
280
|
+
* with the decision for its arguments is not asked again. A state whose `decision` is still undefined has not been
|
|
281
|
+
* confirmed. An approval (or a `not-required` decision) covers the arguments
|
|
282
|
+
* it was made for. A state you pass yourself is compared with a copy of
|
|
283
|
+
* those arguments taken when the decision was made: reused with other
|
|
284
|
+
* arguments, or with the same object changed in place since, it is decided
|
|
285
|
+
* again and `decision` is overwritten; arguments that cannot be copied (a
|
|
286
|
+
* function value, for example) are always decided again. A `decision` you
|
|
287
|
+
* write yourself, rather than the confirmation step, is used as it is. The
|
|
288
|
+
* state `executeTool` makes for its own call is bound to the arguments
|
|
289
|
+
* object itself, so one approval covers every attempt of that call.
|
|
290
|
+
*/
|
|
247
291
|
export type HITLExecutionState = {
|
|
248
|
-
|
|
292
|
+
/** Recorded after the confirmation step; undefined until then */
|
|
293
|
+
decision?: HITLDecision;
|
|
294
|
+
/**
|
|
295
|
+
* Read-only alias of `decision === "approved"`, kept for callers that read
|
|
296
|
+
* it. Never true before the human approved. A plain object passed by a
|
|
297
|
+
* caller does not carry it; read `decision` instead.
|
|
298
|
+
*/
|
|
299
|
+
readonly triggered?: boolean;
|
|
300
|
+
};
|
|
301
|
+
/** Where, and for whom, a confirmation is requested */
|
|
302
|
+
export type HITLConfirmationContext = {
|
|
303
|
+
/** MCP server ID (if this is an external tool) */
|
|
304
|
+
serverId?: string;
|
|
305
|
+
/** User session identifier */
|
|
306
|
+
sessionId?: string;
|
|
307
|
+
/** User identifier */
|
|
308
|
+
userId?: string;
|
|
309
|
+
/** Aborting it withdraws the pending confirmation (`hitl:cancelled`) */
|
|
310
|
+
signal?: AbortSignal;
|
|
311
|
+
};
|
|
312
|
+
/**
|
|
313
|
+
* Result of the shared confirmation step: the arguments to run with, or why
|
|
314
|
+
* the call must not run.
|
|
315
|
+
*/
|
|
316
|
+
export type HITLConfirmationOutcome = {
|
|
317
|
+
decision: "approved" | "not-required";
|
|
318
|
+
/** The approver's modified arguments, else the requested ones */
|
|
319
|
+
args: unknown;
|
|
320
|
+
} | {
|
|
321
|
+
decision: "denied";
|
|
322
|
+
/** The approver's reason, if one was given */
|
|
323
|
+
reason?: string;
|
|
324
|
+
} | {
|
|
325
|
+
decision: "timeout" | "cancelled";
|
|
326
|
+
/** HITLTimeoutError, HITLCancelledError, or whatever ended the wait */
|
|
327
|
+
error: Error;
|
|
328
|
+
};
|
|
329
|
+
/**
|
|
330
|
+
* What the confirmation step means for one tool call, the same on every
|
|
331
|
+
* execution path: run with these arguments, or refuse with this error.
|
|
332
|
+
*/
|
|
333
|
+
export type HITLOutcomeAction = {
|
|
334
|
+
run: true;
|
|
335
|
+
/** The approver's modified arguments, else the requested ones */
|
|
336
|
+
args: unknown;
|
|
337
|
+
} | {
|
|
338
|
+
run: false;
|
|
339
|
+
/** Why the call must not run; its message is the refusal text */
|
|
340
|
+
error: Error;
|
|
249
341
|
};
|
package/dist/types/mcp.d.ts
CHANGED
|
@@ -492,6 +492,11 @@ export type ExternalToolExecutionOptions = {
|
|
|
492
492
|
validateInput?: boolean;
|
|
493
493
|
/** Whether to validate output */
|
|
494
494
|
validateOutput?: boolean;
|
|
495
|
+
/**
|
|
496
|
+
* Aborting it cancels the in-flight MCP request: the SDK rejects the call
|
|
497
|
+
* and sends `notifications/cancelled` to the server.
|
|
498
|
+
*/
|
|
499
|
+
signal?: AbortSignal;
|
|
495
500
|
};
|
|
496
501
|
/**
|
|
497
502
|
* Tool validation result
|
|
@@ -14,7 +14,7 @@ import type { StreamOptions, StreamResult } from "./stream.js";
|
|
|
14
14
|
import type { ProviderError, ProviderErrorRule } from "./errors.js";
|
|
15
15
|
import type { ExternalMCPToolInfo } from "./externalMcp.js";
|
|
16
16
|
import type { ClaudeSubscriptionTier, AnthropicAuthMethod, AnthropicAuthConfig, SubscriptionInfo, OAuthToken } from "./subscription.js";
|
|
17
|
-
import type { Tool } from "./tools.js";
|
|
17
|
+
import type { PauseDeadline, Tool } from "./tools.js";
|
|
18
18
|
export type { LanguageModel, EmbeddingModel, ImageModel, GenerateTextResult, StepResult, ToolCallRepairFunction, PrepareStepFunction, PrepareStepResult, FinishReason, LanguageModelUsage, LanguageModelRequestMetadata, LanguageModelResponseMetadata, } from "./aiCompat.js";
|
|
19
19
|
export type { ClaudeSubscriptionTier, AnthropicAuthMethod, AnthropicAuthConfig, SubscriptionInfo, } from "./subscription.js";
|
|
20
20
|
/**
|
|
@@ -1168,6 +1168,27 @@ export type OpenAICompatCatalogEntry = {
|
|
|
1168
1168
|
* needs — lets call sites pass a minimal object without the full catalog
|
|
1169
1169
|
* entry (e.g. in tests, or a future non-catalog caller). */
|
|
1170
1170
|
export type OpenAICompatConfigInput = Pick<OpenAICompatCatalogEntry, "providerName" | "apiKeyEnvVar" | "baseURLEnvVar" | "defaultBaseURL" | "computedBaseURL" | "configOptions">;
|
|
1171
|
+
/**
|
|
1172
|
+
* What a provider's tool loop passes to the `executeTool` handed to
|
|
1173
|
+
* `setupToolExecutor`, for one model tool call.
|
|
1174
|
+
*/
|
|
1175
|
+
export type ProviderToolExecutorOptions = {
|
|
1176
|
+
/** Attempt timeout set when the tool was registered */
|
|
1177
|
+
timeout?: number;
|
|
1178
|
+
/** Retries set when the tool was registered */
|
|
1179
|
+
maxRetries?: number;
|
|
1180
|
+
/**
|
|
1181
|
+
* The loop's signal for this call: the turn's abort, or the loop's
|
|
1182
|
+
* per-tool deadline. `NeuroLink.executeTool` takes it to the call's
|
|
1183
|
+
* confirmation, its attempts and the tool's execution context.
|
|
1184
|
+
*/
|
|
1185
|
+
abortSignal?: AbortSignal;
|
|
1186
|
+
/**
|
|
1187
|
+
* Pauses the loop's deadlines for this call. `NeuroLink.executeTool`'s
|
|
1188
|
+
* confirmation gate calls it around the wait for a human.
|
|
1189
|
+
*/
|
|
1190
|
+
pauseDeadline?: PauseDeadline;
|
|
1191
|
+
};
|
|
1171
1192
|
/**
|
|
1172
1193
|
* AI Provider type with flexible parameter support
|
|
1173
1194
|
*/
|
|
@@ -1197,7 +1218,7 @@ export type AIProvider = {
|
|
|
1197
1218
|
decide?(request: DecisionRequest): Promise<DecisionResult>;
|
|
1198
1219
|
setupToolExecutor(sdk: {
|
|
1199
1220
|
customTools: Map<string, unknown>;
|
|
1200
|
-
executeTool: (toolName: string, params: unknown) => Promise<unknown>;
|
|
1221
|
+
executeTool: (toolName: string, params: unknown, options?: ProviderToolExecutorOptions) => Promise<unknown>;
|
|
1201
1222
|
}, functionTag: string): void;
|
|
1202
1223
|
/**
|
|
1203
1224
|
* Propagate trace context from NeuroLink SDK for parent-child span hierarchy.
|
package/dist/types/tools.d.ts
CHANGED
|
@@ -51,6 +51,8 @@ export type ExecutionContext<T = StandardRecord> = {
|
|
|
51
51
|
maxRetries?: number;
|
|
52
52
|
startTime?: number;
|
|
53
53
|
hitlState?: HITLExecutionState;
|
|
54
|
+
/** The caller's cancellation signal (`executeTool`'s `abortSignal` option) */
|
|
55
|
+
abortSignal?: AbortSignal;
|
|
54
56
|
};
|
|
55
57
|
/**
|
|
56
58
|
* Cache configuration options
|
|
@@ -155,26 +157,30 @@ export type ToolExecutionOptions = {
|
|
|
155
157
|
* Options for tool registration via registerTool()
|
|
156
158
|
*
|
|
157
159
|
* These options configure per-tool execution behavior. When not provided,
|
|
158
|
-
* the SDK's
|
|
159
|
-
*
|
|
160
|
+
* `executeTool` uses the SDK's defaults: a 120 s timeout per attempt and 3
|
|
161
|
+
* retries (up to 4 attempts), 1 s apart. A per-call `executeTool` option
|
|
162
|
+
* overrides the registered value.
|
|
160
163
|
*
|
|
161
164
|
* @example
|
|
162
165
|
* // Register with custom timeout and no retries
|
|
163
166
|
* sdk.registerTool("myTool", tool, { timeout: 5000, maxRetries: 0 });
|
|
164
167
|
*
|
|
165
|
-
* // Register with defaults
|
|
168
|
+
* // Register with the defaults
|
|
166
169
|
* sdk.registerTool("myTool", tool);
|
|
167
170
|
*/
|
|
168
171
|
export type ToolRegistrationOptions = {
|
|
169
|
-
/**
|
|
170
|
-
* When omitted, the SDK's
|
|
172
|
+
/** Timeout for one attempt, in milliseconds. Only applied when explicitly
|
|
173
|
+
* set. When omitted, the SDK's default (120 s) is used. */
|
|
171
174
|
timeout?: number;
|
|
172
|
-
/** Maximum
|
|
173
|
-
* When omitted, the SDK's
|
|
174
|
-
* Set to 0 to disable retries for this tool
|
|
175
|
+
/** Maximum retries after a failed attempt. Only applied when explicitly set.
|
|
176
|
+
* When omitted, the SDK's default (3 retries, so up to 4 attempts) is used.
|
|
177
|
+
* Set to 0 to disable retries for this tool, as you should for a tool
|
|
178
|
+
* whose effect must not happen twice. */
|
|
175
179
|
maxRetries?: number;
|
|
176
180
|
/** Ceiling on the whole execution across every attempt and the delays
|
|
177
|
-
* between them. When omitted,
|
|
181
|
+
* between them. When omitted,
|
|
182
|
+
* `timeout * (maxRetries + 1) + retryDelayMs * maxRetries` is used, the
|
|
183
|
+
* retry delay being 1 s unless the call sets `retryDelayMs`. */
|
|
178
184
|
totalTimeoutMs?: number;
|
|
179
185
|
/**
|
|
180
186
|
* Whether this tool's result may be served from the tool-result cache
|
|
@@ -223,6 +229,21 @@ export type ToolExecutionMetadata = {
|
|
|
223
229
|
version?: string;
|
|
224
230
|
[key: string]: JsonValue | undefined;
|
|
225
231
|
};
|
|
232
|
+
/**
|
|
233
|
+
* Pauses the deadlines a model loop put around one tool call, for as long as
|
|
234
|
+
* the call waits for something outside the tool (a human confirmation).
|
|
235
|
+
* Returns the function that resumes them with the time that was left.
|
|
236
|
+
*/
|
|
237
|
+
export type PauseDeadline = () => () => void;
|
|
238
|
+
/**
|
|
239
|
+
* A deadline that can be paused (`pause()` returns the resume function) and
|
|
240
|
+
* ended for good (`clear()`: a later resume re-arms nothing and the deadline
|
|
241
|
+
* never fires).
|
|
242
|
+
*/
|
|
243
|
+
export type PausableDeadline = {
|
|
244
|
+
pause: PauseDeadline;
|
|
245
|
+
clear: () => void;
|
|
246
|
+
};
|
|
226
247
|
/**
|
|
227
248
|
* Tool execution context
|
|
228
249
|
*/
|
|
@@ -231,6 +252,10 @@ export type ToolContext = {
|
|
|
231
252
|
userId?: string;
|
|
232
253
|
aiProvider?: string;
|
|
233
254
|
metadata?: ToolExecutionMetadata;
|
|
255
|
+
/** The loop's signal for this call (its turn abort or per-tool deadline) */
|
|
256
|
+
abortSignal?: AbortSignal;
|
|
257
|
+
/** Pauses the loop's deadlines for this call while it waits for a human */
|
|
258
|
+
pauseDeadline?: PauseDeadline;
|
|
234
259
|
};
|
|
235
260
|
/**
|
|
236
261
|
* SDK-specific tool context with additional fields for SDK usage
|
|
@@ -19,5 +19,6 @@
|
|
|
19
19
|
* ```
|
|
20
20
|
*/
|
|
21
21
|
export { delay, sleep } from "./delay.js";
|
|
22
|
+
export { createPausableDeadline, pauseDeadlineOf } from "./pausableDeadline.js";
|
|
22
23
|
export { calculateBackoff, createRetry, DEFAULT_RETRY_OPTIONS, RetryExhaustedError, retry, } from "./retry.js";
|
|
23
|
-
export { TimeoutError, raceWithAbort, withTimeout, withTimeoutFn, } from "./withTimeout.js";
|
|
24
|
+
export { TimeoutError, abortSignalOf, raceWithAbort, withTimeout, withTimeoutFn, } from "./withTimeout.js";
|
|
@@ -19,5 +19,6 @@
|
|
|
19
19
|
* ```
|
|
20
20
|
*/
|
|
21
21
|
export { delay, sleep } from "./delay.js";
|
|
22
|
+
export { createPausableDeadline, pauseDeadlineOf } from "./pausableDeadline.js";
|
|
22
23
|
export { calculateBackoff, createRetry, DEFAULT_RETRY_OPTIONS, RetryExhaustedError, retry, } from "./retry.js";
|
|
23
|
-
export { TimeoutError, raceWithAbort, withTimeout, withTimeoutFn, } from "./withTimeout.js";
|
|
24
|
+
export { TimeoutError, abortSignalOf, raceWithAbort, withTimeout, withTimeoutFn, } from "./withTimeout.js";
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A deadline a tool call can pause while it waits for a human.
|
|
3
|
+
*
|
|
4
|
+
* A model loop bounds each tool call. A call that needs a confirmation spends
|
|
5
|
+
* part of that bound waiting for a person, which says nothing about the tool,
|
|
6
|
+
* so the confirmation pauses the bound and resumes it afterwards with the time
|
|
7
|
+
* that was left, never a fresh one.
|
|
8
|
+
*/
|
|
9
|
+
import type { PauseDeadline, PausableDeadline } from "../../types/index.js";
|
|
10
|
+
/**
|
|
11
|
+
* Arms a deadline of `ms` that calls `onExpire` once when it runs out.
|
|
12
|
+
*
|
|
13
|
+
* - `pause()` stops the clock and returns the resume function. Paused time is
|
|
14
|
+
* not spent: resuming re-arms the timer with what was left. Pauses nest; the
|
|
15
|
+
* clock runs again only once every pause has resumed, and each resume
|
|
16
|
+
* function acts once.
|
|
17
|
+
* - `clear()` ends the deadline for good: `onExpire` never runs, and a resume
|
|
18
|
+
* that arrives later re-arms nothing.
|
|
19
|
+
*
|
|
20
|
+
* The timer is deliberately not unref'd: while a call is in flight it may be
|
|
21
|
+
* the only thing that will end a wedged tool.
|
|
22
|
+
*/
|
|
23
|
+
export declare function createPausableDeadline(ms: number, onExpire: () => void): PausableDeadline;
|
|
24
|
+
/**
|
|
25
|
+
* The `pauseDeadline` in a tool's execute options (the second argument a
|
|
26
|
+
* model loop passes), or undefined when there is none.
|
|
27
|
+
*/
|
|
28
|
+
export declare function pauseDeadlineOf(execOptions: unknown): PauseDeadline | undefined;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A deadline a tool call can pause while it waits for a human.
|
|
3
|
+
*
|
|
4
|
+
* A model loop bounds each tool call. A call that needs a confirmation spends
|
|
5
|
+
* part of that bound waiting for a person, which says nothing about the tool,
|
|
6
|
+
* so the confirmation pauses the bound and resumes it afterwards with the time
|
|
7
|
+
* that was left, never a fresh one.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Arms a deadline of `ms` that calls `onExpire` once when it runs out.
|
|
11
|
+
*
|
|
12
|
+
* - `pause()` stops the clock and returns the resume function. Paused time is
|
|
13
|
+
* not spent: resuming re-arms the timer with what was left. Pauses nest; the
|
|
14
|
+
* clock runs again only once every pause has resumed, and each resume
|
|
15
|
+
* function acts once.
|
|
16
|
+
* - `clear()` ends the deadline for good: `onExpire` never runs, and a resume
|
|
17
|
+
* that arrives later re-arms nothing.
|
|
18
|
+
*
|
|
19
|
+
* The timer is deliberately not unref'd: while a call is in flight it may be
|
|
20
|
+
* the only thing that will end a wedged tool.
|
|
21
|
+
*/
|
|
22
|
+
export function createPausableDeadline(ms, onExpire) {
|
|
23
|
+
let remaining = ms;
|
|
24
|
+
let armedAt = 0;
|
|
25
|
+
let timer;
|
|
26
|
+
let pauses = 0;
|
|
27
|
+
let ended = false;
|
|
28
|
+
const arm = () => {
|
|
29
|
+
armedAt = Date.now();
|
|
30
|
+
timer = setTimeout(() => {
|
|
31
|
+
timer = undefined;
|
|
32
|
+
ended = true;
|
|
33
|
+
onExpire();
|
|
34
|
+
}, Math.max(0, remaining));
|
|
35
|
+
};
|
|
36
|
+
const pause = () => {
|
|
37
|
+
if (ended) {
|
|
38
|
+
return () => undefined;
|
|
39
|
+
}
|
|
40
|
+
if (pauses === 0) {
|
|
41
|
+
clearTimeout(timer);
|
|
42
|
+
timer = undefined;
|
|
43
|
+
remaining -= Date.now() - armedAt;
|
|
44
|
+
}
|
|
45
|
+
pauses++;
|
|
46
|
+
let resumed = false;
|
|
47
|
+
return () => {
|
|
48
|
+
if (resumed) {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
resumed = true;
|
|
52
|
+
pauses--;
|
|
53
|
+
if (pauses === 0 && !ended) {
|
|
54
|
+
arm();
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
arm();
|
|
59
|
+
return {
|
|
60
|
+
pause,
|
|
61
|
+
clear: () => {
|
|
62
|
+
ended = true;
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
timer = undefined;
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The `pauseDeadline` in a tool's execute options (the second argument a
|
|
70
|
+
* model loop passes), or undefined when there is none.
|
|
71
|
+
*/
|
|
72
|
+
export function pauseDeadlineOf(execOptions) {
|
|
73
|
+
if (typeof execOptions !== "object" ||
|
|
74
|
+
execOptions === null ||
|
|
75
|
+
!("pauseDeadline" in execOptions)) {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
const { pauseDeadline } = execOptions;
|
|
79
|
+
if (typeof pauseDeadline !== "function") {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
// Called through a wrapper, so whatever it returns, the caller gets a
|
|
83
|
+
// resume function it can always call.
|
|
84
|
+
return () => {
|
|
85
|
+
const resume = pauseDeadline();
|
|
86
|
+
return typeof resume === "function" ? () => void resume() : () => undefined;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
@@ -61,6 +61,11 @@ export declare function withTimeout<T>(promise: Promise<T>, ms: number, message?
|
|
|
61
61
|
* is swallowed so it can never surface as an unhandled rejection.
|
|
62
62
|
*/
|
|
63
63
|
export declare function raceWithAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T>;
|
|
64
|
+
/**
|
|
65
|
+
* The `abortSignal` in a tool's execute options (the AI SDK's second
|
|
66
|
+
* argument, which every model loop fills), or undefined when there is none.
|
|
67
|
+
*/
|
|
68
|
+
export declare function abortSignalOf(execOptions: unknown): AbortSignal | undefined;
|
|
64
69
|
/**
|
|
65
70
|
* Execute a function with timeout protection.
|
|
66
71
|
*
|
|
@@ -117,6 +117,29 @@ export async function raceWithAbort(promise, signal) {
|
|
|
117
117
|
});
|
|
118
118
|
});
|
|
119
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* The `abortSignal` in a tool's execute options (the AI SDK's second
|
|
122
|
+
* argument, which every model loop fills), or undefined when there is none.
|
|
123
|
+
*/
|
|
124
|
+
export function abortSignalOf(execOptions) {
|
|
125
|
+
if (typeof execOptions !== "object" ||
|
|
126
|
+
execOptions === null ||
|
|
127
|
+
!("abortSignal" in execOptions)) {
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
const { abortSignal } = execOptions;
|
|
131
|
+
return isAbortSignalLike(abortSignal) ? abortSignal : undefined;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Recognised by shape, as ToolsManager's abort race recognises one: a signal
|
|
135
|
+
* from another realm or a polyfill is not an `instanceof AbortSignal`.
|
|
136
|
+
*/
|
|
137
|
+
function isAbortSignalLike(value) {
|
|
138
|
+
return (typeof value === "object" &&
|
|
139
|
+
value !== null &&
|
|
140
|
+
"addEventListener" in value &&
|
|
141
|
+
typeof value.addEventListener === "function");
|
|
142
|
+
}
|
|
120
143
|
/**
|
|
121
144
|
* Execute a function with timeout protection.
|
|
122
145
|
*
|
|
@@ -394,7 +394,22 @@ export declare class CircuitBreaker {
|
|
|
394
394
|
private state;
|
|
395
395
|
private name;
|
|
396
396
|
constructor(failureThreshold?: number, resetTimeoutMs?: number, name?: string);
|
|
397
|
-
|
|
397
|
+
/**
|
|
398
|
+
* Run `operation` through the breaker. An outcome `options.isCancellation`
|
|
399
|
+
* accepts stays out of the count: a failure is rethrown without being
|
|
400
|
+
* counted, and a result is returned without resetting the count. The
|
|
401
|
+
* predicate gets the error on failure and nothing on success. A call its
|
|
402
|
+
* caller cancelled says nothing about the dependency's health.
|
|
403
|
+
*/
|
|
404
|
+
execute<T>(operation: () => Promise<T>, options?: {
|
|
405
|
+
isCancellation?: (error?: unknown) => boolean;
|
|
406
|
+
}): Promise<T>;
|
|
407
|
+
/**
|
|
408
|
+
* Throw `CircuitBreakerOpenError` while the breaker is open and its reset
|
|
409
|
+
* timeout has not elapsed. Unlike `execute`, it never moves an elapsed
|
|
410
|
+
* breaker to half-open, so a caller can ask first without taking the probe.
|
|
411
|
+
*/
|
|
412
|
+
assertAvailable(): void;
|
|
398
413
|
private onSuccess;
|
|
399
414
|
private onFailure;
|
|
400
415
|
getState(): "closed" | "open" | "half-open";
|
|
@@ -410,6 +425,22 @@ export declare class CircuitBreaker {
|
|
|
410
425
|
* which destroys the exact message match.
|
|
411
426
|
*/
|
|
412
427
|
export declare function isAbortError(error: unknown): boolean;
|
|
428
|
+
/**
|
|
429
|
+
* Throw a typed, non-retriable abort error once `signal` has fired, so a call
|
|
430
|
+
* cancelled before it starts never runs. The signal's reason is kept when it
|
|
431
|
+
* is an Error (a loop's per-tool deadline names itself that way).
|
|
432
|
+
*/
|
|
433
|
+
export declare function throwIfSignalAborted(signal: AbortSignal | undefined): void;
|
|
434
|
+
/**
|
|
435
|
+
* Whether `signal` fired because a caller cancelled the call (its own signal,
|
|
436
|
+
* or the turn's abort), not because a deadline expired. A per-tool deadline
|
|
437
|
+
* (the loop engine's, the guard's, an attempt's) aborts with a reason named
|
|
438
|
+
* "TimeoutError", as `AbortSignal.timeout()`'s is too, and is evidence about
|
|
439
|
+
* the tool. Any other reason, including none, is a cancellation and is not:
|
|
440
|
+
* so a turn clock that aborts with no reason (the Vertex and AI Studio turn
|
|
441
|
+
* limits) counts as a cancellation.
|
|
442
|
+
*/
|
|
443
|
+
export declare function isCancelledByCaller(signal: AbortSignal | undefined): boolean;
|
|
413
444
|
/**
|
|
414
445
|
* Error handler that decides whether to retry based on error type
|
|
415
446
|
*/
|
|
@@ -6,7 +6,7 @@ import { ErrorCategory, ErrorSeverity } from "../constants/enums.js";
|
|
|
6
6
|
import { MAX_TIMER_MS } from "../constants/timeouts.js";
|
|
7
7
|
import { logger } from "./logger.js";
|
|
8
8
|
import { CircuitBreakerOpenError } from "../types/index.js";
|
|
9
|
-
import {
|
|
9
|
+
import { HITLError } from "../hitl/hitlErrors.js";
|
|
10
10
|
// Error codes for different scenarios
|
|
11
11
|
export const ERROR_CODES = {
|
|
12
12
|
// Tool errors
|
|
@@ -158,7 +158,9 @@ export class ErrorFactory {
|
|
|
158
158
|
message: `Tool '${toolName}' execution failed: ${originalError.message}`,
|
|
159
159
|
category: ErrorCategory.EXECUTION,
|
|
160
160
|
severity: ErrorSeverity.HIGH,
|
|
161
|
-
|
|
161
|
+
// A human's answer (or a withdrawn card) is final: retrying would raise
|
|
162
|
+
// a second card for a call that was already decided.
|
|
163
|
+
retriable: !(originalError instanceof HITLError),
|
|
162
164
|
originalError,
|
|
163
165
|
toolName,
|
|
164
166
|
serverId,
|
|
@@ -1155,30 +1157,52 @@ export class CircuitBreaker {
|
|
|
1155
1157
|
this.resetTimeoutMs = resetTimeoutMs;
|
|
1156
1158
|
this.name = name;
|
|
1157
1159
|
}
|
|
1158
|
-
|
|
1160
|
+
/**
|
|
1161
|
+
* Run `operation` through the breaker. An outcome `options.isCancellation`
|
|
1162
|
+
* accepts stays out of the count: a failure is rethrown without being
|
|
1163
|
+
* counted, and a result is returned without resetting the count. The
|
|
1164
|
+
* predicate gets the error on failure and nothing on success. A call its
|
|
1165
|
+
* caller cancelled says nothing about the dependency's health.
|
|
1166
|
+
*/
|
|
1167
|
+
async execute(operation, options) {
|
|
1159
1168
|
if (this.state === "open") {
|
|
1160
|
-
|
|
1161
|
-
if (retryAfterMs > 0) {
|
|
1162
|
-
throw new CircuitBreakerOpenError({
|
|
1163
|
-
breakerName: this.name,
|
|
1164
|
-
retryAfter: new Date(this.lastFailureTime + this.resetTimeoutMs),
|
|
1165
|
-
retryAfterMs,
|
|
1166
|
-
breakerState: "open",
|
|
1167
|
-
failureCount: this.failures,
|
|
1168
|
-
});
|
|
1169
|
-
}
|
|
1169
|
+
this.assertAvailable();
|
|
1170
1170
|
this.state = "half-open";
|
|
1171
1171
|
}
|
|
1172
1172
|
try {
|
|
1173
1173
|
const result = await operation();
|
|
1174
|
-
|
|
1174
|
+
if (!options?.isCancellation?.()) {
|
|
1175
|
+
this.onSuccess();
|
|
1176
|
+
}
|
|
1175
1177
|
return result;
|
|
1176
1178
|
}
|
|
1177
1179
|
catch (error) {
|
|
1178
|
-
|
|
1180
|
+
if (!options?.isCancellation?.(error)) {
|
|
1181
|
+
this.onFailure();
|
|
1182
|
+
}
|
|
1179
1183
|
throw error;
|
|
1180
1184
|
}
|
|
1181
1185
|
}
|
|
1186
|
+
/**
|
|
1187
|
+
* Throw `CircuitBreakerOpenError` while the breaker is open and its reset
|
|
1188
|
+
* timeout has not elapsed. Unlike `execute`, it never moves an elapsed
|
|
1189
|
+
* breaker to half-open, so a caller can ask first without taking the probe.
|
|
1190
|
+
*/
|
|
1191
|
+
assertAvailable() {
|
|
1192
|
+
if (this.state !== "open") {
|
|
1193
|
+
return;
|
|
1194
|
+
}
|
|
1195
|
+
const retryAfterMs = this.resetTimeoutMs - (Date.now() - this.lastFailureTime);
|
|
1196
|
+
if (retryAfterMs > 0) {
|
|
1197
|
+
throw new CircuitBreakerOpenError({
|
|
1198
|
+
breakerName: this.name,
|
|
1199
|
+
retryAfter: new Date(this.lastFailureTime + this.resetTimeoutMs),
|
|
1200
|
+
retryAfterMs,
|
|
1201
|
+
breakerState: "open",
|
|
1202
|
+
failureCount: this.failures,
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1182
1206
|
onSuccess() {
|
|
1183
1207
|
this.failures = 0;
|
|
1184
1208
|
this.state = "closed";
|
|
@@ -1230,16 +1254,44 @@ export function isAbortError(error) {
|
|
|
1230
1254
|
}
|
|
1231
1255
|
return false;
|
|
1232
1256
|
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Throw a typed, non-retriable abort error once `signal` has fired, so a call
|
|
1259
|
+
* cancelled before it starts never runs. The signal's reason is kept when it
|
|
1260
|
+
* is an Error (a loop's per-tool deadline names itself that way).
|
|
1261
|
+
*/
|
|
1262
|
+
export function throwIfSignalAborted(signal) {
|
|
1263
|
+
if (signal?.aborted) {
|
|
1264
|
+
throw ErrorFactory.aborted(signal.reason instanceof Error ? signal.reason : undefined);
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Whether `signal` fired because a caller cancelled the call (its own signal,
|
|
1269
|
+
* or the turn's abort), not because a deadline expired. A per-tool deadline
|
|
1270
|
+
* (the loop engine's, the guard's, an attempt's) aborts with a reason named
|
|
1271
|
+
* "TimeoutError", as `AbortSignal.timeout()`'s is too, and is evidence about
|
|
1272
|
+
* the tool. Any other reason, including none, is a cancellation and is not:
|
|
1273
|
+
* so a turn clock that aborts with no reason (the Vertex and AI Studio turn
|
|
1274
|
+
* limits) counts as a cancellation.
|
|
1275
|
+
*/
|
|
1276
|
+
export function isCancelledByCaller(signal) {
|
|
1277
|
+
if (!signal?.aborted) {
|
|
1278
|
+
return false;
|
|
1279
|
+
}
|
|
1280
|
+
const reason = signal.reason;
|
|
1281
|
+
return !(reason instanceof Error && reason.name === "TimeoutError");
|
|
1282
|
+
}
|
|
1233
1283
|
/**
|
|
1234
1284
|
* Error handler that decides whether to retry based on error type
|
|
1235
1285
|
*/
|
|
1236
1286
|
export function isRetriableError(error) {
|
|
1287
|
+
// Denied, timed-out and cancelled confirmations are decisions, not faults:
|
|
1288
|
+
// a retry would ask again, or act without the approval that was withheld.
|
|
1289
|
+
if (error instanceof HITLError) {
|
|
1290
|
+
return false;
|
|
1291
|
+
}
|
|
1237
1292
|
if (error instanceof NeuroLinkError) {
|
|
1238
1293
|
return error.retriable;
|
|
1239
1294
|
}
|
|
1240
|
-
if (error instanceof HITLTimeoutError) {
|
|
1241
|
-
return false;
|
|
1242
|
-
}
|
|
1243
1295
|
// Check for common retriable error patterns
|
|
1244
1296
|
const retriablePatterns = [
|
|
1245
1297
|
/timeout/i,
|
|
@@ -85,7 +85,11 @@ async function isProviderAvailable(providerName) {
|
|
|
85
85
|
}
|
|
86
86
|
try {
|
|
87
87
|
const provider = await AIProviderFactory.createProvider(providerName);
|
|
88
|
-
await provider.generate({
|
|
88
|
+
await provider.generate({
|
|
89
|
+
prompt: "test",
|
|
90
|
+
maxTokens: 1,
|
|
91
|
+
disableTools: true,
|
|
92
|
+
});
|
|
89
93
|
return true;
|
|
90
94
|
}
|
|
91
95
|
catch {
|