From fd62c700696969389c05a16c367398049cbf855b Mon Sep 17 00:00:00 2001 From: Thorsten Hans Date: Mon, 9 Nov 2026 08:10:55 -0700 Subject: [PATCH] sdk: make Zod the source of truth for agent tool schemas interpreterTool() now returns a strict Zod schema as inputSchema, which the Vercel AI SDK consumes directly. toAnthropicTool(), toOpenAITool(), and the new toToolDefinition() derive JSON Schema from it with z.toJSONSchema; hand-written JSON Schema ToolDefinitions are still accepted. - The derived schema and description are identical to the previous hand-written output for every language configuration, pinned by a golden fixture test. - The input type narrows to the configured languages (no `dependencies` for Python-only tools). - inputSchema.safeParse() rejects unknown fields such as allowedHosts, replacing hand-rolled argument checks in the ai-code-executor example. - README documents Interpreter + tool setup for the Vercel AI SDK ToolLoopAgent and the Anthropic SDK. Co-Authored-By: Claude Opus 5.5 --- .../ai-code-executor/api/package-lock.json | 3 + examples/ai-code-executor/api/src/index.ts | 29 +-- examples/app-builder/api/package-lock.json | 3 + examples/sdk-component/api/package-lock.json | 3 + sdk/README.md | 120 ++++++++- sdk/package-lock.json | 12 + sdk/package.json | 3 + sdk/src/index.ts | 13 +- sdk/src/tools.ts | 161 ++++++++---- sdk/test/fixtures/interpreter-tool.json | 237 ++++++++++++++++++ sdk/test/tools.test.ts | 75 +++++- sdk/test/types.assert.ts | 20 ++ 12 files changed, 604 insertions(+), 75 deletions(-) create mode 100644 sdk/test/fixtures/interpreter-tool.json diff --git a/examples/ai-code-executor/api/package-lock.json b/examples/ai-code-executor/api/package-lock.json index a3a0a8a..75a4f4e 100644 --- a/examples/ai-code-executor/api/package-lock.json +++ b/examples/ai-code-executor/api/package-lock.json @@ -26,6 +26,9 @@ "name": "@spinframework/sandbox", "version": "0.1.0", "license": "Apache-2.0", + "dependencies": { + "zod": "^4.6.7" + }, "devDependencies": { "typescript": "^5.6.0" } diff --git a/examples/ai-code-executor/api/src/index.ts b/examples/ai-code-executor/api/src/index.ts index a7e0afc..0169670 100644 --- a/examples/ai-code-executor/api/src/index.ts +++ b/examples/ai-code-executor/api/src/index.ts @@ -14,12 +14,13 @@ import * as variables from "@spinframework/spin-variables"; import { createProvider } from "#llm-provider"; import { Interpreter, type Language } from "@spinframework/sandbox/interpreter"; -import type { HttpInput, RunOpts } from "@spinframework/sandbox/core"; -import { interpreterTool } from "@spinframework/sandbox/tools"; +import type { RunOpts } from "@spinframework/sandbox/core"; +import { interpreterTool, toToolDefinition } from "@spinframework/sandbox/tools"; import { historyFor, type History, type ToolResult } from "./llm/types"; import { log, initLogger } from "./logger"; const INTERPRETER_TOOL = interpreterTool(); +const INTERPRETER_TOOL_JSON = toToolDefinition(INTERPRETER_TOOL); const EXECUTION_POLICY: Pick = { allowedHosts: [], kvEnabled: false, @@ -101,7 +102,7 @@ async function runAgent(prompt: string, history: unknown, emit: Emit): Promise emit({ t: "text_delta", block: `${turn}-${block}`, text }) }, ); const genMs = Date.now() - genStart; @@ -109,21 +110,17 @@ async function runAgent(prompt: string, history: unknown, emit: Emit): Promise; - input?: HttpInput; - }; - if (!input || typeof input !== "object" || Array.isArray(input) || - Object.keys(input).some((key) => !Object.prototype.hasOwnProperty.call(INTERPRETER_TOOL.inputSchema.properties, key))) { - toolResults.push({ id: call.id, content: "error: unsupported tool arguments; execution permissions are controlled by the application", isError: true }); - continue; - } - if ((input.language !== "python" && input.language !== "javascript") || typeof input.code !== "string") { - toolResults.push({ id: call.id, content: "error: arguments must include language (python|javascript) and code", isError: true }); + // The strict Zod schema rejects unknown fields, so the model cannot set execution policy. + const parsed = INTERPRETER_TOOL.inputSchema.safeParse(call.input); + if (!parsed.success) { + toolResults.push({ + id: call.id, + content: `error: invalid tool arguments (${parsed.error.issues.map((i) => i.message).join("; ")}); execution permissions are controlled by the application`, + isError: true, + }); continue; } + const input = parsed.data; const id = toolId++; // Stream the code, requested packages, and application-approved hosts before execution. diff --git a/examples/app-builder/api/package-lock.json b/examples/app-builder/api/package-lock.json index a3a0a8a..75a4f4e 100644 --- a/examples/app-builder/api/package-lock.json +++ b/examples/app-builder/api/package-lock.json @@ -26,6 +26,9 @@ "name": "@spinframework/sandbox", "version": "0.1.0", "license": "Apache-2.0", + "dependencies": { + "zod": "^4.6.7" + }, "devDependencies": { "typescript": "^5.6.0" } diff --git a/examples/sdk-component/api/package-lock.json b/examples/sdk-component/api/package-lock.json index b39503c..4139f84 100644 --- a/examples/sdk-component/api/package-lock.json +++ b/examples/sdk-component/api/package-lock.json @@ -20,6 +20,9 @@ "name": "@spinframework/sandbox", "version": "0.1.0", "license": "Apache-2.0", + "dependencies": { + "zod": "^4.6.7" + }, "devDependencies": { "typescript": "^5.6.0" } diff --git a/sdk/README.md b/sdk/README.md index d6cc111..9052c54 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -31,16 +31,126 @@ or validation failures. ## Agent tools -`interpreterTool()` returns context for the languages served by one interpreter endpoint. -Adapt it to Anthropic or OpenAI tool shapes with `toAnthropicTool()` or `toOpenAITool()`. +`interpreterTool()` returns `{ name, description, inputSchema }` for the languages served +by one interpreter endpoint. `inputSchema` is a strict [Zod](https://zod.dev) schema, which +is the single source of truth: frameworks that take Zod (such as the Vercel AI SDK) use it +directly, and the Anthropic and OpenAI adapters derive JSON Schema from it. + +Every agent setup has the same three parts: the `Interpreter` clients, the tool, and an +`execute` function where the developer sets execution policy. + +```ts +import { Interpreter } from "@spinframework/sandbox/interpreter"; +import { interpreterTool, type InterpreterToolInput } from "@spinframework/sandbox/tools"; + +// One client per private sandbox component. +const interpreters = { + javascript: Interpreter.javascript({ baseUrl: "http://ts-sandbox.spin.internal" }), + python: Interpreter.python({ baseUrl: "http://py-sandbox.spin.internal" }), +}; + +// A Zod-backed tool, limited to the languages you serve. +export const sandboxTool = interpreterTool({ languages: ["javascript", "python"] }); + +// Agent system prompt. Keep the floating-promise rule: un-awaited work is discarded silently. +export const SYSTEM_PROMPT = + "Write code and run it in the sandbox; never compute by hand. Print results to stdout. " + + "In JavaScript, await all asynchronous work: never leave floating promises (an un-awaited " + + "async call, IIFE, or timer), because work still running when the program ends is discarded."; + +// The developer sets execution policy; model arguments never reach these options. +export async function runSandbox(args: InterpreterToolInput, sessionId: string): Promise { + const opts = { + allowedHosts: ["https://api.example.com"], + kvEnabled: true, + identity: sessionId, + packageJson: args.language === "javascript" && args.dependencies ? { dependencies: args.dependencies } : undefined, + }; + const runner = interpreters[args.language]; + if (args.input) { + const res = await runner.runHandler(args.code, args.input, opts); + return `HTTP ${res.status}\n${await res.text()}`; + } + const r = await runner.execute(args.code, opts); + return r.error ? `${r.stdout}\n${r.stderr}\nerror: ${r.error.name}: ${r.error.value}` : r.stdout; +} +``` + +The input type narrows to the configured languages: with `languages: ["python"]`, `language` +is `"python"` and `dependencies` does not exist, matching the schema. + +The model supplies `language`, `code`, optional HTTP `input`, and JavaScript `dependencies`. The developer sets `allowedHosts`, `kvEnabled`, and `identity` in execution options. Validate tool arguments with `inputSchema.safeParse(args)`. The schema is strict, so it rejects unknown fields such as `allowedHosts`. Never spread model arguments into those options. Keep sandbox endpoints private. + +### Vercel AI SDK + +Pass the Zod schema as-is. The AI SDK validates the model's arguments with it, and `execute` +receives them typed. + +```ts +import { ToolLoopAgent, tool, stepCountIs } from "ai"; +import { anthropic } from "@ai-sdk/anthropic"; + +const sessionId = crypto.randomUUID(); +const agent = new ToolLoopAgent({ + model: anthropic("claude-sonnet-5-5"), + instructions: SYSTEM_PROMPT, + tools: { + [sandboxTool.name]: tool({ + description: sandboxTool.description, + inputSchema: sandboxTool.inputSchema, + execute: (args) => runSandbox(args, sessionId), + }), + }, + stopWhen: stepCountIs(10), +}); + +const { text } = await agent.generate({ prompt: "What is the 50th Fibonacci number?" }); +``` + +### Anthropic SDK + +`toAnthropicTool()` derives the JSON Schema from the Zod schema. Validate each `tool_use` +with the same Zod schema before running it. ```ts -import { interpreterTool, toAnthropicTool } from "@spinframework/sandbox/tools"; +import Anthropic from "@anthropic-ai/sdk"; +import { toAnthropicTool } from "@spinframework/sandbox/tools"; -const tools = [toAnthropicTool(interpreterTool({ languages: ["javascript"] }))]; +const client = new Anthropic(); +const sessionId = crypto.randomUUID(); +const tools = [toAnthropicTool(sandboxTool)]; +const messages: Anthropic.MessageParam[] = [{ role: "user", content: "What is the 50th Fibonacci number?" }]; + +for (let step = 0; step < 10; step++) { + const res = await client.messages.create({ + model: "claude-sonnet-5-5", + max_tokens: 4096, + system: SYSTEM_PROMPT, + tools, + messages, + }); + messages.push({ role: "assistant", content: res.content }); + if (res.stop_reason !== "tool_use") break; + + const results: Anthropic.ToolResultBlockParam[] = []; + for (const block of res.content) { + if (block.type !== "tool_use") continue; + const parsed = sandboxTool.inputSchema.safeParse(block.input); // rejects allowedHosts and other unknown fields + results.push( + parsed.success + ? { type: "tool_result", tool_use_id: block.id, content: await runSandbox(parsed.data, sessionId) } + : { type: "tool_result", tool_use_id: block.id, content: parsed.error.message, is_error: true }, + ); + } + messages.push({ role: "user", content: results }); +} ``` -The model supplies `language`, `code`, optional HTTP `input`, and JavaScript `dependencies`. The developer sets `allowedHosts`, `kvEnabled`, and `identity` in execution options. Validate tool arguments, reject unknown fields, and never spread model arguments into those options. Keep sandbox endpoints private. +### OpenAI and plain JSON Schema + +`toOpenAITool(sandboxTool)` returns OpenAI's function-tool shape, and `toToolDefinition()` +returns the provider-neutral JSON Schema form. The adapters also accept a hand-written +`ToolDefinition` with a JSON Schema `inputSchema`. ### Identity and session isolation diff --git a/sdk/package-lock.json b/sdk/package-lock.json index 3fba78d..825ba59 100644 --- a/sdk/package-lock.json +++ b/sdk/package-lock.json @@ -8,6 +8,9 @@ "name": "@spinframework/sandbox", "version": "0.1.0", "license": "Apache-2.0", + "dependencies": { + "zod": "^4.6.7" + }, "devDependencies": { "typescript": "^5.6.0" } @@ -25,6 +28,15 @@ "engines": { "node": ">=14.17" } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/sdk/package.json b/sdk/package.json index f44bbc7..1822f90 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -30,5 +30,8 @@ ], "devDependencies": { "typescript": "^5.6.0" + }, + "dependencies": { + "zod": "^4.6.7" } } diff --git a/sdk/src/index.ts b/sdk/src/index.ts index 68e78a3..0e90507 100644 --- a/sdk/src/index.ts +++ b/sdk/src/index.ts @@ -15,4 +15,15 @@ export * from "./core/index.ts"; export { Interpreter, InterpreterKV, type BoundRunOpts, type InterpreterOptions } from "./interpreter/index.ts"; export { KvCodeStore, serveStoredCode, type KvCodeStoreOptions } from "./store/index.ts"; -export { interpreterTool, toAnthropicTool, toOpenAITool, type InterpreterToolOptions, type ToolDefinition } from "./tools.ts"; +export { + interpreterTool, + toAnthropicTool, + toOpenAITool, + toToolDefinition, + type AnyTool, + type InterpreterToolInput, + type InterpreterToolOptions, + type JsonSchemaObject, + type StructuredTool, + type ToolDefinition, +} from "./tools.ts"; diff --git a/sdk/src/tools.ts b/sdk/src/tools.ts index 6cdb788..ee661b8 100644 --- a/sdk/src/tools.ts +++ b/sdk/src/tools.ts @@ -1,43 +1,87 @@ -import type { Language } from "./core/index.ts"; +import * as z from "zod"; +import type { HttpInput, Language } from "./core/index.ts"; + +/** + * A tool whose input is described by a Zod schema. This is the shape the SDK returns by + * default: `{ description, inputSchema }` is what the Vercel AI SDK's `tool()` expects, and + * `inputSchema.safeParse(args)` validates model-supplied arguments before they are used. + * Convert it with `toAnthropicTool()`, `toOpenAITool()`, or `toToolDefinition()` for + * providers that take JSON Schema. + */ +export interface StructuredTool { + name: string; + description: string; + inputSchema: z.ZodType; +} + +/** A JSON Schema object describing tool arguments, as Anthropic and OpenAI accept it. */ +export interface JsonSchemaObject { + type: "object"; + properties: Record; + required?: string[]; + additionalProperties?: boolean; + [keyword: string]: unknown; +} + +/** Provider-neutral tool metadata with a plain JSON Schema for its input. */ export interface ToolDefinition { name: string; description: string; - inputSchema: { - type: "object"; - properties: Record; - required: string[]; - additionalProperties?: boolean; - }; + inputSchema: JsonSchemaObject; } -export interface InterpreterToolOptions { +/** Either kind of tool the adapters accept. */ +export type AnyTool = StructuredTool | ToolDefinition; + +/** + * Arguments the model supplies to `run_in_wasm_interpreter`, narrowed to the configured + * languages: `dependencies` exists only when JavaScript is served, matching the schema. + */ +export type InterpreterToolInput = { + language: L; + code: string; + input?: HttpInput; +} & ("javascript" extends L + ? { + /** JavaScript only: extra npm dependencies as name -> semver range. */ + dependencies?: Record; + } + : {}); + +export interface InterpreterToolOptions { /** Languages served by this interpreter. Defaults to both sandbox languages. */ - languages?: readonly Language[]; + languages?: readonly L[]; } -const DEPENDENCIES = { - type: "object", - description: - "JavaScript only. Extra npm dependencies as name -> semver ranges. Use ESM import; Python cannot add packages.", - additionalProperties: { type: "string" }, -}; -const HTTP_INPUT = { - type: "object", - description: +const stringMap = () => z.record(z.string(), z.string()); + +const HTTP_INPUT = z + .object({ + method: z.string().optional().describe("HTTP method; defaults to GET."), + path: z.string().optional().describe("Request path; defaults to /."), + headers: stringMap().optional(), + query: stringMap().optional(), + body: z.unknown().optional().describe("Request body as a string or JSON value."), + }) + .describe( "Mock HTTP request for handler code. Supplying it runs a JavaScript `export default { fetch(request) {} }` or Python `handle_request(request)` handler and returns its HTTP response.", - properties: { - method: { type: "string", description: "HTTP method; defaults to GET." }, - path: { type: "string", description: "Request path; defaults to /." }, - headers: { type: "object", additionalProperties: { type: "string" } }, - query: { type: "object", additionalProperties: { type: "string" } }, - body: { description: "Request body as a string or JSON value." }, - }, -}; + ); + +const DEPENDENCIES = stringMap().describe( + "JavaScript only. Extra npm dependencies as name -> semver ranges. Use ESM import; Python cannot add packages.", +); -/** Returns tool metadata for the languages served by one interpreter endpoint. */ -export function interpreterTool(options: InterpreterToolOptions = {}): ToolDefinition { - const languages = options.languages ?? ["python", "javascript"]; +/** + * Returns the `run_in_wasm_interpreter` tool for the languages served by one interpreter + * endpoint. Its `inputSchema` is a strict Zod object: unknown fields (such as + * `allowedHosts`, `kvEnabled`, or `identity`) are rejected, so execution policy stays with + * the application. + */ +export function interpreterTool( + options: InterpreterToolOptions = {}, +): StructuredTool> { + const languages: readonly Language[] = options.languages ?? ["python", "javascript"]; if (languages.length === 0) throw new Error("interpreterTool requires at least one language"); const supportsJavaScript = languages.includes("javascript"); const supportsPython = languages.includes("python"); @@ -73,6 +117,12 @@ export function interpreterTool(options: InterpreterToolOptions = {}): ToolDefin const codeDescription = supportsJavaScript ? "The complete program to run. Print results to stdout. JavaScript supports top-level await: await all asynchronous work directly. Never leave floating promises (an un-awaited async IIFE, main() call, or timer); work still running when the program ends is discarded without any output or error." : "The complete program to run. Print results to stdout."; + const inputSchema = z.strictObject({ + language: z.enum(languages as [Language, ...Language[]]), + code: z.string().describe(codeDescription), + ...(supportsJavaScript ? { dependencies: DEPENDENCIES.optional() } : {}), + input: HTTP_INPUT.optional(), + }) as unknown as z.ZodType>; return { name: "run_in_wasm_interpreter", description: @@ -87,29 +137,48 @@ export function interpreterTool(options: InterpreterToolOptions = {}): ToolDefin `${libraryContext} ` + "Each run is a fresh instance: variables and globals do not carry over. When storage is enabled, persist state in the key-value store. " + "There is no filesystem, shell, subprocess, or raw socket, and no runtime pip install. stdout and stderr are each capped at 256 KB.", - inputSchema: { - type: "object", - properties: { - language: { type: "string", enum: languages }, - code: { type: "string", description: codeDescription }, - ...(supportsJavaScript ? { dependencies: DEPENDENCIES } : {}), - input: HTTP_INPUT, - }, - required: ["language", "code"], - additionalProperties: false, + inputSchema, + }; +} + +function isStructured(tool: AnyTool): tool is StructuredTool { + // Duck-typed instead of `instanceof` so schemas from another copy of zod v4 still work. + return typeof tool.inputSchema === "object" && tool.inputSchema !== null && "_zod" in tool.inputSchema; +} + +/** Returns the tool with a plain JSON Schema input, converting a Zod schema if needed. */ +export function toToolDefinition(tool: AnyTool): ToolDefinition { + if (!isStructured(tool)) return tool; + const { $schema: _, ...schema } = z.toJSONSchema(tool.inputSchema, { + io: "input", + // Zod emits `propertyNames: { type: "string" }` for string-keyed records. It is redundant + // (JSON object keys are always strings) and OpenAI's strict mode rejects the keyword. + override: ({ jsonSchema }) => { + const names = jsonSchema.propertyNames; + if (names && typeof names === "object" && names.type === "string" && Object.keys(names).length === 1) { + delete jsonSchema.propertyNames; + } }, + }); + if (schema.type !== "object") throw new Error(`tool ${tool.name} must take an object input`); + return { + name: tool.name, + description: tool.description, + inputSchema: { properties: {}, ...schema } as JsonSchemaObject, }; } -/** Adapts provider-neutral metadata to Anthropic's tool shape. */ -export function toAnthropicTool(tool: ToolDefinition) { - return { name: tool.name, description: tool.description, input_schema: tool.inputSchema }; +/** Adapts a tool to Anthropic's tool shape. */ +export function toAnthropicTool(tool: AnyTool) { + const { name, description, inputSchema } = toToolDefinition(tool); + return { name, description, input_schema: inputSchema }; } -/** Adapts provider-neutral metadata to OpenAI's function-tool shape. */ -export function toOpenAITool(tool: ToolDefinition) { +/** Adapts a tool to OpenAI's function-tool shape. */ +export function toOpenAITool(tool: AnyTool) { + const { name, description, inputSchema } = toToolDefinition(tool); return { type: "function" as const, - function: { name: tool.name, description: tool.description, parameters: tool.inputSchema }, + function: { name, description, parameters: inputSchema }, }; -} \ No newline at end of file +} diff --git a/sdk/test/fixtures/interpreter-tool.json b/sdk/test/fixtures/interpreter-tool.json new file mode 100644 index 0000000..d24c6df --- /dev/null +++ b/sdk/test/fixtures/interpreter-tool.json @@ -0,0 +1,237 @@ +{ + "default": { + "name": "run_in_wasm_interpreter", + "description": "Run python or javascript code in an isolated WebAssembly sandbox and get back its stdout, stderr, and error. Beyond computation, parsing, and data work, code can call external HTTP APIs, keep data across runs, and serve HTTP requests. Outbound HTTP is denied unless the application permits the destination. JavaScript uses the standard `fetch`. If the destination is not allowed, fetch rejects; the runtime may report the generic error \"An error occurred while using the host API\". Python uses `from spin_sdk.http import send, Request` and `send(Request(method, url, headers, body))`; urllib, http.client, and requests are not available. If the destination is not allowed, the guard returns HttpRequestDenied, surfaced as `Err(ErrorCode_HttpRequestDenied())`. Network permissions are configured by the application and cannot be changed through tool arguments. Persistent storage is available only when enabled by the application, which also controls the storage namespace. Runs in the same namespace share stored KV data, whether they use the same language or different languages. Sharing depends on the namespace, not on reusing an Interpreter client object; different namespaces are isolated. JavaScript: `import { openDefault } from \"@spinframework/spin-kv\"`, then get/set or getJson/setJson. Python: `from spin_sdk import key_value`, then `key_value.open_default()` with get/set (values are bytes). HTTP handlers: supply input to run a handler against that request and get its HTTP response. JavaScript exports `default { async fetch(request) {} }`, awaiting all async work before it returns the Response; Python defines `handle_request(request)` and may return an iterable of str or bytes chunks to stream the body. Python includes numpy, pydantic, pyyaml, regex, beautifulsoup4, jinja2, markdown, tabulate, sqlalchemy, tiktoken (no built-in encodings: get_encoding() fails, so pass your own mergeable_ranks to tiktoken.Encoding), and the standard library except its networking modules. JavaScript (TypeScript syntax is accepted) includes lodash, zod, date-fns, dayjs, cheerio, node-html-parser, js-yaml, uuid, ulidx, and nanoid. For other npm packages, list them in dependencies as name -> semver ranges; they are bundled before the run. Use ESM import, never require(). Each run is a fresh instance: variables and globals do not carry over. When storage is enabled, persist state in the key-value store. There is no filesystem, shell, subprocess, or raw socket, and no runtime pip install. stdout and stderr are each capped at 256 KB.", + "inputSchema": { + "type": "object", + "properties": { + "language": { + "type": "string", + "enum": [ + "python", + "javascript" + ] + }, + "code": { + "type": "string", + "description": "The complete program to run. Print results to stdout. JavaScript supports top-level await: await all asynchronous work directly. Never leave floating promises (an un-awaited async IIFE, main() call, or timer); work still running when the program ends is discarded without any output or error." + }, + "dependencies": { + "type": "object", + "description": "JavaScript only. Extra npm dependencies as name -> semver ranges. Use ESM import; Python cannot add packages.", + "additionalProperties": { + "type": "string" + } + }, + "input": { + "type": "object", + "description": "Mock HTTP request for handler code. Supplying it runs a JavaScript `export default { fetch(request) {} }` or Python `handle_request(request)` handler and returns its HTTP response.", + "properties": { + "method": { + "type": "string", + "description": "HTTP method; defaults to GET." + }, + "path": { + "type": "string", + "description": "Request path; defaults to /." + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "query": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "description": "Request body as a string or JSON value." + } + } + } + }, + "required": [ + "language", + "code" + ], + "additionalProperties": false + } + }, + "python": { + "name": "run_in_wasm_interpreter", + "description": "Run python code in an isolated WebAssembly sandbox and get back its stdout, stderr, and error. Beyond computation, parsing, and data work, code can call external HTTP APIs, keep data across runs, and serve HTTP requests. Outbound HTTP is denied unless the application permits the destination. Python uses `from spin_sdk.http import send, Request` and `send(Request(method, url, headers, body))`; urllib, http.client, and requests are not available. If the destination is not allowed, the guard returns HttpRequestDenied, surfaced as `Err(ErrorCode_HttpRequestDenied())`. Network permissions are configured by the application and cannot be changed through tool arguments. Persistent storage is available only when enabled by the application, which also controls the storage namespace. Runs in the same namespace share stored KV data, whether they use the same language or different languages. Sharing depends on the namespace, not on reusing an Interpreter client object; different namespaces are isolated. Python: `from spin_sdk import key_value`, then `key_value.open_default()` with get/set (values are bytes). HTTP handlers: supply input to run a handler against that request and get its HTTP response. JavaScript exports `default { async fetch(request) {} }`, awaiting all async work before it returns the Response; Python defines `handle_request(request)` and may return an iterable of str or bytes chunks to stream the body. Python includes numpy, pydantic, pyyaml, regex, beautifulsoup4, jinja2, markdown, tabulate, sqlalchemy, tiktoken (no built-in encodings: get_encoding() fails, so pass your own mergeable_ranks to tiktoken.Encoding), and the standard library except its networking modules. Each run is a fresh instance: variables and globals do not carry over. When storage is enabled, persist state in the key-value store. There is no filesystem, shell, subprocess, or raw socket, and no runtime pip install. stdout and stderr are each capped at 256 KB.", + "inputSchema": { + "type": "object", + "properties": { + "language": { + "type": "string", + "enum": [ + "python" + ] + }, + "code": { + "type": "string", + "description": "The complete program to run. Print results to stdout." + }, + "input": { + "type": "object", + "description": "Mock HTTP request for handler code. Supplying it runs a JavaScript `export default { fetch(request) {} }` or Python `handle_request(request)` handler and returns its HTTP response.", + "properties": { + "method": { + "type": "string", + "description": "HTTP method; defaults to GET." + }, + "path": { + "type": "string", + "description": "Request path; defaults to /." + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "query": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "description": "Request body as a string or JSON value." + } + } + } + }, + "required": [ + "language", + "code" + ], + "additionalProperties": false + } + }, + "javascript": { + "name": "run_in_wasm_interpreter", + "description": "Run javascript code in an isolated WebAssembly sandbox and get back its stdout, stderr, and error. Beyond computation, parsing, and data work, code can call external HTTP APIs, keep data across runs, and serve HTTP requests. Outbound HTTP is denied unless the application permits the destination. JavaScript uses the standard `fetch`. If the destination is not allowed, fetch rejects; the runtime may report the generic error \"An error occurred while using the host API\". Network permissions are configured by the application and cannot be changed through tool arguments. Persistent storage is available only when enabled by the application, which also controls the storage namespace. Runs in the same namespace share stored KV data, whether they use the same language or different languages. Sharing depends on the namespace, not on reusing an Interpreter client object; different namespaces are isolated. JavaScript: `import { openDefault } from \"@spinframework/spin-kv\"`, then get/set or getJson/setJson. HTTP handlers: supply input to run a handler against that request and get its HTTP response. JavaScript exports `default { async fetch(request) {} }`, awaiting all async work before it returns the Response; Python defines `handle_request(request)` and may return an iterable of str or bytes chunks to stream the body. JavaScript (TypeScript syntax is accepted) includes lodash, zod, date-fns, dayjs, cheerio, node-html-parser, js-yaml, uuid, ulidx, and nanoid. For other npm packages, list them in dependencies as name -> semver ranges; they are bundled before the run. Use ESM import, never require(). Each run is a fresh instance: variables and globals do not carry over. When storage is enabled, persist state in the key-value store. There is no filesystem, shell, subprocess, or raw socket, and no runtime pip install. stdout and stderr are each capped at 256 KB.", + "inputSchema": { + "type": "object", + "properties": { + "language": { + "type": "string", + "enum": [ + "javascript" + ] + }, + "code": { + "type": "string", + "description": "The complete program to run. Print results to stdout. JavaScript supports top-level await: await all asynchronous work directly. Never leave floating promises (an un-awaited async IIFE, main() call, or timer); work still running when the program ends is discarded without any output or error." + }, + "dependencies": { + "type": "object", + "description": "JavaScript only. Extra npm dependencies as name -> semver ranges. Use ESM import; Python cannot add packages.", + "additionalProperties": { + "type": "string" + } + }, + "input": { + "type": "object", + "description": "Mock HTTP request for handler code. Supplying it runs a JavaScript `export default { fetch(request) {} }` or Python `handle_request(request)` handler and returns its HTTP response.", + "properties": { + "method": { + "type": "string", + "description": "HTTP method; defaults to GET." + }, + "path": { + "type": "string", + "description": "Request path; defaults to /." + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "query": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "description": "Request body as a string or JSON value." + } + } + } + }, + "required": [ + "language", + "code" + ], + "additionalProperties": false + } + }, + "javascript,python": { + "name": "run_in_wasm_interpreter", + "description": "Run javascript or python code in an isolated WebAssembly sandbox and get back its stdout, stderr, and error. Beyond computation, parsing, and data work, code can call external HTTP APIs, keep data across runs, and serve HTTP requests. Outbound HTTP is denied unless the application permits the destination. JavaScript uses the standard `fetch`. If the destination is not allowed, fetch rejects; the runtime may report the generic error \"An error occurred while using the host API\". Python uses `from spin_sdk.http import send, Request` and `send(Request(method, url, headers, body))`; urllib, http.client, and requests are not available. If the destination is not allowed, the guard returns HttpRequestDenied, surfaced as `Err(ErrorCode_HttpRequestDenied())`. Network permissions are configured by the application and cannot be changed through tool arguments. Persistent storage is available only when enabled by the application, which also controls the storage namespace. Runs in the same namespace share stored KV data, whether they use the same language or different languages. Sharing depends on the namespace, not on reusing an Interpreter client object; different namespaces are isolated. JavaScript: `import { openDefault } from \"@spinframework/spin-kv\"`, then get/set or getJson/setJson. Python: `from spin_sdk import key_value`, then `key_value.open_default()` with get/set (values are bytes). HTTP handlers: supply input to run a handler against that request and get its HTTP response. JavaScript exports `default { async fetch(request) {} }`, awaiting all async work before it returns the Response; Python defines `handle_request(request)` and may return an iterable of str or bytes chunks to stream the body. Python includes numpy, pydantic, pyyaml, regex, beautifulsoup4, jinja2, markdown, tabulate, sqlalchemy, tiktoken (no built-in encodings: get_encoding() fails, so pass your own mergeable_ranks to tiktoken.Encoding), and the standard library except its networking modules. JavaScript (TypeScript syntax is accepted) includes lodash, zod, date-fns, dayjs, cheerio, node-html-parser, js-yaml, uuid, ulidx, and nanoid. For other npm packages, list them in dependencies as name -> semver ranges; they are bundled before the run. Use ESM import, never require(). Each run is a fresh instance: variables and globals do not carry over. When storage is enabled, persist state in the key-value store. There is no filesystem, shell, subprocess, or raw socket, and no runtime pip install. stdout and stderr are each capped at 256 KB.", + "inputSchema": { + "type": "object", + "properties": { + "language": { + "type": "string", + "enum": [ + "javascript", + "python" + ] + }, + "code": { + "type": "string", + "description": "The complete program to run. Print results to stdout. JavaScript supports top-level await: await all asynchronous work directly. Never leave floating promises (an un-awaited async IIFE, main() call, or timer); work still running when the program ends is discarded without any output or error." + }, + "dependencies": { + "type": "object", + "description": "JavaScript only. Extra npm dependencies as name -> semver ranges. Use ESM import; Python cannot add packages.", + "additionalProperties": { + "type": "string" + } + }, + "input": { + "type": "object", + "description": "Mock HTTP request for handler code. Supplying it runs a JavaScript `export default { fetch(request) {} }` or Python `handle_request(request)` handler and returns its HTTP response.", + "properties": { + "method": { + "type": "string", + "description": "HTTP method; defaults to GET." + }, + "path": { + "type": "string", + "description": "Request path; defaults to /." + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "query": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "body": { + "description": "Request body as a string or JSON value." + } + } + } + }, + "required": [ + "language", + "code" + ], + "additionalProperties": false + } + } +} diff --git a/sdk/test/tools.test.ts b/sdk/test/tools.test.ts index e9602b6..60794c4 100644 --- a/sdk/test/tools.test.ts +++ b/sdk/test/tools.test.ts @@ -1,10 +1,12 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { interpreterTool, toAnthropicTool, toOpenAITool } from "../src/tools.ts"; +import { interpreterTool, toAnthropicTool, toOpenAITool, toToolDefinition, type ToolDefinition } from "../src/tools.ts"; + +const jsonTool = (options?: Parameters[0]) => toToolDefinition(interpreterTool(options)); test("interpreterTool scopes its schema to the configured language", () => { - const tool = interpreterTool({ languages: ["python"] }); + const tool = jsonTool({ languages: ["python"] }); assert.equal(tool.name, "run_in_wasm_interpreter"); assert.deepEqual(tool.inputSchema.properties.language, { type: "string", enum: ["python"] }); assert.equal("dependencies" in tool.inputSchema.properties, false); @@ -14,7 +16,7 @@ test("interpreterTool scopes its schema to the configured language", () => { test("interpreterTool leaves execution policy to the application", () => { for (const languages of [undefined, ["python"] as const, ["javascript"] as const]) { - const tool = interpreterTool({ languages }); + const tool = jsonTool({ languages }); for (const field of ["allowedHosts", "kvEnabled", "identity"]) { assert.equal(field in tool.inputSchema.properties, false); assert.equal(tool.description.includes(field), false); @@ -25,8 +27,37 @@ test("interpreterTool leaves execution policy to the application", () => { } }); +test("the Zod schema rejects policy fields and unknown arguments", () => { + const { inputSchema } = interpreterTool(); + for (const field of ["allowedHosts", "kvEnabled", "identity", "extra"]) { + const result = inputSchema.safeParse({ language: "python", code: "print(1)", [field]: true }); + assert.equal(result.success, false, field); + } +}); + +test("the Zod schema validates and types model arguments", () => { + const { inputSchema } = interpreterTool(); + const args = { + language: "javascript", + code: "console.log(1)", + dependencies: { marked: "^11.0.0" }, + input: { method: "POST", path: "/x", body: { a: 1 } }, + }; + assert.deepEqual(inputSchema.parse(args), args); + assert.equal(inputSchema.safeParse({ language: "ruby", code: "puts 1" }).success, false); + assert.equal(inputSchema.safeParse({ language: "python" }).success, false); + assert.equal(inputSchema.safeParse({ language: "python", code: 1 }).success, false); + assert.equal(inputSchema.safeParse({ language: "javascript", code: "", dependencies: { x: 1 } }).success, false); +}); + +test("Python-only tools reject JavaScript-only arguments", () => { + const { inputSchema } = interpreterTool({ languages: ["python"] }); + assert.equal(inputSchema.safeParse({ language: "javascript", code: "1" }).success, false); + assert.equal(inputSchema.safeParse({ language: "python", code: "1", dependencies: {} }).success, false); +}); + test("JavaScript tools retain program inputs and asynchronous execution guidance", () => { - const tool = interpreterTool({ languages: ["javascript"] }); + const tool = jsonTool({ languages: ["javascript"] }); assert.deepEqual(Object.keys(tool.inputSchema.properties), ["language", "code", "dependencies", "input"]); assert.match(JSON.stringify(tool.inputSchema.properties.code), /Never leave floating promises/); }); @@ -49,11 +80,41 @@ test("HTTP guidance explains denied destinations using the runtime's actual erro assert.match(javascript.description, /runtime may report the generic error/); }); +test("the derived JSON Schema carries no $schema keyword", () => { + assert.equal("$schema" in jsonTool().inputSchema, false); +}); + test("tool adapters support Anthropic and OpenAI shapes", () => { const tool = interpreterTool({ languages: ["javascript"] }); - assert.deepEqual(toAnthropicTool(tool).input_schema, tool.inputSchema); + const json = toToolDefinition(tool); + assert.deepEqual(toAnthropicTool(tool), { name: json.name, description: json.description, input_schema: json.inputSchema }); assert.deepEqual(toOpenAITool(tool), { type: "function", - function: { name: tool.name, description: tool.description, parameters: tool.inputSchema }, + function: { name: json.name, description: json.description, parameters: json.inputSchema }, }); -}); \ No newline at end of file +}); + +test("tool adapters pass hand-written JSON Schema tools through unchanged", () => { + const custom: ToolDefinition = { + name: "create_app", + description: "Publish an app.", + inputSchema: { type: "object", properties: { code: { type: "string" } }, required: ["code"], additionalProperties: false }, + }; + assert.equal(toToolDefinition(custom), custom); + assert.equal(toAnthropicTool(custom).input_schema, custom.inputSchema); + assert.equal(toOpenAITool(custom).function.parameters, custom.inputSchema); +}); + +test("the derived JSON Schema and description match the pre-Zod hand-written output", async () => { + // Captured from the JSON Schema version of tools.ts. Any drift in what the model sees fails here. + const { default: golden } = await import("./fixtures/interpreter-tool.json", { with: { type: "json" } }); + const configs = { + default: undefined, + python: { languages: ["python"] }, + javascript: { languages: ["javascript"] }, + "javascript,python": { languages: ["javascript", "python"] }, + } as const; + for (const [key, options] of Object.entries(configs)) { + assert.deepStrictEqual(jsonTool(options), (golden as Record)[key], key); + } +}); diff --git a/sdk/test/types.assert.ts b/sdk/test/types.assert.ts index 388affc..e63df27 100644 --- a/sdk/test/types.assert.ts +++ b/sdk/test/types.assert.ts @@ -32,3 +32,23 @@ itp.exec(["echo", "hi"]); // But the interpreter DOES have its scoped-KV power surface. void itp.kv("ns"); + +// The tool's input type narrows to the configured languages, like its schema. +import { interpreterTool, type InterpreterToolInput } from "../src/tools.ts"; +import type * as z from "zod"; +type InputOf = T extends { inputSchema: z.ZodType } ? I : never; +type PyInput = InputOf>>; +declare const py: PyInput; +const pyLang: "python" = py.language; +void pyLang; +// @ts-expect-error a Python-only tool has no dependencies argument +void py.dependencies; +const pyTool = interpreterTool({ languages: ["python"] }); +const parsedPy = pyTool.inputSchema.parse({}); +// @ts-expect-error language is inferred as "python" from the options literal +const notJs: "javascript" = parsedPy.language; +void notJs; +declare const both: InterpreterToolInput; +void both.dependencies; +const lang: "python" | "javascript" = interpreterTool().inputSchema.parse({}).language; +void lang;