@ai-sdk/code-mode 1.0.105 → 1.0.107
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/dist/errors.js +11 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +22 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/run-code-mode.js +6 -1
- package/dist/run-code-mode.js.map +1 -1
- package/package.json +4 -4
- package/src/errors.ts +15 -0
- package/src/index.ts +1 -0
- package/src/run-code-mode.ts +11 -0
- package/src/types.ts +14 -1
package/dist/errors.js
CHANGED
|
@@ -22,6 +22,16 @@ var CodeModeTimeoutError = class extends CodeModeError {
|
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
24
|
/**
|
|
25
|
+
* Raised when sandboxed code exceeds its CPU time limit.
|
|
26
|
+
*
|
|
27
|
+
* Time spent waiting on tools does not count toward this limit.
|
|
28
|
+
*/
|
|
29
|
+
var CodeModeCpuTimeoutError = class extends CodeModeError {
|
|
30
|
+
constructor(cpuTimeoutMs) {
|
|
31
|
+
super(`Code mode execution exceeded its CPU time limit of ${cpuTimeoutMs}ms.`, "CODE_MODE_CPU_TIMEOUT", { cpuTimeoutMs });
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
25
35
|
* Raised when the outer AI SDK abort signal aborts a code-mode invocation.
|
|
26
36
|
*/
|
|
27
37
|
var CodeModeAbortedError = class extends CodeModeError {
|
|
@@ -106,6 +116,6 @@ var CodeModeToolApprovalDeniedError = class extends CodeModeToolError {
|
|
|
106
116
|
}
|
|
107
117
|
};
|
|
108
118
|
//#endregion
|
|
109
|
-
export { CodeModeAbortedError, CodeModeBridgeLimitError, CodeModeConcurrencyError, CodeModeDetachedBridgeRequestError, CodeModeError, CodeModeProtocolError, CodeModeSourceTooLargeError, CodeModeTimeoutError, CodeModeToolApprovalDeniedError, CodeModeToolApprovalRequiredError, CodeModeToolError };
|
|
119
|
+
export { CodeModeAbortedError, CodeModeBridgeLimitError, CodeModeConcurrencyError, CodeModeCpuTimeoutError, CodeModeDetachedBridgeRequestError, CodeModeError, CodeModeProtocolError, CodeModeSourceTooLargeError, CodeModeTimeoutError, CodeModeToolApprovalDeniedError, CodeModeToolApprovalRequiredError, CodeModeToolError };
|
|
110
120
|
|
|
111
121
|
//# sourceMappingURL=errors.js.map
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Base class for errors raised by code mode.\n *\n * All package-specific errors include a stable `code` string and may include\n * structured `details` for diagnostics.\n */\nexport class CodeModeError extends Error {\n /**\n * Stable machine-readable error code.\n */\n code: string;\n /**\n * Optional structured diagnostic details.\n */\n readonly details?: unknown;\n\n constructor(message: string, code = 'CODE_MODE_ERROR', details?: unknown) {\n super(message);\n this.name = new.target.name;\n this.code = code;\n this.details = details;\n }\n}\n\n/**\n * Raised when a sandbox invocation exceeds its timeout.\n */\nexport class CodeModeTimeoutError extends CodeModeError {\n constructor(timeoutMs: number) {\n super(\n `Code mode execution timed out after ${timeoutMs}ms.`,\n 'CODE_MODE_TIMEOUT',\n { timeoutMs },\n );\n }\n}\n\n/**\n * Raised when the outer AI SDK abort signal aborts a code-mode invocation.\n */\nexport class CodeModeAbortedError extends CodeModeError {\n constructor() {\n super('Code mode execution was aborted.', 'CODE_MODE_ABORTED');\n }\n}\n\n/**\n * Raised when the process-global worker cap has been reached.\n *\n * Configure the cap with `setMaxWorkers`.\n */\nexport class CodeModeConcurrencyError extends CodeModeError {\n constructor(maxWorkers: number) {\n super(\n `Code mode maxWorkers limit reached (${maxWorkers}).`,\n 'CODE_MODE_CONCURRENCY_LIMIT',\n { maxWorkers },\n );\n }\n}\n\n/**\n * Raised when the provided source exceeds `executionPolicy.maxSourceBytes`.\n */\nexport class CodeModeSourceTooLargeError extends CodeModeError {\n constructor(bytes: number, maxBytes: number) {\n super(\n `Code mode source exceeds the ${maxBytes} byte size limit.`,\n 'CODE_MODE_SOURCE_TOO_LARGE',\n { bytes, maxBytes },\n );\n }\n}\n\n/**\n * Raised when sandboxed code exceeds bridge request limits.\n */\nexport class CodeModeBridgeLimitError extends CodeModeError {\n constructor(message: string, details?: unknown) {\n super(message, 'CODE_MODE_BRIDGE_LIMIT', details);\n }\n}\n\n/**\n * Raised when sandboxed code starts host bridge work and returns without\n * awaiting or otherwise observing it.\n */\nexport class CodeModeDetachedBridgeRequestError extends CodeModeError {\n constructor(message: string, details?: unknown) {\n super(message, 'CODE_MODE_DETACHED_BRIDGE_REQUEST', details);\n }\n}\n\n/**\n * Raised when the main thread and worker protocol observes an invalid or\n * mismatched message.\n */\nexport class CodeModeProtocolError extends CodeModeError {\n constructor(message: string, details?: unknown) {\n super(message, 'CODE_MODE_PROTOCOL_ERROR', details);\n }\n}\n\n/**\n * Base class for failures caused by nested host tool execution.\n */\nexport class CodeModeToolError extends CodeModeError {\n constructor(message: string, details?: unknown) {\n super(message, 'CODE_MODE_TOOL_ERROR', details);\n }\n}\n\nexport class CodeModeToolApprovalRequiredError extends CodeModeToolError {\n constructor(toolName: string, input: unknown, toolCallId: string) {\n super(`Tool \"${toolName}\" requires approval before execution.`, {\n toolName,\n input,\n toolCallId,\n });\n this.code = 'CODE_MODE_TOOL_APPROVAL_REQUIRED';\n }\n}\n\nexport class CodeModeToolApprovalDeniedError extends CodeModeToolError {\n constructor(\n toolName: string,\n input: unknown,\n toolCallId: string,\n reason?: string,\n ) {\n super(\n `Tool \"${toolName}\" approval was denied${reason ? `: ${reason}` : '.'}`,\n {\n toolName,\n input,\n toolCallId,\n ...(reason !== undefined ? { reason } : {}),\n },\n );\n this.code = 'CODE_MODE_TOOL_APPROVAL_DENIED';\n }\n}\n"],"mappings":";;;;;;;AAMA,IAAa,gBAAb,cAAmC,MAAM;CAUvC,YAAY,SAAiB,OAAO,mBAAmB,SAAmB;EACxE,MAAM,OAAO;EACb,KAAK,OAAO,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E;GACA;GACA;GACA,GAAI,WAAW,KAAA,IAAY,EAAE,OAAO,IAAI,CAAC;EAC3C,CACF;EACA,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Base class for errors raised by code mode.\n *\n * All package-specific errors include a stable `code` string and may include\n * structured `details` for diagnostics.\n */\nexport class CodeModeError extends Error {\n /**\n * Stable machine-readable error code.\n */\n code: string;\n /**\n * Optional structured diagnostic details.\n */\n readonly details?: unknown;\n\n constructor(message: string, code = 'CODE_MODE_ERROR', details?: unknown) {\n super(message);\n this.name = new.target.name;\n this.code = code;\n this.details = details;\n }\n}\n\n/**\n * Raised when a sandbox invocation exceeds its timeout.\n */\nexport class CodeModeTimeoutError extends CodeModeError {\n constructor(timeoutMs: number) {\n super(\n `Code mode execution timed out after ${timeoutMs}ms.`,\n 'CODE_MODE_TIMEOUT',\n { timeoutMs },\n );\n }\n}\n\n/**\n * Raised when sandboxed code exceeds its CPU time limit.\n *\n * Time spent waiting on tools does not count toward this limit.\n */\nexport class CodeModeCpuTimeoutError extends CodeModeError {\n constructor(cpuTimeoutMs: number) {\n super(\n `Code mode execution exceeded its CPU time limit of ${cpuTimeoutMs}ms.`,\n 'CODE_MODE_CPU_TIMEOUT',\n { cpuTimeoutMs },\n );\n }\n}\n\n/**\n * Raised when the outer AI SDK abort signal aborts a code-mode invocation.\n */\nexport class CodeModeAbortedError extends CodeModeError {\n constructor() {\n super('Code mode execution was aborted.', 'CODE_MODE_ABORTED');\n }\n}\n\n/**\n * Raised when the process-global worker cap has been reached.\n *\n * Configure the cap with `setMaxWorkers`.\n */\nexport class CodeModeConcurrencyError extends CodeModeError {\n constructor(maxWorkers: number) {\n super(\n `Code mode maxWorkers limit reached (${maxWorkers}).`,\n 'CODE_MODE_CONCURRENCY_LIMIT',\n { maxWorkers },\n );\n }\n}\n\n/**\n * Raised when the provided source exceeds `executionPolicy.maxSourceBytes`.\n */\nexport class CodeModeSourceTooLargeError extends CodeModeError {\n constructor(bytes: number, maxBytes: number) {\n super(\n `Code mode source exceeds the ${maxBytes} byte size limit.`,\n 'CODE_MODE_SOURCE_TOO_LARGE',\n { bytes, maxBytes },\n );\n }\n}\n\n/**\n * Raised when sandboxed code exceeds bridge request limits.\n */\nexport class CodeModeBridgeLimitError extends CodeModeError {\n constructor(message: string, details?: unknown) {\n super(message, 'CODE_MODE_BRIDGE_LIMIT', details);\n }\n}\n\n/**\n * Raised when sandboxed code starts host bridge work and returns without\n * awaiting or otherwise observing it.\n */\nexport class CodeModeDetachedBridgeRequestError extends CodeModeError {\n constructor(message: string, details?: unknown) {\n super(message, 'CODE_MODE_DETACHED_BRIDGE_REQUEST', details);\n }\n}\n\n/**\n * Raised when the main thread and worker protocol observes an invalid or\n * mismatched message.\n */\nexport class CodeModeProtocolError extends CodeModeError {\n constructor(message: string, details?: unknown) {\n super(message, 'CODE_MODE_PROTOCOL_ERROR', details);\n }\n}\n\n/**\n * Base class for failures caused by nested host tool execution.\n */\nexport class CodeModeToolError extends CodeModeError {\n constructor(message: string, details?: unknown) {\n super(message, 'CODE_MODE_TOOL_ERROR', details);\n }\n}\n\nexport class CodeModeToolApprovalRequiredError extends CodeModeToolError {\n constructor(toolName: string, input: unknown, toolCallId: string) {\n super(`Tool \"${toolName}\" requires approval before execution.`, {\n toolName,\n input,\n toolCallId,\n });\n this.code = 'CODE_MODE_TOOL_APPROVAL_REQUIRED';\n }\n}\n\nexport class CodeModeToolApprovalDeniedError extends CodeModeToolError {\n constructor(\n toolName: string,\n input: unknown,\n toolCallId: string,\n reason?: string,\n ) {\n super(\n `Tool \"${toolName}\" approval was denied${reason ? `: ${reason}` : '.'}`,\n {\n toolName,\n input,\n toolCallId,\n ...(reason !== undefined ? { reason } : {}),\n },\n );\n this.code = 'CODE_MODE_TOOL_APPROVAL_DENIED';\n }\n}\n"],"mappings":";;;;;;;AAMA,IAAa,gBAAb,cAAmC,MAAM;CAUvC,YAAY,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S,wCAAwC;GAC9D;GACA;GACA;EACF,CAAC;EACD,KAAK,OAAO;CACd;AACF;AAEA,IAAa,kCAAb,cAAqD,kBAAkB;CACrE,YACE,UACA,OACA,YACA,QACA;EACA,MACE,SAAS,SAAS,uBAAuB,SAAS,KAAK,WAAW,OAClE;GACE;GACA;GACA;GACA,GAAI,WAAW,KAAA,IAAY,EAAE,OAAO,IAAI,CAAC;EAC3C,CACF;EACA,KAAK,OAAO;CACd;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -118,8 +118,21 @@ type CodeModeApprovalInterrupt = CodeModeInterrupt<CodeModeApprovalInterruptPayl
|
|
|
118
118
|
* Execution limits applied to each sandbox invocation.
|
|
119
119
|
*/
|
|
120
120
|
interface CodeModeExecutionPolicy {
|
|
121
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* Wall-clock limit for one invocation, including time spent waiting on
|
|
123
|
+
* tools.
|
|
124
|
+
*
|
|
125
|
+
* @defaultValue `30_000`
|
|
126
|
+
*/
|
|
122
127
|
timeoutMs?: number;
|
|
128
|
+
/**
|
|
129
|
+
* CPU time limit for sandboxed code in one invocation. Time spent waiting on
|
|
130
|
+
* tools does not count toward it. Only takes effect when lower than
|
|
131
|
+
* `timeoutMs`. Each continuation resume starts with a fresh budget.
|
|
132
|
+
*
|
|
133
|
+
* @defaultValue `10_000`
|
|
134
|
+
*/
|
|
135
|
+
cpuTimeoutMs?: number;
|
|
123
136
|
/** @defaultValue `64 * 1024 * 1024` */
|
|
124
137
|
memoryLimitBytes?: number;
|
|
125
138
|
/** @defaultValue `2 * 1024 * 1024` */
|
|
@@ -236,6 +249,14 @@ export declare class CodeModeError extends Error {
|
|
|
236
249
|
export declare class CodeModeTimeoutError extends CodeModeError {
|
|
237
250
|
constructor(timeoutMs: number);
|
|
238
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* Raised when sandboxed code exceeds its CPU time limit.
|
|
254
|
+
*
|
|
255
|
+
* Time spent waiting on tools does not count toward this limit.
|
|
256
|
+
*/
|
|
257
|
+
export declare class CodeModeCpuTimeoutError extends CodeModeError {
|
|
258
|
+
constructor(cpuTimeoutMs: number);
|
|
259
|
+
}
|
|
239
260
|
/**
|
|
240
261
|
* Raised when the outer AI SDK abort signal aborts a code-mode invocation.
|
|
241
262
|
*/
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/direct-tool-call.ts","../src/types.ts","../src/code-mode-tool.ts","../src/approval-continuation.ts","../src/errors.ts","../src/host-interrupt.ts","../src/interrupt-continuation.ts","../src/run-code-mode.ts","../src/continuation-capability.ts"],"mappings":";;;;;;;;qBAKa;;;;;;KCAD,kBAAkB,eAAe;;;;UAK5B;EACf;EACA,UAAU;EACV,cAAc;EACd;EACA;EACA,oBAAoB;;;;;KAMV,eAAe,KAAK;EAC9B;;;;;UAMe;;;;;;;EAOf;;KAGU;EAGN;EAAmB;;UAER;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAQe;EACf;GACC;;UAGc,4BAA4B;EAC3C;EACA,YAAY;;UAGG,kCACf,iBAAiB,2BAA2B,0BAC5C;EAEA;EACA,SAAS;EACT,YAAY;;UAGG;EACf;EACA;EACA;EACA;EACA;;;;;;;;;UAUe;EACf;EACA;EACA;EACA;EACA;EACA,sBAAsB;EACtB,aAAa;EACb,MAAM;;UA+BS,kBACf,iBAAiB,2BAA2B;EAE5C;EACA;EACA;EACA;EACA;EACA;EACA,SAAS;EACT,cAAc;;KAGJ;EACN;EAAqB;;EACrB;EAAuB,WAAW;;UAEvB,yCAAyC;EACxD;;KAGU,4BACV,kBAAkB;;;;UAKH;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/direct-tool-call.ts","../src/types.ts","../src/code-mode-tool.ts","../src/approval-continuation.ts","../src/errors.ts","../src/host-interrupt.ts","../src/interrupt-continuation.ts","../src/run-code-mode.ts","../src/continuation-capability.ts"],"mappings":";;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AqBa,4BACd,UAAU,gBACV,WAAW,4BACV;;;;;;;;;qBCtFU,sBAAsB;;;;EAIjC;;;;WAIS;EAEG,YAAA,iBAAiB,eAA0B;;;;;qBAW5C,6BAA6B;EAC5B,YAAA;;;;;;;qBAcD,gCAAgC;EAC/B,YAAA;;;;;qBAYD,6BAA6B;EAAA;;;;;;;qBAW7B,iCAAiC;EAChC,YAAA;;;;;qBAYD,oCAAoC;EACnC,YAAA,eAAe;;;;;qBAYhB,iCAAiC;EAChC,YAAA,iBAAiB;;;;;;qBASlB,2CAA2C;EAC1C,YAAA,iBAAiB;;;;;;qBASlB,8BAA8B;EAC7B,YAAA,iBAAiB;;;;;qBAQlB,0BAA0B;EACzB,YAAA,iBAAiB;;qBAKlB,0CAA0C;EACzC,YAAA,kBAAkB,gBAAgB;;qBAUnC,wCAAwC;EAEjD,YAAA,kBACA,gBACA,oBACA;;;;iBC5IY,yBACd,iBAAiB,0BACjB,SAAS;;;iBCYK,oBACd,gBACA,uBAAsB,sCACrB,SAAS;iBA0BU,0BACpB,iBAAiB,2BAA2B,0BAC5C,yBAEA,WACA,YACA,OACA,SACA;EAEA,WAAW,kBAAkB;EAC7B,YAAY;EACZ,OAAO;EACP,UAAU;EACV,uBAAuB,QAAQ;IAC7B;iBAqBY,qBACd,iBACA,uBAAsB,sCACrB;iBA0Ba,qBACd,iBACA,uBAAsB,sCACrB;;;;;;;;;;;;iBC1CmB,YAAY,OAAO,mBAAmB;;;iBCpD5C,kCACd,eAAe,YACf;EAAW"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CodeModeAbortedError, CodeModeBridgeLimitError, CodeModeConcurrencyError, CodeModeDetachedBridgeRequestError, CodeModeError, CodeModeProtocolError, CodeModeSourceTooLargeError, CodeModeTimeoutError, CodeModeToolApprovalDeniedError, CodeModeToolApprovalRequiredError, CodeModeToolError } from "./errors.js";
|
|
1
|
+
import { CodeModeAbortedError, CodeModeBridgeLimitError, CodeModeConcurrencyError, CodeModeCpuTimeoutError, CodeModeDetachedBridgeRequestError, CodeModeError, CodeModeProtocolError, CodeModeSourceTooLargeError, CodeModeTimeoutError, CodeModeToolApprovalDeniedError, CodeModeToolApprovalRequiredError, CodeModeToolError } from "./errors.js";
|
|
2
2
|
import { setCodeModeContinuationSigningKey } from "./continuation-capability.js";
|
|
3
3
|
import { runCodeMode } from "./run-code-mode.js";
|
|
4
4
|
import { continueCodeModeInterrupt, getCodeModeInterrupt, isCodeModeInterrupt, unwrapCodeModeResult } from "./interrupt-continuation.js";
|
|
@@ -7,4 +7,4 @@ import { codeModeTool, createCodeModeTool } from "./code-mode-tool.js";
|
|
|
7
7
|
import { DIRECT_TOOL_CALL } from "./direct-tool-call.js";
|
|
8
8
|
import { requestCodeModeInterrupt } from "./host-interrupt.js";
|
|
9
9
|
import { setMaxWorkers as experimental_setMaxWorkers } from "run";
|
|
10
|
-
export { CodeModeAbortedError, CodeModeBridgeLimitError, CodeModeConcurrencyError, CodeModeDetachedBridgeRequestError, CodeModeError, CodeModeProtocolError, CodeModeSourceTooLargeError, CodeModeTimeoutError, CodeModeToolApprovalDeniedError, CodeModeToolApprovalRequiredError, CodeModeToolError, DIRECT_TOOL_CALL, codeModeTool as experimental_codeModeTool, continueCodeModeApproval as experimental_continueCodeModeApproval, continueCodeModeInterrupt as experimental_continueCodeModeInterrupt, createCodeModeTool as experimental_createCodeModeTool, getCodeModeApprovalResponse as experimental_getCodeModeApprovalResponse, getCodeModeInterrupt as experimental_getCodeModeInterrupt, isCodeModeApprovalInterrupt as experimental_isCodeModeApprovalInterrupt, isCodeModeInterrupt as experimental_isCodeModeInterrupt, requestCodeModeInterrupt as experimental_requestCodeModeInterrupt, runCodeMode as experimental_runCodeMode, setCodeModeContinuationSigningKey as experimental_setCodeModeContinuationSigningKey, experimental_setMaxWorkers, toCodeModeApprovalMessages as experimental_toCodeModeApprovalMessages, unwrapCodeModeResult as experimental_unwrapCodeModeResult };
|
|
10
|
+
export { CodeModeAbortedError, CodeModeBridgeLimitError, CodeModeConcurrencyError, CodeModeCpuTimeoutError, CodeModeDetachedBridgeRequestError, CodeModeError, CodeModeProtocolError, CodeModeSourceTooLargeError, CodeModeTimeoutError, CodeModeToolApprovalDeniedError, CodeModeToolApprovalRequiredError, CodeModeToolError, DIRECT_TOOL_CALL, codeModeTool as experimental_codeModeTool, continueCodeModeApproval as experimental_continueCodeModeApproval, continueCodeModeInterrupt as experimental_continueCodeModeInterrupt, createCodeModeTool as experimental_createCodeModeTool, getCodeModeApprovalResponse as experimental_getCodeModeApprovalResponse, getCodeModeInterrupt as experimental_getCodeModeInterrupt, isCodeModeApprovalInterrupt as experimental_isCodeModeApprovalInterrupt, isCodeModeInterrupt as experimental_isCodeModeInterrupt, requestCodeModeInterrupt as experimental_requestCodeModeInterrupt, runCodeMode as experimental_runCodeMode, setCodeModeContinuationSigningKey as experimental_setCodeModeContinuationSigningKey, experimental_setMaxWorkers, toCodeModeApprovalMessages as experimental_toCodeModeApprovalMessages, unwrapCodeModeResult as experimental_unwrapCodeModeResult };
|
package/dist/run-code-mode.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CodeModeAbortedError, CodeModeBridgeLimitError, CodeModeConcurrencyError, CodeModeDetachedBridgeRequestError, CodeModeError, CodeModeProtocolError, CodeModeSourceTooLargeError, CodeModeTimeoutError, CodeModeToolApprovalDeniedError } from "./errors.js";
|
|
1
|
+
import { CodeModeAbortedError, CodeModeBridgeLimitError, CodeModeConcurrencyError, CodeModeCpuTimeoutError, CodeModeDetachedBridgeRequestError, CodeModeError, CodeModeProtocolError, CodeModeSourceTooLargeError, CodeModeTimeoutError, CodeModeToolApprovalDeniedError } from "./errors.js";
|
|
2
2
|
import { isCodeModeApprovalInterruptPayload, normalizeApprovalResolution } from "./approval.js";
|
|
3
3
|
import { resolveCodeModeContinuationSecurity, signCodeModeContinuation, verifyCodeModeContinuation } from "./continuation-capability.js";
|
|
4
4
|
import { fromJsonPayload, toJsonPayload } from "./utils/serialization.js";
|
|
@@ -10,6 +10,7 @@ import { RunError, createRunner, createSignedContinuationCodec, getHostFunctionC
|
|
|
10
10
|
const SOURCE_LINE_OFFSET = 1;
|
|
11
11
|
const MAX_RUN_LIMIT = 2147483647;
|
|
12
12
|
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
13
|
+
const DEFAULT_CPU_TIMEOUT_MS = 1e4;
|
|
13
14
|
const DEFAULT_MEMORY_LIMIT_BYTES = 67108864;
|
|
14
15
|
const DEFAULT_STACK_LIMIT_BYTES = 2097152;
|
|
15
16
|
const DEFAULT_MAX_RESULT_BYTES = 1048576;
|
|
@@ -90,6 +91,7 @@ async function runCodeMode(input) {
|
|
|
90
91
|
function resolveExecutionPolicy(policy = {}) {
|
|
91
92
|
return {
|
|
92
93
|
timeoutMs: policy.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
94
|
+
cpuTimeoutMs: policy.cpuTimeoutMs ?? DEFAULT_CPU_TIMEOUT_MS,
|
|
93
95
|
memoryLimitBytes: policy.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,
|
|
94
96
|
maxStackSizeBytes: policy.maxStackSizeBytes ?? DEFAULT_STACK_LIMIT_BYTES,
|
|
95
97
|
maxResultBytes: policy.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES,
|
|
@@ -188,6 +190,7 @@ function assertInterruptPayload(value) {
|
|
|
188
190
|
function toRunLimits(policy, source, userSource) {
|
|
189
191
|
return {
|
|
190
192
|
timeoutMs: policy.timeoutMs,
|
|
193
|
+
cpuTimeoutMs: policy.cpuTimeoutMs,
|
|
191
194
|
memoryLimitBytes: policy.memoryLimitBytes,
|
|
192
195
|
maxStackSizeBytes: policy.maxStackSizeBytes,
|
|
193
196
|
maxResultBytes: expandedSerializationLimit(policy.maxResultBytes),
|
|
@@ -309,6 +312,7 @@ function toCodeModeRuntimeError(error) {
|
|
|
309
312
|
switch (error.code) {
|
|
310
313
|
case "RUN_ABORTED": return copyStack(new CodeModeAbortedError(), error);
|
|
311
314
|
case "RUN_TIMEOUT": return copyStack(new CodeModeTimeoutError(Number(details?.timeoutMs ?? 0)), error);
|
|
315
|
+
case "RUN_CPU_TIMEOUT": return copyStack(new CodeModeCpuTimeoutError(Number(details?.cpuTimeoutMs ?? 0)), error);
|
|
312
316
|
case "RUN_CONCURRENCY_LIMIT": return copyStack(new CodeModeConcurrencyError(Number(details?.maxWorkers ?? 0)), error);
|
|
313
317
|
case "RUN_SOURCE_TOO_LARGE": return copyStack(new CodeModeSourceTooLargeError(Number(details?.bytes ?? 0), Number(details?.maxBytes ?? 0)), error);
|
|
314
318
|
case "RUN_BRIDGE_LIMIT": return copyStack(new CodeModeBridgeLimitError(error.message, error.details), error);
|
|
@@ -320,6 +324,7 @@ function toCodeModeRuntimeError(error) {
|
|
|
320
324
|
function translateLimitPath(message) {
|
|
321
325
|
for (const [runPath, codeModePath] of Object.entries({
|
|
322
326
|
"limits.timeoutMs": "executionPolicy.timeoutMs",
|
|
327
|
+
"limits.cpuTimeoutMs": "executionPolicy.cpuTimeoutMs",
|
|
323
328
|
"limits.memoryLimitBytes": "executionPolicy.memoryLimitBytes",
|
|
324
329
|
"limits.maxStackSizeBytes": "executionPolicy.maxStackSizeBytes",
|
|
325
330
|
"limits.maxResultBytes": "executionPolicy.maxResultBytes",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-code-mode.js","names":[],"sources":["../src/run-code-mode.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport { createHash } from 'node:crypto';\nimport {\n createRunner,\n createSignedContinuationCodec,\n getHostFunctionContext,\n RunError,\n type HostFunctions,\n type RunInterruption,\n type RunLimits,\n type RunResolution,\n} from 'run';\nimport {\n isCodeModeApprovalInterruptPayload,\n normalizeApprovalResolution,\n} from './approval.js';\nimport {\n resolveCodeModeContinuationSecurity,\n signCodeModeContinuation,\n verifyCodeModeContinuation,\n} from './continuation-capability.js';\nimport {\n CodeModeAbortedError,\n CodeModeBridgeLimitError,\n CodeModeConcurrencyError,\n CodeModeDetachedBridgeRequestError,\n CodeModeError,\n CodeModeProtocolError,\n CodeModeSourceTooLargeError,\n CodeModeTimeoutError,\n CodeModeToolApprovalDeniedError,\n} from './errors.js';\nimport { invokeHostTool } from './tool-invocation.js';\nimport type {\n CodeModeContinuation,\n CodeModeExecutionPolicy,\n CodeModeInterrupt,\n CodeModeInterruptExecutionContext,\n CodeModeInterruptPayload,\n CodeModePendingInterruption,\n CodeModePendingResolution,\n CodeModeToolExecutionOptions,\n RunCodeModeInput,\n} from './types.js';\nimport { fromJsonPayload, toJsonPayload } from './utils/serialization.js';\n\nconst SOURCE_LINE_OFFSET = 1;\nconst MAX_RUN_LIMIT = 2_147_483_647;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;\nconst DEFAULT_STACK_LIMIT_BYTES = 2 * 1024 * 1024;\nconst DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;\nconst DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;\nconst DEFAULT_MAX_SOURCE_BYTES = 256 * 1024;\nconst DEFAULT_MAX_TOOL_INPUT_BYTES = 1024 * 1024;\nconst DEFAULT_MAX_TOOL_OUTPUT_BYTES = 4 * 1024 * 1024;\nconst DEFAULT_MAX_BRIDGE_REQUESTS = 256;\nconst DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS = 32;\n\nlet invocationCounter = 0;\n\n/**\n * Runs one code-mode invocation directly without wrapping it as an AI SDK tool.\n *\n * The source is executed in a fresh QuickJS context with the provided host tools\n * and execution limits.\n *\n * @param input - Source code, host tools, forwarded tool execution options, and code-mode options.\n * @returns The JSON-serializable value returned by the sandboxed program.\n */\nexport async function runCodeMode(input: RunCodeModeInput): Promise<unknown> {\n const policy = resolveExecutionPolicy(input.options?.executionPolicy);\n assertSourceSize(input.js, policy.maxSourceBytes);\n\n const toolNames = Object.keys(input.tools).sort();\n const continuationState = prepareContinuation(\n input,\n toolNames,\n policy.maxToolOutputBytes,\n );\n if (continuationState.nextInterrupt !== undefined) {\n return continuationState.nextInterrupt;\n }\n\n const outerToolCallId =\n input.toolExecutionOptions?.toolCallId ??\n input.continuation?.outerToolCallId ??\n `code-mode-${++invocationCounter}`;\n const source = createCodeModeSource(input.js, toolNames);\n const codeModeErrors: CodeModeError[] = [];\n const hostFunctions = createHostFunctions({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolNames,\n });\n const continuationSecurity = resolveCodeModeContinuationSecurity(\n input.options?.continuationSecurity,\n );\n const runner = createRunner({\n continuationAudience: '@ai-sdk/code-mode/v2',\n continuationCodec: createSignedContinuationCodec({\n maxAgeMs: continuationSecurity.maxAgeMs,\n secret: createHash('sha256')\n .update(continuationSecurity.signingKey)\n .digest(),\n }),\n });\n\n try {\n const result = await runner.run({\n source,\n hostFunctions,\n limits: toRunLimits(policy, source, input.js),\n continuationContext: { outerToolCallId, toolNames },\n ...(input.toolExecutionOptions?.abortSignal === undefined\n ? {}\n : { abortSignal: input.toolExecutionOptions.abortSignal }),\n ...(continuationState.token === undefined\n ? {}\n : { continuation: continuationState.token }),\n ...(continuationState.resolutions === undefined\n ? {}\n : { resolutions: continuationState.resolutions }),\n });\n\n if (result.status === 'completed') {\n return fromJsonPayload(\n toJsonPayload(result.value, policy.maxResultBytes, 'Code mode result'),\n );\n }\n\n const pendingInterruptions = toPendingInterruptions({\n interruptions: result.interruptions,\n outerToolCallId,\n toolNames,\n });\n const continuation = signCodeModeContinuation(\n {\n version: 2,\n js: input.js,\n outerToolCallId,\n toolNames,\n token: result.continuation,\n pendingInterruptions,\n resolutions: [],\n },\n continuationSecurity,\n );\n return toCodeModeInterrupt(continuation, 0);\n } catch (error) {\n const preserved = findPreservedCodeModeError(error, codeModeErrors);\n if (preserved !== undefined) {\n throw translateSourceStack(preserved);\n }\n throw translateSourceStack(toCodeModeRuntimeError(error));\n }\n}\n\ninterface ResolvedExecutionPolicy {\n timeoutMs: number;\n memoryLimitBytes: number;\n maxStackSizeBytes: number;\n maxResultBytes: number;\n maxConsoleOutputBytes: number;\n maxSourceBytes: number;\n maxToolInputBytes: number;\n maxToolOutputBytes: number;\n maxBridgeRequests: number;\n maxInFlightBridgeRequests: number;\n}\n\nfunction resolveExecutionPolicy(\n policy: CodeModeExecutionPolicy = {},\n): ResolvedExecutionPolicy {\n return {\n timeoutMs: policy.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n memoryLimitBytes: policy.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,\n maxStackSizeBytes: policy.maxStackSizeBytes ?? DEFAULT_STACK_LIMIT_BYTES,\n maxResultBytes: policy.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES,\n maxConsoleOutputBytes:\n policy.maxConsoleOutputBytes ?? DEFAULT_MAX_CONSOLE_OUTPUT_BYTES,\n maxSourceBytes: policy.maxSourceBytes ?? DEFAULT_MAX_SOURCE_BYTES,\n maxToolInputBytes: policy.maxToolInputBytes ?? DEFAULT_MAX_TOOL_INPUT_BYTES,\n maxToolOutputBytes:\n policy.maxToolOutputBytes ?? DEFAULT_MAX_TOOL_OUTPUT_BYTES,\n maxBridgeRequests: policy.maxBridgeRequests ?? DEFAULT_MAX_BRIDGE_REQUESTS,\n maxInFlightBridgeRequests:\n policy.maxInFlightBridgeRequests ?? DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS,\n };\n}\n\nfunction assertSourceSize(source: string, maxBytes: number): void {\n if (!isValidRunLimit(maxBytes)) {\n return;\n }\n const bytes = Buffer.byteLength(source);\n if (bytes > maxBytes) {\n throw new CodeModeSourceTooLargeError(bytes, maxBytes);\n }\n}\n\nfunction createCodeModeSource(js: string, toolNames: string[]): string {\n const bindings = Object.fromEntries(\n toolNames.map((toolName, index) => [toolName, `__codeMode.tool${index}`]),\n );\n const bindingSource = Object.entries(bindings)\n .map(([name, reference]) => `${JSON.stringify(name)}:${reference}`)\n .join(',');\n return `const __codeModeBindings={${bindingSource}};const tools=new Proxy(Object.create(null),{get(_target,name){const binding=__codeModeBindings[name];return typeof binding===\"function\"?(input)=>binding(input):(input)=>__codeMode.missing(String(name),input);}});const __codeModeResult=await(async()=>{\\n${js}\\n})();if(__codeModeResult===undefined)return undefined;return JSON.parse(JSON.stringify(__codeModeResult));`;\n}\n\nfunction createHostFunctions({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolNames,\n}: {\n codeModeErrors: CodeModeError[];\n input: RunCodeModeInput;\n outerToolCallId: string;\n policy: ResolvedExecutionPolicy;\n toolNames: string[];\n}): HostFunctions {\n const group: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const [index, toolName] of toolNames.entries()) {\n group[`tool${index}`] = async (toolInput: unknown) =>\n await invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName,\n });\n }\n group.missing = async (toolName: unknown, toolInput: unknown) =>\n await invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName: String(toolName),\n });\n return { __codeMode: group } as HostFunctions;\n}\n\nasync function invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName,\n}: {\n codeModeErrors: CodeModeError[];\n input: RunCodeModeInput;\n outerToolCallId: string;\n policy: ResolvedExecutionPolicy;\n toolInput: unknown;\n toolName: string;\n}): Promise<unknown> {\n const context = getHostFunctionContext();\n const toolCallId = `${outerToolCallId}:tool-${context.requestIndex}`;\n const forwardedContext =\n input.toolExecutionOptions?.context ??\n input.toolExecutionOptions?.experimental_context;\n const forwardedExperimentalContext =\n input.toolExecutionOptions?.experimental_context ??\n input.toolExecutionOptions?.context;\n const baseExecutionOptions: CodeModeToolExecutionOptions = {\n toolCallId: outerToolCallId,\n messages: input.toolExecutionOptions?.messages ?? [],\n abortSignal: context.abortSignal,\n ...(forwardedContext === undefined ? {} : { context: forwardedContext }),\n ...(forwardedExperimentalContext === undefined\n ? {}\n : { experimental_context: forwardedExperimentalContext }),\n };\n\n let codeModeInterrupt: CodeModeInterruptExecutionContext | undefined;\n let skipApproval = false;\n if (context.resume !== undefined) {\n const payload = assertInterruptPayload(context.resume.payload);\n if (isCodeModeApprovalInterruptPayload(payload)) {\n const decision = normalizeApprovalResolution(context.resume.resolution);\n if (!decision.approved) {\n throw new CodeModeToolApprovalDeniedError(\n toolName,\n toolInput,\n toolCallId,\n decision.reason,\n );\n }\n skipApproval = true;\n } else {\n codeModeInterrupt = {\n interruptId: `${toolCallId}:interrupt`,\n payload,\n resolution: context.resume.resolution,\n };\n }\n }\n\n try {\n const inputJson = toJsonPayload(\n toolInput,\n policy.maxToolInputBytes,\n `Tool \"${toolName}\" input`,\n );\n const outcome = await invokeHostTool({\n toolName,\n inputJson,\n tools: input.tools,\n baseExecutionOptions,\n codeModeOptions: input.options ?? {},\n maxToolInputBytes: policy.maxToolInputBytes,\n maxToolOutputBytes: policy.maxToolOutputBytes,\n toolCallId,\n ...(codeModeInterrupt === undefined ? {} : { codeModeInterrupt }),\n skipApproval,\n });\n if (outcome.type === 'interrupted') {\n return context.interrupt(outcome.payload);\n }\n return fromJsonPayload(outcome.valueJson);\n } catch (error) {\n if (error instanceof CodeModeError) {\n codeModeErrors.push(error);\n throw new RunError(error.message, error.code, error.details);\n }\n if (\n RunError.isInstance(error) ||\n (error instanceof Error && error.name === 'HostFunctionInterruptSignal')\n ) {\n throw error;\n }\n throw new RunError('Host tool failed.', 'CODE_MODE_HOST_TOOL_ERROR');\n }\n}\n\nfunction assertInterruptPayload(value: unknown): CodeModeInterruptPayload {\n if (\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value) ||\n typeof (value as { kind?: unknown }).kind !== 'string'\n ) {\n throw new CodeModeProtocolError(\n 'Code mode interruption payload is malformed.',\n );\n }\n return value as CodeModeInterruptPayload;\n}\n\nfunction toRunLimits(\n policy: ResolvedExecutionPolicy,\n source: string,\n userSource: string,\n): RunLimits {\n return {\n timeoutMs: policy.timeoutMs,\n memoryLimitBytes: policy.memoryLimitBytes,\n maxStackSizeBytes: policy.maxStackSizeBytes,\n maxResultBytes: expandedSerializationLimit(policy.maxResultBytes),\n maxConsoleOutputBytes: policy.maxConsoleOutputBytes,\n maxSourceBytes: withSerializationOverhead(\n policy.maxSourceBytes,\n Buffer.byteLength(source) - Buffer.byteLength(userSource),\n ),\n maxHostFunctionArgumentsBytes: expandedSerializationLimit(\n policy.maxToolInputBytes,\n ),\n maxHostFunctionOutputBytes: expandedSerializationLimit(\n policy.maxToolOutputBytes,\n ),\n maxBridgeRequests: policy.maxBridgeRequests,\n maxInFlightBridgeRequests: policy.maxInFlightBridgeRequests,\n };\n}\n\nfunction expandedSerializationLimit(value: number): number {\n if (!isValidRunLimit(value)) {\n return value;\n }\n return Math.min(MAX_RUN_LIMIT, Math.max(4096, value * 2 + 1024));\n}\n\nfunction withSerializationOverhead(value: number, overhead: number): number {\n return isValidRunLimit(value)\n ? Math.min(MAX_RUN_LIMIT, value + overhead)\n : value;\n}\n\nfunction isValidRunLimit(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_RUN_LIMIT;\n}\n\nfunction prepareContinuation(\n input: RunCodeModeInput,\n toolNames: string[],\n maxToolOutputBytes: number,\n): {\n token?: string;\n resolutions?: RunResolution[];\n nextInterrupt?: CodeModeInterrupt;\n} {\n if (input.continuation === undefined) {\n if (input.interruptResolution !== undefined) {\n throw new CodeModeProtocolError(\n 'A code-mode interrupt resolution was provided without continuation state.',\n );\n }\n return {};\n }\n\n verifyCodeModeContinuation(\n input.continuation,\n input.options?.continuationSecurity,\n );\n if (input.continuation.js !== input.js) {\n throw new CodeModeProtocolError(\n 'Code mode continuation source does not match the resumed source.',\n );\n }\n if (!stringArraysEqual(input.continuation.toolNames, toolNames)) {\n throw new CodeModeProtocolError(\n 'Code mode continuation tool names do not match the resumed tools.',\n );\n }\n if (input.interruptResolution === undefined) {\n throw new CodeModeProtocolError(\n 'A code-mode continuation requires an interrupt resolution.',\n );\n }\n\n const resolutionIndex = input.continuation.resolutions.length;\n const pending = input.continuation.pendingInterruptions[resolutionIndex];\n if (\n pending === undefined ||\n pending.interruptId !== input.interruptResolution.interruptId\n ) {\n throw new CodeModeProtocolError(\n 'Interrupt resolution does not match the next pending code-mode interruption.',\n { interruptId: input.interruptResolution.interruptId },\n );\n }\n const resolutionValue = normalizeResolutionForPending(\n pending,\n input.interruptResolution.resolution,\n maxToolOutputBytes,\n );\n const resolutions: CodeModePendingResolution[] = [\n ...input.continuation.resolutions,\n {\n runInterruptionId: pending.runInterruptionId,\n value: resolutionValue,\n },\n ];\n\n if (resolutions.length < input.continuation.pendingInterruptions.length) {\n const continuation = signCodeModeContinuation(\n {\n ...withoutAuth(input.continuation),\n resolutions,\n },\n resolveCodeModeContinuationSecurity(input.options?.continuationSecurity),\n );\n return {\n nextInterrupt: toCodeModeInterrupt(continuation, resolutions.length),\n };\n }\n\n assertNoDeniedApproval(input.continuation.pendingInterruptions, resolutions);\n return {\n token: input.continuation.token,\n resolutions: resolutions.map(resolution => ({\n interruptionId: resolution.runInterruptionId,\n value: resolution.value,\n })),\n };\n}\n\nfunction normalizeResolutionForPending(\n pending: CodeModePendingInterruption,\n resolution: unknown,\n maxToolOutputBytes: number,\n): unknown {\n return isCodeModeApprovalInterruptPayload(pending.payload)\n ? normalizeApprovalResolution(resolution)\n : fromJsonPayload(\n toJsonPayload(\n resolution,\n maxToolOutputBytes,\n `Resolution \"${pending.interruptId}\"`,\n ),\n );\n}\n\nfunction assertNoDeniedApproval(\n pendingInterruptions: CodeModePendingInterruption[],\n resolutions: CodeModePendingResolution[],\n): void {\n for (const [index, pending] of pendingInterruptions.entries()) {\n if (!isCodeModeApprovalInterruptPayload(pending.payload)) {\n continue;\n }\n const decision = normalizeApprovalResolution(resolutions[index]?.value);\n if (!decision.approved) {\n throw new CodeModeToolApprovalDeniedError(\n pending.toolName,\n pending.input,\n pending.toolCallId,\n decision.reason,\n );\n }\n }\n}\n\nfunction withoutAuth(\n continuation: CodeModeContinuation,\n): Omit<CodeModeContinuation, 'auth'> {\n const { auth: _auth, ...unsigned } = continuation;\n return unsigned;\n}\n\nfunction toPendingInterruptions({\n interruptions,\n outerToolCallId,\n toolNames,\n}: {\n interruptions: RunInterruption[];\n outerToolCallId: string;\n toolNames: string[];\n}): CodeModePendingInterruption[] {\n return interruptions.map(interruption => {\n const requestIndex = interruptionIndex(interruption.id);\n const toolName = toolNameForInterruption(interruption, toolNames);\n const toolCallId = `${outerToolCallId}:tool-${requestIndex}`;\n return {\n runInterruptionId: interruption.id,\n interruptId: `${toolCallId}:interrupt`,\n toolName,\n toolCallId,\n input:\n interruption.hostFunctionName === '__codeMode.missing'\n ? interruption.arguments[1]\n : interruption.arguments[0],\n payload: assertInterruptPayload(interruption.payload),\n };\n });\n}\n\nfunction interruptionIndex(interruptionId: string): number {\n const match = /^interrupt-(\\d+)$/u.exec(interruptionId);\n if (match === null) {\n throw new CodeModeProtocolError(\n `Run returned malformed interruption id \"${interruptionId}\".`,\n );\n }\n return Number(match[1]);\n}\n\nfunction toolNameForInterruption(\n interruption: RunInterruption,\n toolNames: string[],\n): string {\n if (interruption.hostFunctionName === '__codeMode.missing') {\n return String(interruption.arguments[0]);\n }\n const match = /^__codeMode\\.tool(\\d+)$/u.exec(interruption.hostFunctionName);\n const toolName = match === null ? undefined : toolNames[Number(match[1])];\n if (toolName === undefined) {\n throw new CodeModeProtocolError(\n `Run returned an unknown code-mode host function \"${interruption.hostFunctionName}\".`,\n );\n }\n return toolName;\n}\n\nfunction toCodeModeInterrupt(\n continuation: CodeModeContinuation,\n index: number,\n): CodeModeInterrupt {\n const pending = continuation.pendingInterruptions[index];\n if (pending === undefined) {\n throw new CodeModeProtocolError(\n 'Code mode continuation has no pending interruption at the requested index.',\n );\n }\n return {\n type: 'code-mode-interrupt',\n interruptId: pending.interruptId,\n toolName: pending.toolName,\n toolCallId: pending.toolCallId,\n outerToolCallId: continuation.outerToolCallId,\n input: structuredClone(pending.input),\n payload: structuredClone(pending.payload),\n continuation,\n };\n}\n\nfunction stringArraysEqual(left: string[], right: string[]): boolean {\n return (\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n );\n}\n\nfunction findPreservedCodeModeError(\n error: unknown,\n errors: CodeModeError[],\n): CodeModeError | undefined {\n if (!RunError.isInstance(error)) {\n return undefined;\n }\n return errors.find(candidate => candidate.code === error.code);\n}\n\nfunction toCodeModeRuntimeError(error: unknown): unknown {\n if (error instanceof TypeError) {\n error.message = translateLimitPath(error.message);\n }\n if (\n error instanceof Error &&\n error.name === 'SyntaxError' &&\n !/syntax|unexpected|expression expected/iu.test(error.message)\n ) {\n error.message = `Syntax error: ${error.message}`;\n }\n if (!RunError.isInstance(error)) {\n return error;\n }\n const details = error.details as Record<string, unknown> | undefined;\n switch (error.code) {\n case 'RUN_ABORTED':\n return copyStack(new CodeModeAbortedError(), error);\n case 'RUN_TIMEOUT':\n return copyStack(\n new CodeModeTimeoutError(Number(details?.timeoutMs ?? 0)),\n error,\n );\n case 'RUN_CONCURRENCY_LIMIT':\n return copyStack(\n new CodeModeConcurrencyError(Number(details?.maxWorkers ?? 0)),\n error,\n );\n case 'RUN_SOURCE_TOO_LARGE':\n return copyStack(\n new CodeModeSourceTooLargeError(\n Number(details?.bytes ?? 0),\n Number(details?.maxBytes ?? 0),\n ),\n error,\n );\n case 'RUN_BRIDGE_LIMIT':\n return copyStack(\n new CodeModeBridgeLimitError(error.message, error.details),\n error,\n );\n case 'RUN_DETACHED_BRIDGE_REQUEST':\n return copyStack(\n new CodeModeDetachedBridgeRequestError(error.message, error.details),\n error,\n );\n case 'RUN_PROTOCOL_ERROR':\n return copyStack(\n new CodeModeProtocolError(error.message, error.details),\n error,\n );\n default:\n return error;\n }\n}\n\nfunction translateLimitPath(message: string): string {\n const paths: Record<string, string> = {\n 'limits.timeoutMs': 'executionPolicy.timeoutMs',\n 'limits.memoryLimitBytes': 'executionPolicy.memoryLimitBytes',\n 'limits.maxStackSizeBytes': 'executionPolicy.maxStackSizeBytes',\n 'limits.maxResultBytes': 'executionPolicy.maxResultBytes',\n 'limits.maxConsoleOutputBytes': 'executionPolicy.maxConsoleOutputBytes',\n 'limits.maxSourceBytes': 'executionPolicy.maxSourceBytes',\n 'limits.maxHostFunctionArgumentsBytes': 'executionPolicy.maxToolInputBytes',\n 'limits.maxHostFunctionOutputBytes': 'executionPolicy.maxToolOutputBytes',\n 'limits.maxBridgeRequests': 'executionPolicy.maxBridgeRequests',\n 'limits.maxInFlightBridgeRequests':\n 'executionPolicy.maxInFlightBridgeRequests',\n };\n for (const [runPath, codeModePath] of Object.entries(paths)) {\n if (message.includes(runPath)) {\n return message.replace(runPath, codeModePath);\n }\n }\n return message;\n}\n\nfunction copyStack<T extends Error>(target: T, source: Error): T {\n if (source.stack !== undefined) {\n target.stack = source.stack;\n }\n return target;\n}\n\nfunction translateSourceStack<T>(error: T): T {\n if (!(error instanceof Error) || error.stack === undefined) {\n return error;\n }\n error.stack = error.stack.replaceAll(\n /run\\.js:(\\d+):(\\d+)/gu,\n (_match, line: string, column: string) =>\n `code-mode.js:${Math.max(1, Number(line) - SOURCE_LINE_OFFSET)}:${column}`,\n );\n return error;\n}\n"],"mappings":";;;;;;;;;AA8CA,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AACnC,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,mCAAmC;AACzC,MAAM,2BAA2B;AACjC,MAAM,+BAA+B;AACrC,MAAM,gCAAgC;AACtC,MAAM,8BAA8B;AACpC,MAAM,wCAAwC;AAE9C,IAAI,oBAAoB;;;;;;;;;;AAWxB,eAAsB,YAAY,OAA2C;CAC3E,MAAM,SAAS,uBAAuB,MAAM,SAAS,eAAe;CACpE,iBAAiB,MAAM,IAAI,OAAO,cAAc;CAEhD,MAAM,YAAY,OAAO,KAAK,MAAM,KAAK,CAAC,CAA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/B,GACA,KACF;EACF,KAAK,oBACH,OAAO,UACL,IAAI,yBAAyB,MAAM,SAAS,MAAM,OAAO,GACzD,KACF;EACF,KAAK,+BACH,OAAO,UACL,IAAI,mCAAmC,MAAM,SAAS,MAAM,OAAO,GACnE,KACF;EACF,KAAK,sBACH,OAAO,UACL,IAAI,sBAAsB,MAAM,SAAS,MAAM,OAAO,GACtD,KACF;EACF,SACE,OAAO;CACX;AACF;AAEA,SAAS,mBAAmB,SAAyB;CAcnD,KAAK,MAAM,CAAC,SAAS,iBAAiB,OAAO,QAAQ;EAZnD,oBAAoB;EACpB,2BAA2B;EAC3B,4BAA4B;EAC5B,yBAAyB;EACzB,gCAAgC;EAChC,yBAAyB;EACzB,wCAAwC;EACxC,qCAAqC;EACrC,4BAA4B;EAC5B,oCACE;CAEqD,CAAC,GACxD,IAAI,QAAQ,SAAS,OAAO,GAC1B,OAAO,QAAQ,QAAQ,SAAS,YAAY;CAGhD,OAAO;AACT;AAEA,SAAS,UAA2B,QAAW,QAAkB;CAC/D,IAAI,OAAO,UAAU,KAAA,GACnB,OAAO,QAAQ,OAAO;CAExB,OAAO;AACT;AAEA,SAAS,qBAAwB,OAAa;CAC5C,IAAI,EAAE,iBAAiB,UAAU,MAAM,UAAU,KAAA,GAC/C,OAAO;CAET,MAAM,QAAQ,MAAM,MAAM,WACxB,0BACC,QAAQ,MAAc,WACrB,gBAAgB,KAAK,IAAI,GAAG,OAAO,IAAI,IAAI,kBAAkB,EAAE,GAAG,QACtE;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"run-code-mode.js","names":[],"sources":["../src/run-code-mode.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport { createHash } from 'node:crypto';\nimport {\n createRunner,\n createSignedContinuationCodec,\n getHostFunctionContext,\n RunError,\n type HostFunctions,\n type RunInterruption,\n type RunLimits,\n type RunResolution,\n} from 'run';\nimport {\n isCodeModeApprovalInterruptPayload,\n normalizeApprovalResolution,\n} from './approval.js';\nimport {\n resolveCodeModeContinuationSecurity,\n signCodeModeContinuation,\n verifyCodeModeContinuation,\n} from './continuation-capability.js';\nimport {\n CodeModeAbortedError,\n CodeModeBridgeLimitError,\n CodeModeConcurrencyError,\n CodeModeCpuTimeoutError,\n CodeModeDetachedBridgeRequestError,\n CodeModeError,\n CodeModeProtocolError,\n CodeModeSourceTooLargeError,\n CodeModeTimeoutError,\n CodeModeToolApprovalDeniedError,\n} from './errors.js';\nimport { invokeHostTool } from './tool-invocation.js';\nimport type {\n CodeModeContinuation,\n CodeModeExecutionPolicy,\n CodeModeInterrupt,\n CodeModeInterruptExecutionContext,\n CodeModeInterruptPayload,\n CodeModePendingInterruption,\n CodeModePendingResolution,\n CodeModeToolExecutionOptions,\n RunCodeModeInput,\n} from './types.js';\nimport { fromJsonPayload, toJsonPayload } from './utils/serialization.js';\n\nconst SOURCE_LINE_OFFSET = 1;\nconst MAX_RUN_LIMIT = 2_147_483_647;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_CPU_TIMEOUT_MS = 10_000;\nconst DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;\nconst DEFAULT_STACK_LIMIT_BYTES = 2 * 1024 * 1024;\nconst DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;\nconst DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;\nconst DEFAULT_MAX_SOURCE_BYTES = 256 * 1024;\nconst DEFAULT_MAX_TOOL_INPUT_BYTES = 1024 * 1024;\nconst DEFAULT_MAX_TOOL_OUTPUT_BYTES = 4 * 1024 * 1024;\nconst DEFAULT_MAX_BRIDGE_REQUESTS = 256;\nconst DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS = 32;\n\nlet invocationCounter = 0;\n\n/**\n * Runs one code-mode invocation directly without wrapping it as an AI SDK tool.\n *\n * The source is executed in a fresh QuickJS context with the provided host tools\n * and execution limits.\n *\n * @param input - Source code, host tools, forwarded tool execution options, and code-mode options.\n * @returns The JSON-serializable value returned by the sandboxed program.\n */\nexport async function runCodeMode(input: RunCodeModeInput): Promise<unknown> {\n const policy = resolveExecutionPolicy(input.options?.executionPolicy);\n assertSourceSize(input.js, policy.maxSourceBytes);\n\n const toolNames = Object.keys(input.tools).sort();\n const continuationState = prepareContinuation(\n input,\n toolNames,\n policy.maxToolOutputBytes,\n );\n if (continuationState.nextInterrupt !== undefined) {\n return continuationState.nextInterrupt;\n }\n\n const outerToolCallId =\n input.toolExecutionOptions?.toolCallId ??\n input.continuation?.outerToolCallId ??\n `code-mode-${++invocationCounter}`;\n const source = createCodeModeSource(input.js, toolNames);\n const codeModeErrors: CodeModeError[] = [];\n const hostFunctions = createHostFunctions({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolNames,\n });\n const continuationSecurity = resolveCodeModeContinuationSecurity(\n input.options?.continuationSecurity,\n );\n const runner = createRunner({\n continuationAudience: '@ai-sdk/code-mode/v2',\n continuationCodec: createSignedContinuationCodec({\n maxAgeMs: continuationSecurity.maxAgeMs,\n secret: createHash('sha256')\n .update(continuationSecurity.signingKey)\n .digest(),\n }),\n });\n\n try {\n const result = await runner.run({\n source,\n hostFunctions,\n limits: toRunLimits(policy, source, input.js),\n continuationContext: { outerToolCallId, toolNames },\n ...(input.toolExecutionOptions?.abortSignal === undefined\n ? {}\n : { abortSignal: input.toolExecutionOptions.abortSignal }),\n ...(continuationState.token === undefined\n ? {}\n : { continuation: continuationState.token }),\n ...(continuationState.resolutions === undefined\n ? {}\n : { resolutions: continuationState.resolutions }),\n });\n\n if (result.status === 'completed') {\n return fromJsonPayload(\n toJsonPayload(result.value, policy.maxResultBytes, 'Code mode result'),\n );\n }\n\n const pendingInterruptions = toPendingInterruptions({\n interruptions: result.interruptions,\n outerToolCallId,\n toolNames,\n });\n const continuation = signCodeModeContinuation(\n {\n version: 2,\n js: input.js,\n outerToolCallId,\n toolNames,\n token: result.continuation,\n pendingInterruptions,\n resolutions: [],\n },\n continuationSecurity,\n );\n return toCodeModeInterrupt(continuation, 0);\n } catch (error) {\n const preserved = findPreservedCodeModeError(error, codeModeErrors);\n if (preserved !== undefined) {\n throw translateSourceStack(preserved);\n }\n throw translateSourceStack(toCodeModeRuntimeError(error));\n }\n}\n\ninterface ResolvedExecutionPolicy {\n timeoutMs: number;\n cpuTimeoutMs: number;\n memoryLimitBytes: number;\n maxStackSizeBytes: number;\n maxResultBytes: number;\n maxConsoleOutputBytes: number;\n maxSourceBytes: number;\n maxToolInputBytes: number;\n maxToolOutputBytes: number;\n maxBridgeRequests: number;\n maxInFlightBridgeRequests: number;\n}\n\nfunction resolveExecutionPolicy(\n policy: CodeModeExecutionPolicy = {},\n): ResolvedExecutionPolicy {\n return {\n timeoutMs: policy.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n cpuTimeoutMs: policy.cpuTimeoutMs ?? DEFAULT_CPU_TIMEOUT_MS,\n memoryLimitBytes: policy.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,\n maxStackSizeBytes: policy.maxStackSizeBytes ?? DEFAULT_STACK_LIMIT_BYTES,\n maxResultBytes: policy.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES,\n maxConsoleOutputBytes:\n policy.maxConsoleOutputBytes ?? DEFAULT_MAX_CONSOLE_OUTPUT_BYTES,\n maxSourceBytes: policy.maxSourceBytes ?? DEFAULT_MAX_SOURCE_BYTES,\n maxToolInputBytes: policy.maxToolInputBytes ?? DEFAULT_MAX_TOOL_INPUT_BYTES,\n maxToolOutputBytes:\n policy.maxToolOutputBytes ?? DEFAULT_MAX_TOOL_OUTPUT_BYTES,\n maxBridgeRequests: policy.maxBridgeRequests ?? DEFAULT_MAX_BRIDGE_REQUESTS,\n maxInFlightBridgeRequests:\n policy.maxInFlightBridgeRequests ?? DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS,\n };\n}\n\nfunction assertSourceSize(source: string, maxBytes: number): void {\n if (!isValidRunLimit(maxBytes)) {\n return;\n }\n const bytes = Buffer.byteLength(source);\n if (bytes > maxBytes) {\n throw new CodeModeSourceTooLargeError(bytes, maxBytes);\n }\n}\n\nfunction createCodeModeSource(js: string, toolNames: string[]): string {\n const bindings = Object.fromEntries(\n toolNames.map((toolName, index) => [toolName, `__codeMode.tool${index}`]),\n );\n const bindingSource = Object.entries(bindings)\n .map(([name, reference]) => `${JSON.stringify(name)}:${reference}`)\n .join(',');\n return `const __codeModeBindings={${bindingSource}};const tools=new Proxy(Object.create(null),{get(_target,name){const binding=__codeModeBindings[name];return typeof binding===\"function\"?(input)=>binding(input):(input)=>__codeMode.missing(String(name),input);}});const __codeModeResult=await(async()=>{\\n${js}\\n})();if(__codeModeResult===undefined)return undefined;return JSON.parse(JSON.stringify(__codeModeResult));`;\n}\n\nfunction createHostFunctions({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolNames,\n}: {\n codeModeErrors: CodeModeError[];\n input: RunCodeModeInput;\n outerToolCallId: string;\n policy: ResolvedExecutionPolicy;\n toolNames: string[];\n}): HostFunctions {\n const group: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const [index, toolName] of toolNames.entries()) {\n group[`tool${index}`] = async (toolInput: unknown) =>\n await invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName,\n });\n }\n group.missing = async (toolName: unknown, toolInput: unknown) =>\n await invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName: String(toolName),\n });\n return { __codeMode: group } as HostFunctions;\n}\n\nasync function invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName,\n}: {\n codeModeErrors: CodeModeError[];\n input: RunCodeModeInput;\n outerToolCallId: string;\n policy: ResolvedExecutionPolicy;\n toolInput: unknown;\n toolName: string;\n}): Promise<unknown> {\n const context = getHostFunctionContext();\n const toolCallId = `${outerToolCallId}:tool-${context.requestIndex}`;\n const forwardedContext =\n input.toolExecutionOptions?.context ??\n input.toolExecutionOptions?.experimental_context;\n const forwardedExperimentalContext =\n input.toolExecutionOptions?.experimental_context ??\n input.toolExecutionOptions?.context;\n const baseExecutionOptions: CodeModeToolExecutionOptions = {\n toolCallId: outerToolCallId,\n messages: input.toolExecutionOptions?.messages ?? [],\n abortSignal: context.abortSignal,\n ...(forwardedContext === undefined ? {} : { context: forwardedContext }),\n ...(forwardedExperimentalContext === undefined\n ? {}\n : { experimental_context: forwardedExperimentalContext }),\n };\n\n let codeModeInterrupt: CodeModeInterruptExecutionContext | undefined;\n let skipApproval = false;\n if (context.resume !== undefined) {\n const payload = assertInterruptPayload(context.resume.payload);\n if (isCodeModeApprovalInterruptPayload(payload)) {\n const decision = normalizeApprovalResolution(context.resume.resolution);\n if (!decision.approved) {\n throw new CodeModeToolApprovalDeniedError(\n toolName,\n toolInput,\n toolCallId,\n decision.reason,\n );\n }\n skipApproval = true;\n } else {\n codeModeInterrupt = {\n interruptId: `${toolCallId}:interrupt`,\n payload,\n resolution: context.resume.resolution,\n };\n }\n }\n\n try {\n const inputJson = toJsonPayload(\n toolInput,\n policy.maxToolInputBytes,\n `Tool \"${toolName}\" input`,\n );\n const outcome = await invokeHostTool({\n toolName,\n inputJson,\n tools: input.tools,\n baseExecutionOptions,\n codeModeOptions: input.options ?? {},\n maxToolInputBytes: policy.maxToolInputBytes,\n maxToolOutputBytes: policy.maxToolOutputBytes,\n toolCallId,\n ...(codeModeInterrupt === undefined ? {} : { codeModeInterrupt }),\n skipApproval,\n });\n if (outcome.type === 'interrupted') {\n return context.interrupt(outcome.payload);\n }\n return fromJsonPayload(outcome.valueJson);\n } catch (error) {\n if (error instanceof CodeModeError) {\n codeModeErrors.push(error);\n throw new RunError(error.message, error.code, error.details);\n }\n if (\n RunError.isInstance(error) ||\n (error instanceof Error && error.name === 'HostFunctionInterruptSignal')\n ) {\n throw error;\n }\n throw new RunError('Host tool failed.', 'CODE_MODE_HOST_TOOL_ERROR');\n }\n}\n\nfunction assertInterruptPayload(value: unknown): CodeModeInterruptPayload {\n if (\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value) ||\n typeof (value as { kind?: unknown }).kind !== 'string'\n ) {\n throw new CodeModeProtocolError(\n 'Code mode interruption payload is malformed.',\n );\n }\n return value as CodeModeInterruptPayload;\n}\n\nfunction toRunLimits(\n policy: ResolvedExecutionPolicy,\n source: string,\n userSource: string,\n): RunLimits {\n return {\n timeoutMs: policy.timeoutMs,\n cpuTimeoutMs: policy.cpuTimeoutMs,\n memoryLimitBytes: policy.memoryLimitBytes,\n maxStackSizeBytes: policy.maxStackSizeBytes,\n maxResultBytes: expandedSerializationLimit(policy.maxResultBytes),\n maxConsoleOutputBytes: policy.maxConsoleOutputBytes,\n maxSourceBytes: withSerializationOverhead(\n policy.maxSourceBytes,\n Buffer.byteLength(source) - Buffer.byteLength(userSource),\n ),\n maxHostFunctionArgumentsBytes: expandedSerializationLimit(\n policy.maxToolInputBytes,\n ),\n maxHostFunctionOutputBytes: expandedSerializationLimit(\n policy.maxToolOutputBytes,\n ),\n maxBridgeRequests: policy.maxBridgeRequests,\n maxInFlightBridgeRequests: policy.maxInFlightBridgeRequests,\n };\n}\n\nfunction expandedSerializationLimit(value: number): number {\n if (!isValidRunLimit(value)) {\n return value;\n }\n return Math.min(MAX_RUN_LIMIT, Math.max(4096, value * 2 + 1024));\n}\n\nfunction withSerializationOverhead(value: number, overhead: number): number {\n return isValidRunLimit(value)\n ? Math.min(MAX_RUN_LIMIT, value + overhead)\n : value;\n}\n\nfunction isValidRunLimit(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_RUN_LIMIT;\n}\n\nfunction prepareContinuation(\n input: RunCodeModeInput,\n toolNames: string[],\n maxToolOutputBytes: number,\n): {\n token?: string;\n resolutions?: RunResolution[];\n nextInterrupt?: CodeModeInterrupt;\n} {\n if (input.continuation === undefined) {\n if (input.interruptResolution !== undefined) {\n throw new CodeModeProtocolError(\n 'A code-mode interrupt resolution was provided without continuation state.',\n );\n }\n return {};\n }\n\n verifyCodeModeContinuation(\n input.continuation,\n input.options?.continuationSecurity,\n );\n if (input.continuation.js !== input.js) {\n throw new CodeModeProtocolError(\n 'Code mode continuation source does not match the resumed source.',\n );\n }\n if (!stringArraysEqual(input.continuation.toolNames, toolNames)) {\n throw new CodeModeProtocolError(\n 'Code mode continuation tool names do not match the resumed tools.',\n );\n }\n if (input.interruptResolution === undefined) {\n throw new CodeModeProtocolError(\n 'A code-mode continuation requires an interrupt resolution.',\n );\n }\n\n const resolutionIndex = input.continuation.resolutions.length;\n const pending = input.continuation.pendingInterruptions[resolutionIndex];\n if (\n pending === undefined ||\n pending.interruptId !== input.interruptResolution.interruptId\n ) {\n throw new CodeModeProtocolError(\n 'Interrupt resolution does not match the next pending code-mode interruption.',\n { interruptId: input.interruptResolution.interruptId },\n );\n }\n const resolutionValue = normalizeResolutionForPending(\n pending,\n input.interruptResolution.resolution,\n maxToolOutputBytes,\n );\n const resolutions: CodeModePendingResolution[] = [\n ...input.continuation.resolutions,\n {\n runInterruptionId: pending.runInterruptionId,\n value: resolutionValue,\n },\n ];\n\n if (resolutions.length < input.continuation.pendingInterruptions.length) {\n const continuation = signCodeModeContinuation(\n {\n ...withoutAuth(input.continuation),\n resolutions,\n },\n resolveCodeModeContinuationSecurity(input.options?.continuationSecurity),\n );\n return {\n nextInterrupt: toCodeModeInterrupt(continuation, resolutions.length),\n };\n }\n\n assertNoDeniedApproval(input.continuation.pendingInterruptions, resolutions);\n return {\n token: input.continuation.token,\n resolutions: resolutions.map(resolution => ({\n interruptionId: resolution.runInterruptionId,\n value: resolution.value,\n })),\n };\n}\n\nfunction normalizeResolutionForPending(\n pending: CodeModePendingInterruption,\n resolution: unknown,\n maxToolOutputBytes: number,\n): unknown {\n return isCodeModeApprovalInterruptPayload(pending.payload)\n ? normalizeApprovalResolution(resolution)\n : fromJsonPayload(\n toJsonPayload(\n resolution,\n maxToolOutputBytes,\n `Resolution \"${pending.interruptId}\"`,\n ),\n );\n}\n\nfunction assertNoDeniedApproval(\n pendingInterruptions: CodeModePendingInterruption[],\n resolutions: CodeModePendingResolution[],\n): void {\n for (const [index, pending] of pendingInterruptions.entries()) {\n if (!isCodeModeApprovalInterruptPayload(pending.payload)) {\n continue;\n }\n const decision = normalizeApprovalResolution(resolutions[index]?.value);\n if (!decision.approved) {\n throw new CodeModeToolApprovalDeniedError(\n pending.toolName,\n pending.input,\n pending.toolCallId,\n decision.reason,\n );\n }\n }\n}\n\nfunction withoutAuth(\n continuation: CodeModeContinuation,\n): Omit<CodeModeContinuation, 'auth'> {\n const { auth: _auth, ...unsigned } = continuation;\n return unsigned;\n}\n\nfunction toPendingInterruptions({\n interruptions,\n outerToolCallId,\n toolNames,\n}: {\n interruptions: RunInterruption[];\n outerToolCallId: string;\n toolNames: string[];\n}): CodeModePendingInterruption[] {\n return interruptions.map(interruption => {\n const requestIndex = interruptionIndex(interruption.id);\n const toolName = toolNameForInterruption(interruption, toolNames);\n const toolCallId = `${outerToolCallId}:tool-${requestIndex}`;\n return {\n runInterruptionId: interruption.id,\n interruptId: `${toolCallId}:interrupt`,\n toolName,\n toolCallId,\n input:\n interruption.hostFunctionName === '__codeMode.missing'\n ? interruption.arguments[1]\n : interruption.arguments[0],\n payload: assertInterruptPayload(interruption.payload),\n };\n });\n}\n\nfunction interruptionIndex(interruptionId: string): number {\n const match = /^interrupt-(\\d+)$/u.exec(interruptionId);\n if (match === null) {\n throw new CodeModeProtocolError(\n `Run returned malformed interruption id \"${interruptionId}\".`,\n );\n }\n return Number(match[1]);\n}\n\nfunction toolNameForInterruption(\n interruption: RunInterruption,\n toolNames: string[],\n): string {\n if (interruption.hostFunctionName === '__codeMode.missing') {\n return String(interruption.arguments[0]);\n }\n const match = /^__codeMode\\.tool(\\d+)$/u.exec(interruption.hostFunctionName);\n const toolName = match === null ? undefined : toolNames[Number(match[1])];\n if (toolName === undefined) {\n throw new CodeModeProtocolError(\n `Run returned an unknown code-mode host function \"${interruption.hostFunctionName}\".`,\n );\n }\n return toolName;\n}\n\nfunction toCodeModeInterrupt(\n continuation: CodeModeContinuation,\n index: number,\n): CodeModeInterrupt {\n const pending = continuation.pendingInterruptions[index];\n if (pending === undefined) {\n throw new CodeModeProtocolError(\n 'Code mode continuation has no pending interruption at the requested index.',\n );\n }\n return {\n type: 'code-mode-interrupt',\n interruptId: pending.interruptId,\n toolName: pending.toolName,\n toolCallId: pending.toolCallId,\n outerToolCallId: continuation.outerToolCallId,\n input: structuredClone(pending.input),\n payload: structuredClone(pending.payload),\n continuation,\n };\n}\n\nfunction stringArraysEqual(left: string[], right: string[]): boolean {\n return (\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n );\n}\n\nfunction findPreservedCodeModeError(\n error: unknown,\n errors: CodeModeError[],\n): CodeModeError | undefined {\n if (!RunError.isInstance(error)) {\n return undefined;\n }\n return errors.find(candidate => candidate.code === error.code);\n}\n\nfunction toCodeModeRuntimeError(error: unknown): unknown {\n if (error instanceof TypeError) {\n error.message = translateLimitPath(error.message);\n }\n if (\n error instanceof Error &&\n error.name === 'SyntaxError' &&\n !/syntax|unexpected|expression expected/iu.test(error.message)\n ) {\n error.message = `Syntax error: ${error.message}`;\n }\n if (!RunError.isInstance(error)) {\n return error;\n }\n const details = error.details as Record<string, unknown> | undefined;\n switch (error.code) {\n case 'RUN_ABORTED':\n return copyStack(new CodeModeAbortedError(), error);\n case 'RUN_TIMEOUT':\n return copyStack(\n new CodeModeTimeoutError(Number(details?.timeoutMs ?? 0)),\n error,\n );\n case 'RUN_CPU_TIMEOUT':\n return copyStack(\n new CodeModeCpuTimeoutError(Number(details?.cpuTimeoutMs ?? 0)),\n error,\n );\n case 'RUN_CONCURRENCY_LIMIT':\n return copyStack(\n new CodeModeConcurrencyError(Number(details?.maxWorkers ?? 0)),\n error,\n );\n case 'RUN_SOURCE_TOO_LARGE':\n return copyStack(\n new CodeModeSourceTooLargeError(\n Number(details?.bytes ?? 0),\n Number(details?.maxBytes ?? 0),\n ),\n error,\n );\n case 'RUN_BRIDGE_LIMIT':\n return copyStack(\n new CodeModeBridgeLimitError(error.message, error.details),\n error,\n );\n case 'RUN_DETACHED_BRIDGE_REQUEST':\n return copyStack(\n new CodeModeDetachedBridgeRequestError(error.message, error.details),\n error,\n );\n case 'RUN_PROTOCOL_ERROR':\n return copyStack(\n new CodeModeProtocolError(error.message, error.details),\n error,\n );\n default:\n return error;\n }\n}\n\nfunction translateLimitPath(message: string): string {\n const paths: Record<string, string> = {\n 'limits.timeoutMs': 'executionPolicy.timeoutMs',\n 'limits.cpuTimeoutMs': 'executionPolicy.cpuTimeoutMs',\n 'limits.memoryLimitBytes': 'executionPolicy.memoryLimitBytes',\n 'limits.maxStackSizeBytes': 'executionPolicy.maxStackSizeBytes',\n 'limits.maxResultBytes': 'executionPolicy.maxResultBytes',\n 'limits.maxConsoleOutputBytes': 'executionPolicy.maxConsoleOutputBytes',\n 'limits.maxSourceBytes': 'executionPolicy.maxSourceBytes',\n 'limits.maxHostFunctionArgumentsBytes': 'executionPolicy.maxToolInputBytes',\n 'limits.maxHostFunctionOutputBytes': 'executionPolicy.maxToolOutputBytes',\n 'limits.maxBridgeRequests': 'executionPolicy.maxBridgeRequests',\n 'limits.maxInFlightBridgeRequests':\n 'executionPolicy.maxInFlightBridgeRequests',\n };\n for (const [runPath, codeModePath] of Object.entries(paths)) {\n if (message.includes(runPath)) {\n return message.replace(runPath, codeModePath);\n }\n }\n return message;\n}\n\nfunction copyStack<T extends Error>(target: T, source: Error): T {\n if (source.stack !== undefined) {\n target.stack = source.stack;\n }\n return target;\n}\n\nfunction translateSourceStack<T>(error: T): T {\n if (!(error instanceof Error) || error.stack === undefined) {\n return error;\n }\n error.stack = error.stack.replaceAll(\n /run\\.js:(\\d+):(\\d+)/gu,\n (_match, line: string, column: string) =>\n `code-mode.js:${Math.max(1, Number(line) - SOURCE_LINE_OFFSET)}:${column}`,\n );\n return error;\n}\n"],"mappings":";;;;;;;;;AA+CA,MAAM,qBAAqB;AAC3B,MAAM,gBAAg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AA,GACnB,OAAO,QAAQ,OAAO;CAExB,OAAO;AACT;AAEA,SAAS,qBAAwB,OAAa;CAC5C,IAAI,EAAE,iBAAiB,UAAU,MAAM,UAAU,KAAA,GAC/C,OAAO;CAET,MAAM,QAAQ,MAAM,MAAM,WACxB,0BACC,QAAQ,MAAc,WACrB,gBAAgB,KAAK,IAAI,GAAG,OAAO,IAAI,IAAI,kBAAkB,EAAE,GAAG,QACtE;CACA,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/code-mode",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.107",
|
|
4
4
|
"description": "QuickJS-backed code mode tool for AI SDK",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -37,13 +37,13 @@
|
|
|
37
37
|
"README.md"
|
|
38
38
|
],
|
|
39
39
|
"peerDependencies": {
|
|
40
|
-
"ai": "7.0.
|
|
40
|
+
"ai": "7.0.150"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@types/node": "22.19.19",
|
|
44
44
|
"@vercel/ai-tsconfig": "0.0.0",
|
|
45
45
|
"@vercel/ai-tsdown-config": "0.0.0",
|
|
46
|
-
"ai": "7.0.
|
|
46
|
+
"ai": "7.0.150",
|
|
47
47
|
"tsdown": "^0.23.0",
|
|
48
48
|
"typescript": "6.0.3",
|
|
49
49
|
"zod": "3.25.76"
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"url": "https://github.com/vercel/ai/issues"
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
|
-
"run": "^2.
|
|
68
|
+
"run": "^2.1.8"
|
|
69
69
|
},
|
|
70
70
|
"scripts": {
|
|
71
71
|
"build": "pnpm clean && tsdown",
|
package/src/errors.ts
CHANGED
|
@@ -35,6 +35,21 @@ export class CodeModeTimeoutError extends CodeModeError {
|
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Raised when sandboxed code exceeds its CPU time limit.
|
|
40
|
+
*
|
|
41
|
+
* Time spent waiting on tools does not count toward this limit.
|
|
42
|
+
*/
|
|
43
|
+
export class CodeModeCpuTimeoutError extends CodeModeError {
|
|
44
|
+
constructor(cpuTimeoutMs: number) {
|
|
45
|
+
super(
|
|
46
|
+
`Code mode execution exceeded its CPU time limit of ${cpuTimeoutMs}ms.`,
|
|
47
|
+
'CODE_MODE_CPU_TIMEOUT',
|
|
48
|
+
{ cpuTimeoutMs },
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
38
53
|
/**
|
|
39
54
|
* Raised when the outer AI SDK abort signal aborts a code-mode invocation.
|
|
40
55
|
*/
|
package/src/index.ts
CHANGED
package/src/run-code-mode.ts
CHANGED
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
CodeModeAbortedError,
|
|
24
24
|
CodeModeBridgeLimitError,
|
|
25
25
|
CodeModeConcurrencyError,
|
|
26
|
+
CodeModeCpuTimeoutError,
|
|
26
27
|
CodeModeDetachedBridgeRequestError,
|
|
27
28
|
CodeModeError,
|
|
28
29
|
CodeModeProtocolError,
|
|
@@ -47,6 +48,7 @@ import { fromJsonPayload, toJsonPayload } from './utils/serialization.js';
|
|
|
47
48
|
const SOURCE_LINE_OFFSET = 1;
|
|
48
49
|
const MAX_RUN_LIMIT = 2_147_483_647;
|
|
49
50
|
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
51
|
+
const DEFAULT_CPU_TIMEOUT_MS = 10_000;
|
|
50
52
|
const DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;
|
|
51
53
|
const DEFAULT_STACK_LIMIT_BYTES = 2 * 1024 * 1024;
|
|
52
54
|
const DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;
|
|
@@ -160,6 +162,7 @@ export async function runCodeMode(input: RunCodeModeInput): Promise<unknown> {
|
|
|
160
162
|
|
|
161
163
|
interface ResolvedExecutionPolicy {
|
|
162
164
|
timeoutMs: number;
|
|
165
|
+
cpuTimeoutMs: number;
|
|
163
166
|
memoryLimitBytes: number;
|
|
164
167
|
maxStackSizeBytes: number;
|
|
165
168
|
maxResultBytes: number;
|
|
@@ -176,6 +179,7 @@ function resolveExecutionPolicy(
|
|
|
176
179
|
): ResolvedExecutionPolicy {
|
|
177
180
|
return {
|
|
178
181
|
timeoutMs: policy.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
182
|
+
cpuTimeoutMs: policy.cpuTimeoutMs ?? DEFAULT_CPU_TIMEOUT_MS,
|
|
179
183
|
memoryLimitBytes: policy.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,
|
|
180
184
|
maxStackSizeBytes: policy.maxStackSizeBytes ?? DEFAULT_STACK_LIMIT_BYTES,
|
|
181
185
|
maxResultBytes: policy.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES,
|
|
@@ -363,6 +367,7 @@ function toRunLimits(
|
|
|
363
367
|
): RunLimits {
|
|
364
368
|
return {
|
|
365
369
|
timeoutMs: policy.timeoutMs,
|
|
370
|
+
cpuTimeoutMs: policy.cpuTimeoutMs,
|
|
366
371
|
memoryLimitBytes: policy.memoryLimitBytes,
|
|
367
372
|
maxStackSizeBytes: policy.maxStackSizeBytes,
|
|
368
373
|
maxResultBytes: expandedSerializationLimit(policy.maxResultBytes),
|
|
@@ -643,6 +648,11 @@ function toCodeModeRuntimeError(error: unknown): unknown {
|
|
|
643
648
|
new CodeModeTimeoutError(Number(details?.timeoutMs ?? 0)),
|
|
644
649
|
error,
|
|
645
650
|
);
|
|
651
|
+
case 'RUN_CPU_TIMEOUT':
|
|
652
|
+
return copyStack(
|
|
653
|
+
new CodeModeCpuTimeoutError(Number(details?.cpuTimeoutMs ?? 0)),
|
|
654
|
+
error,
|
|
655
|
+
);
|
|
646
656
|
case 'RUN_CONCURRENCY_LIMIT':
|
|
647
657
|
return copyStack(
|
|
648
658
|
new CodeModeConcurrencyError(Number(details?.maxWorkers ?? 0)),
|
|
@@ -679,6 +689,7 @@ function toCodeModeRuntimeError(error: unknown): unknown {
|
|
|
679
689
|
function translateLimitPath(message: string): string {
|
|
680
690
|
const paths: Record<string, string> = {
|
|
681
691
|
'limits.timeoutMs': 'executionPolicy.timeoutMs',
|
|
692
|
+
'limits.cpuTimeoutMs': 'executionPolicy.cpuTimeoutMs',
|
|
682
693
|
'limits.memoryLimitBytes': 'executionPolicy.memoryLimitBytes',
|
|
683
694
|
'limits.maxStackSizeBytes': 'executionPolicy.maxStackSizeBytes',
|
|
684
695
|
'limits.maxResultBytes': 'executionPolicy.maxResultBytes',
|
package/src/types.ts
CHANGED
|
@@ -160,8 +160,21 @@ export type CodeModeApprovalInterrupt =
|
|
|
160
160
|
* Execution limits applied to each sandbox invocation.
|
|
161
161
|
*/
|
|
162
162
|
export interface CodeModeExecutionPolicy {
|
|
163
|
-
/**
|
|
163
|
+
/**
|
|
164
|
+
* Wall-clock limit for one invocation, including time spent waiting on
|
|
165
|
+
* tools.
|
|
166
|
+
*
|
|
167
|
+
* @defaultValue `30_000`
|
|
168
|
+
*/
|
|
164
169
|
timeoutMs?: number;
|
|
170
|
+
/**
|
|
171
|
+
* CPU time limit for sandboxed code in one invocation. Time spent waiting on
|
|
172
|
+
* tools does not count toward it. Only takes effect when lower than
|
|
173
|
+
* `timeoutMs`. Each continuation resume starts with a fresh budget.
|
|
174
|
+
*
|
|
175
|
+
* @defaultValue `10_000`
|
|
176
|
+
*/
|
|
177
|
+
cpuTimeoutMs?: number;
|
|
165
178
|
/** @defaultValue `64 * 1024 * 1024` */
|
|
166
179
|
memoryLimitBytes?: number;
|
|
167
180
|
/** @defaultValue `2 * 1024 * 1024` */
|