@ai-sdk/code-mode 0.0.0-2d998b35-20260731001744

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.
Files changed (51) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +99 -0
  3. package/dist/code-mode-tool.js +40 -0
  4. package/dist/code-mode-tool.js.map +1 -0
  5. package/dist/errors.js +192 -0
  6. package/dist/errors.js.map +1 -0
  7. package/dist/index.d.ts +179 -0
  8. package/dist/index.js +33 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/run-code-mode.js +8 -0
  11. package/dist/run-code-mode.js.map +1 -0
  12. package/dist/runtime/guest-sources.js +260 -0
  13. package/dist/runtime/guest-sources.js.map +1 -0
  14. package/dist/runtime/manager.js +414 -0
  15. package/dist/runtime/manager.js.map +1 -0
  16. package/dist/runtime/max-workers.js +40 -0
  17. package/dist/runtime/max-workers.js.map +1 -0
  18. package/dist/runtime/protocol.js +1 -0
  19. package/dist/runtime/protocol.js.map +1 -0
  20. package/dist/runtime/worker-source.d.ts +11 -0
  21. package/dist/runtime/worker-source.js +2 -0
  22. package/dist/tool-invocation.js +129 -0
  23. package/dist/tool-invocation.js.map +1 -0
  24. package/dist/tool-prompt.js +440 -0
  25. package/dist/tool-prompt.js.map +1 -0
  26. package/dist/types.js +1 -0
  27. package/dist/types.js.map +1 -0
  28. package/dist/utils/options.js +76 -0
  29. package/dist/utils/options.js.map +1 -0
  30. package/dist/utils/serialization.js +49 -0
  31. package/dist/utils/serialization.js.map +1 -0
  32. package/dist/utils/source-cache.js +77 -0
  33. package/dist/utils/source-cache.js.map +1 -0
  34. package/package.json +77 -0
  35. package/src/code-mode-tool.ts +60 -0
  36. package/src/errors.ts +267 -0
  37. package/src/index.ts +26 -0
  38. package/src/run-code-mode.ts +15 -0
  39. package/src/runtime/guest-sources.ts +260 -0
  40. package/src/runtime/manager.ts +498 -0
  41. package/src/runtime/max-workers.ts +65 -0
  42. package/src/runtime/protocol.ts +52 -0
  43. package/src/runtime/worker-source.ts +10 -0
  44. package/src/runtime/worker.ts +497 -0
  45. package/src/tool-invocation.ts +181 -0
  46. package/src/tool-prompt.ts +585 -0
  47. package/src/tsconfig.json +11 -0
  48. package/src/types.ts +111 -0
  49. package/src/utils/options.ts +83 -0
  50. package/src/utils/serialization.ts +66 -0
  51. package/src/utils/source-cache.ts +91 -0
package/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2023 Vercel, Inc.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,99 @@
1
+ # AI SDK Code Mode
2
+
3
+ `@ai-sdk/code-mode` lets models write JavaScript or TypeScript that calls your
4
+ AI SDK tools. The code runs in an isolated QuickJS sandbox and returns a
5
+ JSON-serializable value.
6
+
7
+ Use code mode when a model needs to call several tools, transform their results,
8
+ or run them concurrently. Only the tools you provide are available to the
9
+ generated code.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pnpm add ai @ai-sdk/code-mode
15
+ ```
16
+
17
+ This package runs on the server and requires Node.js 22 or newer.
18
+
19
+ ## Usage
20
+
21
+ ```ts
22
+ import { experimental_codeModeTool as codeModeTool } from '@ai-sdk/code-mode';
23
+ import { generateText, isStepCount, tool } from 'ai';
24
+ import { z } from 'zod';
25
+
26
+ const getInventory = tool({
27
+ description: 'Get available inventory for a product.',
28
+ inputSchema: z.object({ productId: z.string() }),
29
+ outputSchema: z.object({
30
+ productId: z.string(),
31
+ availableUnits: z.number(),
32
+ }),
33
+ execute: async ({ productId }) => ({
34
+ productId,
35
+ availableUnits: 42,
36
+ }),
37
+ });
38
+
39
+ const getDemand = tool({
40
+ description: 'Get requested units for a product.',
41
+ inputSchema: z.object({ productId: z.string() }),
42
+ outputSchema: z.object({
43
+ productId: z.string(),
44
+ requestedUnits: z.number(),
45
+ }),
46
+ execute: async ({ productId }) => ({
47
+ productId,
48
+ requestedUnits: 31,
49
+ }),
50
+ });
51
+
52
+ const tools = {
53
+ code_mode: codeModeTool({
54
+ executionPolicy: {
55
+ timeoutMs: 30_000,
56
+ },
57
+ }),
58
+ getInventory,
59
+ getDemand,
60
+ } as const;
61
+
62
+ const result = await generateText({
63
+ model,
64
+ tools,
65
+ experimental_toolCallers: ({ code_mode }) => ({
66
+ getInventory: [code_mode],
67
+ getDemand: [code_mode],
68
+ }),
69
+ stopWhen: isStepCount(10),
70
+ prompt: 'Compare inventory and demand for product sku_123.',
71
+ });
72
+ ```
73
+
74
+ The model can then generate code like:
75
+
76
+ ```ts
77
+ const [inventory, demand] = await Promise.all([
78
+ tools.getInventory({ productId: 'sku_123' }),
79
+ tools.getDemand({ productId: 'sku_123' }),
80
+ ]);
81
+
82
+ return {
83
+ sufficient: inventory.availableUnits >= demand.requestedUnits,
84
+ remaining: inventory.availableUnits - demand.requestedUnits,
85
+ };
86
+ ```
87
+
88
+ ## Direct Execution
89
+
90
+ Use `experimental_runCodeMode` to run code directly:
91
+
92
+ ```ts
93
+ import { experimental_runCodeMode as runCodeMode } from '@ai-sdk/code-mode';
94
+
95
+ const result = await runCodeMode({
96
+ js: 'return await tools.getInventory({ productId: "sku_123" });',
97
+ tools: { getInventory },
98
+ });
99
+ ```
@@ -0,0 +1,40 @@
1
+ import {
2
+ experimental_toolCaller,
3
+ jsonSchema,
4
+ tool
5
+ } from "ai";
6
+ import { runCodeMode } from "./run-code-mode.js";
7
+ import { buildCodeModeToolDescription } from "./tool-prompt.js";
8
+ function createCodeModeTool(tools, options = {}) {
9
+ return tool({
10
+ description: buildCodeModeToolDescription(tools),
11
+ inputSchema: jsonSchema({
12
+ type: "object",
13
+ properties: {
14
+ js: {
15
+ type: "string",
16
+ description: "Code-mode TypeScript source to execute. The tool description lists the available global `tools` API, input types, and call examples."
17
+ }
18
+ },
19
+ required: ["js"],
20
+ additionalProperties: false
21
+ }),
22
+ execute: async (input, executionOptions) => await runCodeMode({
23
+ js: input.js,
24
+ tools,
25
+ toolExecutionOptions: executionOptions,
26
+ options
27
+ })
28
+ });
29
+ }
30
+ function codeModeTool(options = {}) {
31
+ return experimental_toolCaller(createCodeModeTool({}, options), {
32
+ type: "local",
33
+ bind: (tools) => createCodeModeTool(tools, options)
34
+ });
35
+ }
36
+ export {
37
+ codeModeTool,
38
+ createCodeModeTool
39
+ };
40
+ //# sourceMappingURL=code-mode-tool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/code-mode-tool.ts"],"sourcesContent":["import {\n experimental_toolCaller,\n jsonSchema,\n tool,\n type Experimental_ToolCallerTool,\n} from 'ai';\nimport { runCodeMode } from './run-code-mode.js';\nimport { buildCodeModeToolDescription } from './tool-prompt.js';\nimport type {\n CodeModeOptions,\n CodeModeTool,\n CodeModeToolInput,\n CodeModeToolSet,\n} from './types.js';\n\n/**\n * Creates an AI SDK tool that executes code-mode TypeScript in an isolated\n * sandbox.\n */\nexport function createCodeModeTool(\n tools: CodeModeToolSet,\n options: CodeModeOptions = {},\n): CodeModeTool {\n return tool<CodeModeToolInput, unknown, Record<string, unknown>>({\n description: buildCodeModeToolDescription(tools),\n inputSchema: jsonSchema<CodeModeToolInput>({\n type: 'object',\n properties: {\n js: {\n type: 'string',\n description:\n 'Code-mode TypeScript source to execute. The tool description lists the available global `tools` API, input types, and call examples.',\n },\n },\n required: ['js'],\n additionalProperties: false,\n }),\n execute: async (input, executionOptions) =>\n await runCodeMode({\n js: input.js,\n tools,\n toolExecutionOptions: executionOptions,\n options,\n }),\n }) as CodeModeTool;\n}\n\n/**\n * Creates a code-mode caller whose host tools are bound by the surrounding\n * AI SDK generation call.\n */\nexport function codeModeTool(\n options: CodeModeOptions = {},\n): Experimental_ToolCallerTool<CodeModeTool> {\n return experimental_toolCaller(createCodeModeTool({}, options), {\n type: 'local',\n bind: tools =>\n createCodeModeTool(tools as unknown as CodeModeToolSet, options),\n });\n}\n"],"mappings":"AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,mBAAmB;AAC5B,SAAS,oCAAoC;AAYtC,SAAS,mBACd,OACA,UAA2B,CAAC,GACd;AACd,SAAO,KAA0D;AAAA,IAC/D,aAAa,6BAA6B,KAAK;AAAA,IAC/C,aAAa,WAA8B;AAAA,MACzC,MAAM;AAAA,MACN,YAAY;AAAA,QACV,IAAI;AAAA,UACF,MAAM;AAAA,UACN,aACE;AAAA,QACJ;AAAA,MACF;AAAA,MACA,UAAU,CAAC,IAAI;AAAA,MACf,sBAAsB;AAAA,IACxB,CAAC;AAAA,IACD,SAAS,OAAO,OAAO,qBACrB,MAAM,YAAY;AAAA,MAChB,IAAI,MAAM;AAAA,MACV;AAAA,MACA,sBAAsB;AAAA,MACtB;AAAA,IACF,CAAC;AAAA,EACL,CAAC;AACH;AAMO,SAAS,aACd,UAA2B,CAAC,GACe;AAC3C,SAAO,wBAAwB,mBAAmB,CAAC,GAAG,OAAO,GAAG;AAAA,IAC9D,MAAM;AAAA,IACN,MAAM,WACJ,mBAAmB,OAAqC,OAAO;AAAA,EACnE,CAAC;AACH;","names":[]}
package/dist/errors.js ADDED
@@ -0,0 +1,192 @@
1
+ class CodeModeError extends Error {
2
+ /**
3
+ * Stable machine-readable error code.
4
+ */
5
+ code;
6
+ /**
7
+ * Optional structured diagnostic details.
8
+ */
9
+ details;
10
+ constructor(message, code = "CODE_MODE_ERROR", details) {
11
+ super(message);
12
+ this.name = new.target.name;
13
+ this.code = code;
14
+ this.details = details;
15
+ }
16
+ }
17
+ class CodeModeTimeoutError extends CodeModeError {
18
+ constructor(timeoutMs) {
19
+ super(
20
+ `Code mode execution timed out after ${timeoutMs}ms.`,
21
+ "CODE_MODE_TIMEOUT",
22
+ { timeoutMs }
23
+ );
24
+ }
25
+ }
26
+ class CodeModeAbortedError extends CodeModeError {
27
+ constructor() {
28
+ super("Code mode execution was aborted.", "CODE_MODE_ABORTED");
29
+ }
30
+ }
31
+ class CodeModeConcurrencyError extends CodeModeError {
32
+ constructor(maxWorkers) {
33
+ super(
34
+ `Code mode maxWorkers limit reached (${maxWorkers}).`,
35
+ "CODE_MODE_CONCURRENCY_LIMIT",
36
+ { maxWorkers }
37
+ );
38
+ }
39
+ }
40
+ class CodeModeSourceTooLargeError extends CodeModeError {
41
+ constructor(bytes, maxBytes) {
42
+ super(
43
+ `Code mode source exceeds the ${maxBytes} byte size limit.`,
44
+ "CODE_MODE_SOURCE_TOO_LARGE",
45
+ { bytes, maxBytes }
46
+ );
47
+ }
48
+ }
49
+ class CodeModeBridgeLimitError extends CodeModeError {
50
+ constructor(message, details) {
51
+ super(message, "CODE_MODE_BRIDGE_LIMIT", details);
52
+ }
53
+ }
54
+ class CodeModeDetachedBridgeRequestError extends CodeModeError {
55
+ constructor(message, details) {
56
+ super(message, "CODE_MODE_DETACHED_BRIDGE_REQUEST", details);
57
+ }
58
+ }
59
+ class CodeModeProtocolError extends CodeModeError {
60
+ constructor(message, details) {
61
+ super(message, "CODE_MODE_PROTOCOL_ERROR", details);
62
+ }
63
+ }
64
+ class CodeModeToolError extends CodeModeError {
65
+ constructor(message, details) {
66
+ super(message, "CODE_MODE_TOOL_ERROR", details);
67
+ }
68
+ }
69
+ function serializeError(error) {
70
+ if (error instanceof CodeModeError) {
71
+ const result = compactError({
72
+ name: error.name,
73
+ message: error.message,
74
+ code: error.code
75
+ });
76
+ if (error.stack !== void 0) {
77
+ result.stack = error.stack;
78
+ }
79
+ if (error.details !== void 0) {
80
+ result.details = error.details;
81
+ }
82
+ return result;
83
+ }
84
+ if (error instanceof Error) {
85
+ const result = compactError({
86
+ name: error.name,
87
+ message: error.message
88
+ });
89
+ if (error.stack !== void 0) {
90
+ result.stack = error.stack;
91
+ }
92
+ const maybeCoded = error;
93
+ if (typeof maybeCoded.code === "string") {
94
+ result.code = maybeCoded.code;
95
+ }
96
+ if (maybeCoded.details !== void 0) {
97
+ result.details = maybeCoded.details;
98
+ }
99
+ return result;
100
+ }
101
+ return {
102
+ name: "Error",
103
+ message: String(error)
104
+ };
105
+ }
106
+ function serializeBridgeErrorForGuest(error, context) {
107
+ if (error instanceof CodeModeError) {
108
+ return compactError({
109
+ name: error.name,
110
+ message: error.message,
111
+ code: error.code
112
+ });
113
+ }
114
+ const fallback = context === "tool" ? {
115
+ message: "Host tool failed.",
116
+ code: "CODE_MODE_HOST_TOOL_ERROR"
117
+ } : {
118
+ message: "Host bridge request failed.",
119
+ code: "CODE_MODE_HOST_BRIDGE_ERROR"
120
+ };
121
+ return {
122
+ name: "Error",
123
+ message: fallback.message,
124
+ code: fallback.code
125
+ };
126
+ }
127
+ function compactError(error) {
128
+ return {
129
+ name: error.name,
130
+ message: error.message,
131
+ ...error.stack !== void 0 ? { stack: error.stack } : {},
132
+ ...error.code !== void 0 ? { code: error.code } : {},
133
+ ...error.details !== void 0 ? { details: error.details } : {}
134
+ };
135
+ }
136
+ function deserializeError(error) {
137
+ if (error.code === "CODE_MODE_SOURCE_TOO_LARGE") {
138
+ const details = error.details;
139
+ const result2 = new CodeModeSourceTooLargeError(
140
+ details?.bytes ?? 0,
141
+ details?.maxBytes ?? 0
142
+ );
143
+ restoreStack(result2, error);
144
+ return result2;
145
+ }
146
+ if (error.code === "CODE_MODE_BRIDGE_LIMIT") {
147
+ const result2 = new CodeModeBridgeLimitError(error.message, error.details);
148
+ restoreStack(result2, error);
149
+ return result2;
150
+ }
151
+ if (error.code === "CODE_MODE_DETACHED_BRIDGE_REQUEST") {
152
+ const result2 = new CodeModeDetachedBridgeRequestError(
153
+ error.message,
154
+ error.details
155
+ );
156
+ restoreStack(result2, error);
157
+ return result2;
158
+ }
159
+ if (error.code === "CODE_MODE_PROTOCOL_ERROR") {
160
+ const result2 = new CodeModeProtocolError(error.message, error.details);
161
+ restoreStack(result2, error);
162
+ return result2;
163
+ }
164
+ const result = new CodeModeError(
165
+ error.message,
166
+ error.code ?? "CODE_MODE_ERROR",
167
+ error.details
168
+ );
169
+ result.name = error.name;
170
+ restoreStack(result, error);
171
+ return result;
172
+ }
173
+ function restoreStack(error, serialized) {
174
+ if (serialized.stack) {
175
+ error.stack = serialized.stack;
176
+ }
177
+ }
178
+ export {
179
+ CodeModeAbortedError,
180
+ CodeModeBridgeLimitError,
181
+ CodeModeConcurrencyError,
182
+ CodeModeDetachedBridgeRequestError,
183
+ CodeModeError,
184
+ CodeModeProtocolError,
185
+ CodeModeSourceTooLargeError,
186
+ CodeModeTimeoutError,
187
+ CodeModeToolError,
188
+ deserializeError,
189
+ serializeBridgeErrorForGuest,
190
+ serializeError
191
+ };
192
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts"],"sourcesContent":["import type { SerializableError } from './types.js';\n\n/**\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\n/**\n * Converts an unknown thrown value into a worker-safe serializable shape.\n *\n * @internal\n */\nexport function serializeError(error: unknown): SerializableError {\n if (error instanceof CodeModeError) {\n const result = compactError({\n name: error.name,\n message: error.message,\n code: error.code,\n });\n if (error.stack !== undefined) {\n result.stack = error.stack;\n }\n if (error.details !== undefined) {\n result.details = error.details;\n }\n return result;\n }\n\n if (error instanceof Error) {\n const result = compactError({\n name: error.name,\n message: error.message,\n });\n if (error.stack !== undefined) {\n result.stack = error.stack;\n }\n const maybeCoded = error as Error & { code?: unknown; details?: unknown };\n if (typeof maybeCoded.code === 'string') {\n result.code = maybeCoded.code;\n }\n if (maybeCoded.details !== undefined) {\n result.details = maybeCoded.details;\n }\n return result;\n }\n\n return {\n name: 'Error',\n message: String(error),\n };\n}\n\n/**\n * Converts host bridge failures into a sandbox-visible sanitized shape.\n *\n * This intentionally omits stack traces and diagnostic details. Full host\n * diagnostics remain on the host side.\n *\n * @internal\n */\nexport function serializeBridgeErrorForGuest(\n error: unknown,\n context: 'tool' | 'bridge',\n): SerializableError {\n if (error instanceof CodeModeError) {\n return compactError({\n name: error.name,\n message: error.message,\n code: error.code,\n });\n }\n\n const fallback =\n context === 'tool'\n ? {\n message: 'Host tool failed.',\n code: 'CODE_MODE_HOST_TOOL_ERROR',\n }\n : {\n message: 'Host bridge request failed.',\n code: 'CODE_MODE_HOST_BRIDGE_ERROR',\n };\n\n return {\n name: 'Error',\n message: fallback.message,\n code: fallback.code,\n };\n}\n\nfunction compactError(error: {\n name: string;\n message: string;\n stack?: string;\n code?: string;\n details?: unknown;\n}): SerializableError {\n return {\n name: error.name,\n message: error.message,\n ...(error.stack !== undefined ? { stack: error.stack } : {}),\n ...(error.code !== undefined ? { code: error.code } : {}),\n ...(error.details !== undefined ? { details: error.details } : {}),\n };\n}\n\n/**\n * Rehydrates a serialized worker error into an Error instance.\n *\n * @internal\n */\nexport function deserializeError(error: SerializableError): Error {\n if (error.code === 'CODE_MODE_SOURCE_TOO_LARGE') {\n const details = error.details as\n | { bytes?: number; maxBytes?: number }\n | undefined;\n const result = new CodeModeSourceTooLargeError(\n details?.bytes ?? 0,\n details?.maxBytes ?? 0,\n );\n restoreStack(result, error);\n return result;\n }\n\n if (error.code === 'CODE_MODE_BRIDGE_LIMIT') {\n const result = new CodeModeBridgeLimitError(error.message, error.details);\n restoreStack(result, error);\n return result;\n }\n\n if (error.code === 'CODE_MODE_DETACHED_BRIDGE_REQUEST') {\n const result = new CodeModeDetachedBridgeRequestError(\n error.message,\n error.details,\n );\n restoreStack(result, error);\n return result;\n }\n\n if (error.code === 'CODE_MODE_PROTOCOL_ERROR') {\n const result = new CodeModeProtocolError(error.message, error.details);\n restoreStack(result, error);\n return result;\n }\n\n const result = new CodeModeError(\n error.message,\n error.code ?? 'CODE_MODE_ERROR',\n error.details,\n );\n result.name = error.name;\n restoreStack(result, error);\n return result;\n}\n\nfunction restoreStack(error: Error, serialized: SerializableError): void {\n if (serialized.stack) {\n error.stack = serialized.stack;\n }\n}\n"],"mappings":"AAQO,MAAM,sBAAsB,MAAM;AAAA;AAAA;AAAA;AAAA,EAIvC;AAAA;AAAA;AAAA;AAAA,EAIS;AAAA,EAET,YAAY,SAAiB,OAAO,mBAAmB,SAAmB;AACxE,UAAM,OAAO;AACb,SAAK,OAAO,WAAW;AACvB,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AACF;AAKO,MAAM,6BAA6B,cAAc;AAAA,EACtD,YAAY,WAAmB;AAC7B;AAAA,MACE,uCAAuC,SAAS;AAAA,MAChD;AAAA,MACA,EAAE,UAAU;AAAA,IACd;AAAA,EACF;AACF;AAKO,MAAM,6BAA6B,cAAc;AAAA,EACtD,cAAc;AACZ,UAAM,oCAAoC,mBAAmB;AAAA,EAC/D;AACF;AAOO,MAAM,iCAAiC,cAAc;AAAA,EAC1D,YAAY,YAAoB;AAC9B;AAAA,MACE,uCAAuC,UAAU;AAAA,MACjD;AAAA,MACA,EAAE,WAAW;AAAA,IACf;AAAA,EACF;AACF;AAKO,MAAM,oCAAoC,cAAc;AAAA,EAC7D,YAAY,OAAe,UAAkB;AAC3C;AAAA,MACE,gCAAgC,QAAQ;AAAA,MACxC;AAAA,MACA,EAAE,OAAO,SAAS;AAAA,IACpB;AAAA,EACF;AACF;AAKO,MAAM,iCAAiC,cAAc;AAAA,EAC1D,YAAY,SAAiB,SAAmB;AAC9C,UAAM,SAAS,0BAA0B,OAAO;AAAA,EAClD;AACF;AAMO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AAM,SAAS,IAAI;AAAA,IACjB,MAAM;AAAA,IACN,MAAM,QAAQ;AAAA,IACd,MAAM;AAAA,EACR;AACA,SAAO,OAAO,MAAM;AACpB,eAAa,QAAQ,KAAK;AAC1B,SAAO;AACT;AAEA,SAAS,aAAa,OAAc,YAAqC;AACvE,MAAI,WAAW,OAAO;AACpB,UAAM,QAAQ,WAAW;AAAA,EAC3B;AACF;","names":["result"]}
@@ -0,0 +1,179 @@
1
+ import { Tool, ModelMessage, Experimental_ToolCallerTool } from 'ai';
2
+
3
+ /**
4
+ * Host tools made available to sandboxed code through the global `tools` object.
5
+ */
6
+ type CodeModeToolSet = Record<string, Tool<any, any>>;
7
+ /**
8
+ * AI SDK execution metadata forwarded to nested host tool calls.
9
+ */
10
+ interface CodeModeToolExecutionOptions {
11
+ toolCallId: string;
12
+ messages: ModelMessage[];
13
+ abortSignal?: AbortSignal;
14
+ experimental_context?: unknown;
15
+ context?: unknown;
16
+ }
17
+ /**
18
+ * AI SDK tool returned by `createCodeModeTool`.
19
+ */
20
+ type CodeModeTool = Tool<CodeModeToolInput, unknown> & {
21
+ description: string;
22
+ };
23
+ /**
24
+ * Input accepted by the generated code-mode tool.
25
+ */
26
+ interface CodeModeToolInput {
27
+ /**
28
+ * JavaScript or type-stripped TypeScript source to execute.
29
+ *
30
+ * The source is wrapped in an async function, so top-level `await` and
31
+ * `return` are supported.
32
+ */
33
+ js: string;
34
+ }
35
+ /**
36
+ * Execution limits applied to each sandbox invocation.
37
+ */
38
+ interface CodeModeExecutionPolicy {
39
+ /** @defaultValue `30_000` */
40
+ timeoutMs?: number;
41
+ /** @defaultValue `64 * 1024 * 1024` */
42
+ memoryLimitBytes?: number;
43
+ /** @defaultValue `2 * 1024 * 1024` */
44
+ maxStackSizeBytes?: number;
45
+ /** @defaultValue `1024 * 1024` */
46
+ maxResultBytes?: number;
47
+ /** @defaultValue `64 * 1024` */
48
+ maxConsoleOutputBytes?: number;
49
+ /** @defaultValue `256 * 1024` */
50
+ maxSourceBytes?: number;
51
+ /** @defaultValue `1024 * 1024` */
52
+ maxToolInputBytes?: number;
53
+ /** @defaultValue `4 * 1024 * 1024` */
54
+ maxToolOutputBytes?: number;
55
+ /** @defaultValue `256` */
56
+ maxBridgeRequests?: number;
57
+ /** @defaultValue `32` */
58
+ maxInFlightBridgeRequests?: number;
59
+ }
60
+ /**
61
+ * Options used by `createCodeModeTool` and `runCodeMode`.
62
+ */
63
+ interface CodeModeOptions {
64
+ executionPolicy?: CodeModeExecutionPolicy;
65
+ }
66
+ /**
67
+ * Input for `runCodeMode`.
68
+ */
69
+ interface RunCodeModeInput {
70
+ js: string;
71
+ tools: CodeModeToolSet;
72
+ toolExecutionOptions?: Partial<CodeModeToolExecutionOptions>;
73
+ options?: CodeModeOptions;
74
+ }
75
+
76
+ /**
77
+ * Creates an AI SDK tool that executes code-mode TypeScript in an isolated
78
+ * sandbox.
79
+ */
80
+ declare function createCodeModeTool(tools: CodeModeToolSet, options?: CodeModeOptions): CodeModeTool;
81
+ /**
82
+ * Creates a code-mode caller whose host tools are bound by the surrounding
83
+ * AI SDK generation call.
84
+ */
85
+ declare function codeModeTool(options?: CodeModeOptions): Experimental_ToolCallerTool<CodeModeTool>;
86
+
87
+ /**
88
+ * Base class for errors raised by code mode.
89
+ *
90
+ * All package-specific errors include a stable `code` string and may include
91
+ * structured `details` for diagnostics.
92
+ */
93
+ declare class CodeModeError extends Error {
94
+ /**
95
+ * Stable machine-readable error code.
96
+ */
97
+ code: string;
98
+ /**
99
+ * Optional structured diagnostic details.
100
+ */
101
+ readonly details?: unknown;
102
+ constructor(message: string, code?: string, details?: unknown);
103
+ }
104
+ /**
105
+ * Raised when a sandbox invocation exceeds its timeout.
106
+ */
107
+ declare class CodeModeTimeoutError extends CodeModeError {
108
+ constructor(timeoutMs: number);
109
+ }
110
+ /**
111
+ * Raised when the outer AI SDK abort signal aborts a code-mode invocation.
112
+ */
113
+ declare class CodeModeAbortedError extends CodeModeError {
114
+ constructor();
115
+ }
116
+ /**
117
+ * Raised when the process-global worker cap has been reached.
118
+ *
119
+ * Configure the cap with `setMaxWorkers`.
120
+ */
121
+ declare class CodeModeConcurrencyError extends CodeModeError {
122
+ constructor(maxWorkers: number);
123
+ }
124
+ /**
125
+ * Raised when the provided source exceeds `executionPolicy.maxSourceBytes`.
126
+ */
127
+ declare class CodeModeSourceTooLargeError extends CodeModeError {
128
+ constructor(bytes: number, maxBytes: number);
129
+ }
130
+ /**
131
+ * Raised when sandboxed code exceeds bridge request limits.
132
+ */
133
+ declare class CodeModeBridgeLimitError extends CodeModeError {
134
+ constructor(message: string, details?: unknown);
135
+ }
136
+ /**
137
+ * Raised when sandboxed code starts host bridge work and returns without
138
+ * awaiting or otherwise observing it.
139
+ */
140
+ declare class CodeModeDetachedBridgeRequestError extends CodeModeError {
141
+ constructor(message: string, details?: unknown);
142
+ }
143
+ /**
144
+ * Raised when the main thread and worker protocol observes an invalid or
145
+ * mismatched message.
146
+ */
147
+ declare class CodeModeProtocolError extends CodeModeError {
148
+ constructor(message: string, details?: unknown);
149
+ }
150
+ /**
151
+ * Base class for failures caused by nested host tool execution.
152
+ */
153
+ declare class CodeModeToolError extends CodeModeError {
154
+ constructor(message: string, details?: unknown);
155
+ }
156
+
157
+ /**
158
+ * Runs one code-mode invocation directly without wrapping it as an AI SDK tool.
159
+ *
160
+ * The source is executed in a fresh QuickJS context with the provided host tools
161
+ * and execution limits.
162
+ *
163
+ * @param input - Source code, host tools, forwarded tool execution options, and code-mode options.
164
+ * @returns The JSON-serializable value returned by the sandboxed program.
165
+ */
166
+ declare function runCodeMode(input: RunCodeModeInput): Promise<unknown>;
167
+
168
+ /**
169
+ * Sets the process-global maximum number of active code-mode workers.
170
+ *
171
+ * Pass `undefined` or call without an argument to restore the dynamic
172
+ * memory-based default. The default admits at least one invocation and admits
173
+ * additional workers only when available memory can cover another worker.
174
+ *
175
+ * @param maxWorkers - Positive integer worker cap, or `undefined` to reset.
176
+ */
177
+ declare function setMaxWorkers(maxWorkers?: number): void;
178
+
179
+ export { CodeModeAbortedError, CodeModeBridgeLimitError, CodeModeConcurrencyError, CodeModeDetachedBridgeRequestError, CodeModeError, type CodeModeExecutionPolicy, type CodeModeOptions, CodeModeProtocolError, CodeModeSourceTooLargeError, CodeModeTimeoutError, type CodeModeTool, CodeModeToolError, type CodeModeToolExecutionOptions, type CodeModeToolInput, type CodeModeToolSet, type RunCodeModeInput, codeModeTool as experimental_codeModeTool, createCodeModeTool as experimental_createCodeModeTool, runCodeMode as experimental_runCodeMode, setMaxWorkers as experimental_setMaxWorkers };
package/dist/index.js ADDED
@@ -0,0 +1,33 @@
1
+ import {
2
+ codeModeTool,
3
+ createCodeModeTool
4
+ } from "./code-mode-tool.js";
5
+ import {
6
+ CodeModeAbortedError,
7
+ CodeModeBridgeLimitError,
8
+ CodeModeConcurrencyError,
9
+ CodeModeDetachedBridgeRequestError,
10
+ CodeModeError,
11
+ CodeModeProtocolError,
12
+ CodeModeSourceTooLargeError,
13
+ CodeModeTimeoutError,
14
+ CodeModeToolError
15
+ } from "./errors.js";
16
+ import { runCodeMode } from "./run-code-mode.js";
17
+ import { setMaxWorkers } from "./runtime/max-workers.js";
18
+ export {
19
+ CodeModeAbortedError,
20
+ CodeModeBridgeLimitError,
21
+ CodeModeConcurrencyError,
22
+ CodeModeDetachedBridgeRequestError,
23
+ CodeModeError,
24
+ CodeModeProtocolError,
25
+ CodeModeSourceTooLargeError,
26
+ CodeModeTimeoutError,
27
+ CodeModeToolError,
28
+ codeModeTool as experimental_codeModeTool,
29
+ createCodeModeTool as experimental_createCodeModeTool,
30
+ runCodeMode as experimental_runCodeMode,
31
+ setMaxWorkers as experimental_setMaxWorkers
32
+ };
33
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export {\n codeModeTool as experimental_codeModeTool,\n createCodeModeTool as experimental_createCodeModeTool,\n} from './code-mode-tool.js';\nexport {\n CodeModeAbortedError,\n CodeModeBridgeLimitError,\n CodeModeConcurrencyError,\n CodeModeDetachedBridgeRequestError,\n CodeModeError,\n CodeModeProtocolError,\n CodeModeSourceTooLargeError,\n CodeModeTimeoutError,\n CodeModeToolError,\n} from './errors.js';\nexport { runCodeMode as experimental_runCodeMode } from './run-code-mode.js';\nexport { setMaxWorkers as experimental_setMaxWorkers } from './runtime/max-workers.js';\nexport type {\n CodeModeExecutionPolicy,\n CodeModeOptions,\n CodeModeTool,\n CodeModeToolExecutionOptions,\n CodeModeToolInput,\n CodeModeToolSet,\n RunCodeModeInput,\n} from './types.js';\n"],"mappings":"AAAA;AAAA,EACkB;AAAA,EACM;AAAA,OACjB;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAwB,mBAAgC;AACxD,SAA0B,qBAAkC;","names":[]}
@@ -0,0 +1,8 @@
1
+ import { runManagedCodeMode } from "./runtime/manager.js";
2
+ async function runCodeMode(input) {
3
+ return await runManagedCodeMode(input);
4
+ }
5
+ export {
6
+ runCodeMode
7
+ };
8
+ //# sourceMappingURL=run-code-mode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/run-code-mode.ts"],"sourcesContent":["import { runManagedCodeMode } from './runtime/manager.js';\nimport type { RunCodeModeInput } from './types.js';\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 return await runManagedCodeMode(input);\n}\n"],"mappings":"AAAA,SAAS,0BAA0B;AAYnC,eAAsB,YAAY,OAA2C;AAC3E,SAAO,MAAM,mBAAmB,KAAK;AACvC;","names":[]}