@ai-sdk/code-mode 1.0.79 → 1.0.80
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/approval-continuation.js +48 -74
- package/dist/approval-continuation.js.map +1 -1
- package/dist/approval.js +12 -23
- package/dist/approval.js.map +1 -1
- package/dist/code-mode-tool.js +39 -51
- package/dist/code-mode-tool.js.map +1 -1
- package/dist/continuation-capability.js +74 -105
- package/dist/continuation-capability.js.map +1 -1
- package/dist/direct-tool-call.js +9 -3
- package/dist/direct-tool-call.js.map +1 -1
- package/dist/errors.js +109 -96
- package/dist/errors.js.map +1 -1
- package/dist/host-interrupt.js +7 -12
- package/dist/host-interrupt.js.map +1 -1
- package/dist/index.d.ts +172 -163
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -61
- package/dist/interrupt-continuation.js +54 -90
- package/dist/interrupt-continuation.js.map +1 -1
- package/dist/run-code-mode.js +292 -494
- package/dist/run-code-mode.js.map +1 -1
- package/dist/tool-invocation.js +98 -176
- package/dist/tool-invocation.js.map +1 -1
- package/dist/tool-prompt.js +254 -392
- package/dist/tool-prompt.js.map +1 -1
- package/dist/types.js +1 -1
- package/dist/utils/serialization.js +23 -39
- package/dist/utils/serialization.js.map +1 -1
- package/package.json +6 -6
- package/dist/index.js.map +0 -1
- package/dist/types.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/run-code-mode.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport { createHash } from 'node:crypto';\nimport {\n createRunner,\n createSignedContinuationCodec,\n getHostFunctionContext,\n RunError,\n type HostFunctions,\n type RunInterruption,\n type RunLimits,\n type RunResolution,\n} from 'run';\nimport {\n isCodeModeApprovalInterruptPayload,\n normalizeApprovalResolution,\n} from './approval.js';\nimport {\n resolveCodeModeContinuationSecurity,\n signCodeModeContinuation,\n verifyCodeModeContinuation,\n} from './continuation-capability.js';\nimport {\n CodeModeAbortedError,\n CodeModeBridgeLimitError,\n CodeModeConcurrencyError,\n CodeModeDetachedBridgeRequestError,\n CodeModeError,\n CodeModeProtocolError,\n CodeModeSourceTooLargeError,\n CodeModeTimeoutError,\n CodeModeToolApprovalDeniedError,\n} from './errors.js';\nimport { invokeHostTool } from './tool-invocation.js';\nimport type {\n CodeModeContinuation,\n CodeModeExecutionPolicy,\n CodeModeInterrupt,\n CodeModeInterruptExecutionContext,\n CodeModeInterruptPayload,\n CodeModePendingInterruption,\n CodeModePendingResolution,\n CodeModeToolExecutionOptions,\n RunCodeModeInput,\n} from './types.js';\nimport { fromJsonPayload, toJsonPayload } from './utils/serialization.js';\n\nconst SOURCE_LINE_OFFSET = 1;\nconst MAX_RUN_LIMIT = 2_147_483_647;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;\nconst DEFAULT_STACK_LIMIT_BYTES = 2 * 1024 * 1024;\nconst DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;\nconst DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;\nconst DEFAULT_MAX_SOURCE_BYTES = 256 * 1024;\nconst DEFAULT_MAX_TOOL_INPUT_BYTES = 1024 * 1024;\nconst DEFAULT_MAX_TOOL_OUTPUT_BYTES = 4 * 1024 * 1024;\nconst DEFAULT_MAX_BRIDGE_REQUESTS = 256;\nconst DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS = 32;\n\nlet invocationCounter = 0;\n\n/**\n * Runs one code-mode invocation directly without wrapping it as an AI SDK tool.\n *\n * The source is executed in a fresh QuickJS context with the provided host tools\n * and execution limits.\n *\n * @param input - Source code, host tools, forwarded tool execution options, and code-mode options.\n * @returns The JSON-serializable value returned by the sandboxed program.\n */\nexport async function runCodeMode(input: RunCodeModeInput): Promise<unknown> {\n const policy = resolveExecutionPolicy(input.options?.executionPolicy);\n assertSourceSize(input.js, policy.maxSourceBytes);\n\n const toolNames = Object.keys(input.tools).sort();\n const continuationState = prepareContinuation(\n input,\n toolNames,\n policy.maxToolOutputBytes,\n );\n if (continuationState.nextInterrupt !== undefined) {\n return continuationState.nextInterrupt;\n }\n\n const outerToolCallId =\n input.toolExecutionOptions?.toolCallId ??\n input.continuation?.outerToolCallId ??\n `code-mode-${++invocationCounter}`;\n const source = createCodeModeSource(input.js, toolNames);\n const codeModeErrors: CodeModeError[] = [];\n const hostFunctions = createHostFunctions({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolNames,\n });\n const continuationSecurity = resolveCodeModeContinuationSecurity(\n input.options?.continuationSecurity,\n );\n const runner = createRunner({\n continuationAudience: '@ai-sdk/code-mode/v2',\n continuationCodec: createSignedContinuationCodec({\n maxAgeMs: continuationSecurity.maxAgeMs,\n secret: createHash('sha256')\n .update(continuationSecurity.signingKey)\n .digest(),\n }),\n });\n\n try {\n const result = await runner.run({\n source,\n hostFunctions,\n limits: toRunLimits(policy, source, input.js),\n continuationContext: { outerToolCallId, toolNames },\n ...(input.toolExecutionOptions?.abortSignal === undefined\n ? {}\n : { abortSignal: input.toolExecutionOptions.abortSignal }),\n ...(continuationState.token === undefined\n ? {}\n : { continuation: continuationState.token }),\n ...(continuationState.resolutions === undefined\n ? {}\n : { resolutions: continuationState.resolutions }),\n });\n\n if (result.status === 'completed') {\n return fromJsonPayload(\n toJsonPayload(result.value, policy.maxResultBytes, 'Code mode result'),\n );\n }\n\n const pendingInterruptions = toPendingInterruptions({\n interruptions: result.interruptions,\n outerToolCallId,\n toolNames,\n });\n const continuation = signCodeModeContinuation(\n {\n version: 2,\n js: input.js,\n outerToolCallId,\n toolNames,\n token: result.continuation,\n pendingInterruptions,\n resolutions: [],\n },\n continuationSecurity,\n );\n return toCodeModeInterrupt(continuation, 0);\n } catch (error) {\n const preserved = findPreservedCodeModeError(error, codeModeErrors);\n if (preserved !== undefined) {\n throw translateSourceStack(preserved);\n }\n throw translateSourceStack(toCodeModeRuntimeError(error));\n }\n}\n\ninterface ResolvedExecutionPolicy {\n timeoutMs: number;\n memoryLimitBytes: number;\n maxStackSizeBytes: number;\n maxResultBytes: number;\n maxConsoleOutputBytes: number;\n maxSourceBytes: number;\n maxToolInputBytes: number;\n maxToolOutputBytes: number;\n maxBridgeRequests: number;\n maxInFlightBridgeRequests: number;\n}\n\nfunction resolveExecutionPolicy(\n policy: CodeModeExecutionPolicy = {},\n): ResolvedExecutionPolicy {\n return {\n timeoutMs: policy.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n memoryLimitBytes: policy.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,\n maxStackSizeBytes: policy.maxStackSizeBytes ?? DEFAULT_STACK_LIMIT_BYTES,\n maxResultBytes: policy.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES,\n maxConsoleOutputBytes:\n policy.maxConsoleOutputBytes ?? DEFAULT_MAX_CONSOLE_OUTPUT_BYTES,\n maxSourceBytes: policy.maxSourceBytes ?? DEFAULT_MAX_SOURCE_BYTES,\n maxToolInputBytes: policy.maxToolInputBytes ?? DEFAULT_MAX_TOOL_INPUT_BYTES,\n maxToolOutputBytes:\n policy.maxToolOutputBytes ?? DEFAULT_MAX_TOOL_OUTPUT_BYTES,\n maxBridgeRequests: policy.maxBridgeRequests ?? DEFAULT_MAX_BRIDGE_REQUESTS,\n maxInFlightBridgeRequests:\n policy.maxInFlightBridgeRequests ?? DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS,\n };\n}\n\nfunction assertSourceSize(source: string, maxBytes: number): void {\n if (!isValidRunLimit(maxBytes)) {\n return;\n }\n const bytes = Buffer.byteLength(source);\n if (bytes > maxBytes) {\n throw new CodeModeSourceTooLargeError(bytes, maxBytes);\n }\n}\n\nfunction createCodeModeSource(js: string, toolNames: string[]): string {\n const bindings = Object.fromEntries(\n toolNames.map((toolName, index) => [toolName, `__codeMode.tool${index}`]),\n );\n const bindingSource = Object.entries(bindings)\n .map(([name, reference]) => `${JSON.stringify(name)}:${reference}`)\n .join(',');\n return `const __codeModeBindings={${bindingSource}};const tools=new Proxy(Object.create(null),{get(_target,name){const binding=__codeModeBindings[name];return typeof binding===\"function\"?(input)=>binding(input):(input)=>__codeMode.missing(String(name),input);}});const __codeModeResult=await(async()=>{\\n${js}\\n})();if(__codeModeResult===undefined)return undefined;return JSON.parse(JSON.stringify(__codeModeResult));`;\n}\n\nfunction createHostFunctions({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolNames,\n}: {\n codeModeErrors: CodeModeError[];\n input: RunCodeModeInput;\n outerToolCallId: string;\n policy: ResolvedExecutionPolicy;\n toolNames: string[];\n}): HostFunctions {\n const group: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const [index, toolName] of toolNames.entries()) {\n group[`tool${index}`] = async (toolInput: unknown) =>\n await invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName,\n });\n }\n group.missing = async (toolName: unknown, toolInput: unknown) =>\n await invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName: String(toolName),\n });\n return { __codeMode: group } as HostFunctions;\n}\n\nasync function invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName,\n}: {\n codeModeErrors: CodeModeError[];\n input: RunCodeModeInput;\n outerToolCallId: string;\n policy: ResolvedExecutionPolicy;\n toolInput: unknown;\n toolName: string;\n}): Promise<unknown> {\n const context = getHostFunctionContext();\n const toolCallId = `${outerToolCallId}:tool-${context.requestIndex}`;\n const forwardedContext =\n input.toolExecutionOptions?.context ??\n input.toolExecutionOptions?.experimental_context;\n const forwardedExperimentalContext =\n input.toolExecutionOptions?.experimental_context ??\n input.toolExecutionOptions?.context;\n const baseExecutionOptions: CodeModeToolExecutionOptions = {\n toolCallId: outerToolCallId,\n messages: input.toolExecutionOptions?.messages ?? [],\n abortSignal: context.abortSignal,\n ...(forwardedContext === undefined ? {} : { context: forwardedContext }),\n ...(forwardedExperimentalContext === undefined\n ? {}\n : { experimental_context: forwardedExperimentalContext }),\n };\n\n let codeModeInterrupt: CodeModeInterruptExecutionContext | undefined;\n let skipApproval = false;\n if (context.resume !== undefined) {\n const payload = assertInterruptPayload(context.resume.payload);\n if (isCodeModeApprovalInterruptPayload(payload)) {\n const decision = normalizeApprovalResolution(context.resume.resolution);\n if (!decision.approved) {\n throw new CodeModeToolApprovalDeniedError(\n toolName,\n toolInput,\n toolCallId,\n decision.reason,\n );\n }\n skipApproval = true;\n } else {\n codeModeInterrupt = {\n interruptId: `${toolCallId}:interrupt`,\n payload,\n resolution: context.resume.resolution,\n };\n }\n }\n\n try {\n const inputJson = toJsonPayload(\n toolInput,\n policy.maxToolInputBytes,\n `Tool \"${toolName}\" input`,\n );\n const outcome = await invokeHostTool({\n toolName,\n inputJson,\n tools: input.tools,\n baseExecutionOptions,\n codeModeOptions: input.options ?? {},\n maxToolInputBytes: policy.maxToolInputBytes,\n maxToolOutputBytes: policy.maxToolOutputBytes,\n toolCallId,\n ...(codeModeInterrupt === undefined ? {} : { codeModeInterrupt }),\n skipApproval,\n });\n if (outcome.type === 'interrupted') {\n return context.interrupt(outcome.payload);\n }\n return fromJsonPayload(outcome.valueJson);\n } catch (error) {\n if (error instanceof CodeModeError) {\n codeModeErrors.push(error);\n throw new RunError(error.message, error.code, error.details);\n }\n if (\n RunError.isInstance(error) ||\n (error instanceof Error && error.name === 'HostFunctionInterruptSignal')\n ) {\n throw error;\n }\n throw new RunError('Host tool failed.', 'CODE_MODE_HOST_TOOL_ERROR');\n }\n}\n\nfunction assertInterruptPayload(value: unknown): CodeModeInterruptPayload {\n if (\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value) ||\n typeof (value as { kind?: unknown }).kind !== 'string'\n ) {\n throw new CodeModeProtocolError(\n 'Code mode interruption payload is malformed.',\n );\n }\n return value as CodeModeInterruptPayload;\n}\n\nfunction toRunLimits(\n policy: ResolvedExecutionPolicy,\n source: string,\n userSource: string,\n): RunLimits {\n return {\n timeoutMs: policy.timeoutMs,\n memoryLimitBytes: policy.memoryLimitBytes,\n maxStackSizeBytes: policy.maxStackSizeBytes,\n maxResultBytes: expandedSerializationLimit(policy.maxResultBytes),\n maxConsoleOutputBytes: policy.maxConsoleOutputBytes,\n maxSourceBytes: withSerializationOverhead(\n policy.maxSourceBytes,\n Buffer.byteLength(source) - Buffer.byteLength(userSource),\n ),\n maxHostFunctionArgumentsBytes: expandedSerializationLimit(\n policy.maxToolInputBytes,\n ),\n maxHostFunctionOutputBytes: expandedSerializationLimit(\n policy.maxToolOutputBytes,\n ),\n maxBridgeRequests: policy.maxBridgeRequests,\n maxInFlightBridgeRequests: policy.maxInFlightBridgeRequests,\n };\n}\n\nfunction expandedSerializationLimit(value: number): number {\n if (!isValidRunLimit(value)) {\n return value;\n }\n return Math.min(MAX_RUN_LIMIT, Math.max(4096, value * 2 + 1024));\n}\n\nfunction withSerializationOverhead(value: number, overhead: number): number {\n return isValidRunLimit(value)\n ? Math.min(MAX_RUN_LIMIT, value + overhead)\n : value;\n}\n\nfunction isValidRunLimit(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_RUN_LIMIT;\n}\n\nfunction prepareContinuation(\n input: RunCodeModeInput,\n toolNames: string[],\n maxToolOutputBytes: number,\n): {\n token?: string;\n resolutions?: RunResolution[];\n nextInterrupt?: CodeModeInterrupt;\n} {\n if (input.continuation === undefined) {\n if (input.interruptResolution !== undefined) {\n throw new CodeModeProtocolError(\n 'A code-mode interrupt resolution was provided without continuation state.',\n );\n }\n return {};\n }\n\n verifyCodeModeContinuation(\n input.continuation,\n input.options?.continuationSecurity,\n );\n if (input.continuation.js !== input.js) {\n throw new CodeModeProtocolError(\n 'Code mode continuation source does not match the resumed source.',\n );\n }\n if (!stringArraysEqual(input.continuation.toolNames, toolNames)) {\n throw new CodeModeProtocolError(\n 'Code mode continuation tool names do not match the resumed tools.',\n );\n }\n if (input.interruptResolution === undefined) {\n throw new CodeModeProtocolError(\n 'A code-mode continuation requires an interrupt resolution.',\n );\n }\n\n const resolutionIndex = input.continuation.resolutions.length;\n const pending = input.continuation.pendingInterruptions[resolutionIndex];\n if (\n pending === undefined ||\n pending.interruptId !== input.interruptResolution.interruptId\n ) {\n throw new CodeModeProtocolError(\n 'Interrupt resolution does not match the next pending code-mode interruption.',\n { interruptId: input.interruptResolution.interruptId },\n );\n }\n const resolutionValue = normalizeResolutionForPending(\n pending,\n input.interruptResolution.resolution,\n maxToolOutputBytes,\n );\n const resolutions: CodeModePendingResolution[] = [\n ...input.continuation.resolutions,\n {\n runInterruptionId: pending.runInterruptionId,\n value: resolutionValue,\n },\n ];\n\n if (resolutions.length < input.continuation.pendingInterruptions.length) {\n const continuation = signCodeModeContinuation(\n {\n ...withoutAuth(input.continuation),\n resolutions,\n },\n resolveCodeModeContinuationSecurity(input.options?.continuationSecurity),\n );\n return {\n nextInterrupt: toCodeModeInterrupt(continuation, resolutions.length),\n };\n }\n\n assertNoDeniedApproval(input.continuation.pendingInterruptions, resolutions);\n return {\n token: input.continuation.token,\n resolutions: resolutions.map(resolution => ({\n interruptionId: resolution.runInterruptionId,\n value: resolution.value,\n })),\n };\n}\n\nfunction normalizeResolutionForPending(\n pending: CodeModePendingInterruption,\n resolution: unknown,\n maxToolOutputBytes: number,\n): unknown {\n return isCodeModeApprovalInterruptPayload(pending.payload)\n ? normalizeApprovalResolution(resolution)\n : fromJsonPayload(\n toJsonPayload(\n resolution,\n maxToolOutputBytes,\n `Resolution \"${pending.interruptId}\"`,\n ),\n );\n}\n\nfunction assertNoDeniedApproval(\n pendingInterruptions: CodeModePendingInterruption[],\n resolutions: CodeModePendingResolution[],\n): void {\n for (const [index, pending] of pendingInterruptions.entries()) {\n if (!isCodeModeApprovalInterruptPayload(pending.payload)) {\n continue;\n }\n const decision = normalizeApprovalResolution(resolutions[index]?.value);\n if (!decision.approved) {\n throw new CodeModeToolApprovalDeniedError(\n pending.toolName,\n pending.input,\n pending.toolCallId,\n decision.reason,\n );\n }\n }\n}\n\nfunction withoutAuth(\n continuation: CodeModeContinuation,\n): Omit<CodeModeContinuation, 'auth'> {\n const { auth: _auth, ...unsigned } = continuation;\n return unsigned;\n}\n\nfunction toPendingInterruptions({\n interruptions,\n outerToolCallId,\n toolNames,\n}: {\n interruptions: RunInterruption[];\n outerToolCallId: string;\n toolNames: string[];\n}): CodeModePendingInterruption[] {\n return interruptions.map(interruption => {\n const requestIndex = interruptionIndex(interruption.id);\n const toolName = toolNameForInterruption(interruption, toolNames);\n const toolCallId = `${outerToolCallId}:tool-${requestIndex}`;\n return {\n runInterruptionId: interruption.id,\n interruptId: `${toolCallId}:interrupt`,\n toolName,\n toolCallId,\n input:\n interruption.hostFunctionName === '__codeMode.missing'\n ? interruption.arguments[1]\n : interruption.arguments[0],\n payload: assertInterruptPayload(interruption.payload),\n };\n });\n}\n\nfunction interruptionIndex(interruptionId: string): number {\n const match = /^interrupt-(\\d+)$/u.exec(interruptionId);\n if (match === null) {\n throw new CodeModeProtocolError(\n `Run returned malformed interruption id \"${interruptionId}\".`,\n );\n }\n return Number(match[1]);\n}\n\nfunction toolNameForInterruption(\n interruption: RunInterruption,\n toolNames: string[],\n): string {\n if (interruption.hostFunctionName === '__codeMode.missing') {\n return String(interruption.arguments[0]);\n }\n const match = /^__codeMode\\.tool(\\d+)$/u.exec(interruption.hostFunctionName);\n const toolName = match === null ? undefined : toolNames[Number(match[1])];\n if (toolName === undefined) {\n throw new CodeModeProtocolError(\n `Run returned an unknown code-mode host function \"${interruption.hostFunctionName}\".`,\n );\n }\n return toolName;\n}\n\nfunction toCodeModeInterrupt(\n continuation: CodeModeContinuation,\n index: number,\n): CodeModeInterrupt {\n const pending = continuation.pendingInterruptions[index];\n if (pending === undefined) {\n throw new CodeModeProtocolError(\n 'Code mode continuation has no pending interruption at the requested index.',\n );\n }\n return {\n type: 'code-mode-interrupt',\n interruptId: pending.interruptId,\n toolName: pending.toolName,\n toolCallId: pending.toolCallId,\n outerToolCallId: continuation.outerToolCallId,\n input: structuredClone(pending.input),\n payload: structuredClone(pending.payload),\n continuation,\n };\n}\n\nfunction stringArraysEqual(left: string[], right: string[]): boolean {\n return (\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n );\n}\n\nfunction findPreservedCodeModeError(\n error: unknown,\n errors: CodeModeError[],\n): CodeModeError | undefined {\n if (!RunError.isInstance(error)) {\n return undefined;\n }\n return errors.find(candidate => candidate.code === error.code);\n}\n\nfunction toCodeModeRuntimeError(error: unknown): unknown {\n if (error instanceof TypeError) {\n error.message = translateLimitPath(error.message);\n }\n if (\n error instanceof Error &&\n error.name === 'SyntaxError' &&\n !/syntax|unexpected|expression expected/iu.test(error.message)\n ) {\n error.message = `Syntax error: ${error.message}`;\n }\n if (!RunError.isInstance(error)) {\n return error;\n }\n const details = error.details as Record<string, unknown> | undefined;\n switch (error.code) {\n case 'RUN_ABORTED':\n return copyStack(new CodeModeAbortedError(), error);\n case 'RUN_TIMEOUT':\n return copyStack(\n new CodeModeTimeoutError(Number(details?.timeoutMs ?? 0)),\n error,\n );\n case 'RUN_CONCURRENCY_LIMIT':\n return copyStack(\n new CodeModeConcurrencyError(Number(details?.maxWorkers ?? 0)),\n error,\n );\n case 'RUN_SOURCE_TOO_LARGE':\n return copyStack(\n new CodeModeSourceTooLargeError(\n Number(details?.bytes ?? 0),\n Number(details?.maxBytes ?? 0),\n ),\n error,\n );\n case 'RUN_BRIDGE_LIMIT':\n return copyStack(\n new CodeModeBridgeLimitError(error.message, error.details),\n error,\n );\n case 'RUN_DETACHED_BRIDGE_REQUEST':\n return copyStack(\n new CodeModeDetachedBridgeRequestError(error.message, error.details),\n error,\n );\n case 'RUN_PROTOCOL_ERROR':\n return copyStack(\n new CodeModeProtocolError(error.message, error.details),\n error,\n );\n default:\n return error;\n }\n}\n\nfunction translateLimitPath(message: string): string {\n const paths: Record<string, string> = {\n 'limits.timeoutMs': 'executionPolicy.timeoutMs',\n 'limits.memoryLimitBytes': 'executionPolicy.memoryLimitBytes',\n 'limits.maxStackSizeBytes': 'executionPolicy.maxStackSizeBytes',\n 'limits.maxResultBytes': 'executionPolicy.maxResultBytes',\n 'limits.maxConsoleOutputBytes': 'executionPolicy.maxConsoleOutputBytes',\n 'limits.maxSourceBytes': 'executionPolicy.maxSourceBytes',\n 'limits.maxHostFunctionArgumentsBytes': 'executionPolicy.maxToolInputBytes',\n 'limits.maxHostFunctionOutputBytes': 'executionPolicy.maxToolOutputBytes',\n 'limits.maxBridgeRequests': 'executionPolicy.maxBridgeRequests',\n 'limits.maxInFlightBridgeRequests':\n 'executionPolicy.maxInFlightBridgeRequests',\n };\n for (const [runPath, codeModePath] of Object.entries(paths)) {\n if (message.includes(runPath)) {\n return message.replace(runPath, codeModePath);\n }\n }\n return message;\n}\n\nfunction copyStack<T extends Error>(target: T, source: Error): T {\n if (source.stack !== undefined) {\n target.stack = source.stack;\n }\n return target;\n}\n\nfunction translateSourceStack<T>(error: T): T {\n if (!(error instanceof Error) || error.stack === undefined) {\n return error;\n }\n error.stack = error.stack.replaceAll(\n /run\\.js:(\\d+):(\\d+)/gu,\n (_match, line: string, column: string) =>\n `code-mode.js:${Math.max(1, Number(line) - SOURCE_LINE_OFFSET)}:${column}`,\n );\n return error;\n}\n"],"mappings":"AAAA,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAY/B,SAAS,iBAAiB,qBAAqB;AAE/C,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B,KAAK,OAAO;AAC/C,MAA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AA,QACnE;AAAA,MACF;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,IAAI,sBAAsB,MAAM,SAAS,MAAM,OAAO;AAAA,QACtD;AAAA,MACF;AAAA,IACF;AACE,aAAO;AAAA,EACX;AACF;AAEA,SAAS,mBAAmB,SAAyB;AACnD,QAAM,QAAgC;AAAA,IACpC,oBAAoB;AAAA,IACpB,2BAA2B;AAAA,IAC3B,4BAA4B;AAAA,IAC5B,yBAAyB;AAAA,IACzB,gCAAgC;AAAA,IAChC,yBAAyB;AAAA,IACzB,wCAAwC;AAAA,IACxC,qCAAqC;AAAA,IACrC,4BAA4B;AAAA,IAC5B,oCACE;AAAA,EACJ;AACA,aAAW,CAAC,SAAS,YAAY,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC3D,QAAI,QAAQ,SAAS,OAAO,GAAG;AAC7B,aAAO,QAAQ,QAAQ,SAAS,YAAY;AAAA,IAC9C;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,UAA2B,QAAW,QAAkB;AAC/D,MAAI,OAAO,UAAU,QAAW;AAC9B,WAAO,QAAQ,OAAO;AAAA,EACxB;AACA,SAAO;AACT;AAEA,SAAS,qBAAwB,OAAa;AAC5C,MAAI,EAAE,iBAAiB,UAAU,MAAM,UAAU,QAAW;AAC1D,WAAO;AAAA,EACT;AACA,QAAM,QAAQ,MAAM,MAAM;AAAA,IACxB;AAAA,IACA,CAAC,QAAQ,MAAc,WACrB,gBAAgB,KAAK,IAAI,GAAG,OAAO,IAAI,IAAI,kBAAkB,CAAC,IAAI,MAAM;AAAA,EAC5E;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"file":"run-code-mode.js","names":[],"sources":["../src/run-code-mode.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport { createHash } from 'node:crypto';\nimport {\n createRunner,\n createSignedContinuationCodec,\n getHostFunctionContext,\n RunError,\n type HostFunctions,\n type RunInterruption,\n type RunLimits,\n type RunResolution,\n} from 'run';\nimport {\n isCodeModeApprovalInterruptPayload,\n normalizeApprovalResolution,\n} from './approval.js';\nimport {\n resolveCodeModeContinuationSecurity,\n signCodeModeContinuation,\n verifyCodeModeContinuation,\n} from './continuation-capability.js';\nimport {\n CodeModeAbortedError,\n CodeModeBridgeLimitError,\n CodeModeConcurrencyError,\n CodeModeDetachedBridgeRequestError,\n CodeModeError,\n CodeModeProtocolError,\n CodeModeSourceTooLargeError,\n CodeModeTimeoutError,\n CodeModeToolApprovalDeniedError,\n} from './errors.js';\nimport { invokeHostTool } from './tool-invocation.js';\nimport type {\n CodeModeContinuation,\n CodeModeExecutionPolicy,\n CodeModeInterrupt,\n CodeModeInterruptExecutionContext,\n CodeModeInterruptPayload,\n CodeModePendingInterruption,\n CodeModePendingResolution,\n CodeModeToolExecutionOptions,\n RunCodeModeInput,\n} from './types.js';\nimport { fromJsonPayload, toJsonPayload } from './utils/serialization.js';\n\nconst SOURCE_LINE_OFFSET = 1;\nconst MAX_RUN_LIMIT = 2_147_483_647;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;\nconst DEFAULT_STACK_LIMIT_BYTES = 2 * 1024 * 1024;\nconst DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;\nconst DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;\nconst DEFAULT_MAX_SOURCE_BYTES = 256 * 1024;\nconst DEFAULT_MAX_TOOL_INPUT_BYTES = 1024 * 1024;\nconst DEFAULT_MAX_TOOL_OUTPUT_BYTES = 4 * 1024 * 1024;\nconst DEFAULT_MAX_BRIDGE_REQUESTS = 256;\nconst DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS = 32;\n\nlet invocationCounter = 0;\n\n/**\n * Runs one code-mode invocation directly without wrapping it as an AI SDK tool.\n *\n * The source is executed in a fresh QuickJS context with the provided host tools\n * and execution limits.\n *\n * @param input - Source code, host tools, forwarded tool execution options, and code-mode options.\n * @returns The JSON-serializable value returned by the sandboxed program.\n */\nexport async function runCodeMode(input: RunCodeModeInput): Promise<unknown> {\n const policy = resolveExecutionPolicy(input.options?.executionPolicy);\n assertSourceSize(input.js, policy.maxSourceBytes);\n\n const toolNames = Object.keys(input.tools).sort();\n const continuationState = prepareContinuation(\n input,\n toolNames,\n policy.maxToolOutputBytes,\n );\n if (continuationState.nextInterrupt !== undefined) {\n return continuationState.nextInterrupt;\n }\n\n const outerToolCallId =\n input.toolExecutionOptions?.toolCallId ??\n input.continuation?.outerToolCallId ??\n `code-mode-${++invocationCounter}`;\n const source = createCodeModeSource(input.js, toolNames);\n const codeModeErrors: CodeModeError[] = [];\n const hostFunctions = createHostFunctions({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolNames,\n });\n const continuationSecurity = resolveCodeModeContinuationSecurity(\n input.options?.continuationSecurity,\n );\n const runner = createRunner({\n continuationAudience: '@ai-sdk/code-mode/v2',\n continuationCodec: createSignedContinuationCodec({\n maxAgeMs: continuationSecurity.maxAgeMs,\n secret: createHash('sha256')\n .update(continuationSecurity.signingKey)\n .digest(),\n }),\n });\n\n try {\n const result = await runner.run({\n source,\n hostFunctions,\n limits: toRunLimits(policy, source, input.js),\n continuationContext: { outerToolCallId, toolNames },\n ...(input.toolExecutionOptions?.abortSignal === undefined\n ? {}\n : { abortSignal: input.toolExecutionOptions.abortSignal }),\n ...(continuationState.token === undefined\n ? {}\n : { continuation: continuationState.token }),\n ...(continuationState.resolutions === undefined\n ? {}\n : { resolutions: continuationState.resolutions }),\n });\n\n if (result.status === 'completed') {\n return fromJsonPayload(\n toJsonPayload(result.value, policy.maxResultBytes, 'Code mode result'),\n );\n }\n\n const pendingInterruptions = toPendingInterruptions({\n interruptions: result.interruptions,\n outerToolCallId,\n toolNames,\n });\n const continuation = signCodeModeContinuation(\n {\n version: 2,\n js: input.js,\n outerToolCallId,\n toolNames,\n token: result.continuation,\n pendingInterruptions,\n resolutions: [],\n },\n continuationSecurity,\n );\n return toCodeModeInterrupt(continuation, 0);\n } catch (error) {\n const preserved = findPreservedCodeModeError(error, codeModeErrors);\n if (preserved !== undefined) {\n throw translateSourceStack(preserved);\n }\n throw translateSourceStack(toCodeModeRuntimeError(error));\n }\n}\n\ninterface ResolvedExecutionPolicy {\n timeoutMs: number;\n memoryLimitBytes: number;\n maxStackSizeBytes: number;\n maxResultBytes: number;\n maxConsoleOutputBytes: number;\n maxSourceBytes: number;\n maxToolInputBytes: number;\n maxToolOutputBytes: number;\n maxBridgeRequests: number;\n maxInFlightBridgeRequests: number;\n}\n\nfunction resolveExecutionPolicy(\n policy: CodeModeExecutionPolicy = {},\n): ResolvedExecutionPolicy {\n return {\n timeoutMs: policy.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n memoryLimitBytes: policy.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,\n maxStackSizeBytes: policy.maxStackSizeBytes ?? DEFAULT_STACK_LIMIT_BYTES,\n maxResultBytes: policy.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES,\n maxConsoleOutputBytes:\n policy.maxConsoleOutputBytes ?? DEFAULT_MAX_CONSOLE_OUTPUT_BYTES,\n maxSourceBytes: policy.maxSourceBytes ?? DEFAULT_MAX_SOURCE_BYTES,\n maxToolInputBytes: policy.maxToolInputBytes ?? DEFAULT_MAX_TOOL_INPUT_BYTES,\n maxToolOutputBytes:\n policy.maxToolOutputBytes ?? DEFAULT_MAX_TOOL_OUTPUT_BYTES,\n maxBridgeRequests: policy.maxBridgeRequests ?? DEFAULT_MAX_BRIDGE_REQUESTS,\n maxInFlightBridgeRequests:\n policy.maxInFlightBridgeRequests ?? DEFAULT_MAX_IN_FLIGHT_BRIDGE_REQUESTS,\n };\n}\n\nfunction assertSourceSize(source: string, maxBytes: number): void {\n if (!isValidRunLimit(maxBytes)) {\n return;\n }\n const bytes = Buffer.byteLength(source);\n if (bytes > maxBytes) {\n throw new CodeModeSourceTooLargeError(bytes, maxBytes);\n }\n}\n\nfunction createCodeModeSource(js: string, toolNames: string[]): string {\n const bindings = Object.fromEntries(\n toolNames.map((toolName, index) => [toolName, `__codeMode.tool${index}`]),\n );\n const bindingSource = Object.entries(bindings)\n .map(([name, reference]) => `${JSON.stringify(name)}:${reference}`)\n .join(',');\n return `const __codeModeBindings={${bindingSource}};const tools=new Proxy(Object.create(null),{get(_target,name){const binding=__codeModeBindings[name];return typeof binding===\"function\"?(input)=>binding(input):(input)=>__codeMode.missing(String(name),input);}});const __codeModeResult=await(async()=>{\\n${js}\\n})();if(__codeModeResult===undefined)return undefined;return JSON.parse(JSON.stringify(__codeModeResult));`;\n}\n\nfunction createHostFunctions({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolNames,\n}: {\n codeModeErrors: CodeModeError[];\n input: RunCodeModeInput;\n outerToolCallId: string;\n policy: ResolvedExecutionPolicy;\n toolNames: string[];\n}): HostFunctions {\n const group: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const [index, toolName] of toolNames.entries()) {\n group[`tool${index}`] = async (toolInput: unknown) =>\n await invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName,\n });\n }\n group.missing = async (toolName: unknown, toolInput: unknown) =>\n await invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName: String(toolName),\n });\n return { __codeMode: group } as HostFunctions;\n}\n\nasync function invokeCodeModeTool({\n codeModeErrors,\n input,\n outerToolCallId,\n policy,\n toolInput,\n toolName,\n}: {\n codeModeErrors: CodeModeError[];\n input: RunCodeModeInput;\n outerToolCallId: string;\n policy: ResolvedExecutionPolicy;\n toolInput: unknown;\n toolName: string;\n}): Promise<unknown> {\n const context = getHostFunctionContext();\n const toolCallId = `${outerToolCallId}:tool-${context.requestIndex}`;\n const forwardedContext =\n input.toolExecutionOptions?.context ??\n input.toolExecutionOptions?.experimental_context;\n const forwardedExperimentalContext =\n input.toolExecutionOptions?.experimental_context ??\n input.toolExecutionOptions?.context;\n const baseExecutionOptions: CodeModeToolExecutionOptions = {\n toolCallId: outerToolCallId,\n messages: input.toolExecutionOptions?.messages ?? [],\n abortSignal: context.abortSignal,\n ...(forwardedContext === undefined ? {} : { context: forwardedContext }),\n ...(forwardedExperimentalContext === undefined\n ? {}\n : { experimental_context: forwardedExperimentalContext }),\n };\n\n let codeModeInterrupt: CodeModeInterruptExecutionContext | undefined;\n let skipApproval = false;\n if (context.resume !== undefined) {\n const payload = assertInterruptPayload(context.resume.payload);\n if (isCodeModeApprovalInterruptPayload(payload)) {\n const decision = normalizeApprovalResolution(context.resume.resolution);\n if (!decision.approved) {\n throw new CodeModeToolApprovalDeniedError(\n toolName,\n toolInput,\n toolCallId,\n decision.reason,\n );\n }\n skipApproval = true;\n } else {\n codeModeInterrupt = {\n interruptId: `${toolCallId}:interrupt`,\n payload,\n resolution: context.resume.resolution,\n };\n }\n }\n\n try {\n const inputJson = toJsonPayload(\n toolInput,\n policy.maxToolInputBytes,\n `Tool \"${toolName}\" input`,\n );\n const outcome = await invokeHostTool({\n toolName,\n inputJson,\n tools: input.tools,\n baseExecutionOptions,\n codeModeOptions: input.options ?? {},\n maxToolInputBytes: policy.maxToolInputBytes,\n maxToolOutputBytes: policy.maxToolOutputBytes,\n toolCallId,\n ...(codeModeInterrupt === undefined ? {} : { codeModeInterrupt }),\n skipApproval,\n });\n if (outcome.type === 'interrupted') {\n return context.interrupt(outcome.payload);\n }\n return fromJsonPayload(outcome.valueJson);\n } catch (error) {\n if (error instanceof CodeModeError) {\n codeModeErrors.push(error);\n throw new RunError(error.message, error.code, error.details);\n }\n if (\n RunError.isInstance(error) ||\n (error instanceof Error && error.name === 'HostFunctionInterruptSignal')\n ) {\n throw error;\n }\n throw new RunError('Host tool failed.', 'CODE_MODE_HOST_TOOL_ERROR');\n }\n}\n\nfunction assertInterruptPayload(value: unknown): CodeModeInterruptPayload {\n if (\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value) ||\n typeof (value as { kind?: unknown }).kind !== 'string'\n ) {\n throw new CodeModeProtocolError(\n 'Code mode interruption payload is malformed.',\n );\n }\n return value as CodeModeInterruptPayload;\n}\n\nfunction toRunLimits(\n policy: ResolvedExecutionPolicy,\n source: string,\n userSource: string,\n): RunLimits {\n return {\n timeoutMs: policy.timeoutMs,\n memoryLimitBytes: policy.memoryLimitBytes,\n maxStackSizeBytes: policy.maxStackSizeBytes,\n maxResultBytes: expandedSerializationLimit(policy.maxResultBytes),\n maxConsoleOutputBytes: policy.maxConsoleOutputBytes,\n maxSourceBytes: withSerializationOverhead(\n policy.maxSourceBytes,\n Buffer.byteLength(source) - Buffer.byteLength(userSource),\n ),\n maxHostFunctionArgumentsBytes: expandedSerializationLimit(\n policy.maxToolInputBytes,\n ),\n maxHostFunctionOutputBytes: expandedSerializationLimit(\n policy.maxToolOutputBytes,\n ),\n maxBridgeRequests: policy.maxBridgeRequests,\n maxInFlightBridgeRequests: policy.maxInFlightBridgeRequests,\n };\n}\n\nfunction expandedSerializationLimit(value: number): number {\n if (!isValidRunLimit(value)) {\n return value;\n }\n return Math.min(MAX_RUN_LIMIT, Math.max(4096, value * 2 + 1024));\n}\n\nfunction withSerializationOverhead(value: number, overhead: number): number {\n return isValidRunLimit(value)\n ? Math.min(MAX_RUN_LIMIT, value + overhead)\n : value;\n}\n\nfunction isValidRunLimit(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_RUN_LIMIT;\n}\n\nfunction prepareContinuation(\n input: RunCodeModeInput,\n toolNames: string[],\n maxToolOutputBytes: number,\n): {\n token?: string;\n resolutions?: RunResolution[];\n nextInterrupt?: CodeModeInterrupt;\n} {\n if (input.continuation === undefined) {\n if (input.interruptResolution !== undefined) {\n throw new CodeModeProtocolError(\n 'A code-mode interrupt resolution was provided without continuation state.',\n );\n }\n return {};\n }\n\n verifyCodeModeContinuation(\n input.continuation,\n input.options?.continuationSecurity,\n );\n if (input.continuation.js !== input.js) {\n throw new CodeModeProtocolError(\n 'Code mode continuation source does not match the resumed source.',\n );\n }\n if (!stringArraysEqual(input.continuation.toolNames, toolNames)) {\n throw new CodeModeProtocolError(\n 'Code mode continuation tool names do not match the resumed tools.',\n );\n }\n if (input.interruptResolution === undefined) {\n throw new CodeModeProtocolError(\n 'A code-mode continuation requires an interrupt resolution.',\n );\n }\n\n const resolutionIndex = input.continuation.resolutions.length;\n const pending = input.continuation.pendingInterruptions[resolutionIndex];\n if (\n pending === undefined ||\n pending.interruptId !== input.interruptResolution.interruptId\n ) {\n throw new CodeModeProtocolError(\n 'Interrupt resolution does not match the next pending code-mode interruption.',\n { interruptId: input.interruptResolution.interruptId },\n );\n }\n const resolutionValue = normalizeResolutionForPending(\n pending,\n input.interruptResolution.resolution,\n maxToolOutputBytes,\n );\n const resolutions: CodeModePendingResolution[] = [\n ...input.continuation.resolutions,\n {\n runInterruptionId: pending.runInterruptionId,\n value: resolutionValue,\n },\n ];\n\n if (resolutions.length < input.continuation.pendingInterruptions.length) {\n const continuation = signCodeModeContinuation(\n {\n ...withoutAuth(input.continuation),\n resolutions,\n },\n resolveCodeModeContinuationSecurity(input.options?.continuationSecurity),\n );\n return {\n nextInterrupt: toCodeModeInterrupt(continuation, resolutions.length),\n };\n }\n\n assertNoDeniedApproval(input.continuation.pendingInterruptions, resolutions);\n return {\n token: input.continuation.token,\n resolutions: resolutions.map(resolution => ({\n interruptionId: resolution.runInterruptionId,\n value: resolution.value,\n })),\n };\n}\n\nfunction normalizeResolutionForPending(\n pending: CodeModePendingInterruption,\n resolution: unknown,\n maxToolOutputBytes: number,\n): unknown {\n return isCodeModeApprovalInterruptPayload(pending.payload)\n ? normalizeApprovalResolution(resolution)\n : fromJsonPayload(\n toJsonPayload(\n resolution,\n maxToolOutputBytes,\n `Resolution \"${pending.interruptId}\"`,\n ),\n );\n}\n\nfunction assertNoDeniedApproval(\n pendingInterruptions: CodeModePendingInterruption[],\n resolutions: CodeModePendingResolution[],\n): void {\n for (const [index, pending] of pendingInterruptions.entries()) {\n if (!isCodeModeApprovalInterruptPayload(pending.payload)) {\n continue;\n }\n const decision = normalizeApprovalResolution(resolutions[index]?.value);\n if (!decision.approved) {\n throw new CodeModeToolApprovalDeniedError(\n pending.toolName,\n pending.input,\n pending.toolCallId,\n decision.reason,\n );\n }\n }\n}\n\nfunction withoutAuth(\n continuation: CodeModeContinuation,\n): Omit<CodeModeContinuation, 'auth'> {\n const { auth: _auth, ...unsigned } = continuation;\n return unsigned;\n}\n\nfunction toPendingInterruptions({\n interruptions,\n outerToolCallId,\n toolNames,\n}: {\n interruptions: RunInterruption[];\n outerToolCallId: string;\n toolNames: string[];\n}): CodeModePendingInterruption[] {\n return interruptions.map(interruption => {\n const requestIndex = interruptionIndex(interruption.id);\n const toolName = toolNameForInterruption(interruption, toolNames);\n const toolCallId = `${outerToolCallId}:tool-${requestIndex}`;\n return {\n runInterruptionId: interruption.id,\n interruptId: `${toolCallId}:interrupt`,\n toolName,\n toolCallId,\n input:\n interruption.hostFunctionName === '__codeMode.missing'\n ? interruption.arguments[1]\n : interruption.arguments[0],\n payload: assertInterruptPayload(interruption.payload),\n };\n });\n}\n\nfunction interruptionIndex(interruptionId: string): number {\n const match = /^interrupt-(\\d+)$/u.exec(interruptionId);\n if (match === null) {\n throw new CodeModeProtocolError(\n `Run returned malformed interruption id \"${interruptionId}\".`,\n );\n }\n return Number(match[1]);\n}\n\nfunction toolNameForInterruption(\n interruption: RunInterruption,\n toolNames: string[],\n): string {\n if (interruption.hostFunctionName === '__codeMode.missing') {\n return String(interruption.arguments[0]);\n }\n const match = /^__codeMode\\.tool(\\d+)$/u.exec(interruption.hostFunctionName);\n const toolName = match === null ? undefined : toolNames[Number(match[1])];\n if (toolName === undefined) {\n throw new CodeModeProtocolError(\n `Run returned an unknown code-mode host function \"${interruption.hostFunctionName}\".`,\n );\n }\n return toolName;\n}\n\nfunction toCodeModeInterrupt(\n continuation: CodeModeContinuation,\n index: number,\n): CodeModeInterrupt {\n const pending = continuation.pendingInterruptions[index];\n if (pending === undefined) {\n throw new CodeModeProtocolError(\n 'Code mode continuation has no pending interruption at the requested index.',\n );\n }\n return {\n type: 'code-mode-interrupt',\n interruptId: pending.interruptId,\n toolName: pending.toolName,\n toolCallId: pending.toolCallId,\n outerToolCallId: continuation.outerToolCallId,\n input: structuredClone(pending.input),\n payload: structuredClone(pending.payload),\n continuation,\n };\n}\n\nfunction stringArraysEqual(left: string[], right: string[]): boolean {\n return (\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n );\n}\n\nfunction findPreservedCodeModeError(\n error: unknown,\n errors: CodeModeError[],\n): CodeModeError | undefined {\n if (!RunError.isInstance(error)) {\n return undefined;\n }\n return errors.find(candidate => candidate.code === error.code);\n}\n\nfunction toCodeModeRuntimeError(error: unknown): unknown {\n if (error instanceof TypeError) {\n error.message = translateLimitPath(error.message);\n }\n if (\n error instanceof Error &&\n error.name === 'SyntaxError' &&\n !/syntax|unexpected|expression expected/iu.test(error.message)\n ) {\n error.message = `Syntax error: ${error.message}`;\n }\n if (!RunError.isInstance(error)) {\n return error;\n }\n const details = error.details as Record<string, unknown> | undefined;\n switch (error.code) {\n case 'RUN_ABORTED':\n return copyStack(new CodeModeAbortedError(), error);\n case 'RUN_TIMEOUT':\n return copyStack(\n new CodeModeTimeoutError(Number(details?.timeoutMs ?? 0)),\n error,\n );\n case 'RUN_CONCURRENCY_LIMIT':\n return copyStack(\n new CodeModeConcurrencyError(Number(details?.maxWorkers ?? 0)),\n error,\n );\n case 'RUN_SOURCE_TOO_LARGE':\n return copyStack(\n new CodeModeSourceTooLargeError(\n Number(details?.bytes ?? 0),\n Number(details?.maxBytes ?? 0),\n ),\n error,\n );\n case 'RUN_BRIDGE_LIMIT':\n return copyStack(\n new CodeModeBridgeLimitError(error.message, error.details),\n error,\n );\n case 'RUN_DETACHED_BRIDGE_REQUEST':\n return copyStack(\n new CodeModeDetachedBridgeRequestError(error.message, error.details),\n error,\n );\n case 'RUN_PROTOCOL_ERROR':\n return copyStack(\n new CodeModeProtocolError(error.message, error.details),\n error,\n );\n default:\n return error;\n }\n}\n\nfunction translateLimitPath(message: string): string {\n const paths: Record<string, string> = {\n 'limits.timeoutMs': 'executionPolicy.timeoutMs',\n 'limits.memoryLimitBytes': 'executionPolicy.memoryLimitBytes',\n 'limits.maxStackSizeBytes': 'executionPolicy.maxStackSizeBytes',\n 'limits.maxResultBytes': 'executionPolicy.maxResultBytes',\n 'limits.maxConsoleOutputBytes': 'executionPolicy.maxConsoleOutputBytes',\n 'limits.maxSourceBytes': 'executionPolicy.maxSourceBytes',\n 'limits.maxHostFunctionArgumentsBytes': 'executionPolicy.maxToolInputBytes',\n 'limits.maxHostFunctionOutputBytes': 'executionPolicy.maxToolOutputBytes',\n 'limits.maxBridgeRequests': 'executionPolicy.maxBridgeRequests',\n 'limits.maxInFlightBridgeRequests':\n 'executionPolicy.maxInFlightBridgeRequests',\n };\n for (const [runPath, codeModePath] of Object.entries(paths)) {\n if (message.includes(runPath)) {\n return message.replace(runPath, codeModePath);\n }\n }\n return message;\n}\n\nfunction copyStack<T extends Error>(target: T, source: Error): T {\n if (source.stack !== undefined) {\n target.stack = source.stack;\n }\n return target;\n}\n\nfunction translateSourceStack<T>(error: T): T {\n if (!(error instanceof Error) || error.stack === undefined) {\n return error;\n }\n error.stack = error.stack.replaceAll(\n /run\\.js:(\\d+):(\\d+)/gu,\n (_match, line: string, column: string) =>\n `code-mode.js:${Math.max(1, Number(line) - SOURCE_LINE_OFFSET)}:${column}`,\n );\n return error;\n}\n"],"mappings":";;;;;;;;;AA8CA,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AACnC,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,mCAAmC;AACzC,MAAM,2BAA2B;AACjC,MAAM,+BAA+B;AACrC,MAAM,gCAAgC;AACtC,MAAM,8BAA8B;AACpC,MAAM,wCAAwC;AAE9C,IAAI,oBAAoB;;;;;;;;;;AAWxB,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L,IAAI,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;CAcnD,KAAK,MAAM,CAAC,SAAS,iBAAiB,OAAO,QAAQ;EAZnD,oBAAoB;EACpB,2BAA2B;EAC3B,4BAA4B;EAC5B,yBAAyB;EACzB,gCAAgC;EAChC,yBAAyB;EACzB,wCAAwC;EACxC,qCAAqC;EACrC,4BAA4B;EAC5B,oCACE;CAEqD,CAAC,GACxD,IAAI,QAAQ,SAAS,OAAO,GAC1B,OAAO,QAAQ,QAAQ,SAAS,YAAY;CAGhD,OAAO;AACT;AAEA,SAAS,UAA2B,QAAW,QAAkB;CAC/D,IAAI,OAAO,UAAU,KAAA,GACnB,OAAO,QAAQ,OAAO;CAExB,OAAO;AACT;AAEA,SAAS,qBAAwB,OAAa;CAC5C,IAAI,EAAE,iBAAiB,UAAU,MAAM,UAAU,KAAA,GAC/C,OAAO;CAET,MAAM,QAAQ,MAAM,MAAM,WACxB,0BACC,QAAQ,MAAc,WACrB,gBAAgB,KAAK,IAAI,GAAG,OAAO,IAAI,IAAI,kBAAkB,EAAE,GAAG,QACtE;CACA,OAAO;AACT"}
|
package/dist/tool-invocation.js
CHANGED
|
@@ -1,192 +1,114 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { CodeModeProtocolError, CodeModeToolApprovalDeniedError, CodeModeToolApprovalRequiredError, CodeModeToolError } from "./errors.js";
|
|
2
2
|
import { CODE_MODE_TOOL_APPROVAL_KIND } from "./approval.js";
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if (codeModeOptions.approval?.mode === "interrupt") {
|
|
62
|
-
return {
|
|
63
|
-
type: "interrupted",
|
|
64
|
-
toolName,
|
|
65
|
-
input: validation.value,
|
|
66
|
-
toolCallId,
|
|
67
|
-
payload: { kind: CODE_MODE_TOOL_APPROVAL_KIND }
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
const approval = await raceAgainstAbort(
|
|
71
|
-
Promise.resolve(
|
|
72
|
-
codeModeOptions.approval?.onApprovalRequired?.({
|
|
73
|
-
toolName,
|
|
74
|
-
input: validation.value,
|
|
75
|
-
toolCallId
|
|
76
|
-
})
|
|
77
|
-
),
|
|
78
|
-
baseExecutionOptions.abortSignal
|
|
79
|
-
);
|
|
80
|
-
if (approval === void 0) {
|
|
81
|
-
throw new CodeModeToolApprovalRequiredError(
|
|
82
|
-
toolName,
|
|
83
|
-
validation.value,
|
|
84
|
-
toolCallId
|
|
85
|
-
);
|
|
86
|
-
}
|
|
87
|
-
const approved = typeof approval === "string" ? approval === "approved" : approval?.approved;
|
|
88
|
-
const reason = typeof approval === "string" ? void 0 : approval?.reason;
|
|
89
|
-
if (typeof approved !== "boolean") {
|
|
90
|
-
throw new CodeModeProtocolError(
|
|
91
|
-
`Tool "${toolName}" approval callback returned a malformed approval decision.`,
|
|
92
|
-
{ toolName, toolCallId }
|
|
93
|
-
);
|
|
94
|
-
}
|
|
95
|
-
if (reason !== void 0 && typeof reason !== "string") {
|
|
96
|
-
throw new CodeModeProtocolError(
|
|
97
|
-
`Tool "${toolName}" approval callback returned a malformed approval reason.`,
|
|
98
|
-
{ toolName, toolCallId }
|
|
99
|
-
);
|
|
100
|
-
}
|
|
101
|
-
if (!approved) {
|
|
102
|
-
throw new CodeModeToolApprovalDeniedError(
|
|
103
|
-
toolName,
|
|
104
|
-
validation.value,
|
|
105
|
-
toolCallId,
|
|
106
|
-
reason
|
|
107
|
-
);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
const output = await raceAgainstAbort(
|
|
111
|
-
executeHostTool(hostTool.execute.bind(hostTool), {
|
|
112
|
-
input: validation.value,
|
|
113
|
-
options: executionOptions
|
|
114
|
-
}),
|
|
115
|
-
executionOptions.abortSignal
|
|
116
|
-
);
|
|
117
|
-
return {
|
|
118
|
-
type: "success",
|
|
119
|
-
valueJson: toJsonPayload(
|
|
120
|
-
output,
|
|
121
|
-
maxToolOutputBytes,
|
|
122
|
-
`Tool "${toolName}" output`
|
|
123
|
-
)
|
|
124
|
-
};
|
|
3
|
+
import { assertJsonSerializable, fromJsonPayload, toJsonPayload } from "./utils/serialization.js";
|
|
4
|
+
import { asSchema } from "ai";
|
|
5
|
+
//#region src/tool-invocation.ts
|
|
6
|
+
async function invokeHostTool({ toolName, inputJson, tools, baseExecutionOptions, codeModeOptions, maxToolInputBytes, maxToolOutputBytes, toolCallId, codeModeInterrupt, skipApproval = false }) {
|
|
7
|
+
throwIfAborted(baseExecutionOptions.abortSignal);
|
|
8
|
+
const hostTool = tools[toolName];
|
|
9
|
+
if (!hostTool) throw new CodeModeToolError(`Unknown tool: ${toolName}`, {
|
|
10
|
+
toolName,
|
|
11
|
+
availableTools: Object.keys(tools)
|
|
12
|
+
});
|
|
13
|
+
if (hostTool.execute == null) throw new CodeModeToolError(`Tool "${toolName}" does not have execute().`, { toolName });
|
|
14
|
+
const input = fromJsonPayload(inputJson);
|
|
15
|
+
assertJsonSerializable(input, maxToolInputBytes, `Tool "${toolName}" input`);
|
|
16
|
+
const validation = await raceAgainstAbort(validateToolInput(hostTool.inputSchema, input), baseExecutionOptions.abortSignal);
|
|
17
|
+
if (!validation.success) throw new CodeModeToolError(`Invalid input for tool "${toolName}": ${validation.error.message}`, {
|
|
18
|
+
toolName,
|
|
19
|
+
input,
|
|
20
|
+
cause: validation.error.message
|
|
21
|
+
});
|
|
22
|
+
const executionOptions = {
|
|
23
|
+
...baseExecutionOptions,
|
|
24
|
+
toolCallId,
|
|
25
|
+
...codeModeInterrupt !== void 0 ? { codeModeInterrupt } : {}
|
|
26
|
+
};
|
|
27
|
+
if (!skipApproval && await raceAgainstAbort(requiresApproval(hostTool, validation.value, executionOptions), executionOptions.abortSignal)) {
|
|
28
|
+
if (codeModeOptions.approval?.mode === "interrupt") return {
|
|
29
|
+
type: "interrupted",
|
|
30
|
+
toolName,
|
|
31
|
+
input: validation.value,
|
|
32
|
+
toolCallId,
|
|
33
|
+
payload: { kind: CODE_MODE_TOOL_APPROVAL_KIND }
|
|
34
|
+
};
|
|
35
|
+
const approval = await raceAgainstAbort(Promise.resolve(codeModeOptions.approval?.onApprovalRequired?.({
|
|
36
|
+
toolName,
|
|
37
|
+
input: validation.value,
|
|
38
|
+
toolCallId
|
|
39
|
+
})), baseExecutionOptions.abortSignal);
|
|
40
|
+
if (approval === void 0) throw new CodeModeToolApprovalRequiredError(toolName, validation.value, toolCallId);
|
|
41
|
+
const approved = typeof approval === "string" ? approval === "approved" : approval?.approved;
|
|
42
|
+
const reason = typeof approval === "string" ? void 0 : approval?.reason;
|
|
43
|
+
if (typeof approved !== "boolean") throw new CodeModeProtocolError(`Tool "${toolName}" approval callback returned a malformed approval decision.`, {
|
|
44
|
+
toolName,
|
|
45
|
+
toolCallId
|
|
46
|
+
});
|
|
47
|
+
if (reason !== void 0 && typeof reason !== "string") throw new CodeModeProtocolError(`Tool "${toolName}" approval callback returned a malformed approval reason.`, {
|
|
48
|
+
toolName,
|
|
49
|
+
toolCallId
|
|
50
|
+
});
|
|
51
|
+
if (!approved) throw new CodeModeToolApprovalDeniedError(toolName, validation.value, toolCallId, reason);
|
|
52
|
+
}
|
|
53
|
+
const output = await raceAgainstAbort(executeHostTool(hostTool.execute.bind(hostTool), {
|
|
54
|
+
input: validation.value,
|
|
55
|
+
options: executionOptions
|
|
56
|
+
}), executionOptions.abortSignal);
|
|
57
|
+
return {
|
|
58
|
+
type: "success",
|
|
59
|
+
valueJson: toJsonPayload(output, maxToolOutputBytes, `Tool "${toolName}" output`)
|
|
60
|
+
};
|
|
125
61
|
}
|
|
126
62
|
async function requiresApproval(hostTool, input, options) {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
if (typeof hostTool.needsApproval === "boolean") {
|
|
131
|
-
return hostTool.needsApproval;
|
|
132
|
-
}
|
|
133
|
-
return await hostTool.needsApproval(input, options);
|
|
63
|
+
if (hostTool.needsApproval == null) return false;
|
|
64
|
+
if (typeof hostTool.needsApproval === "boolean") return hostTool.needsApproval;
|
|
65
|
+
return await hostTool.needsApproval(input, options);
|
|
134
66
|
}
|
|
135
67
|
async function validateToolInput(schema, input) {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
68
|
+
const normalizedSchema = asSchema(schema);
|
|
69
|
+
if (normalizedSchema.validate === void 0) return {
|
|
70
|
+
success: true,
|
|
71
|
+
value: input
|
|
72
|
+
};
|
|
73
|
+
return await normalizedSchema.validate(input);
|
|
141
74
|
}
|
|
142
|
-
async function executeHostTool(execute, {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
finalOutput = part;
|
|
151
|
-
}
|
|
152
|
-
return finalOutput;
|
|
153
|
-
}
|
|
154
|
-
return await output;
|
|
75
|
+
async function executeHostTool(execute, { input, options }) {
|
|
76
|
+
const output = execute(input, options);
|
|
77
|
+
if (isAsyncIterable(output)) {
|
|
78
|
+
let finalOutput;
|
|
79
|
+
for await (const part of output) finalOutput = part;
|
|
80
|
+
return finalOutput;
|
|
81
|
+
}
|
|
82
|
+
return await output;
|
|
155
83
|
}
|
|
156
84
|
function isAsyncIterable(value) {
|
|
157
|
-
|
|
85
|
+
return typeof value === "object" && value !== null && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
|
|
158
86
|
}
|
|
159
87
|
async function raceAgainstAbort(operation, abortSignal) {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
return await Promise.race([operation, aborted]);
|
|
177
|
-
} finally {
|
|
178
|
-
abortSignal.removeEventListener("abort", onAbort);
|
|
179
|
-
}
|
|
88
|
+
if (abortSignal === void 0) return await operation;
|
|
89
|
+
throwIfAborted(abortSignal);
|
|
90
|
+
let rejectOnAbort;
|
|
91
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
92
|
+
rejectOnAbort = reject;
|
|
93
|
+
});
|
|
94
|
+
const onAbort = () => {
|
|
95
|
+
rejectOnAbort(abortReason(abortSignal));
|
|
96
|
+
};
|
|
97
|
+
abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
98
|
+
if (abortSignal.aborted) onAbort();
|
|
99
|
+
try {
|
|
100
|
+
return await Promise.race([operation, aborted]);
|
|
101
|
+
} finally {
|
|
102
|
+
abortSignal.removeEventListener("abort", onAbort);
|
|
103
|
+
}
|
|
180
104
|
}
|
|
181
105
|
function throwIfAborted(abortSignal) {
|
|
182
|
-
|
|
183
|
-
throw abortReason(abortSignal);
|
|
184
|
-
}
|
|
106
|
+
if (abortSignal?.aborted) throw abortReason(abortSignal);
|
|
185
107
|
}
|
|
186
108
|
function abortReason(abortSignal) {
|
|
187
|
-
|
|
109
|
+
return abortSignal.reason ?? new DOMException("The operation was aborted.", "AbortError");
|
|
188
110
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
111
|
+
//#endregion
|
|
112
|
+
export { invokeHostTool };
|
|
113
|
+
|
|
192
114
|
//# sourceMappingURL=tool-invocation.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tool-invocation.ts"],"sourcesContent":["import { asSchema } from 'ai';\nimport { CODE_MODE_TOOL_APPROVAL_KIND } from './approval.js';\nimport {\n CodeModeProtocolError,\n CodeModeToolApprovalDeniedError,\n CodeModeToolApprovalRequiredError,\n CodeModeToolError,\n} from './errors.js';\nimport type {\n CodeModeInterruptExecutionContext,\n CodeModeInterruptPayload,\n CodeModeOptions,\n CodeModeToolExecutionOptions,\n CodeModeToolSet,\n} from './types.js';\nimport {\n assertJsonSerializable,\n fromJsonPayload,\n toJsonPayload,\n} from './utils/serialization.js';\n\nexport type HostToolInvocationResult =\n | { type: 'success'; valueJson: string }\n | {\n type: 'interrupted';\n toolName: string;\n input: unknown;\n toolCallId: string;\n payload: CodeModeInterruptPayload;\n };\n\nexport async function invokeHostTool({\n toolName,\n inputJson,\n tools,\n baseExecutionOptions,\n codeModeOptions,\n maxToolInputBytes,\n maxToolOutputBytes,\n toolCallId,\n codeModeInterrupt,\n skipApproval = false,\n}: {\n toolName: string;\n inputJson: string;\n tools: CodeModeToolSet;\n baseExecutionOptions: CodeModeToolExecutionOptions;\n codeModeOptions: CodeModeOptions;\n maxToolInputBytes: number;\n maxToolOutputBytes: number;\n toolCallId: string;\n codeModeInterrupt?: CodeModeInterruptExecutionContext;\n skipApproval?: boolean;\n}): Promise<HostToolInvocationResult> {\n throwIfAborted(baseExecutionOptions.abortSignal);\n\n const hostTool = tools[toolName];\n if (!hostTool) {\n throw new CodeModeToolError(`Unknown tool: ${toolName}`, {\n toolName,\n availableTools: Object.keys(tools),\n });\n }\n if (hostTool.execute == null) {\n throw new CodeModeToolError(`Tool \"${toolName}\" does not have execute().`, {\n toolName,\n });\n }\n\n const input = fromJsonPayload(inputJson);\n assertJsonSerializable(input, maxToolInputBytes, `Tool \"${toolName}\" input`);\n\n const validation = await raceAgainstAbort(\n validateToolInput(hostTool.inputSchema, input),\n baseExecutionOptions.abortSignal,\n );\n if (!validation.success) {\n throw new CodeModeToolError(\n `Invalid input for tool \"${toolName}\": ${validation.error.message}`,\n { toolName, input, cause: validation.error.message },\n );\n }\n\n const executionOptions: CodeModeToolExecutionOptions = {\n ...baseExecutionOptions,\n toolCallId,\n ...(codeModeInterrupt !== undefined ? { codeModeInterrupt } : {}),\n };\n\n const needsApproval =\n !skipApproval &&\n (await raceAgainstAbort(\n requiresApproval(hostTool, validation.value, executionOptions),\n executionOptions.abortSignal,\n ));\n\n if (needsApproval) {\n if (codeModeOptions.approval?.mode === 'interrupt') {\n return {\n type: 'interrupted',\n toolName,\n input: validation.value,\n toolCallId,\n payload: { kind: CODE_MODE_TOOL_APPROVAL_KIND },\n };\n }\n\n const approval = await raceAgainstAbort(\n Promise.resolve(\n codeModeOptions.approval?.onApprovalRequired?.({\n toolName,\n input: validation.value,\n toolCallId,\n }),\n ),\n baseExecutionOptions.abortSignal,\n );\n if (approval === undefined) {\n throw new CodeModeToolApprovalRequiredError(\n toolName,\n validation.value,\n toolCallId,\n );\n }\n const approved =\n typeof approval === 'string'\n ? approval === 'approved'\n : approval?.approved;\n const reason = typeof approval === 'string' ? undefined : approval?.reason;\n if (typeof approved !== 'boolean') {\n throw new CodeModeProtocolError(\n `Tool \"${toolName}\" approval callback returned a malformed approval decision.`,\n { toolName, toolCallId },\n );\n }\n if (reason !== undefined && typeof reason !== 'string') {\n throw new CodeModeProtocolError(\n `Tool \"${toolName}\" approval callback returned a malformed approval reason.`,\n { toolName, toolCallId },\n );\n }\n if (!approved) {\n throw new CodeModeToolApprovalDeniedError(\n toolName,\n validation.value,\n toolCallId,\n reason,\n );\n }\n }\n\n const output = await raceAgainstAbort(\n executeHostTool(hostTool.execute.bind(hostTool), {\n input: validation.value,\n options: executionOptions,\n }),\n executionOptions.abortSignal,\n );\n return {\n type: 'success',\n valueJson: toJsonPayload(\n output,\n maxToolOutputBytes,\n `Tool \"${toolName}\" output`,\n ),\n };\n}\n\nasync function requiresApproval(\n hostTool: CodeModeToolSet[string],\n input: unknown,\n options: CodeModeToolExecutionOptions,\n): Promise<boolean> {\n if (hostTool.needsApproval == null) {\n return false;\n }\n if (typeof hostTool.needsApproval === 'boolean') {\n return hostTool.needsApproval;\n }\n return await hostTool.needsApproval(input as never, options as never);\n}\n\nasync function validateToolInput(\n schema: CodeModeToolSet[string]['inputSchema'],\n input: unknown,\n): Promise<\n { success: true; value: unknown } | { success: false; error: Error }\n> {\n const normalizedSchema = asSchema(schema);\n if (normalizedSchema.validate === undefined) {\n return { success: true, value: input };\n }\n return await normalizedSchema.validate(input);\n}\n\nasync function executeHostTool(\n execute: NonNullable<CodeModeToolSet[string]['execute']>,\n {\n input,\n options,\n }: {\n input: unknown;\n options: CodeModeToolExecutionOptions;\n },\n): Promise<unknown> {\n const output = execute(input as never, options as never);\n if (isAsyncIterable(output)) {\n let finalOutput: unknown;\n for await (const part of output) {\n finalOutput = part;\n }\n return finalOutput;\n }\n return await output;\n}\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n Symbol.asyncIterator in value &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[\n Symbol.asyncIterator\n ] === 'function'\n );\n}\n\nasync function raceAgainstAbort<T>(\n operation: Promise<T>,\n abortSignal: AbortSignal | undefined,\n): Promise<T> {\n if (abortSignal === undefined) {\n return await operation;\n }\n throwIfAborted(abortSignal);\n\n let rejectOnAbort!: (reason?: unknown) => void;\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectOnAbort = reject;\n });\n const onAbort = () => {\n rejectOnAbort(abortReason(abortSignal));\n };\n\n abortSignal.addEventListener('abort', onAbort, { once: true });\n if (abortSignal.aborted) {\n onAbort();\n }\n\n try {\n return await Promise.race([operation, aborted]);\n } finally {\n abortSignal.removeEventListener('abort', onAbort);\n }\n}\n\nfunction throwIfAborted(abortSignal: AbortSignal | undefined): void {\n if (abortSignal?.aborted) {\n throw abortReason(abortSignal);\n }\n}\n\nfunction abortReason(abortSignal: AbortSignal): unknown {\n return (\n abortSignal.reason ??\n new DOMException('The operation was aborted.', 'AbortError')\n );\n}\n"],"mappings":"AAAA,SAAS,gBAAgB;AACzB,SAAS,oCAAoC;AAC7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAQP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP,eAAsB,eAAe;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAe;AACjB,GAWsC;AACpC,iBAAe,qBAAqB,WAAW;AAE/C,QAAM,WAAW,MAAM,QAAQ;AAC/B,MAAI,CAAC,UAAU;AACb,UAAM,IAAI,kBAAkB,iBAAiB,QAAQ,IAAI;AAAA,MACvD;AAAA,MACA,gBAAgB,OAAO,KAAK,KAAK;AAAA,IACnC,CAAC;AAAA,EACH;AACA,M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,MAAM,GAAG;AAC3B,QAAI;AACJ,qBAAiB,QAAQ,QAAQ;AAC/B,oBAAc;AAAA,IAChB;AACA,WAAO;AAAA,EACT;AACA,SAAO,MAAM;AACf;AAEA,SAAS,gBAAgB,OAAiD;AACxE,SACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAO,iBAAiB,SACxB,OAAQ,MACN,OAAO,aACT,MAAM;AAEV;AAEA,eAAe,iBACb,WACA,aACY;AACZ,MAAI,gBAAgB,QAAW;AAC7B,WAAO,MAAM;AAAA,EACf;AACA,iBAAe,WAAW;AAE1B,MAAI;AACJ,QAAM,UAAU,IAAI,QAAe,CAAC,UAAU,WAAW;AACvD,oBAAgB;AAAA,EAClB,CAAC;AACD,QAAM,UAAU,MAAM;AACpB,kBAAc,YAAY,WAAW,CAAC;AAAA,EACxC;AAEA,cAAY,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAC7D,MAAI,YAAY,SAAS;AACvB,YAAQ;AAAA,EACV;AAEA,MAAI;AACF,WAAO,MAAM,QAAQ,KAAK,CAAC,WAAW,OAAO,CAAC;AAAA,EAChD,UAAE;AACA,gBAAY,oBAAoB,SAAS,OAAO;AAAA,EAClD;AACF;AAEA,SAAS,eAAe,aAA4C;AAClE,MAAI,aAAa,SAAS;AACxB,UAAM,YAAY,WAAW;AAAA,EAC/B;AACF;AAEA,SAAS,YAAY,aAAmC;AACtD,SACE,YAAY,UACZ,IAAI,aAAa,8BAA8B,YAAY;AAE/D;","names":[]}
|
|
1
|
+
{"version":3,"file":"tool-invocation.js","names":[],"sources":["../src/tool-invocation.ts"],"sourcesContent":["import { asSchema } from 'ai';\nimport { CODE_MODE_TOOL_APPROVAL_KIND } from './approval.js';\nimport {\n CodeModeProtocolError,\n CodeModeToolApprovalDeniedError,\n CodeModeToolApprovalRequiredError,\n CodeModeToolError,\n} from './errors.js';\nimport type {\n CodeModeInterruptExecutionContext,\n CodeModeInterruptPayload,\n CodeModeOptions,\n CodeModeToolExecutionOptions,\n CodeModeToolSet,\n} from './types.js';\nimport {\n assertJsonSerializable,\n fromJsonPayload,\n toJsonPayload,\n} from './utils/serialization.js';\n\nexport type HostToolInvocationResult =\n | { type: 'success'; valueJson: string }\n | {\n type: 'interrupted';\n toolName: string;\n input: unknown;\n toolCallId: string;\n payload: CodeModeInterruptPayload;\n };\n\nexport async function invokeHostTool({\n toolName,\n inputJson,\n tools,\n baseExecutionOptions,\n codeModeOptions,\n maxToolInputBytes,\n maxToolOutputBytes,\n toolCallId,\n codeModeInterrupt,\n skipApproval = false,\n}: {\n toolName: string;\n inputJson: string;\n tools: CodeModeToolSet;\n baseExecutionOptions: CodeModeToolExecutionOptions;\n codeModeOptions: CodeModeOptions;\n maxToolInputBytes: number;\n maxToolOutputBytes: number;\n toolCallId: string;\n codeModeInterrupt?: CodeModeInterruptExecutionContext;\n skipApproval?: boolean;\n}): Promise<HostToolInvocationResult> {\n throwIfAborted(baseExecutionOptions.abortSignal);\n\n const hostTool = tools[toolName];\n if (!hostTool) {\n throw new CodeModeToolError(`Unknown tool: ${toolName}`, {\n toolName,\n availableTools: Object.keys(tools),\n });\n }\n if (hostTool.execute == null) {\n throw new CodeModeToolError(`Tool \"${toolName}\" does not have execute().`, {\n toolName,\n });\n }\n\n const input = fromJsonPayload(inputJson);\n assertJsonSerializable(input, maxToolInputBytes, `Tool \"${toolName}\" input`);\n\n const validation = await raceAgainstAbort(\n validateToolInput(hostTool.inputSchema, input),\n baseExecutionOptions.abortSignal,\n );\n if (!validation.success) {\n throw new CodeModeToolError(\n `Invalid input for tool \"${toolName}\": ${validation.error.message}`,\n { toolName, input, cause: validation.error.message },\n );\n }\n\n const executionOptions: CodeModeToolExecutionOptions = {\n ...baseExecutionOptions,\n toolCallId,\n ...(codeModeInterrupt !== undefined ? { codeModeInterrupt } : {}),\n };\n\n const needsApproval =\n !skipApproval &&\n (await raceAgainstAbort(\n requiresApproval(hostTool, validation.value, executionOptions),\n executionOptions.abortSignal,\n ));\n\n if (needsApproval) {\n if (codeModeOptions.approval?.mode === 'interrupt') {\n return {\n type: 'interrupted',\n toolName,\n input: validation.value,\n toolCallId,\n payload: { kind: CODE_MODE_TOOL_APPROVAL_KIND },\n };\n }\n\n const approval = await raceAgainstAbort(\n Promise.resolve(\n codeModeOptions.approval?.onApprovalRequired?.({\n toolName,\n input: validation.value,\n toolCallId,\n }),\n ),\n baseExecutionOptions.abortSignal,\n );\n if (approval === undefined) {\n throw new CodeModeToolApprovalRequiredError(\n toolName,\n validation.value,\n toolCallId,\n );\n }\n const approved =\n typeof approval === 'string'\n ? approval === 'approved'\n : approval?.approved;\n const reason = typeof approval === 'string' ? undefined : approval?.reason;\n if (typeof approved !== 'boolean') {\n throw new CodeModeProtocolError(\n `Tool \"${toolName}\" approval callback returned a malformed approval decision.`,\n { toolName, toolCallId },\n );\n }\n if (reason !== undefined && typeof reason !== 'string') {\n throw new CodeModeProtocolError(\n `Tool \"${toolName}\" approval callback returned a malformed approval reason.`,\n { toolName, toolCallId },\n );\n }\n if (!approved) {\n throw new CodeModeToolApprovalDeniedError(\n toolName,\n validation.value,\n toolCallId,\n reason,\n );\n }\n }\n\n const output = await raceAgainstAbort(\n executeHostTool(hostTool.execute.bind(hostTool), {\n input: validation.value,\n options: executionOptions,\n }),\n executionOptions.abortSignal,\n );\n return {\n type: 'success',\n valueJson: toJsonPayload(\n output,\n maxToolOutputBytes,\n `Tool \"${toolName}\" output`,\n ),\n };\n}\n\nasync function requiresApproval(\n hostTool: CodeModeToolSet[string],\n input: unknown,\n options: CodeModeToolExecutionOptions,\n): Promise<boolean> {\n if (hostTool.needsApproval == null) {\n return false;\n }\n if (typeof hostTool.needsApproval === 'boolean') {\n return hostTool.needsApproval;\n }\n return await hostTool.needsApproval(input as never, options as never);\n}\n\nasync function validateToolInput(\n schema: CodeModeToolSet[string]['inputSchema'],\n input: unknown,\n): Promise<\n { success: true; value: unknown } | { success: false; error: Error }\n> {\n const normalizedSchema = asSchema(schema);\n if (normalizedSchema.validate === undefined) {\n return { success: true, value: input };\n }\n return await normalizedSchema.validate(input);\n}\n\nasync function executeHostTool(\n execute: NonNullable<CodeModeToolSet[string]['execute']>,\n {\n input,\n options,\n }: {\n input: unknown;\n options: CodeModeToolExecutionOptions;\n },\n): Promise<unknown> {\n const output = execute(input as never, options as never);\n if (isAsyncIterable(output)) {\n let finalOutput: unknown;\n for await (const part of output) {\n finalOutput = part;\n }\n return finalOutput;\n }\n return await output;\n}\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n Symbol.asyncIterator in value &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[\n Symbol.asyncIterator\n ] === 'function'\n );\n}\n\nasync function raceAgainstAbort<T>(\n operation: Promise<T>,\n abortSignal: AbortSignal | undefined,\n): Promise<T> {\n if (abortSignal === undefined) {\n return await operation;\n }\n throwIfAborted(abortSignal);\n\n let rejectOnAbort!: (reason?: unknown) => void;\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectOnAbort = reject;\n });\n const onAbort = () => {\n rejectOnAbort(abortReason(abortSignal));\n };\n\n abortSignal.addEventListener('abort', onAbort, { once: true });\n if (abortSignal.aborted) {\n onAbort();\n }\n\n try {\n return await Promise.race([operation, aborted]);\n } finally {\n abortSignal.removeEventListener('abort', onAbort);\n }\n}\n\nfunction throwIfAborted(abortSignal: AbortSignal | undefined): void {\n if (abortSignal?.aborted) {\n throw abortReason(abortSignal);\n }\n}\n\nfunction abortReason(abortSignal: AbortSignal): unknown {\n return (\n abortSignal.reason ??\n new DOMException('The operation was aborted.', 'AbortError')\n );\n}\n"],"mappings":";;;;;AA+BA,eAAsB,eAAe,EACnC,UACA,WACA,OACA,sBACA,iBACA,mBACA,oBACA,YACA,mBACA,eAAe,SAYqB;CACpC,eAAe,qBAAqB,WAAW;CAE/C,MAAM,WAAW,MAAM;CACvB,IAAI,CAAC,UACH,MAAM,IAAI,kBAAkB,iBAAiB,YAAY;EACvD;EACA,g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