@ai-sdk/code-mode 1.0.20 → 1.0.22

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 (50) hide show
  1. package/README.md +1 -1
  2. package/dist/continuation-capability.js +5 -0
  3. package/dist/continuation-capability.js.map +1 -1
  4. package/dist/errors.js +1 -136
  5. package/dist/errors.js.map +1 -1
  6. package/dist/host-interrupt.js +2 -14
  7. package/dist/host-interrupt.js.map +1 -1
  8. package/dist/index.d.ts +14 -44
  9. package/dist/index.js +1 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/interrupt-continuation.js +3 -8
  12. package/dist/interrupt-continuation.js.map +1 -1
  13. package/dist/run-code-mode.js +543 -2
  14. package/dist/run-code-mode.js.map +1 -1
  15. package/dist/tool-invocation.js +9 -23
  16. package/dist/tool-invocation.js.map +1 -1
  17. package/dist/utils/serialization.js +4 -0
  18. package/dist/utils/serialization.js.map +1 -1
  19. package/package.json +8 -7
  20. package/src/continuation-capability.ts +18 -0
  21. package/src/errors.ts +0 -190
  22. package/src/host-interrupt.ts +2 -31
  23. package/src/index.ts +1 -1
  24. package/src/interrupt-continuation.ts +13 -15
  25. package/src/run-code-mode.ts +706 -3
  26. package/src/tool-invocation.ts +9 -23
  27. package/src/types.ts +38 -68
  28. package/src/utils/serialization.ts +4 -0
  29. package/dist/runtime/guest-sources.js +0 -350
  30. package/dist/runtime/guest-sources.js.map +0 -1
  31. package/dist/runtime/manager.js +0 -794
  32. package/dist/runtime/manager.js.map +0 -1
  33. package/dist/runtime/max-workers.js +0 -40
  34. package/dist/runtime/max-workers.js.map +0 -1
  35. package/dist/runtime/protocol.js +0 -1
  36. package/dist/runtime/protocol.js.map +0 -1
  37. package/dist/runtime/worker-source.d.ts +0 -11
  38. package/dist/runtime/worker-source.js +0 -2
  39. package/dist/utils/options.js +0 -76
  40. package/dist/utils/options.js.map +0 -1
  41. package/dist/utils/source-cache.js +0 -77
  42. package/dist/utils/source-cache.js.map +0 -1
  43. package/src/runtime/guest-sources.ts +0 -351
  44. package/src/runtime/manager.ts +0 -963
  45. package/src/runtime/max-workers.ts +0 -65
  46. package/src/runtime/protocol.ts +0 -74
  47. package/src/runtime/worker-source.ts +0 -10
  48. package/src/runtime/worker.ts +0 -607
  49. package/src/utils/options.ts +0 -83
  50. package/src/utils/source-cache.ts +0 -91
@@ -1,6 +1,547 @@
1
- import { runManagedCodeMode } from "./runtime/manager.js";
1
+ import { Buffer } from "node:buffer";
2
+ import { createHash } from "node:crypto";
3
+ import {
4
+ createRunner,
5
+ createSignedContinuationCodec,
6
+ getHostFunctionContext,
7
+ RunError
8
+ } from "run";
9
+ import {
10
+ isCodeModeApprovalInterruptPayload,
11
+ normalizeApprovalResolution
12
+ } from "./approval.js";
13
+ import {
14
+ resolveCodeModeContinuationSecurity,
15
+ signCodeModeContinuation,
16
+ verifyCodeModeContinuation
17
+ } from "./continuation-capability.js";
18
+ import {
19
+ CodeModeAbortedError,
20
+ CodeModeBridgeLimitError,
21
+ CodeModeConcurrencyError,
22
+ CodeModeDetachedBridgeRequestError,
23
+ CodeModeError,
24
+ CodeModeProtocolError,
25
+ CodeModeSourceTooLargeError,
26
+ CodeModeTimeoutError,
27
+ CodeModeToolApprovalDeniedError
28
+ } from "./errors.js";
29
+ import { invokeHostTool } from "./tool-invocation.js";
30
+ import { fromJsonPayload, toJsonPayload } from "./utils/serialization.js";
31
+ const SOURCE_LINE_OFFSET = 1;
32
+ const MAX_RUN_LIMIT = 2147483647;
33
+ const DEFAULT_TIMEOUT_MS = 3e4;
34
+ const DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;
35
+ const DEFAULT_STACK_LIMIT_BYTES = 2 * 1024 * 1024;
36
+ const DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;
37
+ const DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;
38
+ const DEFAULT_MAX_SOURCE_BYTES = 256 * 1024;
39
+ const DEFAULT_MAX_TOOL_INPUT_BYTES = 1024 * 1024;
40
+ const DEFAULT_MAX_TOOL_OUTPUT_BYTES = 4 * 1024 * 1024;
41
+ const DEFAULT_MAX_BRIDGE_REQUESTS = 256;
42
+ const DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS = 32;
43
+ let invocationCounter = 0;
2
44
  async function runCodeMode(input) {
3
- return await runManagedCodeMode(input);
45
+ const policy = resolveExecutionPolicy(input.options?.executionPolicy);
46
+ assertSourceSize(input.js, policy.maxSourceBytes);
47
+ const toolNames = Object.keys(input.tools).sort();
48
+ const continuationState = prepareContinuation(
49
+ input,
50
+ toolNames,
51
+ policy.maxToolOutputBytes
52
+ );
53
+ if (continuationState.nextInterrupt !== void 0) {
54
+ return continuationState.nextInterrupt;
55
+ }
56
+ const outerToolCallId = input.toolExecutionOptions?.toolCallId ?? input.continuation?.outerToolCallId ?? `code-mode-${++invocationCounter}`;
57
+ const source = createCodeModeSource(input.js, toolNames);
58
+ const codeModeErrors = [];
59
+ const hostFunctions = createHostFunctions({
60
+ codeModeErrors,
61
+ input,
62
+ outerToolCallId,
63
+ policy,
64
+ toolNames
65
+ });
66
+ const continuationSecurity = resolveCodeModeContinuationSecurity(
67
+ input.options?.continuationSecurity
68
+ );
69
+ const runner = createRunner({
70
+ continuationAudience: "@ai-sdk/code-mode/v2",
71
+ continuationCodec: createSignedContinuationCodec({
72
+ maxAgeMs: continuationSecurity.maxAgeMs,
73
+ secret: createHash("sha256").update(continuationSecurity.signingKey).digest()
74
+ })
75
+ });
76
+ try {
77
+ const result = await runner.run({
78
+ source,
79
+ hostFunctions,
80
+ limits: toRunLimits(policy, source, input.js),
81
+ continuationContext: { outerToolCallId, toolNames },
82
+ ...input.toolExecutionOptions?.abortSignal === void 0 ? {} : { abortSignal: input.toolExecutionOptions.abortSignal },
83
+ ...continuationState.token === void 0 ? {} : { continuation: continuationState.token },
84
+ ...continuationState.resolutions === void 0 ? {} : { resolutions: continuationState.resolutions }
85
+ });
86
+ if (result.status === "completed") {
87
+ return fromJsonPayload(
88
+ toJsonPayload(result.value, policy.maxResultBytes, "Code mode result")
89
+ );
90
+ }
91
+ const pendingInterruptions = toPendingInterruptions({
92
+ interruptions: result.interruptions,
93
+ outerToolCallId,
94
+ toolNames
95
+ });
96
+ const continuation = signCodeModeContinuation(
97
+ {
98
+ version: 2,
99
+ js: input.js,
100
+ outerToolCallId,
101
+ toolNames,
102
+ token: result.continuation,
103
+ pendingInterruptions,
104
+ resolutions: []
105
+ },
106
+ continuationSecurity
107
+ );
108
+ return toCodeModeInterrupt(continuation, 0);
109
+ } catch (error) {
110
+ const preserved = findPreservedCodeModeError(error, codeModeErrors);
111
+ if (preserved !== void 0) {
112
+ throw translateSourceStack(preserved);
113
+ }
114
+ throw translateSourceStack(toCodeModeRuntimeError(error));
115
+ }
116
+ }
117
+ function resolveExecutionPolicy(policy = {}) {
118
+ return {
119
+ timeoutMs: policy.timeoutMs ?? DEFAULT_TIMEOUT_MS,
120
+ memoryLimitBytes: policy.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,
121
+ maxStackSizeBytes: policy.maxStackSizeBytes ?? DEFAULT_STACK_LIMIT_BYTES,
122
+ maxResultBytes: policy.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES,
123
+ maxConsoleOutputBytes: policy.maxConsoleOutputBytes ?? DEFAULT_MAX_CONSOLE_OUTPUT_BYTES,
124
+ maxSourceBytes: policy.maxSourceBytes ?? DEFAULT_MAX_SOURCE_BYTES,
125
+ maxToolInputBytes: policy.maxToolInputBytes ?? DEFAULT_MAX_TOOL_INPUT_BYTES,
126
+ maxToolOutputBytes: policy.maxToolOutputBytes ?? DEFAULT_MAX_TOOL_OUTPUT_BYTES,
127
+ maxBridgeRequests: policy.maxBridgeRequests ?? DEFAULT_MAX_BRIDGE_REQUESTS,
128
+ maxInFlightBridgeRequests: policy.maxInFlightBridgeRequests ?? DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS
129
+ };
130
+ }
131
+ function assertSourceSize(source, maxBytes) {
132
+ if (!isValidRunLimit(maxBytes)) {
133
+ return;
134
+ }
135
+ const bytes = Buffer.byteLength(source);
136
+ if (bytes > maxBytes) {
137
+ throw new CodeModeSourceTooLargeError(bytes, maxBytes);
138
+ }
139
+ }
140
+ function createCodeModeSource(js, toolNames) {
141
+ const bindings = Object.fromEntries(
142
+ toolNames.map((toolName, index) => [toolName, `__codeMode.tool${index}`])
143
+ );
144
+ const bindingSource = Object.entries(bindings).map(([name, reference]) => `${JSON.stringify(name)}:${reference}`).join(",");
145
+ 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()=>{
146
+ ${js}
147
+ })();if(__codeModeResult===undefined)return undefined;return JSON.parse(JSON.stringify(__codeModeResult));`;
148
+ }
149
+ function createHostFunctions({
150
+ codeModeErrors,
151
+ input,
152
+ outerToolCallId,
153
+ policy,
154
+ toolNames
155
+ }) {
156
+ const group = {};
157
+ for (const [index, toolName] of toolNames.entries()) {
158
+ group[`tool${index}`] = async (toolInput) => await invokeCodeModeTool({
159
+ codeModeErrors,
160
+ input,
161
+ outerToolCallId,
162
+ policy,
163
+ toolInput,
164
+ toolName
165
+ });
166
+ }
167
+ group.missing = async (toolName, toolInput) => await invokeCodeModeTool({
168
+ codeModeErrors,
169
+ input,
170
+ outerToolCallId,
171
+ policy,
172
+ toolInput,
173
+ toolName: String(toolName)
174
+ });
175
+ return { __codeMode: group };
176
+ }
177
+ async function invokeCodeModeTool({
178
+ codeModeErrors,
179
+ input,
180
+ outerToolCallId,
181
+ policy,
182
+ toolInput,
183
+ toolName
184
+ }) {
185
+ const context = getHostFunctionContext();
186
+ const toolCallId = `${outerToolCallId}:tool-${context.requestIndex}`;
187
+ const forwardedContext = input.toolExecutionOptions?.context ?? input.toolExecutionOptions?.experimental_context;
188
+ const forwardedExperimentalContext = input.toolExecutionOptions?.experimental_context ?? input.toolExecutionOptions?.context;
189
+ const baseExecutionOptions = {
190
+ toolCallId: outerToolCallId,
191
+ messages: input.toolExecutionOptions?.messages ?? [],
192
+ abortSignal: context.abortSignal,
193
+ ...forwardedContext === void 0 ? {} : { context: forwardedContext },
194
+ ...forwardedExperimentalContext === void 0 ? {} : { experimental_context: forwardedExperimentalContext }
195
+ };
196
+ let codeModeInterrupt;
197
+ let skipApproval = false;
198
+ if (context.resume !== void 0) {
199
+ const payload = assertInterruptPayload(context.resume.payload);
200
+ if (isCodeModeApprovalInterruptPayload(payload)) {
201
+ const decision = normalizeApprovalResolution(context.resume.resolution);
202
+ if (!decision.approved) {
203
+ throw new CodeModeToolApprovalDeniedError(
204
+ toolName,
205
+ toolInput,
206
+ toolCallId,
207
+ decision.reason
208
+ );
209
+ }
210
+ skipApproval = true;
211
+ } else {
212
+ codeModeInterrupt = {
213
+ interruptId: `${toolCallId}:interrupt`,
214
+ payload,
215
+ resolution: context.resume.resolution
216
+ };
217
+ }
218
+ }
219
+ try {
220
+ const inputJson = toJsonPayload(
221
+ toolInput,
222
+ policy.maxToolInputBytes,
223
+ `Tool "${toolName}" input`
224
+ );
225
+ const outcome = await invokeHostTool({
226
+ toolName,
227
+ inputJson,
228
+ tools: input.tools,
229
+ baseExecutionOptions,
230
+ codeModeOptions: input.options ?? {},
231
+ maxToolInputBytes: policy.maxToolInputBytes,
232
+ maxToolOutputBytes: policy.maxToolOutputBytes,
233
+ toolCallId,
234
+ ...codeModeInterrupt === void 0 ? {} : { codeModeInterrupt },
235
+ skipApproval
236
+ });
237
+ if (outcome.type === "interrupted") {
238
+ return context.interrupt(outcome.payload);
239
+ }
240
+ return fromJsonPayload(outcome.valueJson);
241
+ } catch (error) {
242
+ if (error instanceof CodeModeError) {
243
+ codeModeErrors.push(error);
244
+ throw new RunError(error.message, error.code, error.details);
245
+ }
246
+ if (RunError.isInstance(error) || error instanceof Error && error.name === "HostFunctionInterruptSignal") {
247
+ throw error;
248
+ }
249
+ throw new RunError("Host tool failed.", "CODE_MODE_HOST_TOOL_ERROR");
250
+ }
251
+ }
252
+ function assertInterruptPayload(value) {
253
+ if (typeof value !== "object" || value === null || Array.isArray(value) || typeof value.kind !== "string") {
254
+ throw new CodeModeProtocolError(
255
+ "Code mode interruption payload is malformed."
256
+ );
257
+ }
258
+ return value;
259
+ }
260
+ function toRunLimits(policy, source, userSource) {
261
+ return {
262
+ timeoutMs: policy.timeoutMs,
263
+ memoryLimitBytes: policy.memoryLimitBytes,
264
+ maxStackSizeBytes: policy.maxStackSizeBytes,
265
+ maxResultBytes: expandedSerializationLimit(policy.maxResultBytes),
266
+ maxConsoleOutputBytes: policy.maxConsoleOutputBytes,
267
+ maxSourceBytes: withSerializationOverhead(
268
+ policy.maxSourceBytes,
269
+ Buffer.byteLength(source) - Buffer.byteLength(userSource)
270
+ ),
271
+ maxHostFunctionArgumentsBytes: expandedSerializationLimit(
272
+ policy.maxToolInputBytes
273
+ ),
274
+ maxHostFunctionOutputBytes: expandedSerializationLimit(
275
+ policy.maxToolOutputBytes
276
+ ),
277
+ maxBridgeRequests: policy.maxBridgeRequests,
278
+ maxInFlightBridgeRequests: policy.maxInFlightBridgeRequests
279
+ };
280
+ }
281
+ function expandedSerializationLimit(value) {
282
+ if (!isValidRunLimit(value)) {
283
+ return value;
284
+ }
285
+ return Math.min(MAX_RUN_LIMIT, Math.max(4096, value * 2 + 1024));
286
+ }
287
+ function withSerializationOverhead(value, overhead) {
288
+ return isValidRunLimit(value) ? Math.min(MAX_RUN_LIMIT, value + overhead) : value;
289
+ }
290
+ function isValidRunLimit(value) {
291
+ return Number.isInteger(value) && value > 0 && value <= MAX_RUN_LIMIT;
292
+ }
293
+ function prepareContinuation(input, toolNames, maxToolOutputBytes) {
294
+ if (input.continuation === void 0) {
295
+ if (input.interruptResolution !== void 0) {
296
+ throw new CodeModeProtocolError(
297
+ "A code-mode interrupt resolution was provided without continuation state."
298
+ );
299
+ }
300
+ return {};
301
+ }
302
+ verifyCodeModeContinuation(
303
+ input.continuation,
304
+ input.options?.continuationSecurity
305
+ );
306
+ if (input.continuation.js !== input.js) {
307
+ throw new CodeModeProtocolError(
308
+ "Code mode continuation source does not match the resumed source."
309
+ );
310
+ }
311
+ if (!stringArraysEqual(input.continuation.toolNames, toolNames)) {
312
+ throw new CodeModeProtocolError(
313
+ "Code mode continuation tool names do not match the resumed tools."
314
+ );
315
+ }
316
+ if (input.interruptResolution === void 0) {
317
+ throw new CodeModeProtocolError(
318
+ "A code-mode continuation requires an interrupt resolution."
319
+ );
320
+ }
321
+ const resolutionIndex = input.continuation.resolutions.length;
322
+ const pending = input.continuation.pendingInterruptions[resolutionIndex];
323
+ if (pending === void 0 || pending.interruptId !== input.interruptResolution.interruptId) {
324
+ throw new CodeModeProtocolError(
325
+ "Interrupt resolution does not match the next pending code-mode interruption.",
326
+ { interruptId: input.interruptResolution.interruptId }
327
+ );
328
+ }
329
+ const resolutionValue = normalizeResolutionForPending(
330
+ pending,
331
+ input.interruptResolution.resolution,
332
+ maxToolOutputBytes
333
+ );
334
+ const resolutions = [
335
+ ...input.continuation.resolutions,
336
+ {
337
+ runInterruptionId: pending.runInterruptionId,
338
+ value: resolutionValue
339
+ }
340
+ ];
341
+ if (resolutions.length < input.continuation.pendingInterruptions.length) {
342
+ const continuation = signCodeModeContinuation(
343
+ {
344
+ ...withoutAuth(input.continuation),
345
+ resolutions
346
+ },
347
+ resolveCodeModeContinuationSecurity(input.options?.continuationSecurity)
348
+ );
349
+ return {
350
+ nextInterrupt: toCodeModeInterrupt(continuation, resolutions.length)
351
+ };
352
+ }
353
+ assertNoDeniedApproval(input.continuation.pendingInterruptions, resolutions);
354
+ return {
355
+ token: input.continuation.token,
356
+ resolutions: resolutions.map((resolution) => ({
357
+ interruptionId: resolution.runInterruptionId,
358
+ value: resolution.value
359
+ }))
360
+ };
361
+ }
362
+ function normalizeResolutionForPending(pending, resolution, maxToolOutputBytes) {
363
+ return isCodeModeApprovalInterruptPayload(pending.payload) ? normalizeApprovalResolution(resolution) : fromJsonPayload(
364
+ toJsonPayload(
365
+ resolution,
366
+ maxToolOutputBytes,
367
+ `Resolution "${pending.interruptId}"`
368
+ )
369
+ );
370
+ }
371
+ function assertNoDeniedApproval(pendingInterruptions, resolutions) {
372
+ for (const [index, pending] of pendingInterruptions.entries()) {
373
+ if (!isCodeModeApprovalInterruptPayload(pending.payload)) {
374
+ continue;
375
+ }
376
+ const decision = normalizeApprovalResolution(resolutions[index]?.value);
377
+ if (!decision.approved) {
378
+ throw new CodeModeToolApprovalDeniedError(
379
+ pending.toolName,
380
+ pending.input,
381
+ pending.toolCallId,
382
+ decision.reason
383
+ );
384
+ }
385
+ }
386
+ }
387
+ function withoutAuth(continuation) {
388
+ const { auth: _auth, ...unsigned } = continuation;
389
+ return unsigned;
390
+ }
391
+ function toPendingInterruptions({
392
+ interruptions,
393
+ outerToolCallId,
394
+ toolNames
395
+ }) {
396
+ return interruptions.map((interruption) => {
397
+ const requestIndex = interruptionIndex(interruption.id);
398
+ const toolName = toolNameForInterruption(interruption, toolNames);
399
+ const toolCallId = `${outerToolCallId}:tool-${requestIndex}`;
400
+ return {
401
+ runInterruptionId: interruption.id,
402
+ interruptId: `${toolCallId}:interrupt`,
403
+ toolName,
404
+ toolCallId,
405
+ input: interruption.hostFunctionName === "__codeMode.missing" ? interruption.arguments[1] : interruption.arguments[0],
406
+ payload: assertInterruptPayload(interruption.payload)
407
+ };
408
+ });
409
+ }
410
+ function interruptionIndex(interruptionId) {
411
+ const match = /^interrupt-(\d+)$/u.exec(interruptionId);
412
+ if (match === null) {
413
+ throw new CodeModeProtocolError(
414
+ `Run returned malformed interruption id "${interruptionId}".`
415
+ );
416
+ }
417
+ return Number(match[1]);
418
+ }
419
+ function toolNameForInterruption(interruption, toolNames) {
420
+ if (interruption.hostFunctionName === "__codeMode.missing") {
421
+ return String(interruption.arguments[0]);
422
+ }
423
+ const match = /^__codeMode\.tool(\d+)$/u.exec(interruption.hostFunctionName);
424
+ const toolName = match === null ? void 0 : toolNames[Number(match[1])];
425
+ if (toolName === void 0) {
426
+ throw new CodeModeProtocolError(
427
+ `Run returned an unknown code-mode host function "${interruption.hostFunctionName}".`
428
+ );
429
+ }
430
+ return toolName;
431
+ }
432
+ function toCodeModeInterrupt(continuation, index) {
433
+ const pending = continuation.pendingInterruptions[index];
434
+ if (pending === void 0) {
435
+ throw new CodeModeProtocolError(
436
+ "Code mode continuation has no pending interruption at the requested index."
437
+ );
438
+ }
439
+ return {
440
+ type: "code-mode-interrupt",
441
+ interruptId: pending.interruptId,
442
+ toolName: pending.toolName,
443
+ toolCallId: pending.toolCallId,
444
+ outerToolCallId: continuation.outerToolCallId,
445
+ input: structuredClone(pending.input),
446
+ payload: structuredClone(pending.payload),
447
+ continuation
448
+ };
449
+ }
450
+ function stringArraysEqual(left, right) {
451
+ return left.length === right.length && left.every((value, index) => value === right[index]);
452
+ }
453
+ function findPreservedCodeModeError(error, errors) {
454
+ if (!RunError.isInstance(error)) {
455
+ return void 0;
456
+ }
457
+ return errors.find((candidate) => candidate.code === error.code);
458
+ }
459
+ function toCodeModeRuntimeError(error) {
460
+ if (error instanceof TypeError) {
461
+ error.message = translateLimitPath(error.message);
462
+ }
463
+ if (error instanceof Error && error.name === "SyntaxError" && !/syntax|unexpected|expression expected/iu.test(error.message)) {
464
+ error.message = `Syntax error: ${error.message}`;
465
+ }
466
+ if (!RunError.isInstance(error)) {
467
+ return error;
468
+ }
469
+ const details = error.details;
470
+ switch (error.code) {
471
+ case "RUN_ABORTED":
472
+ return copyStack(new CodeModeAbortedError(), error);
473
+ case "RUN_TIMEOUT":
474
+ return copyStack(
475
+ new CodeModeTimeoutError(Number(details?.timeoutMs ?? 0)),
476
+ error
477
+ );
478
+ case "RUN_CONCURRENCY_LIMIT":
479
+ return copyStack(
480
+ new CodeModeConcurrencyError(Number(details?.maxWorkers ?? 0)),
481
+ error
482
+ );
483
+ case "RUN_SOURCE_TOO_LARGE":
484
+ return copyStack(
485
+ new CodeModeSourceTooLargeError(
486
+ Number(details?.bytes ?? 0),
487
+ Number(details?.maxBytes ?? 0)
488
+ ),
489
+ error
490
+ );
491
+ case "RUN_BRIDGE_LIMIT":
492
+ return copyStack(
493
+ new CodeModeBridgeLimitError(error.message, error.details),
494
+ error
495
+ );
496
+ case "RUN_DETACHED_BRIDGE_REQUEST":
497
+ return copyStack(
498
+ new CodeModeDetachedBridgeRequestError(error.message, error.details),
499
+ error
500
+ );
501
+ case "RUN_PROTOCOL_ERROR":
502
+ return copyStack(
503
+ new CodeModeProtocolError(error.message, error.details),
504
+ error
505
+ );
506
+ default:
507
+ return error;
508
+ }
509
+ }
510
+ function translateLimitPath(message) {
511
+ const paths = {
512
+ "limits.timeoutMs": "executionPolicy.timeoutMs",
513
+ "limits.memoryLimitBytes": "executionPolicy.memoryLimitBytes",
514
+ "limits.maxStackSizeBytes": "executionPolicy.maxStackSizeBytes",
515
+ "limits.maxResultBytes": "executionPolicy.maxResultBytes",
516
+ "limits.maxConsoleOutputBytes": "executionPolicy.maxConsoleOutputBytes",
517
+ "limits.maxSourceBytes": "executionPolicy.maxSourceBytes",
518
+ "limits.maxHostFunctionArgumentsBytes": "executionPolicy.maxToolInputBytes",
519
+ "limits.maxHostFunctionOutputBytes": "executionPolicy.maxToolOutputBytes",
520
+ "limits.maxBridgeRequests": "executionPolicy.maxBridgeRequests",
521
+ "limits.maxInFlightBridgeRequests": "executionPolicy.maxInFlightBridgeRequests"
522
+ };
523
+ for (const [runPath, codeModePath] of Object.entries(paths)) {
524
+ if (message.includes(runPath)) {
525
+ return message.replace(runPath, codeModePath);
526
+ }
527
+ }
528
+ return message;
529
+ }
530
+ function copyStack(target, source) {
531
+ if (source.stack !== void 0) {
532
+ target.stack = source.stack;
533
+ }
534
+ return target;
535
+ }
536
+ function translateSourceStack(error) {
537
+ if (!(error instanceof Error) || error.stack === void 0) {
538
+ return error;
539
+ }
540
+ error.stack = error.stack.replaceAll(
541
+ /run\.js:(\d+):(\d+)/gu,
542
+ (_match, line, column) => `code-mode.js:${Math.max(1, Number(line) - SOURCE_LINE_OFFSET)}:${column}`
543
+ );
544
+ return error;
4
545
  }
5
546
  export {
6
547
  runCodeMode
@@ -1 +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":[]}
1
+ {"version":3,"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":"AAAA,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAY/B,SAAS,iBAAiB,qBAAqB;AAE/C,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B,KAAK,OAAO;AAC/C,MAAM,4BAA4B,IAAI,OAAO;AAC7C,MAAM,2BAA2B,OAAO;AACxC,MAAM,mCAAmC,KAAK;AAC9C,MAAM,2BAA2B,MAAM;AACvC,MAAM,+BAA+B,OAAO;AAC5C,MAAM,gCAAgC,IAAI,OAAO;AACjD,MAAM,8BAA8B;AACpC,MAAM,wCAAwC;AAE9C,IAAI,oBAAoB;AAWxB,eAAsB,YAAY,OAA2C;AAC3E,QAAM,SAAS,uBAAuB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BAAyB;AAAA,IACzB,gCAAgC;AAAA,IAChC,yBAAyB;AAAA,IACzB,wCAAwC;AAAA,IACxC,qCAAqC;AAAA,IACrC,4BAA4B;AAAA,IAC5B,oCACE;AAAA,EACJ;AACA,aAAW,CAAC,SAAS,YAAY,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC3D,QAAI,QAAQ,SAAS,OAAO,GAAG;AAC7B,aAAO,QAAQ,QAAQ,SAAS,YAAY;AAAA,IAC9C;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,UAA2B,QAAW,QAAkB;AAC/D,MAAI,OAAO,UAAU,QAAW;AAC9B,WAAO,QAAQ,OAAO;AAAA,EACxB;AACA,SAAO;AACT;AAEA,SAAS,qBAAwB,OAAa;AAC5C,MAAI,EAAE,iBAAiB,UAAU,MAAM,UAAU,QAAW;AAC1D,WAAO;AAAA,EACT;AACA,QAAM,QAAQ,MAAM,MAAM;AAAA,IACxB;AAAA,IACA,CAAC,QAAQ,MAAc,WACrB,gBAAgB,KAAK,IAAI,GAAG,OAAO,IAAI,IAAI,kBAAkB,CAAC,IAAI,MAAM;AAAA,EAC5E;AACA,SAAO;AACT;","names":[]}
@@ -6,9 +6,9 @@ import {
6
6
  CodeModeToolApprovalRequiredError,
7
7
  CodeModeToolError
8
8
  } from "./errors.js";
9
- import { isCodeModeHostInterruptSignal } from "./host-interrupt.js";
10
9
  import {
11
10
  assertJsonSerializable,
11
+ fromJsonPayload,
12
12
  toJsonPayload
13
13
  } from "./utils/serialization.js";
14
14
  async function invokeHostTool({
@@ -36,7 +36,7 @@ async function invokeHostTool({
36
36
  toolName
37
37
  });
38
38
  }
39
- const input = inputJson === "" ? void 0 : JSON.parse(inputJson);
39
+ const input = fromJsonPayload(inputJson);
40
40
  assertJsonSerializable(input, maxToolInputBytes, `Tool "${toolName}" input`);
41
41
  const validation = await raceAgainstAbort(
42
42
  validateToolInput(hostTool.inputSchema, input),
@@ -107,27 +107,13 @@ async function invokeHostTool({
107
107
  );
108
108
  }
109
109
  }
110
- let output;
111
- try {
112
- output = await raceAgainstAbort(
113
- executeHostTool(hostTool.execute.bind(hostTool), {
114
- input: validation.value,
115
- options: executionOptions
116
- }),
117
- executionOptions.abortSignal
118
- );
119
- } catch (error) {
120
- if (isCodeModeHostInterruptSignal(error)) {
121
- return {
122
- type: "interrupted",
123
- toolName,
124
- input: validation.value,
125
- toolCallId,
126
- payload: error.payload
127
- };
128
- }
129
- throw error;
130
- }
110
+ const output = await raceAgainstAbort(
111
+ executeHostTool(hostTool.execute.bind(hostTool), {
112
+ input: validation.value,
113
+ options: executionOptions
114
+ }),
115
+ executionOptions.abortSignal
116
+ );
131
117
  return {
132
118
  type: "success",
133
119
  valueJson: toJsonPayload(