diff --git a/README.md b/README.md index ec79626..6ba9422 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Run untrusted JavaScript/TypeScript and Python in isolated WebAssembly components on [Spin](https://spinframework.dev). This repository includes the sandboxes, an npm -[bundler](packages/typescript/bundler), the [`@spinframework/sandbox`](sdk) client, +[bundler](packages/typescript/bundler), the [`@spinframework/spin-code-sandbox`](sdk) client, and [examples](examples). ## What this repository contains @@ -142,7 +142,7 @@ store.setJson("k", { v: 1 }); store.getJson("k"); ## Deployment model In production, run sandboxes as private components and reach them through Spin service -chaining or the [`@spinframework/sandbox`](sdk) client library. The +chaining or the [`@spinframework/spin-code-sandbox`](sdk) client library. The [AI code executor](examples/ai-code-executor) shows the complete wiring. Sandbox endpoints do not authenticate callers: any component allowed to reach a private route can choose an ID and policy. Grant access only to trusted callers, or authenticate public routes. The application must map requests to sandbox IDs and set `allowedHosts` and `kvEnabled` itself; never accept these from model output or unchecked users. diff --git a/examples/ai-code-executor/AGENTS.md b/examples/ai-code-executor/AGENTS.md index 7a4ed30..78354f2 100644 --- a/examples/ai-code-executor/AGENTS.md +++ b/examples/ai-code-executor/AGENTS.md @@ -10,7 +10,7 @@ Five components; only `ui` and `api` have public routes. - **`api/`** (public `/api/...`): a Hono component (TypeScript to Wasm via esbuild + `j2w`). It runs the agent loop in [`api/src/index.ts`](api/src/index.ts): one tool (`run_in_wasm_interpreter`), the system prompt, and the streaming NDJSON protocol. It - depends on the sandbox client [`@spinframework/sandbox`](../../sdk) (a local `file:` + depends on the sandbox client [`@spinframework/spin-code-sandbox`](../../sdk) (a local `file:` dependency in [`api/package.json`](api/package.json)) and holds one `Interpreter` per language, each pointed at a private interpreter component's `spin.internal` URL. - **`ui/`** (public `/...`): a Nuxt SPA served by the Spin static fileserver. Adapted diff --git a/examples/ai-code-executor/README.md b/examples/ai-code-executor/README.md index dc4e75e..49bffa9 100644 --- a/examples/ai-code-executor/README.md +++ b/examples/ai-code-executor/README.md @@ -2,7 +2,7 @@ A Spin application: an LLM (via the Anthropic Messages API by default, or the OpenAI Chat Completions API) writes code and runs it in the fast Wasm interpreter -through [`@spinframework/sandbox`](../../sdk), with the transcript streamed +through [`@spinframework/spin-code-sandbox`](../../sdk), with the transcript streamed back to a chat UI. ``` @@ -17,7 +17,7 @@ The two interpreters (`ts-sandbox`, `py-sandbox`) are private components of this (`route = { private = true }`), so they have no public route and are reachable only from the `api` component via local service chaining (`.spin.internal`). A private `bundler` component (experimental) packages any extra npm dependencies the model requests. The -API depends on the sandbox client from this repo ([`@spinframework/sandbox`](../../sdk), +API depends on the sandbox client from this repo ([`@spinframework/spin-code-sandbox`](../../sdk), a local `file:` dependency) and holds one `Interpreter` per language, each pointed at its component's internal URL. @@ -196,7 +196,7 @@ requests from other origins. Before deploying: ``` spin.toml wires 5 components: public ui + api, private ts-sandbox + py-sandbox + bundler api/ Hono component: the LLM tool-use loop + the interpreter tool - src/index.ts the agent; imports @spinframework/sandbox; one Interpreter client per component + src/index.ts the agent; imports @spinframework/spin-code-sandbox; one Interpreter client per component src/llm/ provider interface + Anthropic and OpenAI implementations (one bundled per build) ui/ Nuxt SPA chat (near-verbatim from upstream; one filesystem prompt swapped) pages/index.vue the chat UI diff --git a/examples/ai-code-executor/api/build.mjs b/examples/ai-code-executor/api/build.mjs index 743326e..ec98f33 100644 --- a/examples/ai-code-executor/api/build.mjs +++ b/examples/ai-code-executor/api/build.mjs @@ -50,5 +50,7 @@ await build({ '.tsx': 'tsx', }, resolveExtensions: ['.ts', '.tsx', '.js'], + // The SDK is linked from ../../../sdk; resolve its peer dependencies (zod) from this app. + nodePaths: [path.resolve('node_modules')], sourceRoot: path.resolve(process.cwd(), 'src'), }); diff --git a/examples/ai-code-executor/api/package-lock.json b/examples/ai-code-executor/api/package-lock.json index 2b12f47..e9ab0b5 100644 --- a/examples/ai-code-executor/api/package-lock.json +++ b/examples/ai-code-executor/api/package-lock.json @@ -10,11 +10,12 @@ "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { "@anthropic-ai/sdk": "^0.69.0", - "@spinframework/sandbox": "file:../../../sdk", + "@spinframework/spin-code-sandbox": "file:../../../sdk", "@spinframework/spin-variables": "^1.0.1", "@spinframework/wasi-http-proxy": "^2.0.0", - "hono": "^4.7.4", - "openai": "^7.30.0" + "hono": "^4.13.19", + "openai": "^7.30.0", + "zod": "^4.6.7" }, "devDependencies": { "esbuild": "^0.25.8", @@ -23,11 +24,20 @@ } }, "../../../sdk": { - "name": "@spinframework/sandbox", + "name": "@spinframework/spin-code-sandbox", "version": "0.1.0", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "devDependencies": { - "typescript": "^5.6.0" + "typescript": "^5.6.0", + "zod": "^4.6.7" + }, + "peerDependencies": { + "zod": "^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } } }, "node_modules/@ampproject/remapping": { @@ -2530,7 +2540,7 @@ "j2w": "dist/index.js" } }, - "node_modules/@spinframework/sandbox": { + "node_modules/@spinframework/spin-code-sandbox": { "resolved": "../../../sdk", "link": true }, @@ -3261,9 +3271,9 @@ } }, "node_modules/hono": { - "version": "4.13.13", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz", - "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==", + "version": "4.13.19", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.19.tgz", + "integrity": "sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA==", "license": "MIT", "engines": { "node": ">=16.9.0" @@ -3943,6 +3953,15 @@ "engines": { "node": "^20.19.0 || ^22.12.0 || >=23" } + }, + "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/examples/ai-code-executor/api/package.json b/examples/ai-code-executor/api/package.json index 3766c94..4e25f4f 100644 --- a/examples/ai-code-executor/api/package.json +++ b/examples/ai-code-executor/api/package.json @@ -19,11 +19,12 @@ }, "dependencies": { "@anthropic-ai/sdk": "^0.69.0", - "@spinframework/sandbox": "file:../../../sdk", + "@spinframework/spin-code-sandbox": "file:../../../sdk", "@spinframework/spin-variables": "^1.0.1", "@spinframework/wasi-http-proxy": "^2.0.0", - "hono": "^4.7.4", - "openai": "^7.30.0" + "hono": "^4.13.19", + "openai": "^7.30.0", + "zod": "^4.6.7" }, "overrides": { "@bytecodealliance/jco-std": { diff --git a/examples/ai-code-executor/api/src/index.ts b/examples/ai-code-executor/api/src/index.ts index a7e0afc..703868a 100644 --- a/examples/ai-code-executor/api/src/index.ts +++ b/examples/ai-code-executor/api/src/index.ts @@ -1,7 +1,7 @@ // AI Code Executor API, an LLM agent whose tool is a sandbox. // // The model is given one tool: it runs code in the fast Wasm interpreter. The -// model writes the code, we execute it through @spinframework/sandbox and feed +// model writes the code, we execute it through @spinframework/spin-code-sandbox and feed // the result back. The full transcript (reasoning + each tool call + output + // answer) is streamed to the UI. The LLM provider (Anthropic or OpenAI) is chosen // at build time; see build.mjs. @@ -13,14 +13,12 @@ import type { Context } from "hono"; 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 { Interpreter } from "@spinframework/spin-code-sandbox/interpreter"; +import { interpreterTool, toToolDefinition, type ExecutionPolicy } from "@spinframework/spin-code-sandbox/tools"; import { historyFor, type History, type ToolResult } from "./llm/types"; import { log, initLogger } from "./logger"; -const INTERPRETER_TOOL = interpreterTool(); -const EXECUTION_POLICY: Pick = { +const EXECUTION_POLICY: ExecutionPolicy = { allowedHosts: [], kvEnabled: false, }; @@ -58,14 +56,6 @@ function clip(s: string, n: number): string { return s.length > n ? s.slice(0, n) + "…" : s; } -function formatToolResult(stdout: string, stderr: string, error: string | null): string { - const parts: string[] = []; - if (stdout) parts.push("stdout:\n" + stdout); - if (stderr) parts.push("stderr:\n" + stderr); - if (error) parts.push("error: " + error); - return parts.join("\n\n") || "(no output)"; -} - // Runs the agentic loop, emitting each step as soon as it is available so the UI // can render turn by turn (the code the moment the model writes it, then the // output the moment the sandbox returns) instead of waiting for the whole @@ -77,13 +67,18 @@ async function runAgent(prompt: string, history: unknown, emit: Emit): Promise = { - javascript: Interpreter.javascript({ baseUrl: tsUrl, bundlerUrl }), - python: Interpreter.python({ baseUrl: pyUrl }), - }; + // The interpreter is two private, service-chained components, one per language; the tool + // routes each call by the language the model chose. The JS interpreter also knows the + // bundler, so model code can pull extra npm dependencies (the tool's `dependencies` field). + // The policy is the application's; the strict schema stops the model from setting it. + const sandbox = interpreterTool({ + interpreters: { + javascript: Interpreter.javascript({ baseUrl: tsUrl, bundlerUrl }), + python: Interpreter.python({ baseUrl: pyUrl }), + }, + policy: { ...EXECUTION_POLICY, identity: sandboxId }, + }); + const tools = [toToolDefinition(sandbox)]; log.info(`chat: provider=${llm.name} model=${llm.model} prompt=${JSON.stringify(clip(prompt, 80))}`); @@ -101,7 +96,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 +104,13 @@ 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 }); + // Invalid arguments (including any attempt to set policy) go back to the model, naming the field. + const parsed = sandbox.parse(call.input); + if (!parsed.ok) { + toolResults.push({ id: call.id, ...parsed.output }); continue; } + const input = parsed.args; const id = toolId++; // Stream the code, requested packages, and application-approved hosts before execution. @@ -137,41 +124,18 @@ async function runAgent(prompt: string, history: unknown, emit: Emit): Promise/`. See [README.md](README.md) for the full picture; this covers the layout and the invariants. @@ -12,7 +12,7 @@ Five components; only `ui` and `api` have public routes. - **`api/`**: a Hono component (TypeScript to Wasm via esbuild + `j2w`) bound to two HTTP triggers: `/api/...` (control plane) and `/a/...` (live apps). It runs the model loop (provider chosen at build time; see `src/llm/` and `build.mjs`), owns a - `KvCodeStore` (from `@spinframework/sandbox/store`), and serves + `KvCodeStore` (from `@spinframework/spin-code-sandbox/store`), and serves stored apps with `serveStoredCode` plus a presentation layer (`` injection, crash page, hardening headers). - **`ui/`** (public `/...`): a Nuxt SPA served by the Spin static fileserver: a gallery diff --git a/examples/app-builder/README.md b/examples/app-builder/README.md index 35f2b3f..4da575f 100644 --- a/examples/app-builder/README.md +++ b/examples/app-builder/README.md @@ -2,7 +2,7 @@ A Spin application: an LLM (via the Anthropic Messages API by default, or the OpenAI Chat Completions API) writes a self-contained web app (an HTTP handler serving an -HTML UI plus a JSON API), stores the code with [`@spinframework/sandbox`](../../sdk), +HTML UI plus a JSON API), stores the code with [`@spinframework/spin-code-sandbox`](../../sdk), and serves each stored app live at its own URL, executed on demand in a private Wasm sandbox. Click any app to keep editing it by chatting; each change updates it in place at the same URL. @@ -156,7 +156,7 @@ Before deploying: ``` spin.toml 5 components: public ui + api (two triggers), private ts-sandbox + py-sandbox + bundler api/ Hono component: the LLM loop, the code store, and the live-serve routes - src/index.ts imports @spinframework/sandbox/{interpreter,store} + src/index.ts imports @spinframework/spin-code-sandbox/{interpreter,store} src/llm/ provider interface + Anthropic and OpenAI implementations (one bundled per build) ui/ Nuxt SPA: build gallery + create flow pages/index.vue the gallery + "describe an app" UI diff --git a/examples/app-builder/api/package-lock.json b/examples/app-builder/api/package-lock.json index 2b12f47..495b56a 100644 --- a/examples/app-builder/api/package-lock.json +++ b/examples/app-builder/api/package-lock.json @@ -10,10 +10,10 @@ "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { "@anthropic-ai/sdk": "^0.69.0", - "@spinframework/sandbox": "file:../../../sdk", + "@spinframework/spin-code-sandbox": "file:../../../sdk", "@spinframework/spin-variables": "^1.0.1", "@spinframework/wasi-http-proxy": "^2.0.0", - "hono": "^4.7.4", + "hono": "^4.13.19", "openai": "^7.30.0" }, "devDependencies": { @@ -23,11 +23,20 @@ } }, "../../../sdk": { - "name": "@spinframework/sandbox", + "name": "@spinframework/spin-code-sandbox", "version": "0.1.0", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "devDependencies": { - "typescript": "^5.6.0" + "typescript": "^5.6.0", + "zod": "^4.6.7" + }, + "peerDependencies": { + "zod": "^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } } }, "node_modules/@ampproject/remapping": { @@ -2530,7 +2539,7 @@ "j2w": "dist/index.js" } }, - "node_modules/@spinframework/sandbox": { + "node_modules/@spinframework/spin-code-sandbox": { "resolved": "../../../sdk", "link": true }, @@ -3261,9 +3270,9 @@ } }, "node_modules/hono": { - "version": "4.13.13", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz", - "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==", + "version": "4.13.19", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.19.tgz", + "integrity": "sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA==", "license": "MIT", "engines": { "node": ">=16.9.0" diff --git a/examples/app-builder/api/package.json b/examples/app-builder/api/package.json index 84697f9..c896799 100644 --- a/examples/app-builder/api/package.json +++ b/examples/app-builder/api/package.json @@ -19,10 +19,10 @@ }, "dependencies": { "@anthropic-ai/sdk": "^0.69.0", - "@spinframework/sandbox": "file:../../../sdk", + "@spinframework/spin-code-sandbox": "file:../../../sdk", "@spinframework/spin-variables": "^1.0.1", "@spinframework/wasi-http-proxy": "^2.0.0", - "hono": "^4.7.4", + "hono": "^4.13.19", "openai": "^7.30.0" }, "overrides": { diff --git a/examples/app-builder/api/src/index.ts b/examples/app-builder/api/src/index.ts index 43278aa..a1effcd 100644 --- a/examples/app-builder/api/src/index.ts +++ b/examples/app-builder/api/src/index.ts @@ -1,5 +1,5 @@ // App Builder API: an LLM generates a self-contained HTTP-handler web app; we store it via -// @spinframework/sandbox and serve each stored app live at its own URL. The LLM provider +// @spinframework/spin-code-sandbox and serve each stored app live at its own URL. The LLM provider // (Anthropic or OpenAI) is chosen at build time; see build.mjs. // // Two surfaces on one component: @@ -21,10 +21,10 @@ import type { Context } from "hono"; import * as variables from "@spinframework/spin-variables"; import { createProvider } from "#llm-provider"; -import { Interpreter, type Language } from "@spinframework/sandbox/interpreter"; -import { KvCodeStore, serveStoredCode } from "@spinframework/sandbox/store"; -import type { RunOpts } from "@spinframework/sandbox/core"; -import type { ToolDefinition } from "@spinframework/sandbox/tools"; +import { Interpreter, type Language } from "@spinframework/spin-code-sandbox/interpreter"; +import { KvCodeStore, serveStoredCode } from "@spinframework/spin-code-sandbox/store"; +import type { RunOpts } from "@spinframework/spin-code-sandbox/core"; +import type { ToolDefinition } from "@spinframework/spin-code-sandbox/tools"; import { historyFor, type History, type ToolResult } from "./llm/types"; import { log, initLogger } from "./logger"; diff --git a/examples/app-builder/api/src/llm/types.ts b/examples/app-builder/api/src/llm/types.ts index 9a9980f..818e249 100644 --- a/examples/app-builder/api/src/llm/types.ts +++ b/examples/app-builder/api/src/llm/types.ts @@ -2,7 +2,7 @@ // build (see build.mjs): `src/llm/anthropic.ts` by default, `src/llm/openai.ts` for the // `openai` Spin build profile. -import type { ToolDefinition } from "@spinframework/sandbox/tools"; +import type { ToolDefinition } from "@spinframework/spin-code-sandbox/tools"; export type ProviderName = "anthropic" | "openai"; diff --git a/examples/app-builder/spin.toml b/examples/app-builder/spin.toml index c392afb..5baf58f 100644 --- a/examples/app-builder/spin.toml +++ b/examples/app-builder/spin.toml @@ -4,7 +4,7 @@ spin_manifest_version = 2 name = "app-builder" version = "0.1.0" authors = ["Spin Agent Sandbox"] -description = "App Builder: an LLM generates HTTP-handler web apps, stores them via @spinframework/sandbox, and serves each live at its own URL." +description = "App Builder: an LLM generates HTTP-handler web apps, stores them via @spinframework/spin-code-sandbox, and serves each live at its own URL." [variables] log_level = { default = "info" } diff --git a/examples/app-builder/ui/package-lock.json b/examples/app-builder/ui/package-lock.json index 5dbd743..faada2a 100644 --- a/examples/app-builder/ui/package-lock.json +++ b/examples/app-builder/ui/package-lock.json @@ -1,10 +1,12 @@ { "name": "ui", + "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ui", + "version": "0.1.0", "hasInstallScript": true, "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { diff --git a/examples/app-builder/ui/package.json b/examples/app-builder/ui/package.json index 7e1fbd2..9de2a67 100644 --- a/examples/app-builder/ui/package.json +++ b/examples/app-builder/ui/package.json @@ -1,5 +1,6 @@ { "name": "ui", + "version": "0.1.0", "private": true, "license": "Apache-2.0 WITH LLVM-exception", "type": "module", diff --git a/examples/sdk-component/README.md b/examples/sdk-component/README.md index 0e2b308..7b9a03c 100644 --- a/examples/sdk-component/README.md +++ b/examples/sdk-component/README.md @@ -1,6 +1,6 @@ # SDK Component -A minimal Spin application that uses [`@spinframework/sandbox`](../../sdk) from a +A minimal Spin application that uses [`@spinframework/spin-code-sandbox`](../../sdk) from a public Wasm HTTP component. The TypeScript and Python interpreters are private Spin components, reached only through service chaining. diff --git a/examples/sdk-component/api/package-lock.json b/examples/sdk-component/api/package-lock.json index 69d8c15..0b1d7a4 100644 --- a/examples/sdk-component/api/package-lock.json +++ b/examples/sdk-component/api/package-lock.json @@ -1,15 +1,17 @@ { "name": "sdk-component-api", + "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sdk-component-api", + "version": "0.1.0", "license": "Apache-2.0 WITH LLVM-exception", "dependencies": { - "@spinframework/sandbox": "file:../../../sdk", + "@spinframework/spin-code-sandbox": "file:../../../sdk", "@spinframework/wasi-http-proxy": "^2.0.0", - "hono": "^4.7.4" + "hono": "^4.13.19" }, "devDependencies": { "esbuild": "^0.25.8", @@ -17,11 +19,20 @@ } }, "../../../sdk": { - "name": "@spinframework/sandbox", + "name": "@spinframework/spin-code-sandbox", "version": "0.1.0", - "license": "Apache-2.0", + "license": "Apache-2.0 WITH LLVM-exception", "devDependencies": { - "typescript": "^5.6.0" + "typescript": "^5.6.0", + "zod": "^4.6.7" + }, + "peerDependencies": { + "zod": "^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } } }, "node_modules/@ampproject/remapping": { @@ -2478,7 +2489,7 @@ "j2w": "dist/index.js" } }, - "node_modules/@spinframework/sandbox": { + "node_modules/@spinframework/spin-code-sandbox": { "resolved": "../../../sdk", "link": true }, @@ -3200,9 +3211,9 @@ } }, "node_modules/hono": { - "version": "4.13.12", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.12.tgz", - "integrity": "sha512-6E2QDAc9Ick9Sq77ZrGS/dk2WUYni91aufTw6LJKpV7w8kW5/GxVUc650FOADOmlwg3K+f7Pun6XlV+pYmW6gw==", + "version": "4.13.19", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.19.tgz", + "integrity": "sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA==", "license": "MIT", "engines": { "node": ">=16.9.0" diff --git a/examples/sdk-component/api/package.json b/examples/sdk-component/api/package.json index e40f27b..2407745 100644 --- a/examples/sdk-component/api/package.json +++ b/examples/sdk-component/api/package.json @@ -1,5 +1,6 @@ { "name": "sdk-component-api", + "version": "0.1.0", "private": true, "license": "Apache-2.0 WITH LLVM-exception", "type": "module", @@ -7,9 +8,9 @@ "build": "node build.mjs && mkdirp dist && j2w -i build/bundle.js --initLocation http://api.localhost -o dist/api.wasm" }, "dependencies": { - "@spinframework/sandbox": "file:../../../sdk", + "@spinframework/spin-code-sandbox": "file:../../../sdk", "@spinframework/wasi-http-proxy": "^2.0.0", - "hono": "^4.7.4" + "hono": "^4.13.19" }, "devDependencies": { "esbuild": "^0.25.8", diff --git a/examples/sdk-component/api/src/index.ts b/examples/sdk-component/api/src/index.ts index 1bb4243..4529574 100644 --- a/examples/sdk-component/api/src/index.ts +++ b/examples/sdk-component/api/src/index.ts @@ -1,8 +1,8 @@ import { Hono } from "hono"; import { fire } from "hono/service-worker"; -import { Interpreter, type Language } from "@spinframework/sandbox/interpreter"; -import type { HttpInput } from "@spinframework/sandbox/core"; +import { Interpreter, type Language } from "@spinframework/spin-code-sandbox/interpreter"; +import type { HttpInput } from "@spinframework/spin-code-sandbox/core"; const interpreters: Record = { javascript: Interpreter.javascript({ baseUrl: "http://ts-sandbox.spin.internal" }), diff --git a/examples/sdk-component/spin.toml b/examples/sdk-component/spin.toml index ac79176..2c8d785 100644 --- a/examples/sdk-component/spin.toml +++ b/examples/sdk-component/spin.toml @@ -3,7 +3,7 @@ spin_manifest_version = 2 [application] name = "sandbox-sdk-component" version = "0.1.0" -description = "Minimal Spin component using @spinframework/sandbox through private interpreter components." +description = "Minimal Spin component using @spinframework/spin-code-sandbox through private interpreter components." [[trigger.http]] route = "/..." diff --git a/scripts/check-npm-audit.mjs b/scripts/check-npm-audit.mjs index cb0ded7..1dbef1f 100644 --- a/scripts/check-npm-audit.mjs +++ b/scripts/check-npm-audit.mjs @@ -88,113 +88,10 @@ function normalizeVulnerabilities(vulnerabilities) { .sort((left, right) => left.name.localeCompare(right.name)); } -// The example UIs are served as static `nuxt generate` output. deepmerge is -// used by Rollup's node-resolve plugin during the build and has no patched -// release for GHSA-gcqx-w48m-w2h4. Builds must use trusted configuration. -function expectedNuxtFindings() { - const findings = [ - { - name: "@nuxt/nitro-server", - severity: "low", - isDirect: false, - range: ">=3.20.0", - fixAvailable: true, - via: ["nitropack", "nuxt"], - effects: ["nuxt"], - nodes: ["node_modules/@nuxt/nitro-server"], - }, - { - name: "@nuxt/vite-builder", - severity: "low", - isDirect: false, - range: "3.20.0 - 3.21.11 || >=4.2.0", - fixAvailable: true, - via: ["nuxt"], - effects: ["nuxt"], - nodes: ["node_modules/@nuxt/vite-builder"], - }, - { - name: "@nuxt/vite-server", - severity: "low", - isDirect: false, - range: ">=4.6.0", - fixAvailable: true, - via: ["nuxt"], - effects: ["nuxt"], - nodes: ["node_modules/@nuxt/vite-server"], - }, - { - name: "@rollup/plugin-node-resolve", - severity: "low", - isDirect: false, - range: ">=8.0.0", - fixAvailable: true, - via: ["deepmerge"], - effects: ["nitropack"], - nodes: ["node_modules/@rollup/plugin-node-resolve"], - }, - { - name: "deepmerge", - severity: "low", - isDirect: false, - range: ">=4.2.0", - fixAvailable: true, - via: [ - { - source: 1243505, - severity: "low", - url: "https://github.com/advisories/GHSA-gcqx-w48m-w2h4", - range: ">=4.2.0 <=4.3.1", - }, - ], - effects: ["@rollup/plugin-node-resolve"], - nodes: ["node_modules/deepmerge"], - }, - { - name: "nitropack", - severity: "low", - isDirect: false, - range: ">=0.1.0", - fixAvailable: true, - via: ["@rollup/plugin-node-resolve"], - effects: ["@nuxt/nitro-server"], - nodes: ["node_modules/nitropack"], - }, - { - name: "nuxt", - severity: "low", - isDirect: true, - range: "3.20.0 - 3.21.11 || >=4.2.0", - fixAvailable: true, - via: ["@nuxt/nitro-server", "@nuxt/vite-builder", "@nuxt/vite-server"], - effects: ["@nuxt/nitro-server", "@nuxt/vite-builder", "@nuxt/vite-server"], - nodes: ["node_modules/nuxt"], - }, - ]; - - return findings - .map(normalizeVulnerability) - .sort((left, right) => left.name.localeCompare(right.name)); -} - -const nuxtAudit = { - vulnerabilities: expectedNuxtFindings(), - metadata: { - info: 0, - low: 7, - moderate: 0, - high: 0, - critical: 0, - total: 7, - }, -}; - // Keep these as exact snapshots: any advisory or dependency-graph change must // fail CI and be reviewed rather than being absorbed by a broad allowlist. -const auditExceptions = new Map([ - ["examples/ai-code-executor/ui", nuxtAudit], - ["examples/app-builder/ui", nuxtAudit], -]); +// Entries map a project path to its exact expected `{ vulnerabilities, metadata }` result. +const auditExceptions = new Map(); const cleanAudit = { vulnerabilities: [], diff --git a/sdk/README.md b/sdk/README.md index c9c39ba..75d1520 100644 --- a/sdk/README.md +++ b/sdk/README.md @@ -1,18 +1,14 @@ -# @spinframework/sandbox +# @spinframework/spin-code-sandbox -An extensible TypeScript client for sandboxed code execution, consumed from a Spin -application. It ships one backend today, the Wasm code interpreter (this repo's -`ts-sandbox` / `py-sandbox` components), and is built so another backend can be added -later without changing the portable surface. +An extensible TypeScript client for sandboxed code execution, consumed from a Spin application. It ships one backend today, the Wasm code interpreter (this repo's `ts-sandbox` / `py-sandbox` components), and is built so another backend can be added later without changing the portable surface. ## The portable contract -Author a tool against the `CodeRunner` interface and it runs unchanged on any backend; -the host injects the concrete client at the edge. +Author a tool against the `CodeRunner` interface and it runs unchanged on any backend; the host injects the concrete client at the edge. ```ts -import type { CodeRunner } from "@spinframework/sandbox/core"; -import { Interpreter } from "@spinframework/sandbox/interpreter"; +import type { CodeRunner } from "@spinframework/spin-code-sandbox/core"; +import { Interpreter } from "@spinframework/spin-code-sandbox/interpreter"; // A tool depends only on the interface, so the backend can be swapped without touching it. async function compute(runner: CodeRunner, code: string) { @@ -25,37 +21,137 @@ const runner = Interpreter.python({ baseUrl: "http://py-sandbox.spin.internal" } console.log(await compute(runner, "print(6 * 7)")); ``` -`run()` returns data (`{ stdout, stderr, results, error? }`): an exception inside the -sandbox is `Result.error`, not a thrown error. `run()` only throws for transport, auth, -or validation failures. +`run()` returns data (`{ stdout, stderr, results, error? }`): an exception inside the sandbox is `Result.error`, not a thrown error. `run()` only throws for transport, auth, 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()` gives an agent a ready-to-run `run_in_wasm_interpreter` tool. Pass it your `Interpreter` clients (one per language; the tool offers exactly those languages) and your execution policy. It validates the model's arguments against a strict [Zod](https://zod.dev) schema, runs the code, and formats the output for the model. Zod is a peer dependency: install `zod@^4` in apps that import `@spinframework/spin-code-sandbox/tools`. ```ts -import { interpreterTool, toAnthropicTool } from "@spinframework/sandbox/tools"; +import { Interpreter } from "@spinframework/spin-code-sandbox/interpreter"; +import { interpreterTool } from "@spinframework/spin-code-sandbox/tools"; + +const sandbox = interpreterTool({ + interpreters: { + python: Interpreter.python({ baseUrl: "http://py-sandbox.spin.internal" }), + javascript: Interpreter.javascript({ baseUrl: "http://ts-sandbox.spin.internal" }), + }, + // Optional. The default denies egress and KV and uses a fresh identity per run. + policy: { allowedHosts: ["https://api.example.com"] }, +}); + +// 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."; +``` + +| Method | Use it for | +| --- | --- | +| `sandbox.call(input)` | Raw model arguments in, `{ content, isError }` out: validate, run, format. | +| `sandbox.execute(args)` | The Vercel AI SDK `execute`: validated arguments in, text out. | +| `sandbox.parse(input)` | Validation alone: `{ ok: true, args }` or `{ ok: false, output }` for the model. | +| `sandbox.withPolicy(policy)` | A copy of the tool with `policy` merged over its own, e.g. per conversation. | +| `sandbox.anthropic` / `.openai` / `.openaiResponses` | `.tool` for the request and `.results(calls)` for the reply, per provider (below). | +| `sandbox.run(args)` | Running validated arguments; also returns `stdout`, `stderr`, `error`, and handler `status`, e.g. to stream to a UI. | + +The schema is strict, so the model cannot set `allowedHosts`, `kvEnabled`, or `identity`: the application sets them in `policy`. To vary the policy (per user, conversation, or request), derive a tool with `sandbox.withPolicy(...)`; the copy reuses the interpreters, schema, and cached JSON Schema, so it is cheap, and the same pattern works with every provider below. Sandbox and transport failures come back as `isError: true` output for the model rather than as thrown errors. Keep sandbox endpoints private. + +### Vercel AI SDK + +The tool is already in the AI SDK's tool shape: it validates with `inputSchema` and calls `execute`. + +```ts +import { ToolLoopAgent, stepCountIs } from "ai"; +import { anthropic } from "@ai-sdk/anthropic"; + +const agent = new ToolLoopAgent({ + model: anthropic("claude-sonnet-5-5"), + instructions: SYSTEM_PROMPT, + tools: { [sandbox.name]: sandbox }, + stopWhen: stepCountIs(10), +}); + +const { text } = await agent.generate({ prompt: "What is the 50th Fibonacci number?" }); +``` -const tools = [toAnthropicTool(interpreterTool({ languages: ["javascript"] }))]; +### Anthropic SDK + +`sandbox.anthropic.tool` is the tool definition; `sandbox.anthropic.results(res.content)` runs every `tool_use` block for this tool and returns the `tool_result` blocks. + +```ts +import Anthropic from "@anthropic-ai/sdk"; + +const client = new Anthropic(); +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: [sandbox.anthropic.tool], + messages, + }); + messages.push({ role: "assistant", content: res.content }); + if (res.stop_reason !== "tool_use") break; + messages.push({ role: "user", content: await sandbox.anthropic.results(res.content) }); +} ``` -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 SDK + +Chat Completions uses `sandbox.openai`; `results()` parses each tool call's JSON arguments and returns the `tool` messages. + +```ts +import OpenAI from "openai"; + +const client = new OpenAI(); +const messages: OpenAI.ChatCompletionMessageParam[] = [ + { role: "system", content: SYSTEM_PROMPT }, + { role: "user", content: "What is the 50th Fibonacci number?" }, +]; + +for (let step = 0; step < 10; step++) { + const res = await client.chat.completions.create({ model: "gpt-5", tools: [sandbox.openai.tool], messages }); + const message = res.choices[0].message; + messages.push(message); + if (!message.tool_calls?.length) break; + messages.push(...(await sandbox.openai.results(message.tool_calls))); +} +``` + +The Responses API uses `sandbox.openaiResponses`, whose tool sets `strict: false` (the Responses API otherwise defaults to strict mode, which this schema does not support): + +```ts +const tools = [sandbox.openaiResponses.tool]; +let res = await client.responses.create({ model: "gpt-5", instructions: SYSTEM_PROMPT, tools, input: "What is 2**64?" }); +for (let step = 0; step < 10; step++) { + const outputs = await sandbox.openaiResponses.results(res.output); + if (!outputs.length) break; + res = await client.responses.create({ model: "gpt-5", tools, previous_response_id: res.id, input: outputs }); +} +console.log(res.output_text); +``` + +Each `results()` call runs this tool's calls concurrently, keeps their order, and skips any other tool's calls, so you can answer those yourself and combine the arrays. + +### Plain JSON Schema + +`toToolDefinition(sandbox)` returns the provider-neutral form, and `toAnthropicTool()`, `toOpenAITool()`, and `toOpenAIResponsesTool()` adapt any tool, including a hand-written `ToolDefinition` with a JSON Schema `inputSchema`. Use `sandbox.call(input)` for providers without a helper. The derived schema is not OpenAI strict-mode compatible (optional fields are omitted from `required`), so leave `strict` unset on Chat Completions. ### Identity and session isolation An `identity` selects a KV namespace, shared across languages when KV is enabled. Omit it for a new ID per call; reuse it for shared storage. Every execution is a fresh Wasm instance: variables and globals never persist. The model never sees or chooses the identity. To let an agent keep state across calls, generate one ID per conversation and pass it with `kvEnabled: true`: ```ts -const sessionId = crypto.randomUUID(); - -await runner.run(args.code, { - lang: args.language, - input: args.input, - allowedHosts: ["https://api.example.com"], - kvEnabled: true, - identity: sessionId, -}); +const conversation = sandbox.withPolicy({ kvEnabled: true, identity: crypto.randomUUID() }); + +// Then use `conversation` exactly like `sandbox`, with any provider: +tools: { [conversation.name]: conversation } // Vercel AI SDK +await conversation.anthropic.results(res.content) // Anthropic +await conversation.openai.results(message.tool_calls) // OpenAI ``` For reuse across chat turns, store the UUID server-side with its owner and check ownership on every request. IDs select namespaces; they are not authorization. Never accept raw IDs from model output or unchecked client input. Use separate IDs for separate users/conversations, and define quotas and cleanup: abandoning an ID does not delete its KV data. After stopping all writers, use `await javascript.kv(sessionId).clear()` to remove the namespace's keys. This operation is not transactional; a failure may leave some keys behind and can be retried. Resumable side tracks and KV cloning are not provided. @@ -68,14 +164,9 @@ permission, so only trusted components should be granted access. ## Backends -- **`interpreter`**: a thin client over a sandbox component's `POST /ts/run` - (JS/TS) and `/py/run` (Python) routes. Single-shot, buffered, default-deny egress, - plus a scoped KV store (`Interpreter.kv(namespace)`). +- **`interpreter`**: a thin client over a sandbox component's `POST /ts/run` (JS/TS) and `/py/run` (Python) routes. Single-shot, buffered, default-deny egress, plus a scoped KV store (`Interpreter.kv(namespace)`). - The intended deployment is two private components (ts-sandbox, py-sandbox) reached - via service chaining. `.spin.internal` resolves to a component id, so each language - has its own host: use one `Interpreter` per language, each `baseUrl` pointed at its - component: + The intended deployment is two private components (ts-sandbox, py-sandbox) reached via service chaining. `.spin.internal` resolves to a component id, so each language has its own host: use one `Interpreter` per language, each `baseUrl` pointed at its component: ```ts const js = Interpreter.javascript({ baseUrl: "http://ts-sandbox.spin.internal" }); @@ -84,13 +175,9 @@ permission, so only trusted components should be granted access. await py.execute(code); // py-sandbox ``` - `Interpreter.javascript({ baseUrl })` is shorthand for `new Interpreter({ baseUrl, - lang: "javascript" })`. Language-bound clients reject a mismatched `lang` option. Create an unbound - `new Interpreter({ baseUrl })` only when one endpoint really serves both `/ts` and - `/py`; scoped KV and npm bundling require that unbound client or a JavaScript client. + `Interpreter.javascript({ baseUrl })` is shorthand for `new Interpreter({ baseUrl, lang: "javascript" })`. Language-bound clients reject a mismatched `lang` option. Create an unbound `new Interpreter({ baseUrl })` only when one endpoint really serves both `/ts` and `/py`; scoped KV and npm bundling require that unbound client or a JavaScript client. - To invoke an HTTP handler, use `runHandler()` rather than manually constructing an - envelope. It returns the handler's `Response`, including a streamed response body: + To invoke an HTTP handler, use `runHandler()` rather than manually constructing an envelope. It returns the handler's `Response`, including a streamed response body: ```ts const response = await py.runHandler( @@ -100,25 +187,17 @@ permission, so only trusted components should be granted access. console.log(await response.text()); ``` - See [`examples/ai-code-executor`](../examples/ai-code-executor). (A single combined - app that routes both `/ts` and `/py` by path also works; then one `baseUrl` at the - app suffices.) + See [`examples/ai-code-executor`](../examples/ai-code-executor). (A single combined app that routes both `/ts` and `/py` by path also works; then one `baseUrl` at the app suffices.) ## Extending it The library ships no other-backend types, but it is designed to gain them: -- **`core`** (`./core`) is the only shared surface: `CodeRunner`, `RunOpts`, `Result`, - and `Caps`. It carries no transport and nothing interpreter-specific. -- **`Backend`** is a widenable union (`"interpreter" | (string & {})`), so a new - backend names itself without a breaking change. -- **`Caps`** already describes capabilities a heavier backend would light up - (`filesystem`, `sessions`, `exec`, `lifecycle`, `arbitraryImage`, `realTimeout`), so - a tool can branch on them at runtime; native TypeScript tools rely on compile-time - method absence instead. +- **`core`** (`./core`) is the only shared surface: `CodeRunner`, `RunOpts`, `Result`, and `Caps`. It carries no transport and nothing interpreter-specific. +- **`Backend`** is a widenable union (`"interpreter" | (string & {})`), so a new backend names itself without a breaking change. +- **`Caps`** already describes capabilities a heavier backend would light up (`filesystem`, `sessions`, `exec`, `lifecycle`, `arbitraryImage`, `realTimeout`), so a tool can branch on them at runtime; native TypeScript tools rely on compile-time method absence instead. -To add one: create a module under `src/`, implement `CodeRunner`, declare its `Caps`, -and export it from `src/index.ts`. Nothing in `core` or `interpreter` has to change. +To add one: create a module under `src/`, implement `CodeRunner`, declare its `Caps`, and export it from `src/index.ts`. Nothing in `core` or `interpreter` has to change. ## Develop @@ -129,8 +208,7 @@ npm test # node --test (runs the .ts tests directly) npm run check # both ``` -`npm test` runs the TypeScript tests through Node's built-in runner with no build step, so -it needs Node 24+ (native type stripping, plus `--test` glob support). +`npm test` runs the TypeScript tests through Node's built-in runner with no build step, so it needs Node 24+ (native type stripping, plus `--test` glob support). To test the SDK against real sandbox components, first start the root application, then run: diff --git a/sdk/package-lock.json b/sdk/package-lock.json index e6bf0ca..bf2123e 100644 --- a/sdk/package-lock.json +++ b/sdk/package-lock.json @@ -1,15 +1,24 @@ { - "name": "@spinframework/sandbox", + "name": "@spinframework/spin-code-sandbox", "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "@spinframework/sandbox", + "name": "@spinframework/spin-code-sandbox", "version": "0.1.0", "license": "Apache-2.0 WITH LLVM-exception", "devDependencies": { - "typescript": "^5.6.0" + "typescript": "^5.6.0", + "zod": "^4.6.7" + }, + "peerDependencies": { + "zod": "^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } } }, "node_modules/typescript": { @@ -25,6 +34,16 @@ "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==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/sdk/package.json b/sdk/package.json index de14164..bed8506 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -1,5 +1,5 @@ { - "name": "@spinframework/sandbox", + "name": "@spinframework/spin-code-sandbox", "version": "0.1.0", "description": "An extensible client for sandboxed code execution from a Spin application. Ships a Wasm code-interpreter backend; extensible to other backends.", "type": "module", @@ -29,6 +29,15 @@ "tools" ], "devDependencies": { - "typescript": "^5.6.0" + "typescript": "^5.6.0", + "zod": "^4.6.7" + }, + "peerDependencies": { + "zod": "^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } } } diff --git a/sdk/src/core/index.ts b/sdk/src/core/index.ts index 5a8584c..09f6d92 100644 --- a/sdk/src/core/index.ts +++ b/sdk/src/core/index.ts @@ -1,4 +1,4 @@ -// @spinframework/sandbox/core, the portable interface + shared types. +// @spinframework/spin-code-sandbox/core, the portable interface + shared types. // No transport, no dependencies. The extension point: implement `CodeRunner` to // add a backend. diff --git a/sdk/src/index.ts b/sdk/src/index.ts index 68e78a3..41b137b 100644 --- a/sdk/src/index.ts +++ b/sdk/src/index.ts @@ -1,18 +1,18 @@ -// @spinframework/sandbox, an extensible client for sandboxed code execution, +// @spinframework/spin-code-sandbox, an extensible client for sandboxed code execution, // consumed from a Spin application. // -// Author a tool against `CodeRunner` (from "@spinframework/sandbox/core") and it +// Author a tool against `CodeRunner` (from "@spinframework/spin-code-sandbox/core") and it // runs unchanged on any backend; the host injects the concrete client: // -// import { Interpreter } from "@spinframework/sandbox/interpreter"; +// import { Interpreter } from "@spinframework/spin-code-sandbox/interpreter"; // const runner = new Interpreter({ baseUrl: "http://ts-sandbox.spin.internal" }); // // Only the Wasm interpreter backend ships today. To extend it, add a new module // that implements `CodeRunner` and declares itself through `Caps`, and export it // below. The core contract (`CodeRunner`, `RunOpts`, `Result`, `Caps`) is -// backend-neutral. +// backend-neutral. Agent tools live in "@spinframework/spin-code-sandbox/tools" so that only +// apps that use them need the optional `zod` peer dependency. 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"; diff --git a/sdk/src/interpreter/index.ts b/sdk/src/interpreter/index.ts index 03cc605..622c316 100644 --- a/sdk/src/interpreter/index.ts +++ b/sdk/src/interpreter/index.ts @@ -1,4 +1,4 @@ -// @spinframework/sandbox/interpreter, the Wasm code interpreter backend. +// @spinframework/spin-code-sandbox/interpreter, the Wasm code interpreter backend. // // A thin client over a sandbox component's `POST /ts/run` (JS/TS) and `/py/run` // (Python) routes. `core.run()` is intentionally single-shot and buffered. HTTP handler @@ -28,7 +28,7 @@ import type { Caps, CodeRunner, HttpInput, Language, PackageJson, Result, RunOpt import { langToRoute, withDefaults } from "../core/index.ts"; // Re-exported so a consumer can name run languages (and import `Interpreter`) -// from this one module, without also reaching into `@spinframework/sandbox/core`. +// from this one module, without also reaching into `@spinframework/spin-code-sandbox/core`. export type { Language } from "../core/index.ts"; /** A fetch implementation; defaults to the Spin guest's global `fetch`. */ @@ -123,7 +123,7 @@ export class Interpreter implements CodeRunner { /** * Bundle npm dependencies into `code` WITHOUT running it, returning the self-contained * bundle. JavaScript only; requires a `bundlerUrl`. Use it to pre-bundle code you will - * store and run later (see @spinframework/sandbox/store), so it is bundled once at publish + * store and run later (see @spinframework/spin-code-sandbox/store), so it is bundled once at publish * rather than on every request. */ async bundle(code: string, packageJson: PackageJson): Promise { diff --git a/sdk/src/store/index.ts b/sdk/src/store/index.ts index d109064..a29b897 100644 --- a/sdk/src/store/index.ts +++ b/sdk/src/store/index.ts @@ -1,4 +1,4 @@ -// @spinframework/sandbox/store, persist AI-generated code and run it later by id. +// @spinframework/spin-code-sandbox/store, persist AI-generated code and run it later by id. // // KvCodeStore is the one CodeStore implementation today: it keeps code in the sandbox's // scoped KV (via InterpreterKV). serveStoredCode composes a store with interpreters to run diff --git a/sdk/src/tools.ts b/sdk/src/tools.ts index 6cdb788..fa357ca 100644 --- a/sdk/src/tools.ts +++ b/sdk/src/tools.ts @@ -1,115 +1,449 @@ +import * as z from "zod"; + import type { Language } from "./core/index.ts"; +import type { BoundRunOpts, Interpreter } from "./interpreter/index.ts"; -export interface ToolDefinition { +/** + * A tool whose input is described by a Zod schema. `{ 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: { - type: "object"; - properties: Record; - required: string[]; - additionalProperties?: boolean; - }; + inputSchema: z.ZodType; } -export interface InterpreterToolOptions { - /** Languages served by this interpreter. Defaults to both sandbox languages. */ - languages?: readonly Language[]; +/** 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; } -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: +/** Provider-neutral tool metadata with a plain JSON Schema for its input. */ +export interface ToolDefinition { + name: string; + description: string; + inputSchema: JsonSchemaObject; +} + +/** Either kind of tool the adapters accept. */ +export type AnyTool = StructuredTool | ToolDefinition; + +const stringMap = () => z.record(z.string(), z.string()); + +const CODE = z.string(); +const DEPENDENCIES = stringMap().describe( + "JavaScript only. Extra npm dependencies as name -> semver ranges. Use ESM import; Python cannot add packages.", +); +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." }, - }, -}; - -/** Returns tool metadata for the languages served by one interpreter endpoint. */ -export function interpreterTool(options: InterpreterToolOptions = {}): ToolDefinition { - const languages = 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"); - const languageLabel = languages.join(" or "); - const only = (on: boolean, text: string) => (on ? [text] : []); - const httpContext = [ - ...only( - supportsJavaScript, - "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\".", - ), - ...only( - supportsPython, - "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())`.", - ), + ); + +/** + * Arguments the model supplies to `run_in_wasm_interpreter`. `language` narrows to the + * configured languages; `dependencies` is only accepted by the schema when JavaScript is served. + */ +export interface InterpreterToolInput { + language: L; + code: string; + /** JavaScript only: extra npm dependencies as name -> semver range. */ + dependencies?: Record; + input?: z.infer; +} + +/** Execution policy the application sets for every run. Model arguments never reach it. */ +export type ExecutionPolicy = Pick; + +export interface InterpreterToolOptions { + /** + * One client per language you serve, e.g. `{ python: Interpreter.python({ baseUrl }) }`. The + * tool offers exactly these languages, in this order. + */ + interpreters: { readonly [K in L]: Interpreter }; + /** Applied to every run. Defaults deny egress and KV and use a fresh identity per run. */ + policy?: ExecutionPolicy; +} + +/** What to send back to the model for one tool call. */ +export interface ToolOutput { + content: string; + isError: boolean; +} + +/** A finished run: the model-facing output plus its parts, e.g. for streaming to a UI. */ +export interface ToolRun extends ToolOutput { + stdout: string; + stderr: string; + /** Code, sandbox, or transport error; null on success. */ + error: string | null; + /** HTTP status, when `input` ran the code as a handler. */ + status?: number; +} + +/** Result of `InterpreterTool.parse()`: typed arguments, or the error to return to the model. */ +export type ParsedToolCall = + | { ok: true; args: InterpreterToolInput } + | { ok: false; output: ToolOutput }; + +/** The `run_in_wasm_interpreter` tool, bound to interpreter clients and an execution policy. */ +export interface InterpreterTool extends StructuredTool> { + /** Runs validated arguments and returns the text for the model (the Vercel AI SDK `execute`). */ + execute(args: InterpreterToolInput): Promise; + /** Runs validated arguments. */ + run(args: InterpreterToolInput): Promise; + /** Validates raw model arguments (e.g. Anthropic `tool_use.input`), then runs them. */ + call(input: unknown): Promise; + /** Validates raw model arguments; on failure, `output` names the bad fields for the model. */ + parse(input: unknown): ParsedToolCall; + /** + * Returns this tool with `policy` merged over its policy, e.g. `withPolicy({ identity })` per + * conversation. The copy shares the interpreters, schema, and cached JSON Schema. + */ + withPolicy(policy: ExecutionPolicy): InterpreterTool; + /** Anthropic Messages API: `tools: [sandbox.anthropic.tool]`, then `results(response.content)`. */ + readonly anthropic: ProviderHelpers; + /** OpenAI Chat Completions: `tools: [sandbox.openai.tool]`, then `results(message.tool_calls)`. */ + readonly openai: ProviderHelpers; + /** OpenAI Responses API: `tools: [sandbox.openaiResponses.tool]`, then `results(response.output)`. */ + readonly openaiResponses: ProviderHelpers; +} + +/** A provider's tool definition plus a way to answer its tool calls. */ +export interface ProviderHelpers { + /** The tool definition to send to the provider. */ + readonly tool: Tool; + /** + * Runs every call to this tool in a model response, concurrently, and returns the provider's + * result items in order. Items that are not calls to this tool are skipped, so other tools + * can share the response. + */ + results(calls: readonly Call[] | null | undefined): Promise; +} + +/** A content block of an Anthropic response; only `tool_use` blocks are read. */ +export interface AnthropicContentBlock { + type: string; + id?: string; + name?: string; + input?: unknown; +} + +/** An Anthropic `tool_result` content block. */ +export interface AnthropicToolResult { + type: "tool_result"; + tool_use_id: string; + content: string; + is_error: boolean; +} + +/** A tool call in an OpenAI Chat Completions assistant message. */ +export interface OpenAIToolCall { + id: string; + type: string; + function?: { name: string; arguments: string }; +} + +/** An OpenAI Chat Completions `tool` message answering one tool call. */ +export interface OpenAIToolMessage { + role: "tool"; + tool_call_id: string; + content: string; +} + +/** An OpenAI Responses API output item; only `function_call` items are read. */ +export interface OpenAIResponseItem { + type: string; + call_id?: unknown; + name?: unknown; + arguments?: unknown; +} + +/** An OpenAI Responses API `function_call_output` input item. */ +export interface OpenAIFunctionCallOutput { + type: "function_call_output"; + call_id: string; + output: string; +} + +/** + * Returns the `run_in_wasm_interpreter` tool for the given interpreter clients. Its + * `inputSchema` is a strict Zod object: unknown fields (such as `allowedHosts`, `kvEnabled`, or + * `identity`) are rejected, so execution policy stays with the application. + * + * ```ts + * const sandbox = interpreterTool({ + * interpreters: { python: Interpreter.python({ baseUrl: "http://py-sandbox.spin.internal" }) }, + * policy: { allowedHosts: ["https://api.example.com"] }, + * }); + * const { content, isError } = await sandbox.call(toolUse.input); + * ``` + */ +export function interpreterTool( + options: InterpreterToolOptions, +): InterpreterTool { + const { interpreters, policy = {} } = options; + return bindTool(describeTool(Object.keys(interpreters) as L[]), interpreters, policy); +} + +interface ToolSchema { + description: string; + inputSchema: z.ZodType>; +} + +/** Builds the policy-independent part of the tool: what the model sees. */ +function describeTool(languages: L[]): ToolSchema { + if (languages.length === 0) throw new Error("interpreterTool requires at least one interpreter"); + const served = new Set(languages); + const js = served.has("javascript"); + const py = served.has("python"); + + const language = z.enum(languages as [L, ...L[]]); + const code = CODE.describe( + js + ? "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 input = HTTP_INPUT.optional(); + const inputSchema = js + ? z.strictObject({ language, code, dependencies: DEPENDENCIES.optional(), input }) + : z.strictObject({ language, code, input }); + + const description = [ + `Run ${languages.join(" or ")} 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.", + js && "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\".", + py && "Python uses `from spin_sdk.http import send, Request` and `send(Request(method, url, headers, body))`; urllib, http.client, and requests are not available.", + py && "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.", - ].join(" "); - const kvContext = [ - ...only(supportsJavaScript, "JavaScript: `import { openDefault } from \"@spinframework/spin-kv\"`, then get/set or getJson/setJson."), - ...only(supportsPython, "Python: `from spin_sdk import key_value`, then `key_value.open_default()` with get/set (values are bytes)."), - ].join(" "); - const libraryContext = [ - ...only( - supportsPython, - "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.", - ), - ...only( - supportsJavaScript, - "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().", - ), - ].join(" "); - 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."; - return { + "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.", + js && "JavaScript: `import { openDefault } from \"@spinframework/spin-kv\"`, then get/set or getJson/setJson.", + py && "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.", + py && "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.", + js && "JavaScript (TypeScript syntax is accepted) includes lodash, zod, date-fns, dayjs, cheerio, node-html-parser, js-yaml, uuid, ulidx, and nanoid.", + js && "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.", + ] + .filter(Boolean) + .join(" "); + + return { description, inputSchema }; +} + +/** Binds the tool's schema to interpreter clients and a policy. */ +function bindTool( + schema: ToolSchema, + interpreters: { readonly [K in L]: Interpreter }, + policy: ExecutionPolicy, +): InterpreterTool { + const { inputSchema } = schema; + + const parse = (input: unknown): ParsedToolCall => { + const parsed = inputSchema.safeParse(input); + if (parsed.success) return { ok: true, args: parsed.data }; + const content = `error: invalid tool arguments:\n${z.prettifyError(parsed.error)}\nExecution permissions are controlled by the application.`; + return { ok: false, output: { content, isError: true } }; + }; + + const run = async (args: InterpreterToolInput): Promise => { + const interpreter: Interpreter | undefined = interpreters[args.language]; + if (!interpreter) return toolRun({ error: `unsupported language: ${String(args.language)}` }); + const dependencies = args.language === "javascript" ? args.dependencies : undefined; + const opts: BoundRunOpts = { + ...policy, + packageJson: dependencies && Object.keys(dependencies).length ? { dependencies } : undefined, + }; + try { + if (args.input) { + const response = await interpreter.runHandler(args.code, args.input, opts); + return toolRun({ stdout: await response.text(), status: response.status }); + } + const result = await interpreter.execute(args.code, opts); + return toolRun({ + stdout: result.stdout, + stderr: result.stderr, + // Runtime errors arrive with the generic name "error"; only specific kinds add information. + error: result.error && (result.error.name === "error" ? result.error.value : `${result.error.name}: ${result.error.value}`), + }); + } catch (e) { + return toolRun({ error: `sandbox error: ${e instanceof Error ? e.message : String(e)}` }); + } + }; + + const tool: InterpreterTool = { name: "run_in_wasm_interpreter", - description: - `Run ${languageLabel} 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. ${httpContext} ` + - "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. ${kvContext} ` + - "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. " + - `${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, + ...schema, + parse, + run, + execute: async (args) => (await run(args)).content, + call, + withPolicy: (overrides) => bindTool(schema, interpreters, { ...policy, ...overrides }), + get anthropic(): InterpreterTool["anthropic"] { + return providerHelpers(toAnthropicTool(tool), ({ type, name, id, input }: AnthropicContentBlock) => { + if (type !== "tool_use" || name !== tool.name || id === undefined) return undefined; + return async () => { + const { content, isError } = await call(input); + return { type: "tool_result", tool_use_id: id, content, is_error: isError }; + }; + }); + }, + get openai(): InterpreterTool["openai"] { + return providerHelpers(toOpenAITool(tool), ({ id, function: fn }: OpenAIToolCall) => { + if (fn?.name !== tool.name) return undefined; + return async () => { + const { content } = await callJson(fn.arguments); + return { role: "tool", tool_call_id: id, content }; + }; + }); + }, + get openaiResponses(): InterpreterTool["openaiResponses"] { + return providerHelpers(toOpenAIResponsesTool(tool), ({ type, name, call_id, arguments: args }: OpenAIResponseItem) => { + if (type !== "function_call" || name !== tool.name || typeof call_id !== "string") return undefined; + return async () => { + const { content } = await callJson(typeof args === "string" ? args : ""); + return { type: "function_call_output", call_id, output: content }; + }; + }); }, }; -} + return tool; -/** 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 }; + async function call(input: unknown): Promise { + const parsed = parse(input); + return parsed.ok ? run(parsed.args) : parsed.output; + } + + // OpenAI sends arguments as a JSON string. + async function callJson(json: string): Promise { + let input: unknown; + try { + input = JSON.parse(json); + } catch { + return { content: "error: tool arguments are not valid JSON", isError: true }; + } + return call(input); + } } -/** Adapts provider-neutral metadata to OpenAI's function-tool shape. */ -export function toOpenAITool(tool: ToolDefinition) { +/** + * Builds a provider's helpers from its tool definition and a matcher that returns a runner for + * each call addressed to this tool (and undefined for anything else in the response). + */ +function providerHelpers( + tool: Tool, + match: (call: Call) => (() => Promise) | undefined, +): ProviderHelpers { return { - type: "function" as const, - function: { name: tool.name, description: tool.description, parameters: tool.inputSchema }, + tool, + results: (calls) => Promise.all((calls ?? []).flatMap((c) => match(c) ?? []).map((runCall) => runCall())), }; -} \ No newline at end of file +} + +function toolRun({ stdout = "", stderr = "", error = null, status }: Partial): ToolRun { + const content = + status === undefined + ? [stdout && `stdout:\n${stdout}`, stderr && `stderr:\n${stderr}`, error && `error: ${error}`] + .filter(Boolean) + .join("\n\n") || "(no output)" + : `HTTP ${status}\n${stdout}`; + return { content, isError: error !== null, stdout, stderr, error, status }; +} + +function isStructured(tool: AnyTool): tool is StructuredTool { + // Zod v4 marks every schema with `_zod`; checking it also accepts schemas from another zod copy. + return typeof tool.inputSchema === "object" && tool.inputSchema !== null && "_zod" in tool.inputSchema; +} + +const jsonSchemas = new WeakMap(); + +/** + * Returns the tool with a plain JSON Schema input, converting a Zod schema if needed. The + * conversion is cached per schema, so calling an adapter on every model turn, or on every + * `withPolicy()` copy, is cheap. + */ +export function toToolDefinition(tool: AnyTool): ToolDefinition { + if (!isStructured(tool)) return tool; + let inputSchema = jsonSchemas.get(tool.inputSchema); + if (!inputSchema) { + inputSchema = toJsonSchema(tool); + jsonSchemas.set(tool.inputSchema, inputSchema); + } + return { name: tool.name, description: tool.description, inputSchema }; +} + +function toJsonSchema(tool: StructuredTool): JsonSchemaObject { + const { $schema: _, ...schema } = z.toJSONSchema(tool.inputSchema, { + io: "input", + // Zod emits `propertyNames: { type: "string" }` for string-keyed records. JSON object keys + // are always strings, so the keyword adds nothing for the model; drop it to keep the schema lean. + 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 { properties: {}, required: [], ...schema } as JsonSchemaObject; +} + +/** Adapts a tool to Anthropic's tool shape. */ +export function toAnthropicTool(tool: AnyTool): AnthropicTool { + const { name, description, inputSchema } = toToolDefinition(tool); + return { name, description, input_schema: inputSchema }; +} + +/** The tool shape the Anthropic Messages API takes. */ +export interface AnthropicTool { + name: string; + description: string; + input_schema: JsonSchemaObject; +} + +/** The function-tool shape OpenAI Chat Completions takes. */ +export interface OpenAITool { + type: "function"; + function: { name: string; description: string; parameters: JsonSchemaObject }; +} + +/** The function-tool shape the OpenAI Responses API takes. */ +export interface OpenAIResponsesTool { + type: "function"; + name: string; + description: string; + parameters: JsonSchemaObject; + strict: false; +} + +/** Adapts a tool to OpenAI Chat Completions' function-tool shape (non-strict). */ +export function toOpenAITool(tool: AnyTool): OpenAITool { + const { name, description, inputSchema } = toToolDefinition(tool); + return { type: "function", function: { name, description, parameters: inputSchema } }; +} + +/** + * Adapts a tool to the OpenAI Responses API's function-tool shape. `strict` is false because the + * Responses API otherwise defaults to strict mode, which rejects optional fields. + */ +export function toOpenAIResponsesTool(tool: AnyTool): OpenAIResponsesTool { + const { name, description, inputSchema } = toToolDefinition(tool); + return { type: "function", name, description, parameters: inputSchema, strict: false }; +} 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..2d1cd5d 100644 --- a/sdk/test/tools.test.ts +++ b/sdk/test/tools.test.ts @@ -1,59 +1,248 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { interpreterTool, toAnthropicTool, toOpenAITool } from "../src/tools.ts"; - -test("interpreterTool scopes its schema to the configured language", () => { - const tool = interpreterTool({ 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); - assert.ok("input" in tool.inputSchema.properties); - assert.deepEqual(Object.keys(tool.inputSchema.properties), ["language", "code", "input"]); -}); - -test("interpreterTool leaves execution policy to the application", () => { - for (const languages of [undefined, ["python"] as const, ["javascript"] as const]) { - const tool = interpreterTool({ languages }); - for (const field of ["allowedHosts", "kvEnabled", "identity"]) { - assert.equal(field in tool.inputSchema.properties, false); - assert.equal(tool.description.includes(field), false); - } - assert.deepEqual(tool.inputSchema.required, ["language", "code"]); - assert.equal(tool.inputSchema.additionalProperties, false); - assert.match(tool.description, /configured by the application/); +import { Interpreter } from "../src/interpreter/index.ts"; +import { interpreterTool, toAnthropicTool, toOpenAITool, toToolDefinition, type ToolDefinition } from "../src/tools.ts"; + +type Reply = { body: unknown; status?: number }; +// Interpreter clients whose sandbox answers every request with `reply`; `requests` records envelopes. +function stubInterpreters(reply: Reply = { body: { stdout: "" } }) { + const requests: Array<{ url: string; body: any }> = []; + const fetch = (async (url: string, init?: RequestInit) => { + requests.push({ url, body: JSON.parse(String(init?.body)) }); + const body = typeof reply.body === "string" ? reply.body : JSON.stringify(reply.body); + return new Response(body, { status: reply.status ?? 200 }); + }) as typeof globalThis.fetch; + const python = Interpreter.python({ baseUrl: "http://py", fetch }); + const javascript = Interpreter.javascript({ baseUrl: "http://ts", fetch }); + return { requests, python, javascript }; +} + +const { python, javascript } = stubInterpreters(); +const tool = interpreterTool({ interpreters: { python, javascript } }); +const { inputSchema } = tool; +const json = toToolDefinition(tool); + +test("the derived JSON Schema and description match the reviewed golden output", async () => { + // Any drift in what the model sees fails here; update the fixture deliberately. + const { default: golden } = await import("./fixtures/interpreter-tool.json", { with: { type: "json" } }); + const configs = { + default: { python, javascript }, + python: { python }, + javascript: { javascript }, + "javascript,python": { javascript, python }, + }; + for (const [key, interpreters] of Object.entries(configs)) { + assert.deepStrictEqual(toToolDefinition(interpreterTool({ interpreters })), golden[key as keyof typeof golden], key); } }); -test("JavaScript tools retain program inputs and asynchronous execution guidance", () => { - const tool = interpreterTool({ 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/); +test("a single-language tool only describes and accepts that language", () => { + const pyTool = interpreterTool({ interpreters: { python } }); + const { properties } = toToolDefinition(pyTool).inputSchema; + assert.deepEqual(Object.keys(properties), ["language", "code", "input"]); + assert.equal(pyTool.inputSchema.safeParse({ language: "javascript", code: "1" }).success, false); + assert.equal(pyTool.inputSchema.safeParse({ language: "python", code: "1", dependencies: {} }).success, false); + assert.doesNotMatch(pyTool.description, /fetch rejects|lodash/); + + const jsTool = interpreterTool({ interpreters: { javascript } }); + assert.deepEqual(Object.keys(toToolDefinition(jsTool).inputSchema.properties), ["language", "code", "dependencies", "input"]); + assert.doesNotMatch(jsTool.description, /HttpRequestDenied|numpy/); +}); + +test("at least one interpreter is required", () => { + assert.throws(() => interpreterTool({ interpreters: {} }), /at least one interpreter/); +}); + +test("call() runs code with the application's policy and formats the output", async () => { + const stub = stubInterpreters({ body: { stdout: "42\n", stderr: "warn\n" } }); + const sandbox = interpreterTool({ + interpreters: { python: stub.python }, + policy: { allowedHosts: ["https://api.example.com"], kvEnabled: true, identity: "app" }, + }); + const output = await sandbox.call({ language: "python", code: "print(42)" }); + assert.deepEqual(output, { + content: "stdout:\n42\n\n\nstderr:\nwarn\n", + isError: false, + stdout: "42\n", + stderr: "warn\n", + error: null, + status: undefined, + }); + const [{ url, body }] = stub.requests; + assert.match(url, /^http:\/\/py\//); + assert.deepEqual(body.allowedHosts, ["https://api.example.com"]); + assert.equal(body.kvEnabled, true); + assert.equal(body.sandboxId, "app"); +}); + +test("call() returns invalid arguments to the model with the offending field", async () => { + const output = await tool.call({ language: "javascript", code: "1", dependencies: { marked: 11 } }); + assert.equal(output.isError, true); + assert.match(output.content, /dependencies\.marked/); + const policy = await tool.call({ language: "python", code: "1", allowedHosts: ["*"] }); + assert.equal(policy.isError, true); + assert.match(policy.content, /allowedHosts/); +}); + +test("run() reports code errors and transport failures as error output, not throws", async () => { + const failing = stubInterpreters({ body: { stdout: "", error: "NameError: x" } }); + const codeError = await interpreterTool({ interpreters: { python: failing.python } }).run({ language: "python", code: "x" }); + assert.equal(codeError.isError, true); + assert.equal(codeError.content, "error: NameError: x"); + + const down = stubInterpreters({ body: "bad gateway", status: 502 }); + const transport = await interpreterTool({ interpreters: { python: down.python } }).run({ language: "python", code: "1" }); + assert.equal(transport.isError, true); + assert.match(transport.content, /^error: sandbox error: .*502/); +}); + +test("run() returns a handler's HTTP response when input is supplied", async () => { + const stub = stubInterpreters({ body: "hello", status: 201 }); + const sandbox = interpreterTool({ interpreters: { javascript: stub.javascript } }); + const output = await sandbox.run({ language: "javascript", code: "export default {}", input: { path: "/x" } }); + assert.equal(output.content, "HTTP 201\nhello"); + assert.equal(output.status, 201); + assert.equal(stub.requests[0].body.input.path, "/x"); +}); + +test("execute() returns the model-facing text, as the Vercel AI SDK expects", async () => { + const stub = stubInterpreters({ body: { stdout: "ok" } }); + const sandbox = interpreterTool({ interpreters: { python: stub.python } }); + assert.equal(await sandbox.execute({ language: "python", code: "print('ok')" }), "stdout:\nok"); +}); + +test("the tool leaves execution policy to the application", () => { + for (const field of ["allowedHosts", "kvEnabled", "identity"]) { + assert.equal(field in json.inputSchema.properties, false); + assert.equal(json.description.includes(field), false); + } + assert.deepEqual(json.inputSchema.required, ["language", "code"]); + assert.equal(json.inputSchema.additionalProperties, false); + assert.match(json.description, /configured by the application/); + assert.equal("$schema" in json.inputSchema, false); }); -test("KV guidance describes sharing between runs rather than language or client reuse", () => { - for (const languages of [undefined, ["python"] as const, ["javascript"] as const]) { - const tool = interpreterTool({ languages }); - assert.match(tool.description, /same language or different languages/); - assert.match(tool.description, /not on reusing an Interpreter client object/); - assert.match(tool.description, /variables and globals do not carry over/); +test("the Zod schema rejects policy fields and unknown arguments", () => { + 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("HTTP guidance explains denied destinations using the runtime's actual errors", () => { - const python = interpreterTool({ languages: ["python"] }); - assert.match(python.description, /destination is not allowed/); - assert.match(python.description, /guard returns HttpRequestDenied/); - const javascript = interpreterTool({ languages: ["javascript"] }); - assert.match(javascript.description, /destination is not allowed, fetch rejects/); - assert.match(javascript.description, /runtime may report the generic error/); +test("the Zod schema validates model arguments", () => { + 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("the description carries the runtime guidance the model relies on", () => { + assert.match(JSON.stringify(json.inputSchema.properties.code), /Never leave floating promises/); + assert.match(json.description, /same language or different languages/); + assert.match(json.description, /not on reusing an Interpreter client object/); + assert.match(json.description, /variables and globals do not carry over/); + assert.match(json.description, /guard returns HttpRequestDenied/); + assert.match(json.description, /destination is not allowed, fetch rejects/); +}); + +test("withPolicy() merges a policy into a copy that shares the schema", async () => { + const stub = stubInterpreters({ body: { stdout: "" } }); + const base = interpreterTool({ + interpreters: { python: stub.python }, + policy: { allowedHosts: ["https://api.example.com"], identity: "app" }, + }); + const session = base.withPolicy({ identity: "session-1", kvEnabled: true }); + assert.equal(session.inputSchema, base.inputSchema); + assert.equal(toToolDefinition(session).inputSchema, toToolDefinition(base).inputSchema); + + await session.call({ language: "python", code: "1" }); + await base.call({ language: "python", code: "1" }); + const [derived, original] = stub.requests.map((r) => r.body); + assert.deepEqual([derived.sandboxId, derived.kvEnabled, derived.allowedHosts], ["session-1", true, ["https://api.example.com"]]); + assert.deepEqual([original.sandboxId, original.kvEnabled], ["app", false]); +}); + +test("JSON Schema conversion is cached per schema", () => { + assert.equal(toToolDefinition(tool).inputSchema, json.inputSchema); }); test("tool adapters support Anthropic and OpenAI shapes", () => { - const tool = interpreterTool({ languages: ["javascript"] }); - assert.deepEqual(toAnthropicTool(tool).input_schema, tool.inputSchema); + 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("anthropic.results() answers this tool's tool_use blocks and skips everything else", async () => { + const stub = stubInterpreters({ body: { stdout: "2" } }); + const sandbox = interpreterTool({ interpreters: { python: stub.python }, policy: { identity: "s1" } }); + assert.deepEqual(sandbox.anthropic.tool, toAnthropicTool(sandbox)); + const results = await sandbox.anthropic.results([ + { type: "text" }, + { type: "tool_use", id: "a", name: sandbox.name, input: { language: "python", code: "print(1+1)" } }, + { type: "tool_use", id: "b", name: "other_tool", input: {} }, + { type: "tool_use", id: "c", name: sandbox.name, input: { language: "python" } }, + ]); + assert.deepEqual(results.map((r) => [r.type, r.tool_use_id, r.is_error]), [ + ["tool_result", "a", false], + ["tool_result", "c", true], + ]); + assert.equal(results[0].content, "stdout:\n2"); + assert.match(results[1].content, /code/); + assert.equal(stub.requests.length, 1); + assert.equal(stub.requests[0].body.sandboxId, "s1"); +}); + +test("openai.results() parses JSON arguments and answers with tool messages", async () => { + const stub = stubInterpreters({ body: { stdout: "ok" } }); + const sandbox = interpreterTool({ interpreters: { python: stub.python } }); + assert.deepEqual(sandbox.openai.tool, toOpenAITool(sandbox)); + const messages = await sandbox.openai.results([ + { id: "1", type: "function", function: { name: sandbox.name, arguments: '{"language":"python","code":"1"}' } }, + { id: "2", type: "function", function: { name: sandbox.name, arguments: "{not json" } }, + { id: "3", type: "function", function: { name: "other_tool", arguments: "{}" } }, + ]); + assert.deepEqual(messages, [ + { role: "tool", tool_call_id: "1", content: "stdout:\nok" }, + { role: "tool", tool_call_id: "2", content: "error: tool arguments are not valid JSON" }, + ]); + assert.deepEqual(await sandbox.openai.results(undefined), []); +}); + +test("openaiResponses uses a non-strict tool and answers function_call items", async () => { + const stub = stubInterpreters({ body: { stdout: "ok" } }); + const sandbox = interpreterTool({ interpreters: { python: stub.python } }); + const { tool: responsesTool } = sandbox.openaiResponses; + assert.equal(responsesTool.strict, false); + assert.equal(responsesTool.name, sandbox.name); + assert.deepEqual(responsesTool.parameters, toToolDefinition(sandbox).inputSchema); + const outputs = await sandbox.openaiResponses.results([ + { type: "message" }, + { type: "function_call", call_id: "c1", name: sandbox.name, arguments: '{"language":"python","code":"1"}' }, + ]); + assert.deepEqual(outputs, [{ type: "function_call_output", call_id: "c1", output: "stdout:\nok" }]); +}); diff --git a/sdk/test/types.assert.ts b/sdk/test/types.assert.ts index 388affc..80571f9 100644 --- a/sdk/test/types.assert.ts +++ b/sdk/test/types.assert.ts @@ -32,3 +32,25 @@ itp.exec(["echo", "hi"]); // But the interpreter DOES have its scoped-KV power surface. void itp.kv("ns"); + +// The tool's languages and input type come from the interpreters it is given. +import { interpreterTool, type InterpreterToolInput } from "../src/tools.ts"; +const both = interpreterTool({ interpreters: { python: itp, javascript: itp } }); +const parsed: InterpreterToolInput = both.inputSchema.parse({}); +const lang: "python" | "javascript" = parsed.language; +void lang; +const deps: Record | undefined = parsed.dependencies; +void deps; +// @ts-expect-error execution policy is not a tool argument +void parsed.allowedHosts; +const pyOnly = interpreterTool({ interpreters: { python: itp } }); +// @ts-expect-error language is inferred as "python" from the interpreters given +const notPy: "javascript" = pyOnly.inputSchema.parse({}).language; +void notPy; +// @ts-expect-error a Python-only tool cannot run JavaScript +void pyOnly.run({ language: "javascript", code: "" }); +// @ts-expect-error a policy cannot smuggle in run options such as packageJson +void both.withPolicy({ packageJson: {} }); +// withPolicy keeps the tool's languages. +const pyAgain: "python" = pyOnly.withPolicy({ identity: "s" }).inputSchema.parse({}).language; +void pyAgain; diff --git a/templates/sandbox-app/content/README.md b/templates/sandbox-app/content/README.md index a85e5d5..9a0d7f3 100644 --- a/templates/sandbox-app/content/README.md +++ b/templates/sandbox-app/content/README.md @@ -7,7 +7,7 @@ A Spin application that scaffolds two **private** code sandboxes (JS/TS and Pyth | `ts-sandbox` | JavaScript / TS | `http://ts-sandbox.spin.internal` | | `py-sandbox` | Python | `http://py-sandbox.spin.internal` | -Neither has a public route, because they run untrusted code. Add your own component that calls them with `@spinframework/sandbox`, and add both hosts to its `allowed_outbound_hosts`: +Neither has a public route, because they run untrusted code. Add your own component that calls them with `@spinframework/spin-code-sandbox`, and add both hosts to its `allowed_outbound_hosts`: ```ts const js = new Interpreter({ baseUrl: "http://ts-sandbox.spin.internal" }); diff --git a/templates/sandbox-app/content/spin.toml b/templates/sandbox-app/content/spin.toml index 919f856..cd61163 100644 --- a/templates/sandbox-app/content/spin.toml +++ b/templates/sandbox-app/content/spin.toml @@ -13,7 +13,7 @@ description = "{{project-description}}" # Both components are PRIVATE (no public route): they run untrusted code and are reachable # only via service chaining from another component in this app. Add your own component that -# drives them through @spinframework/sandbox (see examples/ai-code-executor) and list +# drives them through @spinframework/spin-code-sandbox (see examples/ai-code-executor) and list # "http://ts-sandbox.spin.internal" / "http://py-sandbox.spin.internal" in its # `allowed_outbound_hosts`. diff --git a/templates/sandbox-py/content/spin.toml b/templates/sandbox-py/content/spin.toml index aab6ee5..670be0a 100644 --- a/templates/sandbox-py/content/spin.toml +++ b/templates/sandbox-py/content/spin.toml @@ -10,7 +10,7 @@ description = "{{project-description}}" # PRIVATE component: it runs untrusted code, so it has no public route and is reachable # only from other components in this app via service chaining. Add your own component that -# drives it through @spinframework/sandbox (see examples/ai-code-executor): +# drives it through @spinframework/spin-code-sandbox (see examples/ai-code-executor): # # const py = new Interpreter({ baseUrl: "http://{{project-name | kebab_case}}.spin.internal" }); # diff --git a/templates/sandbox-py/metadata/snippets/component.txt b/templates/sandbox-py/metadata/snippets/component.txt index 5f739a3..0378c6b 100644 --- a/templates/sandbox-py/metadata/snippets/component.txt +++ b/templates/sandbox-py/metadata/snippets/component.txt @@ -1,6 +1,6 @@ # Added as a PRIVATE component. It runs untrusted code, so it is only # reachable from other components in this app via service chaining -# (http://{{project-name | kebab_case}}.spin.internal), which is how @spinframework/sandbox +# (http://{{project-name | kebab_case}}.spin.internal), which is how @spinframework/spin-code-sandbox # is meant to consume it. Do not give it a public route. # # Add this to your calling component's `allowed_outbound_hosts`: diff --git a/templates/sandbox-ts/content/spin.toml b/templates/sandbox-ts/content/spin.toml index 23ed202..237517e 100644 --- a/templates/sandbox-ts/content/spin.toml +++ b/templates/sandbox-ts/content/spin.toml @@ -17,7 +17,7 @@ esm_base_url = { default = "https://esm.sh" } # This app scaffolds two PRIVATE building blocks: a JS/TS code sandbox and its dependency # bundler. Both are private (no public route) and reachable only via service chaining from # another component in this app. Add your own component that drives them through -# @spinframework/sandbox (see examples/ai-code-executor), or `spin add -t sandbox-ts` +# @spinframework/spin-code-sandbox (see examples/ai-code-executor), or `spin add -t sandbox-ts` # this pair into an existing app instead. The Interpreter wiring: # # const js = new Interpreter({ diff --git a/templates/sandbox-ts/metadata/snippets/component.txt b/templates/sandbox-ts/metadata/snippets/component.txt index a48a9c1..508f366 100644 --- a/templates/sandbox-ts/metadata/snippets/component.txt +++ b/templates/sandbox-ts/metadata/snippets/component.txt @@ -2,9 +2,9 @@ # PRIVATE (service-chained), so neither is publicly routable: the sandbox runs untrusted # code, and the bundler (experimental) fetches arbitrary npm from esm.sh. Keeping them # separate isolates the "fetch npm" capability from the "run untrusted code" capability. -# Reach them from your own component through @spinframework/sandbox: +# Reach them from your own component through @spinframework/spin-code-sandbox: # -# import { Interpreter } from "@spinframework/sandbox/interpreter"; +# import { Interpreter } from "@spinframework/spin-code-sandbox/interpreter"; # const js = new Interpreter({ # baseUrl: "http://{{project-name | kebab_case}}.spin.internal", # bundlerUrl: "http://{{project-name | kebab_case}}-bundler.spin.internal",