@ai-sdk/code-mode 1.0.119 → 1.0.121
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/code-mode-tool.js +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/run-code-mode.js +17 -5
- package/dist/run-code-mode.js.map +1 -1
- package/dist/tool-prompt.js +1 -1
- package/dist/tool-prompt.js.map +1 -1
- package/package.json +3 -3
- package/src/run-code-mode.ts +29 -6
- package/src/tool-prompt.ts +1 -1
package/dist/code-mode-tool.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { runCodeMode } from "./run-code-mode.js";
|
|
2
1
|
import { buildCodeModeToolCatalogMessage, buildCodeModeToolDescription } from "./tool-prompt.js";
|
|
2
|
+
import { runCodeMode } from "./run-code-mode.js";
|
|
3
3
|
import { experimental_toolCaller, jsonSchema, tool } from "ai";
|
|
4
4
|
//#region src/code-mode-tool.ts
|
|
5
5
|
/**
|
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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A8B;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;;;;;;;;;;;;
|
|
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;EAA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5IY,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;;;;;;;;;;;;iBCzCmB,YAAY,OAAO,mBAAmB;;;iBCrD5C,kCACd,eAAe,YACf;EAAW"}
|
package/dist/run-code-mode.js
CHANGED
|
@@ -3,6 +3,7 @@ import { isCodeModeApprovalInterruptPayload, normalizeApprovalResolution } from
|
|
|
3
3
|
import { resolveCodeModeContinuationSecurity, signCodeModeContinuation, verifyCodeModeContinuation } from "./continuation-capability.js";
|
|
4
4
|
import { fromJsonPayload, toJsonPayload } from "./utils/serialization.js";
|
|
5
5
|
import { invokeHostTool } from "./tool-invocation.js";
|
|
6
|
+
import { formatPropertyAccess } from "./tool-prompt.js";
|
|
6
7
|
import { createHash } from "node:crypto";
|
|
7
8
|
import { Buffer } from "node:buffer";
|
|
8
9
|
import { RunError, createRunner, createSignedContinuationCodec, getHostFunctionContext } from "run";
|
|
@@ -85,7 +86,7 @@ async function runCodeMode(input) {
|
|
|
85
86
|
} catch (error) {
|
|
86
87
|
const preserved = findPreservedCodeModeError(error, codeModeErrors);
|
|
87
88
|
if (preserved !== void 0) throw translateSourceStack(preserved);
|
|
88
|
-
throw translateSourceStack(toCodeModeRuntimeError(error));
|
|
89
|
+
throw translateSourceStack(toCodeModeRuntimeError(error, toolNames));
|
|
89
90
|
}
|
|
90
91
|
}
|
|
91
92
|
function resolveExecutionPolicy(policy = {}) {
|
|
@@ -278,11 +279,14 @@ function interruptionIndex(interruptionId) {
|
|
|
278
279
|
}
|
|
279
280
|
function toolNameForInterruption(interruption, toolNames) {
|
|
280
281
|
if (interruption.hostFunctionName === "__codeMode.missing") return String(interruption.arguments[0]);
|
|
281
|
-
const
|
|
282
|
-
const toolName = match === null ? void 0 : toolNames[Number(match[1])];
|
|
282
|
+
const toolName = toolNameForHostFunction(interruption.hostFunctionName, toolNames);
|
|
283
283
|
if (toolName === void 0) throw new CodeModeProtocolError(`Run returned an unknown code-mode host function "${interruption.hostFunctionName}".`);
|
|
284
284
|
return toolName;
|
|
285
285
|
}
|
|
286
|
+
function toolNameForHostFunction(hostFunctionName, toolNames) {
|
|
287
|
+
const match = /^__codeMode\.tool(\d+)$/u.exec(hostFunctionName);
|
|
288
|
+
return match === null ? void 0 : toolNames[Number(match[1])];
|
|
289
|
+
}
|
|
286
290
|
function toCodeModeInterrupt(continuation, index) {
|
|
287
291
|
const pending = continuation.pendingInterruptions[index];
|
|
288
292
|
if (pending === void 0) throw new CodeModeProtocolError("Code mode continuation has no pending interruption at the requested index.");
|
|
@@ -304,7 +308,7 @@ function findPreservedCodeModeError(error, errors) {
|
|
|
304
308
|
if (!RunError.isInstance(error)) return;
|
|
305
309
|
return errors.find((candidate) => candidate.code === error.code);
|
|
306
310
|
}
|
|
307
|
-
function toCodeModeRuntimeError(error) {
|
|
311
|
+
function toCodeModeRuntimeError(error, toolNames) {
|
|
308
312
|
if (error instanceof TypeError) error.message = translateLimitPath(error.message);
|
|
309
313
|
if (error instanceof Error && error.name === "SyntaxError" && !/syntax|unexpected|expression expected/iu.test(error.message)) error.message = `Syntax error: ${error.message}`;
|
|
310
314
|
if (!RunError.isInstance(error)) return error;
|
|
@@ -316,7 +320,15 @@ function toCodeModeRuntimeError(error) {
|
|
|
316
320
|
case "RUN_CONCURRENCY_LIMIT": return copyStack(new CodeModeConcurrencyError(Number(details?.maxWorkers ?? 0)), error);
|
|
317
321
|
case "RUN_SOURCE_TOO_LARGE": return copyStack(new CodeModeSourceTooLargeError(Number(details?.bytes ?? 0), Number(details?.maxBytes ?? 0)), error);
|
|
318
322
|
case "RUN_BRIDGE_LIMIT": return copyStack(new CodeModeBridgeLimitError(error.message, error.details), error);
|
|
319
|
-
case "RUN_DETACHED_BRIDGE_REQUEST":
|
|
323
|
+
case "RUN_DETACHED_BRIDGE_REQUEST": {
|
|
324
|
+
let message = error.message;
|
|
325
|
+
const hostFunctionName = details?.name;
|
|
326
|
+
if (typeof hostFunctionName === "string") {
|
|
327
|
+
const toolName = toolNameForHostFunction(hostFunctionName, toolNames);
|
|
328
|
+
if (toolName !== void 0) message = message.replace(hostFunctionName, () => `tools${formatPropertyAccess(toolName)}`);
|
|
329
|
+
}
|
|
330
|
+
return copyStack(new CodeModeDetachedBridgeRequestError(message, error.details), error);
|
|
331
|
+
}
|
|
320
332
|
case "RUN_PROTOCOL_ERROR": return copyStack(new CodeModeProtocolError(error.message, error.details), error);
|
|
321
333
|
default: return error;
|
|
322
334
|
}
|
|
@@ -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 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,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,yBAAyB;AAC/B,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,MAA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,yBAAyB,OAAO,SAAS,cAAc,CAAC,CAAC,GAC7D,KACF;EACF,KAAK,wBACH,OAAO,UACL,IAAI,4BACF,OAAO,SAAS,SAAS,CAAC,GAC1B,OAAO,SAAS,YAAY,CAAC,CAC/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;CAenD,KAAK,MAAM,CAAC,SAAS,iBAAiB,OAAO,QAAQ;EAbnD,oBAAoB;EACpB,uBAAuB;EACvB,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 { formatPropertyAccess } from './tool-prompt.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, toolNames));\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 toolName = toolNameForHostFunction(\n interruption.hostFunctionName,\n toolNames,\n );\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 toolNameForHostFunction(\n hostFunctionName: string,\n toolNames: string[],\n): string | undefined {\n const match = /^__codeMode\\.tool(\\d+)$/u.exec(hostFunctionName);\n return match === null ? undefined : toolNames[Number(match[1])];\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, toolNames: string[]): 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 let message = error.message;\n const hostFunctionName = details?.name;\n if (typeof hostFunctionName === 'string') {\n const toolName = toolNameForHostFunction(hostFunctionName, toolNames);\n if (toolName !== undefined) {\n message = message.replace(\n hostFunctionName,\n () => `tools${formatPropertyAccess(toolName)}`,\n );\n }\n }\n return copyStack(\n new CodeModeDetachedBridgeRequestError(message, error.details),\n error,\n );\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":";;;;;;;;;;AAgDA,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,yBAAyB;AAC/B,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,CAAC,KAAK;CAChD,MAAM,oBAAoB,oBACxB,OACA,WACA,OAAO,kBACT;CACA,IAAI,kBAAkB,kBAAkB,KAAA,GACtC,OAAO,kBAAkB;CAG3B,MAAM,kBACJ,MAAM,sBAAsB,cAC5B,MAAM,cAAc,mBACpB,aAAa,EAAE;CACjB,MAAM,SAAS,qBAAqB,MAAM,IAAI,SAAS;CACvD,MAAM,iBAAkC,CAAC;CACzC,MAAM,gBAAgB,oBAAoB;EACxC;EACA;EACA;EACA;EACA;CACF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AA+B;GAClC,IAAI,UAAU,MAAM;GACpB,MAAM,mBAAmB,SAAS;GAClC,IAAI,OAAO,qBAAqB,UAAU;IACxC,MAAM,WAAW,wBAAwB,kBAAkB,SAAS;IACpE,IAAI,aAAa,KAAA,GACf,UAAU,QAAQ,QAChB,wBACM,QAAQ,qBAAqB,QAAQ,GAC7C;GAEJ;GACA,OAAO,UACL,IAAI,mCAAmC,SAAS,MAAM,OAAO,GAC7D,KACF;EACF;EACA,KAAK,sBACH,OAAO,UACL,IAAI,sBAAsB,MAAM,SAAS,MAAM,OAAO,GACtD,KACF;EACF,SACE,OAAO;CACX;AACF;AAEA,SAAS,mBAAmB,SAAyB;CAenD,KAAK,MAAM,CAAC,SAAS,iBAAiB,OAAO,QAAQ;EAbnD,oBAAoB;EACpB,uBAAuB;EACvB,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"}
|
package/dist/tool-prompt.js
CHANGED
|
@@ -325,6 +325,6 @@ function isPromiseLike(value) {
|
|
|
325
325
|
return isRecord(value) && typeof value.then === "function";
|
|
326
326
|
}
|
|
327
327
|
//#endregion
|
|
328
|
-
export { buildCodeModeToolCatalogMessage, buildCodeModeToolDescription };
|
|
328
|
+
export { buildCodeModeToolCatalogMessage, buildCodeModeToolDescription, formatPropertyAccess };
|
|
329
329
|
|
|
330
330
|
//# sourceMappingURL=tool-prompt.js.map
|
package/dist/tool-prompt.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-prompt.js","names":[],"sources":["../src/tool-prompt.ts"],"sourcesContent":["import { asSchema } from 'ai';\nimport type { CodeModeToolSet } from './types.js';\n\ntype JsonSchema = Record<string, unknown>;\n\ninterface SchemaContext {\n root: JsonSchema;\n seenRefs: Set<string>;\n depth: number;\n}\n\nconst MAX_SCHEMA_DEPTH = 8;\nconst MAX_COMPACT_OBJECT_TYPE_LENGTH = 120;\n\nexport function buildCodeModeToolDescription(\n tools: CodeModeToolSet,\n toolDiscovery: 'description' | 'conversation' = 'description',\n): string {\n const sections = [\n 'Execute code-mode TypeScript in an isolated sandbox.',\n '',\n 'Put the full program in `js`; top-level `await`/`return` work. Return a JSON-serializable result.',\n 'Call host tools only as async `tools.name(input)`; await each or use `Promise.all` for independent calls.',\n toolDiscovery === 'description'\n ? 'Use exact names/types below. `JSON.parse`/`JSON.stringify` are available.'\n : 'Use exact names/types from the latest capability update. `JSON.parse`/`JSON.stringify` are available.',\n 'Fetch: `fetch` is not available.',\n ];\n\n if (toolDiscovery === 'conversation') {\n sections.push(\n '',\n 'Tools:',\n 'The current host-tool API is provided in \"Code mode capability update\" user messages. Follow the latest catalog and ignore earlier catalogs.',\n );\n return sections.join('\\n');\n }\n\n const { typeBlock, exampleBlock } = renderToolCatalog(tools);\n sections.push('', 'Tools:', typeBlock);\n\n if (exampleBlock.length > 0) {\n sections.push(exampleBlock);\n }\n\n return sections.join('\\n');\n}\n\nexport function buildCodeModeToolCatalogMessage(\n tools: CodeModeToolSet,\n): string {\n const { typeBlock, exampleBlock } = renderToolCatalog(tools);\n const sections = [\n 'Code mode capability update.',\n '',\n 'This catalog replaces all previous code mode capability catalogs. Only the tools listed below are currently available through `tools`.',\n '',\n 'Tools:',\n typeBlock,\n ];\n\n if (exampleBlock.length > 0) {\n sections.push(exampleBlock);\n }\n\n return sections.join('\\n');\n}\n\nfunction renderToolCatalog(tools: CodeModeToolSet): {\n typeBlock: string;\n exampleBlock: string;\n} {\n const toolEntries = Object.entries(tools);\n const typeBlock =\n toolEntries.length === 0\n ? 'No host tools. Do not call `tools.*`.'\n : [\n '```ts',\n 'declare const tools: {',\n ...toolEntries.flatMap(renderToolType),\n '};',\n '```',\n ].join('\\n');\n\n const exampleBlock =\n toolEntries.length === 0\n ? ''\n : [\n '',\n 'Tool call examples:',\n '```ts',\n ...renderToolExamples(toolEntries),\n '```',\n ].join('\\n');\n\n return { typeBlock, exampleBlock };\n}\n\nfunction renderToolType([toolName, tool]: [\n string,\n CodeModeToolSet[string],\n]): string[] {\n const schema = resolveInputSchema(tool);\n const inputType =\n schema === undefined ? 'unknown' : schemaToType(schema, schema);\n const outputSchema = resolveOutputSchema(tool);\n const outputType =\n outputSchema === undefined\n ? 'unknown'\n : schemaToType(outputSchema, outputSchema);\n const description = firstString(tool.description, tool.title);\n const lines: string[] = [];\n\n if (description !== undefined) {\n lines.push(` /** ${toComment(description)} */`);\n }\n\n lines.push(\n ` ${formatObjectKey(toolName)}: (input: ${indentType(inputType, 2)}) => Promise<${indentType(outputType, 2)}>;`,\n );\n return lines;\n}\n\nfunction renderToolExamples(\n toolEntries: Array<[string, CodeModeToolSet[string]]>,\n): string[] {\n if (toolEntries.length === 1) {\n const toolEntry = toolEntries[0]!;\n const projection = renderToolProjection('result', toolEntry[1]);\n return [\n `const result = await ${renderToolExampleCall(toolEntry)};`,\n `return ${projection};`,\n ];\n }\n\n const variableNames = uniqueToolVariableNames(\n toolEntries.map(([toolName]) => toolName),\n );\n const calls = toolEntries.map(\n toolEntry => ` ${renderToolExampleCall(toolEntry)},`,\n );\n return [\n `const [${variableNames.join(', ')}] = await Promise.all([`,\n ...calls,\n ']);',\n 'return {',\n ...toolEntries.map(([toolName, tool], index) => {\n const projection = renderToolProjection(variableNames[index]!, tool);\n return ` ${formatObjectKey(toolName)}: ${projection},`;\n }),\n '};',\n ];\n}\n\nfunction renderToolExampleCall([toolName, tool]: [\n string,\n CodeModeToolSet[string],\n]): string {\n const schema = resolveInputSchema(tool);\n const input =\n firstInputExample(tool) ??\n (schema === undefined ? {} : sampleFromSchema(schema, schema));\n return `tools${formatPropertyAccess(toolName)}(${JSON.stringify(input)})`;\n}\n\nfunction renderToolProjection(\n variableName: string,\n tool: CodeModeToolSet[string],\n): string {\n const field = firstObjectProperty(resolveOutputSchema(tool));\n if (field === undefined) {\n return variableName;\n }\n return `{ ${formatObjectKey(field)}: ${variableName}${formatPropertyAccess(field)} }`;\n}\n\nfunction firstObjectProperty(\n schema: JsonSchema | undefined,\n): string | undefined {\n if (schema === undefined || !isRecord(schema.properties)) {\n return undefined;\n }\n return Object.entries(schema.properties).find(entry =>\n isRecord(entry[1]),\n )?.[0];\n}\n\nfunction resolveInputSchema(\n tool: CodeModeToolSet[string],\n): JsonSchema | undefined {\n try {\n const jsonSchema = asSchema(tool.inputSchema).jsonSchema;\n if (isPromiseLike(jsonSchema) || !isRecord(jsonSchema)) {\n return undefined;\n }\n return jsonSchema;\n } catch {\n return undefined;\n }\n}\n\nfunction resolveOutputSchema(\n tool: CodeModeToolSet[string],\n): JsonSchema | undefined {\n try {\n const outputSchema = tool.outputSchema;\n if (outputSchema === undefined) {\n return undefined;\n }\n const jsonSchema = asSchema(outputSchema).jsonSchema;\n if (isPromiseLike(jsonSchema) || !isRecord(jsonSchema)) {\n return undefined;\n }\n return jsonSchema;\n } catch {\n return undefined;\n }\n}\n\nfunction schemaToType(schema: JsonSchema, root: JsonSchema): string {\n return schemaToTypeInner(schema, {\n root,\n seenRefs: new Set(),\n depth: 0,\n });\n}\n\nfunction schemaToTypeInner(schema: JsonSchema, context: SchemaContext): string {\n if (context.depth > MAX_SCHEMA_DEPTH) {\n return 'unknown';\n }\n\n const ref = firstString(schema.$ref);\n if (ref !== undefined) {\n const resolved = resolveRef(ref, context.root, context.seenRefs);\n return resolved === undefined\n ? 'unknown'\n : schemaToTypeInner(resolved, nextContext(context));\n }\n\n const constValue = schema.const;\n if (constValue !== undefined) {\n return literalType(constValue);\n }\n\n const enumValues = asArray(schema.enum);\n if (enumValues !== undefined) {\n return union(enumValues.map(literalType));\n }\n\n const oneOf = schemaArray(schema.oneOf);\n if (oneOf !== undefined) {\n return union(\n oneOf.map(part => schemaToTypeInner(part, nextContext(context))),\n );\n }\n\n const anyOf = schemaArray(schema.anyOf);\n if (anyOf !== undefined) {\n return union(\n anyOf.map(part => schemaToTypeInner(part, nextContext(context))),\n );\n }\n\n const allOf = schemaArray(schema.allOf);\n if (allOf !== undefined) {\n return allOf\n .map(part => schemaToTypeInner(part, nextContext(context)))\n .join(' & ');\n }\n\n const type = schema.type;\n if (Array.isArray(type)) {\n return union(\n type.map(part => schemaToTypeInner({ ...schema, type: part }, context)),\n );\n }\n\n if (type === 'object' || isRecord(schema.properties)) {\n return objectType(schema, context);\n }\n\n if (type === 'array' || schema.items !== undefined) {\n return arrayType(schema, context);\n }\n\n if (type === 'string') {\n return 'string';\n }\n\n if (type === 'number' || type === 'integer') {\n return 'number';\n }\n\n if (type === 'boolean') {\n return 'boolean';\n }\n\n if (type === 'null') {\n return 'null';\n }\n\n return 'unknown';\n}\n\nfunction objectType(schema: JsonSchema, context: SchemaContext): string {\n const properties = isRecord(schema.properties) ? schema.properties : {};\n const required = new Set(asArray(schema.required)?.filter(isString));\n const entries = Object.entries(properties).filter(\n (entry): entry is [string, JsonSchema] => isRecord(entry[1]),\n );\n\n if (entries.length === 0) {\n const additionalProperties = schema.additionalProperties;\n if (isRecord(additionalProperties)) {\n return `Record<string, ${schemaToTypeInner(additionalProperties, nextContext(context))}>`;\n }\n if (additionalProperties === true) {\n return 'Record<string, unknown>';\n }\n return '{}';\n }\n\n const lines = entries.flatMap(([name, value]) => {\n const propertyLines: string[] = [];\n const description = firstString(value.description);\n if (description !== undefined) {\n propertyLines.push(` /** ${toComment(description)} */`);\n }\n propertyLines.push(\n ` ${formatObjectKey(name)}${required.has(name) ? '' : '?'}: ${indentType(\n schemaToTypeInner(value, nextContext(context)),\n 2,\n )};`,\n );\n return propertyLines;\n });\n\n const additionalProperties = schema.additionalProperties;\n if (isRecord(additionalProperties)) {\n lines.push(\n ` [key: string]: ${schemaToTypeInner(additionalProperties, nextContext(context))};`,\n );\n } else if (additionalProperties === true) {\n lines.push(' [key: string]: unknown;');\n }\n\n const compact = compactObjectType(lines);\n if (compact !== undefined) {\n return compact;\n }\n\n return `{\\n${lines.join('\\n')}\\n}`;\n}\n\nfunction arrayType(schema: JsonSchema, context: SchemaContext): string {\n const items = schema.items;\n if (Array.isArray(items)) {\n return `[${items\n .map(item =>\n isRecord(item)\n ? schemaToTypeInner(item, nextContext(context))\n : 'unknown',\n )\n .join(', ')}]`;\n }\n if (isRecord(items)) {\n const itemType = schemaToTypeInner(items, nextContext(context));\n return needsParentheses(itemType) || itemType.includes('\\n')\n ? `Array<${itemType}>`\n : `${itemType}[]`;\n }\n return 'unknown[]';\n}\n\nfunction sampleFromSchema(schema: JsonSchema, root: JsonSchema): unknown {\n return sampleFromSchemaInner(schema, {\n root,\n seenRefs: new Set(),\n depth: 0,\n });\n}\n\nfunction sampleFromSchemaInner(\n schema: JsonSchema,\n context: SchemaContext,\n): unknown {\n if (context.depth > MAX_SCHEMA_DEPTH) {\n return null;\n }\n\n if (schema.default !== undefined) {\n return schema.default;\n }\n\n const ref = firstString(schema.$ref);\n if (ref !== undefined) {\n const resolved = resolveRef(ref, context.root, context.seenRefs);\n return resolved === undefined\n ? null\n : sampleFromSchemaInner(resolved, nextContext(context));\n }\n\n if (schema.const !== undefined) {\n return schema.const;\n }\n\n const enumValues = asArray(schema.enum);\n if (enumValues !== undefined) {\n return enumValues[0] ?? null;\n }\n\n const oneOf = schemaArray(schema.oneOf);\n if (oneOf !== undefined) {\n return sampleFromSchemaInner(oneOf[0] ?? {}, nextContext(context));\n }\n\n const anyOf = schemaArray(schema.anyOf);\n if (anyOf !== undefined) {\n return sampleFromSchemaInner(anyOf[0] ?? {}, nextContext(context));\n }\n\n const type = schema.type;\n if (Array.isArray(type)) {\n return sampleFromSchemaInner(\n { ...schema, type: type.find(part => part !== 'null') ?? type[0] },\n context,\n );\n }\n\n if (type === 'object' || isRecord(schema.properties)) {\n const properties = isRecord(schema.properties) ? schema.properties : {};\n return Object.fromEntries(\n Object.entries(properties)\n .filter((entry): entry is [string, JsonSchema] => isRecord(entry[1]))\n .map(([name, value]) => [\n name,\n sampleFromSchemaInner(value, nextContext(context)),\n ]),\n );\n }\n\n if (type === 'array' || schema.items !== undefined) {\n const items = Array.isArray(schema.items) ? schema.items[0] : schema.items;\n return [\n isRecord(items)\n ? sampleFromSchemaInner(items, nextContext(context))\n : null,\n ];\n }\n\n if (type === 'number' || type === 'integer') {\n return 1;\n }\n\n if (type === 'boolean') {\n return true;\n }\n\n if (type === 'null') {\n return null;\n }\n\n if (type === 'string' || type === undefined) {\n const examples = asArray(schema.examples);\n if (examples?.[0] !== undefined) {\n return examples[0];\n }\n const format = firstString(schema.format);\n if (format === 'uri' || format === 'url') {\n return 'https://example.com';\n }\n if (format === 'date-time') {\n return '2026-01-01T00:00:00.000Z';\n }\n if (format === 'date') {\n return '2026-01-01';\n }\n return 'string';\n }\n\n return null;\n}\n\nfunction firstInputExample(tool: CodeModeToolSet[string]): unknown {\n const examples = asArray(tool.inputExamples);\n const first = examples?.[0];\n return isRecord(first) && 'input' in first ? first.input : undefined;\n}\n\nfunction resolveRef(\n ref: string,\n root: JsonSchema,\n seenRefs: Set<string>,\n): JsonSchema | undefined {\n if (!ref.startsWith('#/') || seenRefs.has(ref)) {\n return undefined;\n }\n\n seenRefs.add(ref);\n const value = ref\n .slice(2)\n .split('/')\n .map(part => part.replace(/~1/g, '/').replace(/~0/g, '~'))\n .reduce<unknown>((current, part) => {\n if (!isRecord(current)) {\n return undefined;\n }\n return current[part];\n }, root);\n\n return isRecord(value) ? value : undefined;\n}\n\nfunction nextContext(context: SchemaContext): SchemaContext {\n return {\n ...context,\n depth: context.depth + 1,\n };\n}\n\nfunction union(types: string[]): string {\n const unique = [...new Set(types)];\n return unique.length === 0 ? 'unknown' : unique.join(' | ');\n}\n\nfunction literalType(value: unknown): string {\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n if (\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n value === null\n ) {\n return String(value);\n }\n return 'unknown';\n}\n\nfunction indentType(type: string, spaces: number): string {\n if (!type.includes('\\n')) {\n return type;\n }\n\n const padding = ' '.repeat(spaces);\n return type.replaceAll('\\n', `\\n${padding}`);\n}\n\nfunction needsParentheses(type: string): boolean {\n return type.includes(' | ') || type.includes(' & ');\n}\n\nfunction formatObjectKey(key: string): string {\n return isIdentifier(key) ? key : JSON.stringify(key);\n}\n\nfunction formatPropertyAccess(key: string): string {\n return isIdentifier(key) ? `.${key}` : `[${JSON.stringify(key)}]`;\n}\n\nfunction uniqueToolVariableNames(toolNames: string[]): string[] {\n const seen = new Map<string, number>();\n return toolNames.map(toolName => {\n const base = toIdentifier(toolName);\n const count = seen.get(base) ?? 0;\n seen.set(base, count + 1);\n return count === 0 ? base : `${base}${count + 1}`;\n });\n}\n\nfunction toIdentifier(value: string): string {\n const identifier = value\n .replace(/[^A-Za-z0-9_$]/g, '_')\n .replace(/^[^A-Za-z_$]+/, '');\n return identifier.length === 0 ? 'tool' : identifier;\n}\n\nfunction isIdentifier(value: string): boolean {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value);\n}\n\nfunction compactObjectType(lines: string[]): string | undefined {\n if (lines.length === 0 || lines.some(line => line.includes('/**'))) {\n return undefined;\n }\n\n const fields = lines.map(line => line.trim());\n if (fields.some(field => field.includes('\\n'))) {\n return undefined;\n }\n\n const compact = `{ ${fields.join(' ')} }`;\n return compact.length <= MAX_COMPACT_OBJECT_TYPE_LENGTH ? compact : undefined;\n}\n\nfunction toComment(value: string): string {\n return value.replaceAll('*/', '* /').replace(/\\s+/g, ' ').trim();\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n return values.find(isString);\n}\n\nfunction schemaArray(value: unknown): JsonSchema[] | undefined {\n const values = asArray(value);\n if (values === undefined || !values.every(isRecord)) {\n return undefined;\n }\n return values;\n}\n\nfunction asArray(value: unknown): unknown[] | undefined {\n return Array.isArray(value) ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is JsonSchema {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return isRecord(value) && typeof value.then === 'function';\n}\n"],"mappings":";;AAWA,MAAM,mBAAmB;AACzB,MAAM,iCAAiC;AAEvC,SAAgB,6BACd,OACA,gBAAgD,eACxC;CACR,MAAM,WAAW;EACf;EACA;EACA;EACA;EACA,kBAAkB,gBACd,8EACA;EACJ;CACF;CAEA,IAAI,kBAAkB,gBAAgB;EACpC,SAAS,KACP,IACA,UACA,gJACF;EACA,OAAO,SAAS,KAAK,IAAI;CAC3B;CAEA,MAAM,EAAE,WAAW,iBAAiB,kBAAkB,KAAK;CAC3D,SAAS,KAAK,IAAI,UAAU,SAAS;CAErC,IAAI,aAAa,SAAS,GACxB,SAAS,KAAK,YAAY;CAG5B,OAAO,SAAS,KAAK,IAAI;AAC3B;AAEA,SAAgB,gCACd,OACQ;CACR,MAAM,EAAE,WAAW,iBAAiB,kBAAkB,KAAK;CAC3D,MAAM,WAAW;EACf;EACA;EACA;EACA;EACA;EACA;CACF;CAEA,IAAI,aAAa,SAAS,GACxB,SAAS,KAAK,YAAY;CAG5B,OAAO,SAAS,KAAK,IAAI;AAC3B;AAEA,SAAS,kBAAkB,OAGzB;CACA,MAAM,cAAc,OAAO,QAAQ,KAAK;CAuBxC,OAAO;EAAE,WArBP,YAAY,WAAW,IACnB,0CAC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UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAiC;CACjD,OAAO,OAAO,UAAU;AAC1B;AAEA,SAAS,cAAc,OAA+C;CACpE,OAAO,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS;AAClD"}
|
|
1
|
+
{"version":3,"file":"tool-prompt.js","names":[],"sources":["../src/tool-prompt.ts"],"sourcesContent":["import { asSchema } from 'ai';\nimport type { CodeModeToolSet } from './types.js';\n\ntype JsonSchema = Record<string, unknown>;\n\ninterface SchemaContext {\n root: JsonSchema;\n seenRefs: Set<string>;\n depth: number;\n}\n\nconst MAX_SCHEMA_DEPTH = 8;\nconst MAX_COMPACT_OBJECT_TYPE_LENGTH = 120;\n\nexport function buildCodeModeToolDescription(\n tools: CodeModeToolSet,\n toolDiscovery: 'description' | 'conversation' = 'description',\n): string {\n const sections = [\n 'Execute code-mode TypeScript in an isolated sandbox.',\n '',\n 'Put the full program in `js`; top-level `await`/`return` work. Return a JSON-serializable result.',\n 'Call host tools only as async `tools.name(input)`; await each or use `Promise.all` for independent calls.',\n toolDiscovery === 'description'\n ? 'Use exact names/types below. `JSON.parse`/`JSON.stringify` are available.'\n : 'Use exact names/types from the latest capability update. `JSON.parse`/`JSON.stringify` are available.',\n 'Fetch: `fetch` is not available.',\n ];\n\n if (toolDiscovery === 'conversation') {\n sections.push(\n '',\n 'Tools:',\n 'The current host-tool API is provided in \"Code mode capability update\" user messages. Follow the latest catalog and ignore earlier catalogs.',\n );\n return sections.join('\\n');\n }\n\n const { typeBlock, exampleBlock } = renderToolCatalog(tools);\n sections.push('', 'Tools:', typeBlock);\n\n if (exampleBlock.length > 0) {\n sections.push(exampleBlock);\n }\n\n return sections.join('\\n');\n}\n\nexport function buildCodeModeToolCatalogMessage(\n tools: CodeModeToolSet,\n): string {\n const { typeBlock, exampleBlock } = renderToolCatalog(tools);\n const sections = [\n 'Code mode capability update.',\n '',\n 'This catalog replaces all previous code mode capability catalogs. Only the tools listed below are currently available through `tools`.',\n '',\n 'Tools:',\n typeBlock,\n ];\n\n if (exampleBlock.length > 0) {\n sections.push(exampleBlock);\n }\n\n return sections.join('\\n');\n}\n\nfunction renderToolCatalog(tools: CodeModeToolSet): {\n typeBlock: string;\n exampleBlock: string;\n} {\n const toolEntries = Object.entries(tools);\n const typeBlock =\n toolEntries.length === 0\n ? 'No host tools. Do not call `tools.*`.'\n : [\n '```ts',\n 'declare const tools: {',\n ...toolEntries.flatMap(renderToolType),\n '};',\n '```',\n ].join('\\n');\n\n const exampleBlock =\n toolEntries.length === 0\n ? ''\n : [\n '',\n 'Tool call examples:',\n '```ts',\n ...renderToolExamples(toolEntries),\n '```',\n ].join('\\n');\n\n return { typeBlock, exampleBlock };\n}\n\nfunction renderToolType([toolName, tool]: [\n string,\n CodeModeToolSet[string],\n]): string[] {\n const schema = resolveInputSchema(tool);\n const inputType =\n schema === undefined ? 'unknown' : schemaToType(schema, schema);\n const outputSchema = resolveOutputSchema(tool);\n const outputType =\n outputSchema === undefined\n ? 'unknown'\n : schemaToType(outputSchema, outputSchema);\n const description = firstString(tool.description, tool.title);\n const lines: string[] = [];\n\n if (description !== undefined) {\n lines.push(` /** ${toComment(description)} */`);\n }\n\n lines.push(\n ` ${formatObjectKey(toolName)}: (input: ${indentType(inputType, 2)}) => Promise<${indentType(outputType, 2)}>;`,\n );\n return lines;\n}\n\nfunction renderToolExamples(\n toolEntries: Array<[string, CodeModeToolSet[string]]>,\n): string[] {\n if (toolEntries.length === 1) {\n const toolEntry = toolEntries[0]!;\n const projection = renderToolProjection('result', toolEntry[1]);\n return [\n `const result = await ${renderToolExampleCall(toolEntry)};`,\n `return ${projection};`,\n ];\n }\n\n const variableNames = uniqueToolVariableNames(\n toolEntries.map(([toolName]) => toolName),\n );\n const calls = toolEntries.map(\n toolEntry => ` ${renderToolExampleCall(toolEntry)},`,\n );\n return [\n `const [${variableNames.join(', ')}] = await Promise.all([`,\n ...calls,\n ']);',\n 'return {',\n ...toolEntries.map(([toolName, tool], index) => {\n const projection = renderToolProjection(variableNames[index]!, tool);\n return ` ${formatObjectKey(toolName)}: ${projection},`;\n }),\n '};',\n ];\n}\n\nfunction renderToolExampleCall([toolName, tool]: [\n string,\n CodeModeToolSet[string],\n]): string {\n const schema = resolveInputSchema(tool);\n const input =\n firstInputExample(tool) ??\n (schema === undefined ? {} : sampleFromSchema(schema, schema));\n return `tools${formatPropertyAccess(toolName)}(${JSON.stringify(input)})`;\n}\n\nfunction renderToolProjection(\n variableName: string,\n tool: CodeModeToolSet[string],\n): string {\n const field = firstObjectProperty(resolveOutputSchema(tool));\n if (field === undefined) {\n return variableName;\n }\n return `{ ${formatObjectKey(field)}: ${variableName}${formatPropertyAccess(field)} }`;\n}\n\nfunction firstObjectProperty(\n schema: JsonSchema | undefined,\n): string | undefined {\n if (schema === undefined || !isRecord(schema.properties)) {\n return undefined;\n }\n return Object.entries(schema.properties).find(entry =>\n isRecord(entry[1]),\n )?.[0];\n}\n\nfunction resolveInputSchema(\n tool: CodeModeToolSet[string],\n): JsonSchema | undefined {\n try {\n const jsonSchema = asSchema(tool.inputSchema).jsonSchema;\n if (isPromiseLike(jsonSchema) || !isRecord(jsonSchema)) {\n return undefined;\n }\n return jsonSchema;\n } catch {\n return undefined;\n }\n}\n\nfunction resolveOutputSchema(\n tool: CodeModeToolSet[string],\n): JsonSchema | undefined {\n try {\n const outputSchema = tool.outputSchema;\n if (outputSchema === undefined) {\n return undefined;\n }\n const jsonSchema = asSchema(outputSchema).jsonSchema;\n if (isPromiseLike(jsonSchema) || !isRecord(jsonSchema)) {\n return undefined;\n }\n return jsonSchema;\n } catch {\n return undefined;\n }\n}\n\nfunction schemaToType(schema: JsonSchema, root: JsonSchema): string {\n return schemaToTypeInner(schema, {\n root,\n seenRefs: new Set(),\n depth: 0,\n });\n}\n\nfunction schemaToTypeInner(schema: JsonSchema, context: SchemaContext): string {\n if (context.depth > MAX_SCHEMA_DEPTH) {\n return 'unknown';\n }\n\n const ref = firstString(schema.$ref);\n if (ref !== undefined) {\n const resolved = resolveRef(ref, context.root, context.seenRefs);\n return resolved === undefined\n ? 'unknown'\n : schemaToTypeInner(resolved, nextContext(context));\n }\n\n const constValue = schema.const;\n if (constValue !== undefined) {\n return literalType(constValue);\n }\n\n const enumValues = asArray(schema.enum);\n if (enumValues !== undefined) {\n return union(enumValues.map(literalType));\n }\n\n const oneOf = schemaArray(schema.oneOf);\n if (oneOf !== undefined) {\n return union(\n oneOf.map(part => schemaToTypeInner(part, nextContext(context))),\n );\n }\n\n const anyOf = schemaArray(schema.anyOf);\n if (anyOf !== undefined) {\n return union(\n anyOf.map(part => schemaToTypeInner(part, nextContext(context))),\n );\n }\n\n const allOf = schemaArray(schema.allOf);\n if (allOf !== undefined) {\n return allOf\n .map(part => schemaToTypeInner(part, nextContext(context)))\n .join(' & ');\n }\n\n const type = schema.type;\n if (Array.isArray(type)) {\n return union(\n type.map(part => schemaToTypeInner({ ...schema, type: part }, context)),\n );\n }\n\n if (type === 'object' || isRecord(schema.properties)) {\n return objectType(schema, context);\n }\n\n if (type === 'array' || schema.items !== undefined) {\n return arrayType(schema, context);\n }\n\n if (type === 'string') {\n return 'string';\n }\n\n if (type === 'number' || type === 'integer') {\n return 'number';\n }\n\n if (type === 'boolean') {\n return 'boolean';\n }\n\n if (type === 'null') {\n return 'null';\n }\n\n return 'unknown';\n}\n\nfunction objectType(schema: JsonSchema, context: SchemaContext): string {\n const properties = isRecord(schema.properties) ? schema.properties : {};\n const required = new Set(asArray(schema.required)?.filter(isString));\n const entries = Object.entries(properties).filter(\n (entry): entry is [string, JsonSchema] => isRecord(entry[1]),\n );\n\n if (entries.length === 0) {\n const additionalProperties = schema.additionalProperties;\n if (isRecord(additionalProperties)) {\n return `Record<string, ${schemaToTypeInner(additionalProperties, nextContext(context))}>`;\n }\n if (additionalProperties === true) {\n return 'Record<string, unknown>';\n }\n return '{}';\n }\n\n const lines = entries.flatMap(([name, value]) => {\n const propertyLines: string[] = [];\n const description = firstString(value.description);\n if (description !== undefined) {\n propertyLines.push(` /** ${toComment(description)} */`);\n }\n propertyLines.push(\n ` ${formatObjectKey(name)}${required.has(name) ? '' : '?'}: ${indentType(\n schemaToTypeInner(value, nextContext(context)),\n 2,\n )};`,\n );\n return propertyLines;\n });\n\n const additionalProperties = schema.additionalProperties;\n if (isRecord(additionalProperties)) {\n lines.push(\n ` [key: string]: ${schemaToTypeInner(additionalProperties, nextContext(context))};`,\n );\n } else if (additionalProperties === true) {\n lines.push(' [key: string]: unknown;');\n }\n\n const compact = compactObjectType(lines);\n if (compact !== undefined) {\n return compact;\n }\n\n return `{\\n${lines.join('\\n')}\\n}`;\n}\n\nfunction arrayType(schema: JsonSchema, context: SchemaContext): string {\n const items = schema.items;\n if (Array.isArray(items)) {\n return `[${items\n .map(item =>\n isRecord(item)\n ? schemaToTypeInner(item, nextContext(context))\n : 'unknown',\n )\n .join(', ')}]`;\n }\n if (isRecord(items)) {\n const itemType = schemaToTypeInner(items, nextContext(context));\n return needsParentheses(itemType) || itemType.includes('\\n')\n ? `Array<${itemType}>`\n : `${itemType}[]`;\n }\n return 'unknown[]';\n}\n\nfunction sampleFromSchema(schema: JsonSchema, root: JsonSchema): unknown {\n return sampleFromSchemaInner(schema, {\n root,\n seenRefs: new Set(),\n depth: 0,\n });\n}\n\nfunction sampleFromSchemaInner(\n schema: JsonSchema,\n context: SchemaContext,\n): unknown {\n if (context.depth > MAX_SCHEMA_DEPTH) {\n return null;\n }\n\n if (schema.default !== undefined) {\n return schema.default;\n }\n\n const ref = firstString(schema.$ref);\n if (ref !== undefined) {\n const resolved = resolveRef(ref, context.root, context.seenRefs);\n return resolved === undefined\n ? null\n : sampleFromSchemaInner(resolved, nextContext(context));\n }\n\n if (schema.const !== undefined) {\n return schema.const;\n }\n\n const enumValues = asArray(schema.enum);\n if (enumValues !== undefined) {\n return enumValues[0] ?? null;\n }\n\n const oneOf = schemaArray(schema.oneOf);\n if (oneOf !== undefined) {\n return sampleFromSchemaInner(oneOf[0] ?? {}, nextContext(context));\n }\n\n const anyOf = schemaArray(schema.anyOf);\n if (anyOf !== undefined) {\n return sampleFromSchemaInner(anyOf[0] ?? {}, nextContext(context));\n }\n\n const type = schema.type;\n if (Array.isArray(type)) {\n return sampleFromSchemaInner(\n { ...schema, type: type.find(part => part !== 'null') ?? type[0] },\n context,\n );\n }\n\n if (type === 'object' || isRecord(schema.properties)) {\n const properties = isRecord(schema.properties) ? schema.properties : {};\n return Object.fromEntries(\n Object.entries(properties)\n .filter((entry): entry is [string, JsonSchema] => isRecord(entry[1]))\n .map(([name, value]) => [\n name,\n sampleFromSchemaInner(value, nextContext(context)),\n ]),\n );\n }\n\n if (type === 'array' || schema.items !== undefined) {\n const items = Array.isArray(schema.items) ? schema.items[0] : schema.items;\n return [\n isRecord(items)\n ? sampleFromSchemaInner(items, nextContext(context))\n : null,\n ];\n }\n\n if (type === 'number' || type === 'integer') {\n return 1;\n }\n\n if (type === 'boolean') {\n return true;\n }\n\n if (type === 'null') {\n return null;\n }\n\n if (type === 'string' || type === undefined) {\n const examples = asArray(schema.examples);\n if (examples?.[0] !== undefined) {\n return examples[0];\n }\n const format = firstString(schema.format);\n if (format === 'uri' || format === 'url') {\n return 'https://example.com';\n }\n if (format === 'date-time') {\n return '2026-01-01T00:00:00.000Z';\n }\n if (format === 'date') {\n return '2026-01-01';\n }\n return 'string';\n }\n\n return null;\n}\n\nfunction firstInputExample(tool: CodeModeToolSet[string]): unknown {\n const examples = asArray(tool.inputExamples);\n const first = examples?.[0];\n return isRecord(first) && 'input' in first ? first.input : undefined;\n}\n\nfunction resolveRef(\n ref: string,\n root: JsonSchema,\n seenRefs: Set<string>,\n): JsonSchema | undefined {\n if (!ref.startsWith('#/') || seenRefs.has(ref)) {\n return undefined;\n }\n\n seenRefs.add(ref);\n const value = ref\n .slice(2)\n .split('/')\n .map(part => part.replace(/~1/g, '/').replace(/~0/g, '~'))\n .reduce<unknown>((current, part) => {\n if (!isRecord(current)) {\n return undefined;\n }\n return current[part];\n }, root);\n\n return isRecord(value) ? value : undefined;\n}\n\nfunction nextContext(context: SchemaContext): SchemaContext {\n return {\n ...context,\n depth: context.depth + 1,\n };\n}\n\nfunction union(types: string[]): string {\n const unique = [...new Set(types)];\n return unique.length === 0 ? 'unknown' : unique.join(' | ');\n}\n\nfunction literalType(value: unknown): string {\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n if (\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n value === null\n ) {\n return String(value);\n }\n return 'unknown';\n}\n\nfunction indentType(type: string, spaces: number): string {\n if (!type.includes('\\n')) {\n return type;\n }\n\n const padding = ' '.repeat(spaces);\n return type.replaceAll('\\n', `\\n${padding}`);\n}\n\nfunction needsParentheses(type: string): boolean {\n return type.includes(' | ') || type.includes(' & ');\n}\n\nfunction formatObjectKey(key: string): string {\n return isIdentifier(key) ? key : JSON.stringify(key);\n}\n\nexport function formatPropertyAccess(key: string): string {\n return isIdentifier(key) ? `.${key}` : `[${JSON.stringify(key)}]`;\n}\n\nfunction uniqueToolVariableNames(toolNames: string[]): string[] {\n const seen = new Map<string, number>();\n return toolNames.map(toolName => {\n const base = toIdentifier(toolName);\n const count = seen.get(base) ?? 0;\n seen.set(base, count + 1);\n return count === 0 ? base : `${base}${count + 1}`;\n });\n}\n\nfunction toIdentifier(value: string): string {\n const identifier = value\n .replace(/[^A-Za-z0-9_$]/g, '_')\n .replace(/^[^A-Za-z_$]+/, '');\n return identifier.length === 0 ? 'tool' : identifier;\n}\n\nfunction isIdentifier(value: string): boolean {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value);\n}\n\nfunction compactObjectType(lines: string[]): string | undefined {\n if (lines.length === 0 || lines.some(line => line.includes('/**'))) {\n return undefined;\n }\n\n const fields = lines.map(line => line.trim());\n if (fields.some(field => field.includes('\\n'))) {\n return undefined;\n }\n\n const compact = `{ ${fields.join(' ')} }`;\n return compact.length <= MAX_COMPACT_OBJECT_TYPE_LENGTH ? compact : undefined;\n}\n\nfunction toComment(value: string): string {\n return value.replaceAll('*/', '* /').replace(/\\s+/g, ' ').trim();\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n return values.find(isString);\n}\n\nfunction schemaArray(value: unknown): JsonSchema[] | undefined {\n const values = asArray(value);\n if (values === undefined || !values.every(isRecord)) {\n return undefined;\n }\n return values;\n}\n\nfunction asArray(value: unknown): unknown[] | undefined {\n return Array.isArray(value) ? value : undefined;\n}\n\nfunction isRecord(value: unknown): value is JsonSchema {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return isRecord(value) && typeof value.then === 'function';\n}\n"],"mappings":";;AAWA,MAAM,mBAAmB;AACzB,MAAM,iCAAiC;AAEvC,SAAgB,6BACd,OACA,gBAAgD,eACxC;CACR,MAAM,WAAW;EACf;EACA;EACA;EACA;EACA,kBAAkB,gBACd,8EACA;EACJ;CACF;CAEA,IAAI,kBAAkB,gBAAgB;EACpC,SAAS,KACP,IACA,UACA,gJACF;EACA,OAAO,SAAS,KAAK,IAAI;CAC3B;CAEA,MAAM,EAAE,WAAW,iBAAiB,kBAAkB,KAAK;CAC3D,SAAS,KAAK,IAAI,UAAU,SAAS;CAErC,IAAI,aAAa,SAAS,GACxB,SAAS,KAAK,YAAY;CAG5B,OAAO,SAAS,KAAK,IAAI;AAC3B;AAEA,SAAgB,gCACd,OACQ;CACR,MAAM,EAAE,WAAW,iBAAiB,kBAAkB,KAAK;CAC3D,MAAM,WAAW;EACf;EACA;EACA;EACA;EACA;EACA;CACF;CAEA,IAAI,aAAa,SAAS,GACxB,SAAS,KAAK,YAAY;CAG5B,OAAO,SAAS,KAAK,IAAI;AAC3B;AAEA,SAAS,kBAAkB,OAGzB;CACA,MAAM,cAAc,OAAO,QAAQ,KAAK;CAuBxC,OAAO;EAAE,WArBP,YAAY,WAAW,IACnB,0CACA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UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAiC;CACjD,OAAO,OAAO,UAAU;AAC1B;AAEA,SAAS,cAAc,OAA+C;CACpE,OAAO,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS;AAClD"}
|
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.121",
|
|
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.164"
|
|
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.164",
|
|
47
47
|
"tsdown": "^0.23.0",
|
|
48
48
|
"typescript": "6.0.3",
|
|
49
49
|
"zod": "3.25.76"
|
package/src/run-code-mode.ts
CHANGED
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
CodeModeToolApprovalDeniedError,
|
|
33
33
|
} from './errors.js';
|
|
34
34
|
import { invokeHostTool } from './tool-invocation.js';
|
|
35
|
+
import { formatPropertyAccess } from './tool-prompt.js';
|
|
35
36
|
import type {
|
|
36
37
|
CodeModeContinuation,
|
|
37
38
|
CodeModeExecutionPolicy,
|
|
@@ -156,7 +157,7 @@ export async function runCodeMode(input: RunCodeModeInput): Promise<unknown> {
|
|
|
156
157
|
if (preserved !== undefined) {
|
|
157
158
|
throw translateSourceStack(preserved);
|
|
158
159
|
}
|
|
159
|
-
throw translateSourceStack(toCodeModeRuntimeError(error));
|
|
160
|
+
throw translateSourceStack(toCodeModeRuntimeError(error, toolNames));
|
|
160
161
|
}
|
|
161
162
|
}
|
|
162
163
|
|
|
@@ -576,8 +577,10 @@ function toolNameForInterruption(
|
|
|
576
577
|
if (interruption.hostFunctionName === '__codeMode.missing') {
|
|
577
578
|
return String(interruption.arguments[0]);
|
|
578
579
|
}
|
|
579
|
-
const
|
|
580
|
-
|
|
580
|
+
const toolName = toolNameForHostFunction(
|
|
581
|
+
interruption.hostFunctionName,
|
|
582
|
+
toolNames,
|
|
583
|
+
);
|
|
581
584
|
if (toolName === undefined) {
|
|
582
585
|
throw new CodeModeProtocolError(
|
|
583
586
|
`Run returned an unknown code-mode host function "${interruption.hostFunctionName}".`,
|
|
@@ -586,6 +589,14 @@ function toolNameForInterruption(
|
|
|
586
589
|
return toolName;
|
|
587
590
|
}
|
|
588
591
|
|
|
592
|
+
function toolNameForHostFunction(
|
|
593
|
+
hostFunctionName: string,
|
|
594
|
+
toolNames: string[],
|
|
595
|
+
): string | undefined {
|
|
596
|
+
const match = /^__codeMode\.tool(\d+)$/u.exec(hostFunctionName);
|
|
597
|
+
return match === null ? undefined : toolNames[Number(match[1])];
|
|
598
|
+
}
|
|
599
|
+
|
|
589
600
|
function toCodeModeInterrupt(
|
|
590
601
|
continuation: CodeModeContinuation,
|
|
591
602
|
index: number,
|
|
@@ -625,7 +636,7 @@ function findPreservedCodeModeError(
|
|
|
625
636
|
return errors.find(candidate => candidate.code === error.code);
|
|
626
637
|
}
|
|
627
638
|
|
|
628
|
-
function toCodeModeRuntimeError(error: unknown): unknown {
|
|
639
|
+
function toCodeModeRuntimeError(error: unknown, toolNames: string[]): unknown {
|
|
629
640
|
if (error instanceof TypeError) {
|
|
630
641
|
error.message = translateLimitPath(error.message);
|
|
631
642
|
}
|
|
@@ -671,11 +682,23 @@ function toCodeModeRuntimeError(error: unknown): unknown {
|
|
|
671
682
|
new CodeModeBridgeLimitError(error.message, error.details),
|
|
672
683
|
error,
|
|
673
684
|
);
|
|
674
|
-
case 'RUN_DETACHED_BRIDGE_REQUEST':
|
|
685
|
+
case 'RUN_DETACHED_BRIDGE_REQUEST': {
|
|
686
|
+
let message = error.message;
|
|
687
|
+
const hostFunctionName = details?.name;
|
|
688
|
+
if (typeof hostFunctionName === 'string') {
|
|
689
|
+
const toolName = toolNameForHostFunction(hostFunctionName, toolNames);
|
|
690
|
+
if (toolName !== undefined) {
|
|
691
|
+
message = message.replace(
|
|
692
|
+
hostFunctionName,
|
|
693
|
+
() => `tools${formatPropertyAccess(toolName)}`,
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
675
697
|
return copyStack(
|
|
676
|
-
new CodeModeDetachedBridgeRequestError(
|
|
698
|
+
new CodeModeDetachedBridgeRequestError(message, error.details),
|
|
677
699
|
error,
|
|
678
700
|
);
|
|
701
|
+
}
|
|
679
702
|
case 'RUN_PROTOCOL_ERROR':
|
|
680
703
|
return copyStack(
|
|
681
704
|
new CodeModeProtocolError(error.message, error.details),
|
package/src/tool-prompt.ts
CHANGED
|
@@ -555,7 +555,7 @@ function formatObjectKey(key: string): string {
|
|
|
555
555
|
return isIdentifier(key) ? key : JSON.stringify(key);
|
|
556
556
|
}
|
|
557
557
|
|
|
558
|
-
function formatPropertyAccess(key: string): string {
|
|
558
|
+
export function formatPropertyAccess(key: string): string {
|
|
559
559
|
return isIdentifier(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
|
|
560
560
|
}
|
|
561
561
|
|