Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion examples/ai-code-executor/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions examples/ai-code-executor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

```
Expand All @@ -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 (`<component>.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.

Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions examples/ai-code-executor/api/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
});
39 changes: 29 additions & 10 deletions examples/ai-code-executor/api/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions examples/ai-code-executor/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
92 changes: 28 additions & 64 deletions examples/ai-code-executor/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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<RunOpts, "allowedHosts" | "kvEnabled"> = {
const EXECUTION_POLICY: ExecutionPolicy = {
allowedHosts: [],
kvEnabled: false,
};
Expand Down Expand Up @@ -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
Expand All @@ -77,13 +67,18 @@ async function runAgent(prompt: string, history: unknown, emit: Emit): Promise<v
const pyUrl = variables.get("py_interpreter_url") ?? "http://py-sandbox.spin.internal";
const bundlerUrl = variables.get("bundler_url") ?? "http://bundler.spin.internal";

// The interpreter is two private, service-chained components, one per language, so pick
// the client by the language the model chose. The JS interpreter also knows the bundler, so
// model code can pull extra npm dependencies (see the tool's `dependencies` field).
const interpreters: Record<Language, Interpreter> = {
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))}`);

Expand All @@ -101,29 +96,21 @@ async function runAgent(prompt: string, history: unknown, emit: Emit): Promise<v
// produced, instead of arriving in one buffered blob at the end of the turn.
const res = await llm.turn(
messages,
{ system: systemPrompt(), tools: [INTERPRETER_TOOL], maxTokens: 4096 },
{ system: systemPrompt(), tools, maxTokens: 4096 },
{ onText: (block, text) => emit({ t: "text_delta", block: `${turn}-${block}`, text }) },
);
const genMs = Date.now() - genStart;
log.info(`generate: turn=${turn} ${genMs}ms stop=${res.stop} in=${res.usage.input} out=${res.usage.output}`);

const toolResults: ToolResult[] = [];
for (const call of res.toolCalls) {
const input = call.input as {
language: Language;
code: string;
dependencies?: Record<string, string>;
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.
Expand All @@ -137,41 +124,18 @@ async function runAgent(prompt: string, history: unknown, emit: Emit): Promise<v
genMs,
});

let stdout = "";
let stderr = "";
let error: string | null = null;
let execMs = 0;
try {
const t = Date.now();
const runOpts = {
...EXECUTION_POLICY,
identity: sandboxId,
packageJson:
input.language === "javascript" && input.dependencies && Object.keys(input.dependencies).length
? { dependencies: input.dependencies }
: undefined,
};
if (input.input) {
const response = await interpreters[input.language].runHandler(input.code, input.input, runOpts);
stdout = `HTTP ${response.status}\n${await response.text()}`;
} else {
const r = await interpreters[input.language].execute(input.code, runOpts);
stdout = r.stdout;
stderr = r.stderr;
error = r.error ? `${r.error.name}: ${r.error.value}` : null;
}
execMs = Date.now() - t;
} catch (e: any) {
error = `sandbox error: ${String(e?.message ?? e)}`;
}
const t = Date.now();
const { content, isError, stdout, stderr, error, status } = await sandbox.run(input);
const execMs = Date.now() - t;
log.info(
`execute: sandbox=wasm_interpreter lang=${input.language} exec=${execMs}ms ` +
`${error ? "error=" + JSON.stringify(error) : "ok"} stdout=${stdout.length}b`,
);

// Stream the output the moment the sandbox returns.
emit({ t: "tool_end", id, execMs, stdout, stderr, error });
toolResults.push({ id: call.id, content: formatToolResult(stdout, stderr, error), isError: error !== null });
const shown = status === undefined ? stdout : `HTTP ${status}\n${stdout}`;
emit({ t: "tool_end", id, execMs, stdout: shown, stderr, error });
toolResults.push({ id: call.id, content, isError });
}

if (res.toolCalls.length === 0) {
Expand Down
2 changes: 1 addition & 1 deletion examples/ai-code-executor/api/src/llm/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down
3 changes: 2 additions & 1 deletion examples/ai-code-executor/api/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"allowImportingTsExtensions": true,
"noEmit": true,
"paths": {
"#llm-provider": ["./src/llm/anthropic.ts"]
"#llm-provider": ["./src/llm/anthropic.ts"],
"zod": ["./node_modules/zod"]
}
},
"include": [
Expand Down
2 changes: 2 additions & 0 deletions examples/ai-code-executor/ui/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions examples/ai-code-executor/ui/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"name": "ui",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0 WITH LLVM-exception",
"type": "module",
Expand Down
4 changes: 2 additions & 2 deletions examples/app-builder/AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# AGENTS.md: App Builder example

A Spin app where an LLM generates a self-contained web app (one HTTP handler), stores
the code via [`@spinframework/sandbox`](../../sdk), and serves each stored app live at
the code via [`@spinframework/spin-code-sandbox`](../../sdk), and serves each stored app live at
`/a/<id>/`. See [README.md](README.md) for the full picture; this covers the layout and
the invariants.

Expand All @@ -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 (`<base>` injection,
crash page, hardening headers).
- **`ui/`** (public `/...`): a Nuxt SPA served by the Spin static fileserver: a gallery
Expand Down
4 changes: 2 additions & 2 deletions examples/app-builder/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading