The Open Framework for Building Agents
refactor(sandbox): run core on the public provider contract and add workspace roots (#5284)
Andrew Barba00aa593595b2
diff --git a/.changeset/sandbox-core-public-provider-contract.md b/.changeset/sandbox-core-public-provider-contract.mdnew file mode 100644index 000000000..6c6e59dd5--- /dev/null+++ b/.changeset/sandbox-core-public-provider-contract.md@@ -0,0 +1,5 @@+---+"eve": patch+---++eve now runs every sandbox provider, including `DefaultSandbox`, directly on the public `defineSandboxProvider()` contract, and calls `connection.close()` when the step that opened a connection ends, so the next step resumes through a new connection. Server shutdown stops only connections eve still holds, so a custom provider that defines `close()` and runs remote compute should bound idle compute itself, for example with an idle timeout.diff --git a/.changeset/sandbox-workspace-root-paths.md b/.changeset/sandbox-workspace-root-paths.mdnew file mode 100644index 000000000..c739d33e6--- /dev/null+++ b/.changeset/sandbox-workspace-root-paths.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Custom sandbox providers can declare `workspaceRoot` on a connection, and eve resolves relative paths, the default working directory, `resolvePath(".")`, and build-time workspace seeding from it; built-in providers keep `/workspace`. The `read_file`, `write_file`, `glob`, and `grep` tools now accept paths relative to the workspace root, and the workspace and skills prompt sections no longer name `/workspace`.diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.mdindex db85aa587..594882b2b 100644--- a/docs/concepts/built-in-tools.md+++ b/docs/concepts/built-in-tools.md@@ -81,7 +81,7 @@ export default disableTool();### `read_file`-`read_file` reads text files from the sandbox with line-numbered output, and shows PNG, JPEG, GIF, and WebP images up to 3 MiB and 8000 pixels per side, and PDFs up to 20 MiB, to the model as files. Images and PDFs are detected from their bytes, so a missing or mismatched filename extension does not matter, and other text files are always read as text. It accepts absolute paths and paths beginning with `$HOME/`.+`read_file` reads text files from the sandbox with line-numbered output, and shows PNG, JPEG, GIF, and WebP images up to 3 MiB and 8000 pixels per side, and PDFs up to 20 MiB, to the model as files. Images and PDFs are detected from their bytes, so a missing or mismatched filename extension does not matter, and other text files are always read as text. It accepts absolute paths, paths relative to the workspace root where `bash` commands start, and paths beginning with `$HOME/`. Results and errors name the resolved absolute path.```sheve add tool/read_file@@ -113,7 +113,7 @@ export default disableTool();### `write_file`-`write_file` writes complete files in the sandbox. It enforces read-before-write and stale-read detection, and accepts absolute paths and paths beginning with `$HOME/`.+`write_file` writes complete files in the sandbox. It enforces read-before-write and stale-read detection, and accepts the same paths as `read_file`.```sheve add tool/write_file@@ -131,10 +131,15 @@ import { writeFile } from "eve/tools/write_file";export default defineTool({...writeFile,- description: "Write approved project files in the sandbox.",+ description: "Write notes in the sandbox's notes directory.",async execute(input, ctx) {- if (!input.filePath.startsWith("/workspace/")) {- throw new Error("write_file is limited to /workspace");+ const sandbox = await ctx.getSandbox();+ const notes = `${sandbox.resolvePath("notes")}/`;+ if (+ input.filePath.startsWith("$HOME") ||+ !sandbox.resolvePath(input.filePath).startsWith(notes)+ ) {+ throw new Error("write_file is limited to the notes directory");}return writeFile.execute(input, ctx);},@@ -374,7 +379,7 @@ export default askQuestion();### `glob`-`glob` finds sandbox files by glob pattern. Add it:+`glob` finds sandbox files by glob pattern. It searches the workspace root unless the model passes a directory, which accepts the same paths as `read_file`. Add it:```sheve add tool/glob@@ -400,7 +405,7 @@ Remove the file to remove the tool. `disableTool()` is unnecessary because `glob### `grep`-`grep` searches sandbox file contents with a regular expression. Add it:+`grep` searches sandbox file contents with a regular expression. It searches the workspace root unless the model passes a directory or file, which accepts the same paths as `read_file`. Add it:```sheve add tool/grepdiff --git a/docs/reference/agent-files.md b/docs/reference/agent-files.mdindex 7378d5cc5..5999a4b6a 100644--- a/docs/reference/agent-files.md+++ b/docs/reference/agent-files.md@@ -59,7 +59,7 @@ Paths below are relative to the agent directory. Root agents can use every path;| `lib/` | Shared authored helper code | Yes | Import-only; not copied into the sandbox. || `memory.ts` or `memory/<name>.ts` | Cross-session memory | Yes | Provider-backed slots. See [Memory](/docs/memory). || `sandbox.ts` or `sandbox/sandbox.ts` | The agent's sandbox | Yes | The framework default applies when neither is authored. When `sandbox/` exists, only `sandbox/sandbox.ts` is read. |-| `sandbox/workspace/**` | Files seeded into the sandbox | Yes | Copied into the prepared environment; each new session sandbox starts with them in `/workspace/`. |+| `sandbox/workspace/**` | Files seeded into the sandbox | Yes | Copied into the prepared environment; each new session sandbox starts with them in the workspace root. || `tools/` | Typed executable integrations | Yes | Module-backed only. || `schedules/` | Recurring jobs | No | `defineSchedule` modules or Markdown prompts with `cron` frontmatter; recursive nesting is supported. || `subagents/` | Specialist child agents | Yes | Local directories or remote-agent definitions; nested subagents are supported. |@@ -82,7 +82,7 @@ Explicit imports, sandbox workspace files, and packaged skill resources are unaf## Files available in the sandbox-Agent source files are not automatically available to shell commands. Put files to copy into the sandbox's `/workspace/` under `agent/sandbox/workspace/`. Skill runtime files are seeded separately under `$HOME/.agents/skills/`, with `/workspace/skills/` as the fallback when the sandbox has no usable `$HOME`. See [Sandboxes](/docs/sandbox) and [Skills](/docs/skills).+Agent source files are not automatically available to shell commands. Put files to copy into the sandbox's workspace root (`/workspace/` on built-in providers) under `agent/sandbox/workspace/`. Skill runtime files are seeded separately under `$HOME/.agents/skills/`, with `skills/` under the workspace root as the fallback when the sandbox has no usable `$HOME`. See [Sandboxes](/docs/sandbox) and [Skills](/docs/skills).## Local subagentsdiff --git a/docs/sandbox/custom-providers.mdx b/docs/sandbox/custom-providers.mdxindex 2c4e1370c..9b2283c87 100644--- a/docs/sandbox/custom-providers.mdx+++ b/docs/sandbox/custom-providers.mdx@@ -116,10 +116,15 @@ A `SandboxConnection` is the byte-level link to one sandbox. Each method has a f- `writeFiles({ files, abortSignal })` writes every file, creating missing parent directories and overwriting existing files. It is the only write primitive.- `removePath({ path, force, recursive, abortSignal })` removes a file or directory. `force` ignores a missing path, and `recursive` removes a non-empty directory.- `stop()` releases compute and keeps the sandbox's files.-- `close()` is optional. It releases what this process holds for the connection, such as a local interpreter, without touching the sandbox. eve calls it whenever it lets go of a connection: after `stop()`, before deletion and terminal cleanup, and when a keyed call ends.+- `close()` is optional. It releases what this process holds for the connection, such as a local interpreter or child processes, without touching the sandbox. eve calls it whenever it lets go of a connection: when the step that opened it ends, after `stop()`, and before deletion. A connection lasts at most one step, so the next step resumes the sandbox through a new connection.- `extensions` is optional. It is a plain object whose own properties eve merges onto the session, such as `setNetworkPolicy()`. Use closures rather than class methods, because eve does not copy inherited members.+- `workspaceRoot` is optional. It is the session's workspace root: the absolute sandbox directory where commands start by default. It defaults to `/workspace`, which every built-in provider uses. Set it when your sandbox keeps its working files somewhere else, such as `/home/user/project`. The directory must exist before eve runs a command in it.-Every path a connection receives is absolute, and `workingDirectory` is always set. eve resolves relative paths and a missing or relative working directory from `/workspace` before it calls the connection.+Every path a connection receives is absolute, and `workingDirectory` is always set. eve resolves relative paths and a missing or relative working directory from the workspace root before it calls the connection, and `session.resolvePath(".")` returns the root. The built-in file tools, attachment staging, and GitHub checkouts use the same root. eve throws when it opens a connection whose `workspaceRoot` is not absolute:++```text+Sandbox connection workspaceRoot must be an absolute path, but received "project".+```eve builds the rest of the session from these methods: `run()` over `spawn()`, the binary and text read and write variants, encodings and line ranges, `writeFiles()`, `resolvePath()`, and abort-signal binding. An extension member named like a session method, or `stop` or `delete`, is a type error, and eve throws when it opens the connection:@@ -133,17 +138,18 @@ Type the connection with its extensions, such as `SandboxConnection<{ setNetworkeve calls the lifecycle methods at these points:-| When | eve calls |-| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `eve build`, or the first sandbox access in `eve dev` | `prepare(ctx)`, and stores the artifact it returns with the deployment |-| The first sandbox access in a session | `start(ctx, options, artifact)` from `environment.open(options)` in the selector |-| A later workflow step or process | `resume(ctx, artifact, state)` |-| `sandbox.stop()` | `connection.stop()`, then `connection.close()` |-| `sandbox.delete()` | `connection.close()`, then `onSessionEnd(ctx, state, { reason: "deleted" })` |-| The eve server shuts down | `connection.stop()`, then `connection.close()`, on every open session connection; eve logs failures and does not throw them |-| The owning session reaches a terminal outcome | `connection.close()` on this process's connections for the session, then `onSessionEnd(ctx, state, { reason })` with `"completed"`, `"expired"`, or `"failed"` |+| When | eve calls |+| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `eve build`, or the first sandbox access in `eve dev` | `prepare(ctx)`, and stores the artifact it returns with the deployment |+| The first sandbox access in a session | `start(ctx, options, artifact)` from `environment.open(options)` in the selector |+| A later workflow step or process | `resume(ctx, artifact, state)` |+| The step that opened a connection ends | `connection.close()`, for a turn's step, a `"use step"` function, or an `invokeTool` call |+| `sandbox.stop()` | `connection.stop()`, then `connection.close()` |+| `sandbox.delete()` | `connection.close()`, then `onSessionEnd(ctx, state, { reason: "deleted" })` |+| The eve server shuts down | `connection.stop()`, then `connection.close()`, on every connection eve still holds: any connection mid-step, and between steps a connection without `close()`; eve logs failures and does not throw them |+| The owning session reaches a terminal outcome | `connection.close()` on a connection the ending step still holds, then `onSessionEnd(ctx, state, { reason })` with `"completed"`, `"expired"`, or `"failed"` |-eve calls `close()` at most once per connection, retrying only after a failure. `stop()` can run again after the session uses a stopped connection, so make it a no-op when the sandbox is already stopped. A failed `close()` never prevents `onSessionEnd()` from deleting the sandbox.+eve calls `close()` at most once per connection, retrying only after a failure. After a turn's step ends, eve keeps a connection without `close()` registered, so server shutdown still stops the session's sandbox. eve lets go of a connection with `close()` at the end of its step or after `stop()`, so server shutdown between steps does not stop that sandbox. If your provider defines `close()` and runs remote compute, bound idle compute yourself, for example with an idle timeout. `stop()` can run again after the session uses a stopped connection, so make it a no-op when the sandbox is already stopped. A failed `close()` never prevents `onSessionEnd()` from deleting the sandbox.### `prepare()`@@ -173,7 +179,7 @@ Validate the shape of your own state in `resume()`. When you change it incompati## Bake files into templates-Call `ctx.populate(connection)` on the build instance before you capture it. `populate()` writes the agent's workspace files to `/workspace` and its skill files to `$HOME/.agents/skills` in one `writeFiles()` batch, then runs the authored `prepare` callback with a session over the same connection. eve finds `$HOME` by running a command through `spawn()`. When the sandbox has no usable home directory, skills go to `/workspace/skills`.+Call `ctx.populate(connection)` on the build instance before you capture it. `populate()` writes the agent's workspace files to the connection's workspace root and its skill files to `$HOME/.agents/skills` in one `writeFiles()` batch, then runs the authored `prepare` callback with a session over the same connection. eve finds `$HOME` by running a command through `spawn()`. When the sandbox has no usable home directory, skills go to `skills/` under the workspace root.A provider that can mount host directories can avoid writing every file. `ctx.resourcesDirectory()` resolves to a stable read-only host directory that contains `workspace/` and `skills/`, or to `undefined` when there is none. Mount it in the build instance and pass its sandbox path:@@ -189,7 +195,7 @@ await ctx.populate();```-With `mountedAt`, `populate()` copies `<mountedAt>/workspace/.` into `/workspace` and `<mountedAt>/skills/.` into `$HOME/.agents/skills` with `cp -a`. When eve has no resource directory, `populate()` ignores `mountedAt` and writes the files instead.+With `mountedAt`, `populate()` copies `<mountedAt>/workspace/.` into the workspace root and `<mountedAt>/skills/.` into `$HOME/.agents/skills` with `cp -a`. When eve has no resource directory, `populate()` ignores `mountedAt` and writes the files instead.`ctx.templateKey(identity)` returns a SHA-256 hex key that changes whenever `identity`, the workspace files, the skill files, or the sandbox file's source changes. Pass every option that affects the template, such as the base image, and use the key to name or look up a cached template. `identity` accepts JSON values, `undefined` (omitted), plain objects and arrays, and functions (hashed by their source). `resources` and `sourceRevision` are reserved, and eve throws if `identity` sets either one. The source revision covers only the sandbox file, so a `prepare` callback imported from another module does not change the key.diff --git a/docs/sandbox/index.mdx b/docs/sandbox/index.mdxindex a23f42e74..c5d008ce0 100644--- a/docs/sandbox/index.mdx+++ b/docs/sandbox/index.mdx@@ -3,7 +3,7 @@ title: "Sandbox"description: "Configure the isolated filesystem and command environment used by an eve agent."----Every eve agent has one sandbox rooted at `/workspace`. The built-in `bash`, `read_file`, and `write_file` tools use it. Without an authored sandbox file, eve selects the best available environment automatically.+Every eve agent has one sandbox. Its workspace root, where commands start and relative paths resolve from, is `/workspace` on every built-in provider. The built-in `bash`, `read_file`, and `write_file` tools use it. Without an authored sandbox file, eve selects the best available environment automatically.## Use the sandbox@@ -26,7 +26,7 @@ export default defineTool({});```-Relative paths resolve under `/workspace`. `run()` returns `{ exitCode, stdout, stderr }`; a nonzero exit code does not throw automatically. Use `spawn()` for a long-running process.+Relative paths resolve from the workspace root, and `sandbox.resolvePath(".")` returns its absolute path. `run()` returns `{ exitCode, stdout, stderr }`; a nonzero exit code does not throw automatically. Use `spawn()` for a long-running process.Built-in environments set `AI_AGENT=eve` on every `run()` and `spawn()` call, including the `bash` tool and `prepare`, so agent-aware CLIs such as `vercel` skip interactive prompts. To use a different value, set `AI_AGENT` in the environment's `env` option or pass it in the `env` of one `run()` or `spawn()` call.@@ -128,33 +128,13 @@ agent/sandbox/Files under `agent/sandbox/workspace/` seed writable `/workspace`. eve copies the seed into the prepared environment when it prepares a new environment generation, and each new session sandbox starts from that copy. Existing live sandbox state is not overwritten by later seed changes.-Agent skills are compiled into a separate resource tree and exposed at `$HOME/.agents/skills`. These are stable paths across every built-in provider, so instructions and tools can refer to `/workspace` and `$HOME/.agents/skills`. eve resolves `$HOME` by reading it inside the sandbox; when a sandbox has no usable home directory, skill paths fall back to `/workspace/skills`. Do not refer to a concrete home directory or `/eve/resources`, which is provider-internal staging.+Agent skills are compiled into a separate resource tree and exposed at `$HOME/.agents/skills`. These are stable paths across every built-in provider, so instructions and tools can refer to `/workspace` and `$HOME/.agents/skills`. A [custom provider](/docs/sandbox/custom-providers) can declare a different workspace root, so prefer relative paths in code that runs on any provider. eve resolves `$HOME` by reading it inside the sandbox; when a sandbox has no usable home directory, skill paths fall back to `skills/` under the workspace root. Do not refer to a concrete home directory or `/eve/resources`, which is provider-internal staging.-Providers receive both trees with explicit metadata. `source.kind` is `"none"` when the agent has no managed workspace or skill files, `"materialized"` when eve has also written the compiled files to the host directory at `path`, and `"inline"` when the contents are available only in each tree's `files`:--```ts-interface SandboxProviderResources {- source:- | { kind: "none" }- | { kind: "inline"; key: string }- | { kind: "materialized"; key: string; path: string };- workspace?: SandboxProviderResourceTree;- skills?: SandboxProviderResourceTree;-}--interface SandboxProviderResourceTree {- key: string;- files: SandboxProviderResourceFile[];- mountPath: string;- targetPath: string;-}-```--Docker mounts the compiled trees read-only under `/eve/resources`, copies workspace seeds into writable `/workspace`, and exposes skills read-only where possible. Vercel's snapshot environment writes workspace and skill contents before capturing its snapshot. Custom providers decide whether to upload, mount, or write each tree, but must expose the final target paths before authored preparation runs.+Docker mounts the compiled trees read-only under `/eve/resources` and copies them into place. Vercel Sandbox writes workspace and skill files into the build sandbox before capturing its snapshot. A custom provider seeds both trees with `ctx.populate()` when it prepares a template; see [Bake files into templates](/docs/sandbox/custom-providers#bake-files-into-templates).## Inbound attachments-eve writes byte-backed files that reach the agent into the sandbox under `/workspace/.eve/attachments/` and keeps only a reference in session history. This covers files attached to user messages and files that tools return to the model with `toolOutputPart.file` or as MCP image, audio, and blob content.+eve writes byte-backed files that reach the agent into the sandbox under `.eve/attachments/` in the workspace root (`/workspace/.eve/attachments/` on built-in providers) and keeps only a reference in session history. This covers files attached to user messages and files that tools return to the model with `toolOutputPart.file` or as MCP image, audio, and blob content.Files that tools return by URL with `toolOutputPart.fileUrl` are not staged: the model provider reads the URL directly. See [Send a file by URL](/docs/tools#send-a-file-by-url).diff --git a/docs/skills.mdx b/docs/skills.mdxindex 030f1a26a..8d3a843c3 100644--- a/docs/skills.mdx+++ b/docs/skills.mdx@@ -9,7 +9,7 @@ A skill is a model-loadable procedure that follows the `SKILL.md` convention. Iteve scans the files under `agent/skills/` and lists each one's name and description in the system prompt. When a request matches a skill's description (or you name the skill outright), the model loads it with `eve__skill({ name })`, and the skill's markdown becomes the call's result in the active turn. An agent with skills always has the [`eve__skill` tool](./concepts/built-in-tools#eve__search-eve__tool-and-eve__skill). A load reports a `load-skill` action named for the skill, and `t.loadedSkill` asserts it in [evals](./evals/assertions).-Listing skills and loading their instructions do not require a sandbox: loading returns static instructions from the compiled agent and dynamic instructions from session state. Only access to supporting package files requires a sandbox. Builds may also prewarm sandbox templates that contain static package files. Supporting files are available under `$HOME/.agents/skills/<skill>/`, with `/workspace/skills/<skill>/` as the fallback when `$HOME` is unavailable. Sibling references inside `SKILL.md`, such as `references/checklist.md`, are relative to the directory containing that specific `SKILL.md`.+Listing skills and loading their instructions do not require a sandbox: loading returns static instructions from the compiled agent and dynamic instructions from session state. Only access to supporting package files requires a sandbox. Builds may also prewarm sandbox templates that contain static package files. Supporting files are available under `$HOME/.agents/skills/<skill>/`, with `skills/<skill>/` under the workspace root as the fallback when `$HOME` is unavailable. Sibling references inside `SKILL.md`, such as `references/checklist.md`, are relative to the directory containing that specific `SKILL.md`.The description is a routing hint, not a label. Write it as the task that should trigger activation:diff --git a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts b/e2e/fixtures/agent-compaction-regressions/agent/agent.tsindex 5e2b1e4bf..5d0e27460 100644--- a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts+++ b/e2e/fixtures/agent-compaction-regressions/agent/agent.ts@@ -18,14 +18,14 @@ import { HANDOFF_REFERENCE, REVIEW_REFERENCE } from "../release-reports";const TEST_CONTEXT_WINDOW_TOKENS = 32_000;// eve estimates this fixture's request envelope (instructions, task system// block, and 10 advertised tools; with nothing deferred and no skills or-// connections, the agent has no catalog tools) at 2,273+// connections, the agent has no catalog tools) at 2,311.5// tokens. This allowance sits 230.25 tokens below that estimate, the offset the// cases have always run with, so the threshold leaves them a ~670-token history// budget. When eve's fixed instructions or tools change, re-measure: log what// `estimateRequestEnvelope` (packages/eve/src/harness/request-envelope.ts)// returns while `EVE_E2E_MODEL=mock pnpm exec eve eval --strict// content-output-file-stub` runs in this fixture, subtract 230.25, and round up.-const TEST_REQUEST_ENVELOPE_TOKENS = 2_043;+const TEST_REQUEST_ENVELOPE_TOKENS = 2_082;// Fit the capped file-output exchange, while forcing the larger review and// handoff reports into the assistant checkpoint consumed by the script.const TEST_HISTORY_BUDGET_TOKENS = 900;diff --git a/e2e/fixtures/agent-mcp/agent/tools/read_note.ts b/e2e/fixtures/agent-mcp/agent/tools/read_note.tsindex fdc4eef49..4ca0ba672 100644--- a/e2e/fixtures/agent-mcp/agent/tools/read_note.ts+++ b/e2e/fixtures/agent-mcp/agent/tools/read_note.ts@@ -8,6 +8,10 @@ export default defineTool({inputSchema: z.object({}),async execute(_input, ctx) {const sandbox = await ctx.getSandbox();- return { text: await sandbox.readTextFile({ path: NOTE_PATH }) };+ // `write_note` writes through the file API; reading through the shell+ // proves both resolve the relative path from the same workspace root.+ const result = await sandbox.run({ command: `cat ${NOTE_PATH}` });+ if (result.exitCode !== 0) throw new Error(`Reading the note failed: ${result.stderr}`);+ return { text: result.stdout };},});diff --git a/e2e/fixtures/agent-mcp/fixture.ts b/e2e/fixtures/agent-mcp/fixture.tsindex 4d06e657c..b287f8704 100644--- a/e2e/fixtures/agent-mcp/fixture.ts+++ b/e2e/fixtures/agent-mcp/fixture.ts@@ -22,7 +22,7 @@ export const MCP_PATH = "/eve/v1/mcp";export const DESTRUCTIVE_DENIAL = "The front desk does not run tools the server marks destructive.";/** Where the note tools keep the front-desk note in the sandbox. */-export const NOTE_PATH = "/workspace/front-desk-note.txt";+export const NOTE_PATH = "front-desk-note.txt";/** This deployment's MCP channel, the way `kennelUrl()` reaches its own kennel. */export function selfMcpUrl(): string {diff --git a/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts b/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.tsindex 068cc37db..e876c9abd 100644--- a/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts+++ b/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts@@ -26,6 +26,9 @@ export function respond(request: MockModelRequest): MockModelResponse | string {if (message.includes("EVE_SANDBOX_BASH_JOB")) {return respondToBashJob(message, request);}+ if (message.includes("EVE_SANDBOX_FILE_TOOLS")) {+ return respondToFileTools(message, request);+ }if (message.includes("DYNAMIC-TURN-REPLAY-START")) {const gate = request.toolResults.find((result) => result.name === "dynamic-turn-replay-gate");if (gate === undefined) {@@ -110,6 +113,23 @@ function respondToBashJob(message: string, request: MockModelRequest): MockModelreturn "index job stopped";}+/** Writes, reads, greps, and cats the note by the relative paths the prompt names. */+function respondToFileTools(+ message: string,+ request: MockModelRequest,+): MockModelResponse | string {+ const [, path = "", content = ""] =+ /create (\S+) with exactly this content: (\S+)/u.exec(message) ?? [];+ const steps = [+ { input: { content, filePath: path }, name: "write_file" },+ { input: { filePath: path }, name: "read_file" },+ { input: { path: "notes", pattern: content }, name: "grep" },+ { input: { command: `cat ${path}` }, name: "bash" },+ ];+ const next = steps[request.toolResults.length];+ return next === undefined ? bashStdout(request) : { toolCalls: [next] };+}+/** The `[Tasks]` note and `<task_result>` messages are eve's, not the user's. */function isFrameworkMessage(text: string): boolean {const trimmed = text.trim();diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.tsindex b3752b51a..7b1c750cf 100644--- a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/sandbox.ts@@ -8,6 +8,8 @@ import {} from "eve/sandbox/provider";export const CUSTOM_PROVIDER_TOKEN = "custom-provider-session-ok-P7M";+/** The machine keeps its working files outside eve's default `/workspace`. */+export const CUSTOM_WORKSPACE_ROOT = "/srv/app";/*** One in-memory machine per session, standing in for a remote sandbox@@ -96,6 +98,7 @@ function connect(sessionId: string, machine: Machine): SandboxConnection<CustomEfor (const file of removed) machine.files.delete(file);},async stop() {},+ workspaceRoot: CUSTOM_WORKSPACE_ROOT,extensions: {machineId: () => machine.id,probe: async () => `${CUSTOM_PROVIDER_TOKEN}:${sessionId}`,diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/verify-provider-session.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/verify-provider-session.tsindex fea879509..ebaf1201d 100644--- a/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/verify-provider-session.ts+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/custom-provider/tools/verify-provider-session.ts@@ -1,11 +1,23 @@import { defineTool } from "eve/tools";import { z } from "zod";+import { CUSTOM_WORKSPACE_ROOT } from "../sandbox.js";+export default defineTool({- description: "Reads the marker initialized through the custom provider session method.",+ description:+ "Reads the session marker and leaves Bob a checklist in the custom provider's workspace.",inputSchema: z.object({}),async execute(_input, ctx) {const sandbox = await ctx.getSandbox();- return await sandbox.readTextFile({ path: "/workspace/probe.txt" });+ const checklist = "Bob, the checklist is ready.";+ await sandbox.writeTextFile({ content: checklist, path: "handoff/checklist.txt" });+ return {+ checklist: await sandbox.readTextFile({ path: "handoff/checklist.txt" }),+ checklistAtRoot: await sandbox.readTextFile({+ path: `${CUSTOM_WORKSPACE_ROOT}/handoff/checklist.txt`,+ }),+ probe: await sandbox.readTextFile({ path: `${CUSTOM_WORKSPACE_ROOT}/probe.txt` }),+ root: sandbox.resolvePath("."),+ };},});diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/prepare_note.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/prepare_note.tsindex 07a732598..52af96887 100644--- a/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/prepare_note.ts+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/prepare_note.ts@@ -20,7 +20,7 @@ async function prepareNote(ctx: WorkflowStepToolContext) {// Writing the whole file keeps a retried step's write the same.await sandbox.writeTextFile({content: "step-sandbox-note-ok-H3R:prepared-in-step",- path: "/workspace/step-note.txt",+ path: "step-note.txt",});return "prepared";}diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/read_note.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/read_note.tsindex 9e33db347..9e6e8212f 100644--- a/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/read_note.ts+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/read_note.ts@@ -6,6 +6,6 @@ export default defineTool({inputSchema: z.object({}),async execute(_input, ctx) {const sandbox = await ctx.getSandbox();- return await sandbox.readTextFile({ path: "/workspace/step-note.txt" });+ return await sandbox.readTextFile({ path: "step-note.txt" });},});diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.tsindex 31dab1be6..146afa24b 100644--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.ts+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/custom-provider-session.eval.ts@@ -1,18 +1,38 @@import { defineEval } from "eve/evals";-import { includes } from "eve/evals/expect";+import { equals, includes } from "eve/evals/expect";const TOKEN = "custom-provider-session-ok-P7M";+const WORKSPACE_ROOT = "/srv/app";+const CHECKLIST = "Bob, the checklist is ready.";export default defineEval({- description: "Sandbox: custom provider session methods survive framework lifecycle wrapping.",+ description:+ "Sandbox: custom provider session methods survive framework lifecycle wrapping, and paths resolve from the connection's workspace root.",async test(t) {const turn = await t.send(- "Ask the `custom-provider` subagent with message: Verify the custom provider session marker.",+ "Ask the `custom-provider` subagent with message: Verify the custom provider session marker and leave Bob his checklist.",);turn.expectOk();+ const started = turn.events.find(+ (event) => event.type === "agent.started" && event.data.name === "custom-provider",+ );+ if (started?.type !== "agent.started") {+ throw new Error("The turn did not call the custom-provider subagent.");+ }+ const child = (await t.target.watchTurn(started.data.sessionId).result()).expectOk();t.succeeded();t.calledSubagent("custom-provider", { count: 1, status: "completed" });- t.check(turn.message, includes(TOKEN));+ const verified = child.requireToolCall("verify-provider-session").output as {+ checklist: string | null;+ checklistAtRoot: string | null;+ probe: string | null;+ root: string;+ };+ // The selector's relative write and the tool's relative round trip land under the connection's root.+ t.check(verified.root, equals(WORKSPACE_ROOT));+ t.check(verified.probe, includes(TOKEN));+ t.check(verified.checklist, equals(CHECKLIST));+ t.check(verified.checklistAtRoot, equals(CHECKLIST));},});diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/file-tools.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/file-tools.eval.tsindex 18410e1a4..85e9e1087 100644--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/file-tools.eval.ts+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/file-tools.eval.ts@@ -1,29 +1,34 @@import { defineEval } from "eve/evals";-// The default `write_file` tool and opt-in framework `grep` tool both target-// the sandbox filesystem. Writing a unique token with `write_file`, then-// locating it with `grep`, proves they operate on the same `/workspace` as-// `bash`.+// The file tools resolve relative paths from the workspace root, where `bash`+// commands start. A note written and read back by relative path, found by+// `grep` under a relative directory, and printed by `cat` from the default+// working directory proves all four tools share one root.const FILE_TOOLS_TOKEN = "sandbox-file-tools-ok-Q2H";-const FILE_TOOLS_PATH = "/workspace/file-tools-note.txt";+const FILE_TOOLS_PATH = "notes/handoff.txt";export default defineEval({- tags: ["real-model"],- description: "Sandbox: write_file and opt-in grep operate on the sandbox filesystem.",+ description: "Sandbox: file tools and bash resolve relative paths from one workspace root.",async test(t) {await t.send([- `Use the write_file tool to create the file ${FILE_TOOLS_PATH} with exactly this content: ${FILE_TOOLS_TOKEN}`,- `Then use the grep tool to search for ${FILE_TOOLS_TOKEN} under /workspace.`,- "Reply with the matching line verbatim.",+ "EVE_SANDBOX_FILE_TOOLS",+ "Alice is leaving a handoff note for Bob in the workspace.",+ `Use the write_file tool to create ${FILE_TOOLS_PATH} with exactly this content: ${FILE_TOOLS_TOKEN}`,+ `Then read ${FILE_TOOLS_PATH} back with the read_file tool.`,+ `Then use the grep tool to search for ${FILE_TOOLS_TOKEN} in notes.`,+ `Finally, run the bash command \`cat ${FILE_TOOLS_PATH}\` and reply with its output verbatim.`,].join("\n"),);t.succeeded();- t.calledTool("write_file");- t.calledTool("grep", {- output: new RegExp(FILE_TOOLS_TOKEN),- });+ t.calledTool("write_file", { output: { path: /^\/.+\/notes\/handoff\.txt$/u } });+ // The scripted model runs every step; a live model may skip the read-back and search.+ if (process.env.EVE_E2E_MODEL === "mock") {+ t.calledTool("read_file", { output: { content: new RegExp(FILE_TOOLS_TOKEN) } });+ t.calledTool("grep", { output: new RegExp(FILE_TOOLS_TOKEN) });+ }+ t.calledTool("bash", { output: { stdout: new RegExp(FILE_TOOLS_TOKEN) } });t.messageIncludes(FILE_TOOLS_TOKEN);},});diff --git a/e2e/fixtures/agent-tools/agent/agent.ts b/e2e/fixtures/agent-tools/agent/agent.tsindex 9ac25076c..59468dd25 100644--- a/e2e/fixtures/agent-tools/agent/agent.ts+++ b/e2e/fixtures/agent-tools/agent/agent.ts@@ -4,7 +4,7 @@ import type { MockModelRequest } from "eve/evals";import { readStripeColors, STRIPE_COUNT } from "./lib/stripes";-const STAGED_IMAGE_PATH = /\/workspace\/\.eve\/attachments\/\S+\.png/u;+const STAGED_IMAGE_PATH = /\.eve\/attachments\/\S+\.png/u;/*** Stripe colors in the latest tool-result image the prompt carries, whetherdiff --git a/e2e/fixtures/agent-tools/evals/static-tools/read-file-reopens-compacted-image.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/read-file-reopens-compacted-image.eval.tsindex 3440f8679..34ab5d031 100644--- a/e2e/fixtures/agent-tools/evals/static-tools/read-file-reopens-compacted-image.eval.ts+++ b/e2e/fixtures/agent-tools/evals/static-tools/read-file-reopens-compacted-image.eval.ts@@ -59,8 +59,8 @@ export default defineEval({},});-/** Where eve stages a tool-result file: its content hash and filename. */+/** Where eve stages a tool-result file, relative to the workspace root: its content hash and filename. */function stagedImagePath(base64: string): string {const sha = createHash("sha256").update(Buffer.from(base64, "base64")).digest("hex");- return `/workspace/.eve/attachments/${sha.slice(0, 16)}/stripes.png`;+ return `.eve/attachments/${sha.slice(0, 16)}/stripes.png`;}diff --git a/packages/eve-git/extension/lib/github-shell-schema.ts b/packages/eve-git/extension/lib/github-shell-schema.tsindex 2cabc3b85..49f0c1889 100644--- a/packages/eve-git/extension/lib/github-shell-schema.ts+++ b/packages/eve-git/extension/lib/github-shell-schema.ts@@ -21,5 +21,5 @@ export const githubShellInputSchema = z.object({.min(1).max(1_000).optional()- .describe("sandbox workspace directory; defaults to /workspace"),+ .describe("sandbox workspace directory; defaults to the workspace root"),});diff --git a/packages/eve/extension-contracts/compatibility/channel/v68.ts b/packages/eve/extension-contracts/compatibility/channel/v68.tsnew file mode 100644index 000000000..7a0f6932d--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/channel/v68.ts@@ -0,0 +1,16 @@+// Epoch 68 of the channel capability. Epoch 69 makes the provider runtime behind+// `SandboxEnvironment` opaque and drops its unused configuration hash; channels that+// reach the sandbox through `ctx.getSandbox()` are unchanged, as this example shows.+import { defineChannel } from "#public/channels/index.js";++export default defineChannel({+ routes: [],+ events: {+ "turn.completed": async (_event, _channel, ctx) => {+ const sandbox = await ctx.getSandbox();+ await sandbox.writeFiles({+ files: [{ content: new TextEncoder().encode("Sent to Alice."), path: "reports/sent.txt" }],+ });+ },+ },+});diff --git a/packages/eve/extension-contracts/compatibility/connection/v56.ts b/packages/eve/extension-contracts/compatibility/connection/v56.tsnew file mode 100644index 000000000..639f11f51--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/connection/v56.ts@@ -0,0 +1,8 @@+// Epoch 56 of the connection capability. Epoch 57 changes only the sandbox environment type it+// reaches (an opaque provider runtime); connection authoring is unchanged, as this example shows.+import { defineMcpClientConnection } from "#public/connections/index.js";++export default defineMcpClientConnection({+ description: "Read Bob's calendar.",+ url: "https://calendar.example.com/mcp",+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v91.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v91.tsnew file mode 100644index 000000000..d23a9b484--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v91.ts@@ -0,0 +1,18 @@+// Epoch 91 of the dynamicTool capability. Epoch 92 makes the provider runtime behind+// `SandboxEnvironment` opaque and drops its unused configuration hash; dynamic tools that+// reach the sandbox through `ctx.getSandbox()` are unchanged, as this example shows.+import { defineDynamic, defineTool } from "#public/tools/index.js";++export default defineDynamic({+ events: {+ "turn.started": () =>+ defineTool({+ description: "Read Bob's latest report.",+ inputSchema: { type: "object", properties: {} },+ async execute(_input, ctx) {+ const sandbox = await ctx.getSandbox();+ return await sandbox.readTextFile({ path: sandbox.resolvePath("reports/latest.md") });+ },+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/hook/v50.ts b/packages/eve/extension-contracts/compatibility/hook/v50.tsnew file mode 100644index 000000000..f5f37b2e4--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/hook/v50.ts@@ -0,0 +1,13 @@+// Epoch 50 of the hook capability. Epoch 51 makes the provider runtime behind+// `SandboxEnvironment` opaque and drops its unused configuration hash; hooks that+// reach the sandbox through `ctx.getSandbox()` are unchanged, as this example shows.+import { defineHook } from "#public/hooks/index.js";++export default defineHook({+ events: {+ "turn.completed": async (_event, ctx) => {+ const sandbox = await ctx.getSandbox();+ await sandbox.removePath({ force: true, path: ".eve/scratch", recursive: true });+ },+ },+});diff --git a/packages/eve/extension-contracts/compatibility/state/v15.ts b/packages/eve/extension-contracts/compatibility/state/v15.tsnew file mode 100644index 000000000..608d6ada4--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/state/v15.ts@@ -0,0 +1,5 @@+// Epoch 15 of the state capability. Epoch 16 changes only the sandbox environment type it reaches+// (an opaque provider runtime); state authoring is unchanged, as this example shows.+import { defineState } from "#public/context/index.js";++export const reviews = defineState("compatibility.reviews", () => ({ count: 0, reviewer: "Bob" }));diff --git a/packages/eve/extension-contracts/compatibility/tool/v101.ts b/packages/eve/extension-contracts/compatibility/tool/v101.tsnew file mode 100644index 000000000..d8cbad792--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v101.ts@@ -0,0 +1,18 @@+// Epoch 101 of the tool capability. Epoch 102 makes the provider runtime behind+// `SandboxEnvironment` opaque and drops its unused configuration hash; tools that+// reach the sandbox through `ctx.getSandbox()` are unchanged, as this example shows.+import { defineTool } from "#public/tools/index.js";++export default defineTool({+ description: "Archive Alice's notes and pause the sandbox.",+ inputSchema: { type: "object", properties: {}, additionalProperties: false },+ async execute(_input, ctx) {+ const sandbox = await ctx.getSandbox();+ await sandbox.writeFiles({+ files: [{ content: new TextEncoder().encode("Feed the cat."), path: "notes/alice.txt" }],+ });+ const result = await sandbox.run({ command: "tar -czf notes.tgz notes" });+ await sandbox.stop();+ return { exitCode: result.exitCode };+ },+});diff --git a/packages/eve/extension-contracts/reports/channel/v69.json b/packages/eve/extension-contracts/reports/channel/v69.jsonnew file mode 100644index 000000000..b3d3415d1--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v69.json@@ -0,0 +1,24 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 69,+ "sha256": "fec26dbd51a5275ec79c40fe237a479b42146f2672c75479246659839f1d9ae4",+ "exports": [+ "DELETE",+ "GET",+ "HEAD",+ "InvalidSessionHistoryError",+ "OPTIONS",+ "PATCH",+ "POST",+ "PUT",+ "SessionStrandedError",+ "WS",+ "attachmentError",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "disableRoute",+ "isChannel",+ "isDisabledRouteSentinel"+ ]+}diff --git a/packages/eve/extension-contracts/reports/connection/v57.json b/packages/eve/extension-contracts/reports/connection/v57.jsonnew file mode 100644index 000000000..a5896f518--- /dev/null+++ b/packages/eve/extension-contracts/reports/connection/v57.json@@ -0,0 +1,16 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "connection",+ "epoch": 57,+ "sha256": "08a4990aa3a727abe88ec98219fb21232e5eaa702e3b32830aa9eab2419f88d9",+ "exports": [+ "ConnectionAuthorizationFailedError",+ "ConnectionAuthorizationRequiredError",+ "defineDynamic",+ "defineInteractiveAuthorization",+ "defineMcpClientConnection",+ "defineOpenAPIConnection",+ "isConnectionAuthorizationFailedError",+ "isConnectionAuthorizationRequiredError"+ ]+}diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v92.json b/packages/eve/extension-contracts/reports/dynamicTool/v92.jsonnew file mode 100644index 000000000..48c46c297--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v92.json@@ -0,0 +1,16 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 92,+ "sha256": "331383947e1e057128220f8be29a31a8de351cd6087e97245f37ef48235a7343",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "auto",+ "defineDurableCallback",+ "defineDurableSchema",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/hook/v51.json b/packages/eve/extension-contracts/reports/hook/v51.jsonnew file mode 100644index 000000000..241a78610--- /dev/null+++ b/packages/eve/extension-contracts/reports/hook/v51.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "hook",+ "epoch": 51,+ "sha256": "13631c98c5f1c0a588a8d64f8a3d861f87a9a35fb0ba738b468ca056b70906b2",+ "exports": ["defineHook"]+}diff --git a/packages/eve/extension-contracts/reports/state/v16.json b/packages/eve/extension-contracts/reports/state/v16.jsonnew file mode 100644index 000000000..274106bfe--- /dev/null+++ b/packages/eve/extension-contracts/reports/state/v16.json@@ -0,0 +1,15 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "state",+ "epoch": 16,+ "sha256": "a1de6c7b5998712560a2b88b0e7b8e44e2c7d420cada8b59662ea6248ddb4e3f",+ "exports": [+ "Session",+ "SessionAuth",+ "SessionAuthContext",+ "SessionContext",+ "SessionParent",+ "SessionTurn",+ "defineState"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v102.json b/packages/eve/extension-contracts/reports/tool/v102.jsonnew file mode 100644index 000000000..02bab0dca--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v102.json@@ -0,0 +1,29 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 102,+ "sha256": "9bbfc7c44ba81fa5a5faf44c11b1fd4205a10f8766ab2694ea6f6d937a0da02d",+ "exports": [+ "AgentRouterInput",+ "AgentRouterTool",+ "WorkflowStepToolContext",+ "WorkflowTool",+ "WorkflowToolDefinition",+ "WorkflowToolInput",+ "WorkflowToolOptions",+ "agentRouter",+ "decide",+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "serializeModelInputSchema",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch",+ "workflow"+ ]+}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 16cebeb10..292d441fd 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,10 +22,10 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 101,+ current: 102,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78, 80, 81, 82, 84,- 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 97, 98, 99, 100, 101,+ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 97, 98, 99, 100, 101, 102,],dropped: {14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",@@ -91,11 +91,11 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},dynamicTool: {- current: 91,+ current: 92,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,- 85, 86, 87, 89, 90, 91,+ 85, 86, 87, 89, 90, 91, 92,],dropped: {21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",@@ -137,11 +137,11 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},channel: {- current: 68,+ current: 69,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42,43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 65, 66, 67,- 68,+ 68, 69,],dropped: {12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",@@ -195,10 +195,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},connection: {- current: 56,+ current: 57,supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 32, 33, 34,- 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56,+ 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57,],dropped: {9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",@@ -215,10 +215,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},hook: {- current: 50,+ current: 51,supported: [20, 21, 22, 23, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 49,- 50,+ 50, 51,],dropped: {1: "Model identity moved from session.started runtime metadata to step.started call attribution.",@@ -279,8 +279,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},config: { current: 1, supported: [1], dropped: {} },state: {- current: 15,- supported: [1, 2, 3, 4, 5, 7, 9, 10, 12, 14, 15],+ current: 16,+ supported: [1, 2, 3, 4, 5, 7, 9, 10, 12, 14, 15, 16],dropped: {6: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",8: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",diff --git a/packages/eve/src/compiler/normalize-sandbox.test.ts b/packages/eve/src/compiler/normalize-sandbox.test.tsindex 5e0a9b43a..535b27ed6 100644--- a/packages/eve/src/compiler/normalize-sandbox.test.ts+++ b/packages/eve/src/compiler/normalize-sandbox.test.ts@@ -1,8 +1,8 @@import { describe, expect, it } from "vitest";import { defineParentSandbox, defineSandbox } from "#public/definitions/sandbox.js";-import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";+import { defineSandboxProvider } from "#sandbox/provider.js";-const provider = defineLegacySandboxProvider({+const provider = defineSandboxProvider({name: "test",environment: () => ({async onSessionEnd() {},diff --git a/packages/eve/src/context/dynamic-skill-lifecycle.test.ts b/packages/eve/src/context/dynamic-skill-lifecycle.test.tsindex 17d54a82a..887fec786 100644--- a/packages/eve/src/context/dynamic-skill-lifecycle.test.ts+++ b/packages/eve/src/context/dynamic-skill-lifecycle.test.ts@@ -26,10 +26,7 @@ import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";import { defineSandbox } from "#public/definitions/sandbox.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";-import {- defineLegacySandboxProvider,- type SandboxProviderSessionContext,-} from "#shared/sandbox-provider.js";+import { defineSandboxProvider } from "#sandbox/provider.js";import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import type { SkillPackageDefinition } from "#shared/skill-definition.js";@@ -70,13 +67,7 @@ function persistedSandbox(id: string): SandboxSessionState {function recreatableSandbox() {const sandboxes: ReturnType<typeof mockSandbox>[] = [];let gone = false;- const handle = (sandbox: ReturnType<typeof mockSandbox>) => ({- sandbox: sandbox.session,- onRuntimeShutdown: async () => {},- onSandboxDelete: async () => {},- onSandboxStop: async () => {},- });- const environment = defineLegacySandboxProvider({+ const environment = defineSandboxProvider({name: "recreatable",environment: () => ({onSessionEnd: async () => {},@@ -86,16 +77,16 @@ function recreatableSandbox() {gone = false;throw new SandboxSessionGoneError("The sandbox was removed.");}- return handle(sandboxes.at(-1)!);+ return sandboxes.at(-1)!.connection;},- async start(context: SandboxProviderSessionContext) {+ async start(context) {const sandbox = mockSandbox({commands: {[HOME_PROBE_COMMAND]: { exitCode: 0, stderr: "", stdout: "/home/agent\n" },},});sandboxes.push(sandbox);- return { handle: handle(sandbox), state: { name: `sandbox-${context.session.id}` } };+ return { connection: sandbox.connection, state: { name: `sandbox-${context.session.id}` } };},}),}).environment();diff --git a/packages/eve/src/context/providers/sandbox.test.ts b/packages/eve/src/context/providers/sandbox.test.tsindex 9930f5d9f..17cbbcff3 100644--- a/packages/eve/src/context/providers/sandbox.test.ts+++ b/packages/eve/src/context/providers/sandbox.test.ts@@ -59,7 +59,7 @@ describe("sandboxProvider", () => {beforeEach(() => {vi.mocked(ensureSandboxAccess).mockResolvedValue({captureState: vi.fn().mockResolvedValue({ initialized: false, session: null }),- detach: vi.fn().mockResolvedValue(undefined),+ release: vi.fn().mockResolvedValue(undefined),end: vi.fn().mockResolvedValue(undefined),get: vi.fn().mockResolvedValue(null),stop: vi.fn().mockResolvedValue(undefined),@@ -95,7 +95,7 @@ describe("sandboxProvider", () => {const end = vi.fn().mockResolvedValue(undefined);vi.mocked(ensureSandboxAccess).mockResolvedValueOnce({captureState: vi.fn().mockResolvedValue({ session: null }),- detach: vi.fn().mockResolvedValue(undefined),+ release: vi.fn().mockResolvedValue(undefined),end,get: vi.fn().mockResolvedValue(null),stop: vi.fn().mockResolvedValue(undefined),@@ -127,4 +127,30 @@ describe("sandboxProvider", () => {}),);});++ it("closes the step's connection when the scope ends, without throwing", async () => {+ const ctx = new ContextContainer();+ ctx.set(+ BundleKey,+ createBundle({ agentName: "weather-agent", registry: createStubSandboxRegistry() }),+ );+ ctx.set(SessionIdKey, "session_1");+ const release = vi+ .fn()+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error("interpreter stuck"));+ vi.mocked(ensureSandboxAccess).mockResolvedValue({+ captureState: vi.fn(),+ end: vi.fn(),+ get: vi.fn(),+ release,+ stop: vi.fn(),+ });+ const created = await sandboxProvider.create(ctx, createHarnessSession());++ await sandboxProvider.dispose?.(created!.value);+ await expect(sandboxProvider.dispose?.(created!.value)).resolves.toBeUndefined();++ expect(release).toHaveBeenCalledTimes(2);+ });});diff --git a/packages/eve/src/context/providers/sandbox.ts b/packages/eve/src/context/providers/sandbox.tsindex 65a5c8928..d69a35950 100644--- a/packages/eve/src/context/providers/sandbox.ts+++ b/packages/eve/src/context/providers/sandbox.ts@@ -1,4 +1,4 @@-import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";+import { ensureSandboxAccess, type EnsuredSandboxAccess } from "#execution/sandbox/ensure.js";import type { HarnessSessionBase } from "#harness/types.js";import type { SandboxAccess, SandboxState } from "#sandbox/state.js";import type { ContextContainer } from "#context/container.js";@@ -6,6 +6,9 @@ import { SandboxKey, SandboxTerminalCleanupKey, SessionIdKey } from "#context/keimport { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";import { getActiveRuntimeNode } from "#context/node.js";import type { FrameworkContextProvider } from "#context/provider.js";+import { createLogger, logError } from "#internal/logging.js";++const log = createLogger("context.sandbox");export const sandboxProvider: FrameworkContextProvider<SandboxAccess> = {key: SandboxKey,@@ -40,4 +43,11 @@ export const sandboxProvider: FrameworkContextProvider<SandboxAccess> = {const state = await access.captureState();return { ...session, sandboxState: state };},++ // Closes the connection the step opened; `create` built the access.+ async dispose(access) {+ await (access as EnsuredSandboxAccess).release().catch((error: unknown) => {+ logError(log, "failed to close a step's sandbox connection", error);+ });+ },};diff --git a/packages/eve/src/evals/cli/eval.ts b/packages/eve/src/evals/cli/eval.tsindex 0b96a566e..0d5ec9531 100644--- a/packages/eve/src/evals/cli/eval.ts+++ b/packages/eve/src/evals/cli/eval.ts@@ -3,7 +3,7 @@ import { readFile } from "node:fs/promises";import { basename, join } from "node:path";import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";-import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";+import { shutdownActiveSandboxConnections } from "#execution/sandbox/active-connections.js";import {EVE_DEV_STATE_DIR_ENV,EVE_EVALUATION_ENV_FLAG,@@ -216,7 +216,8 @@ export async function runEvalCommand(} finally {for (const cleanup of [() => devServer?.close(),- () => devServer && shutdownActiveSandboxHandles({ log: (message) => logger.error(message) }),+ () =>+ devServer && shutdownActiveSandboxConnections({ log: (message) => logger.error(message) }),() => devStateDirectory && removeEvalStateDirectory(devStateDirectory),() => config.teardown?.(setupContext),]) {diff --git a/packages/eve/src/execution/invoke-tool.test.ts b/packages/eve/src/execution/invoke-tool.test.tsindex 0738a9b60..3f9622367 100644--- a/packages/eve/src/execution/invoke-tool.test.ts+++ b/packages/eve/src/execution/invoke-tool.test.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { ApprovalPolicy } from "#approval/definition.js";import type { SessionAuthContext } from "#channel/types.js";-import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";+import { shutdownActiveSandboxConnections } from "#execution/sandbox/active-connections.js";import { invokeTool, type InvokeToolRuntime } from "#execution/invoke-tool.js";import { createToolExecuteWithAuth } from "#execution/tool-auth.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";@@ -18,7 +18,7 @@ vi.mock("#runtime/sandbox/prepared-artifacts.js", () => ({loadSandboxPreparedArtifact: vi.fn(async () => null),}));-afterEach(() => shutdownActiveSandboxHandles());+afterEach(() => shutdownActiveSandboxConnections());const alice: SessionAuthContext = {attributes: {},@@ -294,7 +294,7 @@ describe("invokeTool", () => {expect(started).toHaveLength(2);expect(started[0]).not.toBe(started[1]);expect(deleted).toHaveBeenCalledTimes(2);- await shutdownActiveSandboxHandles();+ await shutdownActiveSandboxConnections();expect(shutdown).not.toHaveBeenCalled();});@@ -321,7 +321,7 @@ describe("invokeTool", () => {expect(await invokeTool(runtime, "pause", {}, { auth: alice })).toMatchObject({status: "completed",});- await shutdownActiveSandboxHandles();+ await shutdownActiveSandboxConnections();expect(shutdown).toHaveBeenCalledOnce();expect(closed).toHaveBeenCalledTimes(2);@@ -372,7 +372,7 @@ describe("invokeTool", () => {expect(await result).toMatchObject({ status: "failed" });expect(deleted).toHaveBeenCalledTimes(1);- await shutdownActiveSandboxHandles();+ await shutdownActiveSandboxConnections();expect(shutdown).not.toHaveBeenCalled();});@@ -458,7 +458,7 @@ describe("invokeTool", () => {expect(released).toEqual([handles[1], handles[0], handles[2]]);// No call's connection is left for server shutdown, and the sandbox itself stays.- await shutdownActiveSandboxHandles();+ await shutdownActiveSandboxConnections();expect(stopped).not.toHaveBeenCalled();expect(new Set(kinds)).toEqual(new Set(["tool-session"]));expect(deleted).not.toHaveBeenCalled();diff --git a/packages/eve/src/execution/invoke-tool.ts b/packages/eve/src/execution/invoke-tool.tsindex 07dfd7dc4..7b05cf6aa 100644--- a/packages/eve/src/execution/invoke-tool.ts+++ b/packages/eve/src/execution/invoke-tool.ts@@ -16,11 +16,6 @@ import { ContextContainer, contextStorage } from "#context/container.js";import { AuthKey, InitiatorAuthKey, SandboxKey, SessionIdKey, SessionKey } from "#context/keys.js";import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";import { deriveToolSessionId, validateToolSessionKey } from "#execution/tool-session/id.js";-import {- assertToolSessionSandboxSupport,- releaseToolSessionHandle,- ToolSessionSandboxUnsupportedError,-} from "#execution/tool-session/sandbox.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import {AuthorizationHookKey,@@ -40,6 +35,7 @@ import { isAsyncIterable } from "#shared/async-iterable.js";import { toErrorMessage } from "#shared/errors.js";import type { JsonObject } from "#shared/json.js";import type { SandboxAccess } from "#sandbox/state.js";+import { ToolSessionSandboxUnsupportedError } from "#shared/sandbox-tool-session-error.js";import { createUlid } from "#shared/ulid.js";import {type InvokeToolObserver,@@ -215,7 +211,7 @@ interface CallSandbox {* through the provider's `start`, an upsert on the session id, and kept after* the call. Concurrent first calls in this process share one start. The call* does not own the sandbox, so a failed start never deletes it, and release- * only lets go of this call's handle: an overlapping call keeps its own.+ * only closes this call's connection: an overlapping call keeps its own.*/async function keyedSandbox(runtime: InvokeToolRuntime, sessionId: string): Promise<CallSandbox> {const access = await ensureSandboxAccess({@@ -224,21 +220,10 @@ async function keyedSandbox(runtime: InvokeToolRuntime, sessionId: string): PromownsSandbox: false,registry: runtime.sandboxRegistry,sessionId,+ shutdownTracking: "call",state: null,});- return {- access: {- ...access,- async get() {- assertToolSessionSandboxSupport(runtime.sandboxRegistry);- return await access.get();- },- },- async release() {- const handle = await access.detach();- if (handle !== undefined) await releaseToolSessionHandle(runtime.sandboxRegistry, handle);- },- };+ return { access, release: () => access.release() };}/**diff --git a/packages/eve/src/execution/sandbox/active-connections.test.ts b/packages/eve/src/execution/sandbox/active-connections.test.tsnew file mode 100644index 000000000..62321664b--- /dev/null+++ b/packages/eve/src/execution/sandbox/active-connections.test.ts@@ -0,0 +1,98 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ shutdownActiveSandboxConnections,+ trackActiveSandboxConnection,+} from "#execution/sandbox/active-connections.js";++afterEach(async () => {+ await shutdownActiveSandboxConnections();+});++describe("shutdownActiveSandboxConnections", () => {+ it("shuts down every tracked connection and clears the registry", async () => {+ const first = { stop: vi.fn(async () => {}) };+ const second = { stop: vi.fn(async () => {}) };+ trackActiveSandboxConnection({+ providerName: "docker",+ connection: first,+ sessionId: "session-1",+ });+ trackActiveSandboxConnection({+ providerName: "docker",+ connection: second,+ sessionId: "session-2",+ });++ await shutdownActiveSandboxConnections();+ await shutdownActiveSandboxConnections();++ expect(first.stop).toHaveBeenCalledTimes(1);+ expect(second.stop).toHaveBeenCalledTimes(1);+ });++ it("replaces the tracked connection when the same session is reopened", async () => {+ const stale = { stop: vi.fn(async () => {}) };+ const fresh = { stop: vi.fn(async () => {}) };+ trackActiveSandboxConnection({+ providerName: "docker",+ connection: stale,+ sessionId: "session-1",+ });+ trackActiveSandboxConnection({+ providerName: "docker",+ connection: fresh,+ sessionId: "session-1",+ });++ await shutdownActiveSandboxConnections();++ expect(stale.stop).not.toHaveBeenCalled();+ expect(fresh.stop).toHaveBeenCalledTimes(1);+ });++ it("tracks the same session key on different providers separately", async () => {+ const docker = { stop: vi.fn(async () => {}) };+ const vercel = { stop: vi.fn(async () => {}) };+ trackActiveSandboxConnection({+ providerName: "docker",+ connection: docker,+ sessionId: "session-1",+ });+ trackActiveSandboxConnection({+ providerName: "vercel",+ connection: vercel,+ sessionId: "session-1",+ });++ await shutdownActiveSandboxConnections();++ expect(docker.stop).toHaveBeenCalledTimes(1);+ expect(vercel.stop).toHaveBeenCalledTimes(1);+ });++ it("logs a failed shutdown and still shuts down the remaining connections", async () => {+ const failing = {+ stop: vi.fn(async () => {+ throw new Error("provider unreachable");+ }),+ };+ const healthy = { stop: vi.fn(async () => {}) };+ trackActiveSandboxConnection({+ providerName: "docker",+ connection: failing,+ sessionId: "session-1",+ });+ trackActiveSandboxConnection({+ providerName: "docker",+ connection: healthy,+ sessionId: "session-2",+ });+ const log = vi.fn();++ await expect(shutdownActiveSandboxConnections({ log })).resolves.toBeUndefined();++ expect(healthy.stop).toHaveBeenCalledTimes(1);+ expect(log).toHaveBeenCalledWith(expect.stringContaining("provider unreachable"));+ });+});diff --git a/packages/eve/src/execution/sandbox/active-connections.ts b/packages/eve/src/execution/sandbox/active-connections.tsnew file mode 100644index 000000000..917e1135a--- /dev/null+++ b/packages/eve/src/execution/sandbox/active-connections.ts@@ -0,0 +1,69 @@+import { toErrorMessage } from "#shared/errors.js";++/** A live connection the server stops, then closes, when it shuts down. */+interface ActiveSandboxConnection {+ stop(): Promise<void>;+}++/**+ * Process-level registry of live sandbox connections, keyed by provider name+ * and durable session ID so a resumed connection replaces the previous one+ * for that session rather than accumulating entries.+ *+ * `ensureSandboxAccess` registers the connections it opens; the server+ * shutdown path drains the registry so no sandbox compute outlives the eve+ * server process.+ */+const activeSandboxConnections = new Map<string, ActiveSandboxConnection>();++interface ActiveSandboxConnectionKey {+ readonly providerName: string;+ readonly sessionId: string;+}++function createKey(input: ActiveSandboxConnectionKey): string {+ return `${input.providerName}\0${input.sessionId}`;+}++/** Registers a live connection. A later one for the same provider and session replaces it. */+export function trackActiveSandboxConnection(+ input: ActiveSandboxConnectionKey & { readonly connection: ActiveSandboxConnection },+): void {+ activeSandboxConnections.set(createKey(input), input.connection);+}++/**+ * Drops `connection` from shutdown tracking, unless a newer one replaced it,+ * or whatever the session has tracked when `connection` is omitted.+ */+export function untrackActiveSandboxConnection(+ input: ActiveSandboxConnectionKey & { readonly connection?: ActiveSandboxConnection },+): void {+ const key = createKey(input);+ if (input.connection === undefined || activeSandboxConnections.get(key) === input.connection) {+ activeSandboxConnections.delete(key);+ }+}++/**+ * Stops every tracked connection in parallel, then clears the registry.+ * Failures are logged and never thrown so one misbehaving sandbox cannot+ * block server shutdown.+ */+export async function shutdownActiveSandboxConnections(input?: {+ readonly log?: (message: string) => void;+}): Promise<void> {+ const entries = [...activeSandboxConnections.entries()];+ activeSandboxConnections.clear();++ const results = await Promise.allSettled(entries.map(([, connection]) => connection.stop()));++ for (const [index, result] of results.entries()) {+ if (result.status === "rejected") {+ const entry = entries[index];+ input?.log?.(+ `failed to shut down sandbox "${entry?.[0] ?? "unknown"}": ${toErrorMessage(result.reason)}`,+ );+ }+ }+}diff --git a/packages/eve/src/execution/sandbox/active-handles.test.ts b/packages/eve/src/execution/sandbox/active-handles.test.tsdeleted file mode 100644index cd12d34e9..000000000--- a/packages/eve/src/execution/sandbox/active-handles.test.ts+++ /dev/null@@ -1,66 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";--import {- shutdownActiveSandboxHandles,- trackActiveSandboxHandle,-} from "#execution/sandbox/active-handles.js";--afterEach(async () => {- await shutdownActiveSandboxHandles();-});--describe("shutdownActiveSandboxHandles", () => {- it("shuts down every tracked handle and clears the registry", async () => {- const first = { onRuntimeShutdown: vi.fn(async () => {}) };- const second = { onRuntimeShutdown: vi.fn(async () => {}) };- trackActiveSandboxHandle({ providerName: "docker", handle: first, sessionId: "session-1" });- trackActiveSandboxHandle({ providerName: "docker", handle: second, sessionId: "session-2" });-- await shutdownActiveSandboxHandles();- await shutdownActiveSandboxHandles();-- expect(first.onRuntimeShutdown).toHaveBeenCalledTimes(1);- expect(second.onRuntimeShutdown).toHaveBeenCalledTimes(1);- });-- it("replaces the tracked handle when the same session is reopened", async () => {- const stale = { onRuntimeShutdown: vi.fn(async () => {}) };- const fresh = { onRuntimeShutdown: vi.fn(async () => {}) };- trackActiveSandboxHandle({ providerName: "docker", handle: stale, sessionId: "session-1" });- trackActiveSandboxHandle({ providerName: "docker", handle: fresh, sessionId: "session-1" });-- await shutdownActiveSandboxHandles();-- expect(stale.onRuntimeShutdown).not.toHaveBeenCalled();- expect(fresh.onRuntimeShutdown).toHaveBeenCalledTimes(1);- });-- it("tracks the same session key on different providers separately", async () => {- const docker = { onRuntimeShutdown: vi.fn(async () => {}) };- const vercel = { onRuntimeShutdown: vi.fn(async () => {}) };- trackActiveSandboxHandle({ providerName: "docker", handle: docker, sessionId: "session-1" });- trackActiveSandboxHandle({ providerName: "vercel", handle: vercel, sessionId: "session-1" });-- await shutdownActiveSandboxHandles();-- expect(docker.onRuntimeShutdown).toHaveBeenCalledTimes(1);- expect(vercel.onRuntimeShutdown).toHaveBeenCalledTimes(1);- });-- it("logs a failed shutdown and still shuts down the remaining handles", async () => {- const failing = {- onRuntimeShutdown: vi.fn(async () => {- throw new Error("provider unreachable");- }),- };- const healthy = { onRuntimeShutdown: vi.fn(async () => {}) };- trackActiveSandboxHandle({ providerName: "docker", handle: failing, sessionId: "session-1" });- trackActiveSandboxHandle({ providerName: "docker", handle: healthy, sessionId: "session-2" });- const log = vi.fn();-- await expect(shutdownActiveSandboxHandles({ log })).resolves.toBeUndefined();-- expect(healthy.onRuntimeShutdown).toHaveBeenCalledTimes(1);- expect(log).toHaveBeenCalledWith(expect.stringContaining("provider unreachable"));- });-});diff --git a/packages/eve/src/execution/sandbox/active-handles.ts b/packages/eve/src/execution/sandbox/active-handles.tsdeleted file mode 100644index fda41f7d1..000000000--- a/packages/eve/src/execution/sandbox/active-handles.ts+++ /dev/null@@ -1,73 +0,0 @@-import { toErrorMessage } from "#shared/errors.js";--/**- * The provider handle capability the shutdown registry needs.- * Structural so handles of any session-options generic register without- * variance friction.- */-interface ShutdownCapableSandboxHandle {- onRuntimeShutdown(): Promise<void>;-}--/**- * Process-level registry of live sandbox provider handles, keyed by- * provider name and durable session ID so a resumed handle replaces the- * previous handle for that session rather than accumulating entries.- *- * `ensureSandboxAccess` registers every handle it opens; the server- * shutdown path drains the registry so no sandbox compute outlives the- * eve server process.- */-const activeSandboxHandles = new Map<string, ShutdownCapableSandboxHandle>();--function createActiveSandboxHandleKey(providerName: string, sessionId: string): string {- return `${providerName}\0${sessionId}`;-}--/**- * Registers a live sandbox handle for shutdown tracking. A later handle- * for the same provider and durable session replaces the previous entry.- */-export function trackActiveSandboxHandle(input: {- readonly providerName: string;- readonly handle: ShutdownCapableSandboxHandle;- readonly sessionId: string;-}): void {- activeSandboxHandles.set(- createActiveSandboxHandleKey(input.providerName, input.sessionId),- input.handle,- );-}--/** Drops a handle from shutdown tracking, unless a newer handle replaced it. */-export function untrackActiveSandboxHandle(input: {- readonly providerName: string;- readonly handle: ShutdownCapableSandboxHandle;- readonly sessionId: string;-}): void {- const key = createActiveSandboxHandleKey(input.providerName, input.sessionId);- if (activeSandboxHandles.get(key) === input.handle) activeSandboxHandles.delete(key);-}--/**- * Stops every tracked sandbox by invoking its runtime-shutdown hook in- * parallel, then clears the registry. Failures are logged and never- * thrown so one misbehaving sandbox cannot block server shutdown.- */-export async function shutdownActiveSandboxHandles(input?: {- readonly log?: (message: string) => void;-}): Promise<void> {- const entries = [...activeSandboxHandles.entries()];- activeSandboxHandles.clear();-- const results = await Promise.allSettled(entries.map(([, handle]) => handle.onRuntimeShutdown()));-- for (const [index, result] of results.entries()) {- if (result.status === "rejected") {- const entry = entries[index];- input?.log?.(- `failed to shut down sandbox "${entry?.[0] ?? "unknown"}": ${toErrorMessage(result.reason)}`,- );- }- }-}diff --git a/packages/eve/src/execution/sandbox/bash.scenario.test.ts b/packages/eve/src/execution/sandbox/bash.scenario.test.tsindex 4e5f5ea17..80381a013 100644--- a/packages/eve/src/execution/sandbox/bash.scenario.test.ts+++ b/packages/eve/src/execution/sandbox/bash.scenario.test.ts@@ -10,7 +10,7 @@ import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-rooimport type { SandboxSession } from "#shared/sandbox-session.js";import { executeBashOnSandbox } from "./bash.js";-import { buildSandboxSession } from "./session.js";+import { createConnectionSession } from "./session.js";const createScratchDirectory = useTemporaryDirectories();@@ -95,11 +95,11 @@ async function createHostSandbox(): Promise<{const unsupported = async (): Promise<never> => {throw new Error("not used by the bash tool");};- const sandbox = buildSandboxSession({+ const sandbox = createConnectionSession({readFile: unsupported,removePath: unsupported,- resolvePath: (path) => path,- writeFile: unsupported,+ stop: unsupported,+ writeFiles: unsupported,async spawn(options) {const child = spawn("bash", ["-lc", options.command], {cwd: home,diff --git a/packages/eve/src/execution/sandbox/bindings/docker-compat.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/docker-compat.integration.test.tsindex 7e2e882bc..dcf8655fe 100644--- a/packages/eve/src/execution/sandbox/bindings/docker-compat.integration.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker-compat.integration.test.ts@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";import { EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV } from "#execution/sandbox/development-run.js";-import { createDockerSandboxRuntime } from "#internal/testing/docker-sandbox-runtime.js";+import { createDockerSandboxHarness } from "#internal/testing/docker-sandbox-runtime.js";import {createFakeDockerCli,fakeDockerContainerIdentity,@@ -13,7 +13,6 @@ import {isContainerInspect,type FakeResponse,} from "#internal/testing/fake-docker-cli.js";-import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";import type {DockerSandboxEnvironmentOptions,@@ -27,10 +26,7 @@ function createEngine(input: {readonly options?: DockerSandboxEnvironmentOptions;readonly runtimeOptions?: DockerSandboxRuntimeOptions;}) {- return createSandboxProviderHarness(- createDockerSandboxRuntime(input.options, input.cli),- input.runtimeOptions ?? {},- );+ return createDockerSandboxHarness({ ...input, runtimeOptions: input.runtimeOptions ?? {} });}// Literal values recorded from the previous release. Running sessions persistdiff --git a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.tsindex dba58e225..057ef9399 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts@@ -21,7 +21,7 @@ import type {} from "#public/sandbox/docker-sandbox.js";import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";-import { createDockerSandboxRuntime } from "#internal/testing/docker-sandbox-runtime.js";+import { createDockerSandboxHarness } from "#internal/testing/docker-sandbox-runtime.js";import {createFakeDockerCli,fakeDockerContainerIdentity,@@ -29,13 +29,9 @@ import {isContainerInspect,type FakeResponse,} from "#internal/testing/fake-docker-cli.js";-import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";-import { createSandboxProviderFiles } from "#execution/sandbox/provider-files.js";-import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";-import { createSandboxProviderResources } from "#shared/sandbox-provider.js";const createScratchDirectory = useTemporaryDirectories();@@ -44,11 +40,11 @@ function createEngine(input: {readonly options?: DockerSandboxEnvironmentOptions;readonly runtimeOptions?: DockerSandboxRuntimeOptions;}) {- return createSandboxProviderHarness(- createDockerSandboxRuntime(input.options, input.cli),- input.runtimeOptions ?? {},- { preparedArtifact: () => ({ imageReference: TEMPLATE_IMAGE }) },- );+ return createDockerSandboxHarness({+ ...input,+ preparedArtifact: () => ({ imageReference: TEMPLATE_IMAGE }),+ runtimeOptions: input.runtimeOptions ?? {},+ });}function isImageInspect(args: readonly string[], reference: string): boolean {@@ -276,7 +272,9 @@ describe("Docker provider prewarm", () => {(args) =>args[0] === "exec" &&// The spawn wrapper re-quotes the script for `bash -lc`, escaping its quoted root.- (args.at(-1) ?? "").includes("cp -a '\\''/eve/resources'\\''/workspace/. /workspace/"),+ (args.at(-1) ?? "").includes(+ "cp -a '\\''/eve/resources'\\''/workspace/. '\\''/workspace'\\''/",+ ),),).toBeDefined();});@@ -380,7 +378,7 @@ describe("Docker provider create", () => {// An authored stop releases the container; filesystem state survives// for the next `create` to restart from.- await handle.onSandboxStop();+ await handle.connection.stop();expect(findCall(calls, (args) => args[0] === "stop")?.args).toEqual(["stop","-t",@@ -705,11 +703,8 @@ describe("Docker template prune", () => {// Mirrors how prewarm and session start build the provider context.async function prepareLikeDevelopment(appRoot: string, cli: DockerCli) {- return await createDockerSandboxRuntime(undefined, cli).prepare({- files: createSandboxProviderFiles(join(appRoot, "sandbox")),- host: createSandboxProviderHost(appRoot),- resources: createSandboxProviderResources({}),- sourceRevision: "test-source-revision",+ return await createDockerSandboxHarness({ cli }).prepare({+ appRoot,storagePath: resolveSandboxCacheDirectory(appRoot),});}diff --git a/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.tsindex 46189acc1..b659a7926 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts@@ -1,8 +1,7 @@import { describe, expect, it, vi } from "vitest";import { DockerUnavailableError } from "#execution/sandbox/bindings/docker-cli.js";-import { createDockerSandboxRuntime } from "#internal/testing/docker-sandbox-runtime.js";-import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";+import { createDockerSandboxHarness } from "#internal/testing/docker-sandbox-runtime.js";import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";const createScratchDirectory = useTemporaryDirectories();@@ -12,7 +11,7 @@ describe("docker CLI resolution", () => {vi.stubEnv("EVE_DOCKER_PATH", "/nonexistent/docker-binary");try {const appRoot = await createScratchDirectory("eve-docker-missing-");- const engine = createSandboxProviderHarness(createDockerSandboxRuntime(), undefined);+ const engine = createDockerSandboxHarness();await expect(engine.prepare({ appRoot })).rejects.toThrow(DockerUnavailableError);} finally {diff --git a/packages/eve/src/execution/sandbox/bindings/docker.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.test.tsindex f3d864351..fe7074999 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.test.ts@@ -1,7 +1,6 @@import { describe, expect, it, vi } from "vitest";-import { createDockerSandboxRuntime } from "#internal/testing/docker-sandbox-runtime.js";-import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";+import { createDockerSandboxHarness } from "#internal/testing/docker-sandbox-runtime.js";import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";function createContainerStoreCli() {@@ -67,16 +66,14 @@ describe("Docker sandbox deletion", () => {throw new Error("stream is not used by this test");},};- const provider = createSandboxProviderHarness(- createDockerSandboxRuntime(undefined, dockerCli),- {},- { preparedArtifact: () => ({ imageReference: "prepared-image" }) },- );- const oldHandle = await provider.openSession({- appRoot: "/tmp/eve-app",- sandboxName: "session-key",+ const provider = createDockerSandboxHarness({+ cli: dockerCli,+ preparedArtifact: () => ({ imageReference: "prepared-image" }),+ runtimeOptions: {},});- await oldHandle.onSandboxDelete();+ const session = { appRoot: "/tmp/eve-app", sandboxName: "session-key" };+ const oldHandle = await provider.start(session);+ await provider.endSession({ ...session, reason: "deleted", state: oldHandle.state });containerId = "container-id-2";await provider.openSession({appRoot: "/tmp/eve-app",@@ -98,20 +95,18 @@ describe("Docker sandbox deletion", () => {it("deletes the session container by name with the caller's signal, even when it is already gone", async () => {const { dockerCli, run } = createContainerStoreCli();- const provider = createSandboxProviderHarness(- createDockerSandboxRuntime(undefined, dockerCli),- {},- { preparedArtifact: () => ({ imageReference: "image-a" }) },- );- const { handle, state } = await provider.start({- appRoot: "/tmp/eve-app",- sandboxName: "session-key",+ const provider = createDockerSandboxHarness({+ cli: dockerCli,+ preparedArtifact: () => ({ imageReference: "image-a" }),+ runtimeOptions: {},});+ const session = { appRoot: "/tmp/eve-app", sandboxName: "session-key" };+ const { state } = await provider.start(session);const abortSignal = new AbortController().signal;vi.mocked(run).mockClear();- await handle.onSandboxDelete({ abortSignal });- await handle.onSandboxDelete({ abortSignal });+ await provider.endSession({ ...session, abortSignal, reason: "deleted", state });+ await provider.endSession({ ...session, abortSignal, reason: "deleted", state });expect(vi.mocked(run).mock.calls.filter(([args]) => args[0] === "rm")).toEqual([[["rm", "-f", state.containerName], { signal: abortSignal }],[["rm", "-f", state.containerName], { signal: abortSignal }],@@ -122,11 +117,11 @@ describe("Docker sandbox deletion", () => {describe("Docker sandbox session identity", () => {it("names the container from the session key alone and removes it by key at session end", async () => {const { dockerCli, run } = createContainerStoreCli();- const provider = createSandboxProviderHarness(- createDockerSandboxRuntime(undefined, dockerCli),- {},- { preparedArtifact: () => ({ imageReference: "image-a" }) },- );+ const provider = createDockerSandboxHarness({+ cli: dockerCli,+ preparedArtifact: () => ({ imageReference: "image-a" }),+ runtimeOptions: {},+ });const session = { appRoot: "/tmp/eve-app", sandboxName: "session-key" };const { state } = await provider.start(session);@@ -148,16 +143,16 @@ describe("Docker sandbox session identity", () => {describe("Docker sandbox network policy", () => {it("rejects a domain allow-list at open before creating a container", async () => {const run = vi.fn<DockerCli["run"]>();- const provider = createSandboxProviderHarness(- createDockerSandboxRuntime(undefined, {+ const provider = createDockerSandboxHarness({+ cli: {run,stream() {throw new Error("stream is not used by this test");},- }),- {},- { preparedArtifact: () => ({ imageReference: "image-a" }) },- );+ },+ preparedArtifact: () => ({ imageReference: "image-a" }),+ runtimeOptions: {},+ });await expect(provider.start({diff --git a/packages/eve/src/execution/sandbox/bindings/immutable-resources.test.ts b/packages/eve/src/execution/sandbox/bindings/immutable-resources.test.tsdeleted file mode 100644index 39e6871e0..000000000--- a/packages/eve/src/execution/sandbox/bindings/immutable-resources.test.ts+++ /dev/null@@ -1,17 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { hydrateSandboxFromImmutableResources } from "#execution/sandbox/bindings/immutable-resources.js";--describe("hydrateSandboxFromImmutableResources", () => {- it("copies materialized workspace and skills so the prepared image keeps them without the mount", async () => {- const run = vi.fn(async (_input: { readonly command: string }) => ({- exitCode: 0,- stderr: "",- stdout: "",- }));- await hydrateSandboxFromImmutableResources({ run } as never, "'/eve/resources'");- const command = run.mock.calls[0]?.[0].command ?? "";- expect(command).toContain("cp -a '/eve/resources'/workspace/. /workspace/");- expect(command).toContain(`cp -a '/eve/resources'/skills/. "$HOME/.agents/skills/"`);- });-});diff --git a/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts b/packages/eve/src/execution/sandbox/bindings/immutable-resources.tsdeleted file mode 100644index 2e483bf2e..000000000--- a/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts+++ /dev/null@@ -1,45 +0,0 @@-import { join } from "node:path";--import { copyDirectoryAtomically } from "#execution/sandbox/bindings/local-provider-utils.js";-import type { SandboxSession } from "#shared/sandbox-session.js";--function resolveImmutableResourcesPath(input: {- readonly storagePath: string;- readonly provider: string;- readonly resourcesKey: string;-}): string {- return join(input.storagePath, input.provider, "resources", input.resourcesKey);-}--export async function prepareImmutableResources(input: {- readonly storagePath: string;- readonly provider: string;- readonly resourcesKey: string;- readonly sourcePath: string;-}): Promise<string> {- const path = resolveImmutableResourcesPath(input);- await copyDirectoryAtomically(input.sourcePath, path);- return path;-}--/** `quotedRoot` is interpolated into the shell script, so callers pass it shell-quoted. */-export async function hydrateSandboxFromImmutableResources(- session: SandboxSession,- quotedRoot: string,-): Promise<void> {- const result = await session.run({- command: [- "set -e",- `if [ -d ${quotedRoot}/workspace ]; then cp -a ${quotedRoot}/workspace/. /workspace/; fi`,- `if [ -d ${quotedRoot}/skills ]; then`,- ' mkdir -p "$HOME/.agents"',- ' rm -rf "$HOME/.agents/skills"',- ' mkdir -p "$HOME/.agents/skills"',- ` cp -a ${quotedRoot}/skills/. "$HOME/.agents/skills/"`,- "fi",- ].join("\n"),- });- if (result.exitCode !== 0) {- throw new Error(`Failed to hydrate sandbox resources: ${result.stderr || result.stdout}`);- }-}diff --git a/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts b/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.tsindex c09336029..8c4131601 100644--- a/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/just-bash.scenario.test.ts@@ -116,7 +116,7 @@ describe("just-bash sandbox file API", () => {await handle.sandbox.writeTextFile({ content: "scratch", path: "scratch.txt" });expect(await readFile(join(sourceRoot, "instructions.md"), "utf8")).toBe("after");expect(existsSync(join(sourceRoot, "scratch.txt"))).toBe(false);- await handle.onRuntimeShutdown();+ await handle.connection.stop();});it("applies the filesystem factory only to live sessions", async () => {@@ -141,7 +141,7 @@ describe("just-bash sandbox file API", () => {});expect(factoryCalls).toBe(1);await expect(handle.sandbox.readTextFile({ path: "seed.txt" })).resolves.toBe("from template");- await handle.onRuntimeShutdown();+ await handle.connection.stop();});it("writes a file via the public session and reads it back", async () => {@@ -286,7 +286,7 @@ describe("just-bash sandbox file API", () => {appRoot,});- const { handle: firstHandle, state } = await provider.start({+ const { state, ...firstHandle } = await provider.start({appRoot,sandboxName: "session-reconnect",});@@ -295,7 +295,7 @@ describe("just-bash sandbox file API", () => {path: "persisted.txt",});- await firstHandle.onSandboxStop();+ await firstHandle.connection.stop();const { rootPath } = state as { readonly rootPath: string };await expect(@@ -317,7 +317,7 @@ describe("just-bash sandbox file API", () => {const provider = createJustBashProvider();await provider.prepare({ appRoot });const session = { appRoot, sandboxName: "session-end" };- const { handle } = await provider.start(session);+ const handle = await provider.start(session);await handle.sandbox.writeTextFile({ content: "left behind", path: "left.txt" });await provider.endSession({ ...session, state: null });@@ -452,7 +452,7 @@ describe("just-bash custom commands", () => {exitCode: 23,stderr: "cap failed\n",});- await handle.onRuntimeShutdown();+ await handle.connection.stop();});});@@ -558,12 +558,12 @@ describe("just-bash provider", () => {appRoot,});- const { handle: initialHandle, state: initialState } = await provider.start({+ const { state: initialState, ...initialHandle } = await provider.start({appRoot,sandboxName: "session-seeded-later",});await initialHandle.sandbox.writeTextFile({ content: "kept", path: "notes.txt" });- await initialHandle.onRuntimeShutdown();+ await initialHandle.connection.stop();await provider.prepare({appRoot,diff --git a/packages/eve/src/execution/sandbox/bindings/local-provider-utils.ts b/packages/eve/src/execution/sandbox/bindings/local-provider-utils.tsindex f89e0c85f..e587a7a76 100644--- a/packages/eve/src/execution/sandbox/bindings/local-provider-utils.ts+++ b/packages/eve/src/execution/sandbox/bindings/local-provider-utils.ts@@ -2,22 +2,6 @@ import { randomUUID } from "node:crypto";import { access, cp, mkdir, rename, rm, utimes } from "node:fs/promises";import { dirname, join } from "node:path";-import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";-import { resolveSandboxModelPath } from "#shared/skill-paths.js";-import type { SandboxSession } from "#shared/sandbox-session.js";--interface SandboxSeedFile {- readonly content: string | Uint8Array;- readonly path: string;-}--export function resolveWorkspacePath(path: string): string {- if (path.startsWith("/")) {- return path;- }- return `${WORKSPACE_ROOT}/${path}`;-}-export async function pathExists(path: string): Promise<boolean> {try {await access(path);@@ -78,21 +62,3 @@ export function resolveLocalProviderSessionRootPath(): string {return join(cacheDirectory, providerCacheName, "sessions", sessionKey);}--export async function writeSandboxSeedFiles(- session: SandboxSession,- seedFiles: ReadonlyArray<SandboxSeedFile>,-): Promise<void> {- for (const file of seedFiles) {- const path = await resolveSandboxModelPath({- path: file.path,- sandbox: session,- });-- if (typeof file.content === "string") {- await session.writeTextFile({ content: file.content, path });- } else {- await session.writeBinaryFile({ content: file.content, path });- }- }-}diff --git a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts b/packages/eve/src/execution/sandbox/bindings/vercel.test.tsindex cba6d70cd..37fbc47ea 100644--- a/packages/eve/src/execution/sandbox/bindings/vercel.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/vercel.test.ts@@ -9,11 +9,10 @@ import {type VercelSandboxPreparedArtifact,type VercelSandboxSessionState,} from "#execution/sandbox/bindings/vercel.js";-import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";+import { createSandboxEnvironmentHarness } from "#internal/testing/sandbox-provider-harness.js";import { defineSandboxProvider } from "#public/sandbox/provider.js";import type { VercelSandboxSession } from "#public/sandbox/vercel.js";import type { VercelSandboxRuntimeOptions } from "#public/sandbox/vercel-sandbox.js";-import type { LegacySandboxProviderImplementation } from "#shared/sandbox-provider.js";import { VercelSandbox } from "#sandbox/providers/vercel.js";import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";import { DefaultSandbox } from "#sandbox/providers/default.js";@@ -243,27 +242,26 @@ type VercelTestInput = NonNullable<Parameters<typeof createVercelImplementation>readonly prepare?: (sandbox: VercelSandboxSession) => Promise<void> | void;};-/** The binding behind the public provider contract, as core runs it. */-function vercelImplementation({ prepare, ...input }: VercelTestInput = {}) {+/** The binding behind the public provider contract, driven as core runs it. */+function vercelHarness(+ { prepare, ...input }: VercelTestInput = {},+ options: VercelSandboxRuntimeOptions = {},+ harnessOptions: { readonly preparedArtifact?: () => VercelSandboxPreparedArtifact } = {},+) {const provider = defineSandboxProvider({name: "vercel",environment: () => createVercelImplementation(input),});- const environment = provider.environment(prepare === undefined ? {} : { prepare });- return getSandboxEnvironmentRuntime(environment)- .implementation as LegacySandboxProviderImplementation<+ return createSandboxEnvironmentHarness<VercelSandboxRuntimeOptions,VercelSandboxPreparedArtifact,VercelSandboxSessionState,VercelSandboxSession- >;+ >(provider.environment(prepare === undefined ? {} : { prepare }), options, harnessOptions);}function createVercelSandbox(input: VercelTestInput = {}) {- return createSandboxProviderHarness(- vercelImplementation({ prepare: async () => {}, ...input }),- {},- );+ return vercelHarness({ prepare: async () => {}, ...input });}function createTestVercelSandbox(input: VercelTestInput = {}) {@@ -740,11 +738,11 @@ describe("createVercelSandbox", () => {}const sessionSandbox = createMockSandbox({ name: "session" });const create = vi.fn().mockResolvedValue(sessionSandbox);- const provider = createSandboxProviderHarness(- vercelImplementation({+ const provider = vercelHarness(+ {loadSandboxModule: async () =>({ Sandbox: { create, get: vi.fn().mockResolvedValue(null) } }) as never,- }),+ },{mounts: {"/data": new Drive(),@@ -809,10 +807,7 @@ describe("createVercelSandbox", () => {vi.stubEnv("VERCEL_TOKEN", "token_golden");const fake = createFakeVercelProvider();sdk.module = fake.sandboxModule;- const provider = createSandboxProviderHarness(- getSandboxEnvironmentRuntime(DefaultSandbox.environment()).implementation,- undefined,- );+ const provider = createSandboxEnvironmentHarness(DefaultSandbox.environment());const artifact = await provider.prepare({ appRoot });const session = await provider.start({ appRoot, sandboxName: "session_golden" });@@ -1431,13 +1426,13 @@ describe("createVercelSandbox", () => {workspace: { content: string; relativePath: string }[] = [],) => {const create = vi.fn(async (options: { name: string }) => createMockSandbox(options));- const provider = createSandboxProviderHarness(- vercelImplementation({+ const provider = vercelHarness(+ {...input,createSandbox: async ({ createOptions }) => (await create(createOptions)) as never,loadSandboxModule: async () =>({ Sandbox: { create, get: vi.fn().mockResolvedValue(null) } }) as never,- }),+ },{},);return {@@ -1516,7 +1511,7 @@ describe("createVercelSandbox", () => {it("stops the session sandbox on shutdown so no VM outlives the server", async () => {const { handle, sessionSandbox } = await createTestVercelSession();- await handle.onRuntimeShutdown();+ await handle.connection.stop();expect(sessionSandbox.stop).toHaveBeenCalledTimes(1);});@@ -1526,7 +1521,7 @@ describe("createVercelSandbox", () => {vi.mocked(sessionSandbox.runCommand).mockResolvedValue(createMockDetachedCommand() as never);vi.mocked(sessionSandbox.runCommand).mockClear();- await handle.onSandboxStop();+ await handle.connection.stop();await handle.sandbox.run({ command: "printf resumed" });expect(sessionSandbox.stop).toHaveBeenCalledTimes(1);@@ -1539,9 +1534,9 @@ describe("createVercelSandbox", () => {const { handle, sessionSandbox } = await createTestVercelSession();vi.mocked(sessionSandbox.runCommand).mockResolvedValue(createMockDetachedCommand() as never);- await handle.onSandboxStop();+ await handle.connection.stop();await handle.sandbox.run({ command: "printf resumed" });- await handle.onRuntimeShutdown();+ await handle.connection.stop();expect(sessionSandbox.stop).toHaveBeenCalledTimes(2);});@@ -1551,15 +1546,17 @@ describe("createVercelSandbox", () => {const provider = createTestVercelSandbox({loadSandboxModule: async () => fake.sandboxModule as never,});- const handle = await provider.openSession({- appRoot: "/tmp/test-app-root",+ const session = { appRoot: "/tmp/test-app-root", sandboxName: "session-key" };+ const handle = await provider.start({+ ...session,prepared: { snapshotId: "prepared-snapshot" },- sandboxName: "session-key",});const sandbox = fake.sandboxes.get(handle.sandbox.name)!;const abortSignal = new AbortController().signal;- await expect(handle.onSandboxDelete({ abortSignal })).resolves.toBeUndefined();+ await expect(+ provider.endSession({ ...session, abortSignal, reason: "deleted", state: handle.state }),+ ).resolves.toBeUndefined();expect(fake.sandboxModule.Sandbox.get).toHaveBeenLastCalledWith(expect.objectContaining({ name: handle.sandbox.name, resume: false, signal: abortSignal }),@@ -1595,7 +1592,7 @@ describe("createVercelSandbox", () => {sandboxName: "session-key",});- await handle.onRuntimeShutdown();+ await handle.connection.stop();expect(sessionSandbox.stop).not.toHaveBeenCalled();});@@ -1604,7 +1601,7 @@ describe("createVercelSandbox", () => {const { handle, sessionSandbox } = await createTestVercelSession();sessionSandbox.stop.mockRejectedValueOnce(new Error("provider unreachable"));- await expect(handle.onSandboxStop()).rejects.toThrow("provider unreachable");+ await expect(handle.connection.stop()).rejects.toThrow("provider unreachable");});it.each([@@ -1613,8 +1610,8 @@ describe("createVercelSandbox", () => {])("applies the policy from %s after template-less base setup", async (_, environment, open) => {const sessionSandbox = createMockSandbox({ name: "session" });const create = vi.fn().mockResolvedValue(sessionSandbox);- const provider = createSandboxProviderHarness(- vercelImplementation({+ const provider = vercelHarness(+ {createOptions: environment,createSandbox: async ({ createOptions }) => {await create(createOptions);@@ -1622,7 +1619,7 @@ describe("createVercelSandbox", () => {},loadSandboxModule: async () =>({ Sandbox: { create, get: vi.fn().mockResolvedValue(null) } }) as never,- }),+ },open,{ preparedArtifact: () => ({}) },);@@ -1640,12 +1637,12 @@ describe("createVercelSandbox", () => {const sessionSandbox = createMockSandbox({ name: "session" });sessionSandbox.update.mockRejectedValueOnce(new Error("policy rejected"));const fake = createFakeVercelProvider(sessionSandbox);- const provider = createSandboxProviderHarness(- vercelImplementation({+ const provider = vercelHarness(+ {createSandbox: async ({ createOptions, sandboxModule }) =>await sandboxModule.Sandbox.create(createOptions),loadSandboxModule: async () => fake.sandboxModule as never,- }),+ },{ networkPolicy: "deny-all" },{ preparedArtifact: () => ({}) },);@@ -1847,9 +1844,9 @@ describe("createVercelSandbox", () => {]) as never): createMockCommandResult(),);- const readEnv = async (handle: typeof first.handle) =>+ const readEnv = async (handle: { readonly sandbox: VercelSandboxSession }) =>JSON.parse((await handle.sandbox.run({ command: "env" })).stdout);- expect(await readEnv(first.handle)).toEqual({ AI_AGENT: "alice-bot", REVIEW_VALUE: "initial" });+ expect(await readEnv(first)).toEqual({ AI_AGENT: "alice-bot", REVIEW_VALUE: "initial" });const reopened = await provider.start({appRoot: "/tmp/test-app-root",@@ -1867,7 +1864,7 @@ describe("createVercelSandbox", () => {prepared: {},existing: first.state,});- expect(await readEnv(reopened.handle)).toEqual({+ expect(await readEnv(reopened)).toEqual({AI_AGENT: "alice-bot",REVIEW_VALUE: "initial",});diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.tsindex 13234dbf0..b68fd6c67 100644--- a/packages/eve/src/execution/sandbox/ensure.test.ts+++ b/packages/eve/src/execution/sandbox/ensure.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";+import { shutdownActiveSandboxConnections } from "#execution/sandbox/active-connections.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";import { readDurableSession } from "#execution/durable-session-store.js";@@ -7,10 +7,7 @@ import { importConversation, readLegacySnapshot } from "#execution/legacy-sessioimport { ensureSandboxAccess } from "#execution/sandbox/ensure.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import { defineParentSandbox, defineSandbox } from "#public/definitions/sandbox.js";-import {- defineLegacySandboxProvider,- type SandboxProviderSessionContext,-} from "#shared/sandbox-provider.js";+import { defineSandboxProvider, type SandboxSessionContext } from "#sandbox/provider.js";import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";@@ -21,27 +18,28 @@ vi.mock("#runtime/sandbox/prepared-artifacts.js", () => ({loadSandboxPreparedArtifact: vi.fn(async () => null),}));-function fixture(setup?: () => void, returnCopy = false) {- const deleteSandbox = vi.fn(async () => {});+function fixture(+ options: {+ readonly closable?: boolean;+ readonly returnCopy?: boolean;+ readonly setup?: () => void;+ } = {},+) {+ const { returnCopy = false, setup } = options;const onSessionEnd = vi.fn(async () => {});const stopSandbox = vi.fn(async () => {});- const shutdownSandbox = vi.fn(async () => {});+ const closeSandbox = vi.fn(async () => {});const create = vi.fn(async () => {- const sandbox = mockSandbox();- return {- sandbox: sandbox.session,- onSandboxDelete: deleteSandbox,- onRuntimeShutdown: shutdownSandbox,- onSandboxStop: stopSandbox,- };+ const { connection } = mockSandbox({ stop: stopSandbox });+ return options.closable === true ? { ...connection, close: closeSandbox } : connection;});- const start = vi.fn(async (context: SandboxProviderSessionContext) => ({- handle: await create(),+ const start = vi.fn(async (context: SandboxSessionContext) => ({+ connection: await create(),state: { key: context.session.id },}));- const provider = defineLegacySandboxProvider({+ const provider = defineSandboxProvider({name: "test",- environment: () => ({ onSessionEnd, prepare: async () => null, resume: create, start }),+ environment: () => ({ onSessionEnd, prepare: async () => null, start, resume: create }),});const environment = provider.environment();const selector = defineSandbox(async () => {@@ -63,43 +61,26 @@ function fixture(setup?: () => void, returnCopy = false) {workspaceResourceRoot: { logicalPath: "", rootEntries: [] },},};- return {- create,- deleteSandbox,- onSessionEnd,- registry,- shutdownSandbox,- start,- stopSandbox,- };+ return { closeSandbox, create, onSessionEnd, registry, start, stopSandbox };}/** A provider that honors the contract: `start` upserts on the session id, and cleanup deletes by it. */function upsertingFixture() {const live = new Map<string, ReturnType<typeof mockSandbox>>();- const handle = (sessionId: string) => {+ const connect = (sessionId: string) => {let sandbox = live.get(sessionId);if (sandbox === undefined) {sandbox = mockSandbox();live.set(sessionId, sandbox);}- return {- sandbox: sandbox.session,- onRuntimeShutdown: async () => {},- onSandboxDelete: async () => void live.delete(sessionId),- onSandboxStop: async () => {},- };+ return sandbox.connection;};- const environment = defineLegacySandboxProvider({+ const environment = defineSandboxProvider({name: "upserting",environment: () => ({- onSessionEnd: async (context: SandboxProviderSessionContext) =>- void live.delete(context.session.id),+ onSessionEnd: async (context) => void live.delete(context.session.id),prepare: async () => null,- resume: async (context: SandboxProviderSessionContext) => handle(context.session.id),- start: async (context: SandboxProviderSessionContext) => ({- handle: handle(context.session.id),- state: null,- }),+ start: async (context) => ({ connection: connect(context.session.id), state: null }),+ resume: async (context) => connect(context.session.id),}),}).environment();const registry: RuntimeSandboxRegistry = {@@ -164,7 +145,7 @@ function inheritingChildRegistry(rootRegistry: RuntimeSandboxRegistry): RuntimeS},};}-afterEach(() => shutdownActiveSandboxHandles());+afterEach(() => shutdownActiveSandboxConnections());describe("ensureSandboxAccess", () => {it("does not prepare or start anything until the sandbox is requested", async () => {@@ -192,10 +173,15 @@ describe("ensureSandboxAccess", () => {const value = fixture();expect((await open(value.registry)).sandbox).toBeTruthy();expect(value.create).toHaveBeenCalledOnce();+ expect(value.start).toHaveBeenCalledWith(+ expect.objectContaining({ kind: "session" }),+ undefined,+ null,+ );});it("resumes persisted provider state without invoking the selector", async () => {const setup = vi.fn();- const value = fixture(setup);+ const value = fixture({ setup });await open(value.registry, "session-1", {session: { providerName: "test", state: null, stateProtocolVersion: 1 },});@@ -206,7 +192,7 @@ describe("ensureSandboxAccess", () => {// https://github.com/vercel/eve/issues/5113it("starts a fresh sandbox when the persisted one is gone", async () => {const setup = vi.fn();- const value = fixture(setup);+ const value = fixture({ setup });value.create.mockRejectedValueOnce(new SandboxSessionGoneError('docker session "ses_1" is no longer available to resume.'),);@@ -228,7 +214,7 @@ describe("ensureSandboxAccess", () => {it("starts a fresh sandbox for a session saved with the removed microsandbox provider", async () => {const setup = vi.fn();- const value = fixture(setup);+ const value = fixture({ setup });const { access } = await open(value.registry, "session-1", {session: { providerName: "microsandbox", state: { key: "old" }, stateProtocolVersion: 1 },});@@ -249,7 +235,7 @@ describe("ensureSandboxAccess", () => {["another state protocol", { providerName: "test", stateProtocolVersion: 2 }],])("starts a fresh sandbox for state %s recorded", async (_, record) => {const setup = vi.fn();- const value = fixture(setup);+ const value = fixture({ setup });const { access } = await open(value.registry, "session-1", {session: { ...record, state: { key: "old" } },});@@ -285,7 +271,7 @@ describe("ensureSandboxAccess", () => {it("starts a fresh sandbox for a session imported from eve 0.54", async () => {const setup = vi.fn();- const value = fixture(setup);+ const value = fixture({ setup });const imported = importConversation(readLegacySnapshot({sessionId: "session-1",@@ -322,7 +308,7 @@ describe("ensureSandboxAccess", () => {it("runs the parent's selector when a child that inherits its sandbox opens it first", async () => {const setup = vi.fn();- const value = fixture(setup);+ const value = fixture({ setup });await open(inheritingChildRegistry(value.registry), "parent-session", null, "child");@@ -335,7 +321,7 @@ describe("ensureSandboxAccess", () => {});it("rejects a fabricated sandbox", async () => {- const value = fixture(undefined, true);+ const value = fixture({ returnCopy: true });await expect(open(value.registry)).rejects.toThrow("must return the sandbox it opens");});@@ -401,9 +387,12 @@ describe("ensureSandboxAccess", () => {it("retries session setup after a selector failure", async () => {let attempts = 0;- const value = fixture(() => {- attempts += 1;- if (attempts === 1) throw new Error("setup failed");+ const value = fixture({+ closable: true,+ setup: () => {+ attempts += 1;+ if (attempts === 1) throw new Error("setup failed");+ },});const context = new ContextContainer();context.set(SessionKey, {@@ -420,26 +409,99 @@ describe("ensureSandboxAccess", () => {state: null,});await expect(access.get()).rejects.toThrow("setup failed");- await shutdownActiveSandboxHandles();- expect(value.shutdownSandbox).not.toHaveBeenCalled();+ // The rejected connection is closed and left out of shutdown tracking.+ expect(value.closeSandbox).toHaveBeenCalledOnce();+ await shutdownActiveSandboxConnections();+ expect(value.stopSandbox).not.toHaveBeenCalled();await expect(access.get()).resolves.toBeTruthy();});expect(attempts).toBe(2);});- it("tracks dedicated handles for server shutdown", async () => {- const value = fixture();+ it("stops and closes tracked connections at server shutdown", async () => {+ const value = fixture({ closable: true });await open(value.registry);- await shutdownActiveSandboxHandles();- expect(value.shutdownSandbox).toHaveBeenCalledOnce();+ await shutdownActiveSandboxConnections();+ expect(value.stopSandbox).toHaveBeenCalledOnce();+ expect(value.closeSandbox).toHaveBeenCalledOnce();});- it("deletes a dedicated sandbox and creates a fresh handle on next access", async () => {+ it("closes a connection it cannot use", async () => {+ const value = fixture();+ value.create.mockImplementationOnce(async () => ({+ ...mockSandbox().connection,+ close: value.closeSandbox,+ workspaceRoot: "app",+ }));+ await expect(open(value.registry)).rejects.toThrow("workspaceRoot must be an absolute path");+ expect(value.closeSandbox).toHaveBeenCalledOnce();+ });++ it("stops a stopped sandbox without close() again at shutdown until its session ends", async () => {+ const value = fixture();+ const { access, sandbox } = await open(value.registry);+ if (sandbox === null) throw new Error("Expected a sandbox.");+ await access.stop();+ // A resumed connection is still running, so shutdown stops it again.+ await sandbox.run({ command: "true" });+ expect(value.create).toHaveBeenCalledOnce();+ await shutdownActiveSandboxConnections();+ expect(value.stopSandbox).toHaveBeenCalledTimes(2);++ const ended = await open(value.registry, "session-2");+ await ended.access.stop();+ await ended.access.end("completed");+ await shutdownActiveSandboxConnections();+ expect(value.stopSandbox).toHaveBeenCalledTimes(3);++ // A connection with close() is closed by stop() and cannot resume.+ const closable = fixture({ closable: true });+ await (await open(closable.registry, "session-3")).access.stop();+ await shutdownActiveSandboxConnections();+ expect(closable.stopSandbox).toHaveBeenCalledOnce();+ });++ it.each([+ ["session", false, { closed: 0, stopped: 1 }],+ ["session", true, { closed: 1, stopped: 0 }],+ ["call", false, { closed: 0, stopped: 0 }],+ ["none", true, { closed: 1, stopped: 0 }],+ ] as const)(+ "lets go of a %s access's connection (closable: %s) when its step ends",+ async (shutdownTracking, closable, expected) => {+ const value = fixture({ closable });+ const access = await ensureSandboxAccess({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ nodeId: "__root__",+ registry: value.registry,+ sessionId: "session-1",+ shutdownTracking,+ state: null,+ });+ await access.get();++ await access.release();+ // Only a connection without close() stays for shutdown, and only a session's own.+ await shutdownActiveSandboxConnections();++ expect(value.closeSandbox).toHaveBeenCalledTimes(expected.closed);+ expect(value.stopSandbox).toHaveBeenCalledTimes(expected.stopped);+ // The next use in the session opens a new connection.+ await access.get();+ expect(value.create).toHaveBeenCalledTimes(2);+ },+ );++ it("deletes a dedicated sandbox and creates a fresh connection on next access", async () => {const value = fixture();const { access } = await open(value.registry);await access.delete?.();await access.get();- expect(value.deleteSandbox).toHaveBeenCalledOnce();+ expect(value.onSessionEnd).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ session: expect.objectContaining({ id: "session-1" }) }),+ { key: "session-1" },+ { abortSignal: undefined, reason: "deleted" },+ );expect(value.create).toHaveBeenCalledTimes(2);});@@ -454,7 +516,6 @@ describe("ensureSandboxAccess", () => {{ key: "session-1" },{ reason: "expired" },);- expect(value.deleteSandbox).not.toHaveBeenCalled();await expect(access.captureState()).resolves.toEqual({ session: null });});diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.tsindex 4fe50cd5b..c26ce9b8d 100644--- a/packages/eve/src/execution/sandbox/ensure.ts+++ b/packages/eve/src/execution/sandbox/ensure.ts@@ -1,4 +1,5 @@import { randomUUID } from "node:crypto";+import { resolve } from "node:path";import { ensureDevelopmentSandboxesPrepared } from "#execution/sandbox/development-lazy-prewarm.js";import { isEveDevEnvironment } from "#internal/application/dev-environment.js";@@ -9,10 +10,11 @@ import {withRuntimeSandboxLifecycle,} from "#context/build-callback-context.js";import {- trackActiveSandboxHandle,- untrackActiveSandboxHandle,-} from "#execution/sandbox/active-handles.js";-import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";+ trackActiveSandboxConnection,+ untrackActiveSandboxConnection,+} from "#execution/sandbox/active-connections.js";+import { createConnectionSession } from "#execution/sandbox/session.js";+import { isToolSessionId } from "#execution/tool-session/id.js";import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";import {getRuntimeCompiledArtifactsSandboxAppRoot,@@ -20,6 +22,12 @@ import {} from "#runtime/compiled-artifacts-source.js";import { loadSandboxPreparedArtifact } from "#runtime/sandbox/prepared-artifacts.js";import { owningSandboxDefinition, type RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";+import type {+ SandboxConnection,+ SandboxJson,+ SandboxProviderRuntime,+ SandboxSessionContext,+} from "#sandbox/provider.js";import {getSessionEndWithArtifact,resolvePersistedSandboxSessionState,@@ -32,16 +40,11 @@ import {getSandboxEnvironmentRuntime,runWithSandboxConstructorRuntime,} from "#shared/sandbox-environment.js";-import {- isSandboxPreparedArtifact,- type SandboxDeleteOptions,- type SandboxProviderHandle,- type SandboxProviderRuntime,- type SandboxProviderSessionContext,-} from "#shared/sandbox-provider.js";-import type { RuntimeSandboxSession } from "#shared/sandbox-session.js";+import { isSandboxPreparedArtifact, type SandboxDeleteOptions } from "#shared/sandbox-provider.js";+import type { RuntimeSandboxSession, SandboxSession } from "#shared/sandbox-session.js";import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";+import { ToolSessionSandboxUnsupportedError } from "#shared/sandbox-tool-session-error.js";interface EnsureSandboxAccessInput {readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;@@ -52,12 +55,15 @@ interface EnsureSandboxAccessInput {readonly sessionId: string;readonly state: SandboxState | null;/**- * `true` for a caller that borrows a session's sandbox outside its turns,- * such as a workflow step. Its handle stays out of the shutdown registry,- * which tracks one handle per session, so it never replaces or drops the- * session's own.+ * How long the server-shutdown registry, which holds one connection per+ * session, keeps this access's connection. `"session"`, the default for a+ * session's own steps, keeps a connection without `close()` after release,+ * so shutdown still stops the session's sandbox. `"call"` drops it at+ * release, for a keyed tool call, whose sandbox no session ends. `"none"`+ * never registers it, for a workflow step that borrows a session's sandbox+ * outside its turns and must not replace or drop the session's own.*/- readonly borrowed?: boolean;+ readonly shutdownTracking?: "call" | "none" | "session";}/** The access `ensureSandboxAccess` builds, with what the opener may do beyond the sandbox API. */@@ -69,19 +75,23 @@ export interface EnsuredSandboxAccess extends SandboxAccess {*/end(reason: SandboxSessionEndReason): Promise<void>;/**- * Lets go of the handle this access opened, if any, without stopping or- * deleting the sandbox, and returns it so the caller can free what it- * holds in this process. For a sandbox that outlives the access, such as a- * tool session's. Waits for an open still in flight, so a caller that- * finished early never leaves that handle behind.+ * Lets go of the connection this access opened, if any, when the step that+ * opened it ends: closes it without stopping or deleting the sandbox.+ * Waits for an open still in flight, so a caller that finished early never+ * leaves that connection behind.*/- detach(): Promise<SandboxProviderHandle | undefined>;+ release(): Promise<void>;}+/** A connection this access opened, with the lifecycle eve maps onto it. */interface OpenedSandbox {- readonly handle: SandboxProviderHandle;+ readonly closable: boolean;readonly providerName: string;readonly sandbox: RuntimeSandboxSession;+ close(): Promise<void>;+ delete(options?: SandboxDeleteOptions): Promise<void>;+ /** Releases compute, then closes the connection. */+ stop(): Promise<void>;}// Parent and subagent sessions that share a sandbox each build their own@@ -106,16 +116,11 @@ export async function ensureSandboxAccess(: undefined,);let opened: OpenedSandbox | undefined;- let opening: Promise<SandboxProviderHandle> | undefined;- let requiring: Promise<SandboxProviderHandle> | undefined;- // The handle this access registered for shutdown. A stopped handle stays- // registered, since its connection can resume, until the session lets go.- let tracked: Parameters<typeof untrackActiveSandboxHandle>[0] | undefined;- const track: typeof trackActiveSandboxHandle = (entry) => {- if (input.borrowed === true) return;- trackActiveSandboxHandle(entry);- tracked = entry;- };+ // A stopped connection without `close()` resumes on its next use, so shutdown keeps it until the session lets go.+ let stopped: OpenedSandbox | undefined;+ let opening: Promise<OpenedSandbox> | undefined;+ let requiring: Promise<OpenedSandbox> | undefined;+ const tracking = input.shutdownTracking ?? "session";const appRoot =getRuntimeCompiledArtifactsSandboxAppRoot(input.compiledArtifactsSource) ?? process.cwd();const captured = (): SandboxState => ({ session: persisted });@@ -124,20 +129,18 @@ export async function ensureSandboxAccess(async captureState() {return captured();},- async detach() {- return undefined;- },async end() {},async get() {return null;},+ async release() {},async stop() {},};}const ownerDefinition = owningSandboxDefinition(registered);const ownerNodeId = registered.inheritance?.nodeId ?? input.nodeId;- function providerContext(turnId: string): SandboxProviderSessionContext {+ function providerContext(turnId: string): SandboxSessionContext {const activeSession =contextStorage.getStore() === undefined? {@@ -147,7 +150,8 @@ export async function ensureSandboxAccess(}: buildCallbackContext().session;return {- host: createSandboxProviderHost(appRoot),+ kind: isToolSessionId(input.sessionId) ? "tool-session" : "session",+ resolveProjectPath: (path) => resolve(appRoot, path),session: { ...activeSession, id: input.sessionId },storagePath: resolveSandboxCacheDirectory(appRoot),};@@ -181,7 +185,7 @@ export async function ensureSandboxAccess(provider: SandboxProviderRuntime,options: object | undefined,environment: object,- context: SandboxProviderSessionContext,+ context: SandboxSessionContext,): Promise<RuntimeSandboxSession> {if (opening !== undefined)throw new Error(@@ -203,44 +207,31 @@ export async function ensureSandboxAccess(}const artifact = await loadArtifact(provider);- const createHandle = async () => {+ const start = async () => {const result = await provider.implementation.start(context, options, artifact);if (!isSandboxPreparedArtifact(result.state)) {throw new Error(`Sandbox provider "${provider.providerName}" returned non-serializable session state.`,);}+ const started = await openSandbox(provider, context, result.connection, result.state);persisted = {generation: randomUUID(),providerName: provider.providerName,state: result.state,stateProtocolVersion: provider.stateProtocolVersion,};- return result.handle;+ return started;};- opening = createHandle().catch((error: unknown) => {+ opening = start().catch((error: unknown) => {opening = undefined;throw error;});-- const handle = await opening;- return installHandle(provider.providerName, handle);+ opened = await opening;+ return opened.sandbox;}- function installHandle(- providerName: string,- handle: SandboxProviderHandle,- ): RuntimeSandboxSession {- const sandbox = withRuntimeSandboxLifecycle(- handle.sandbox,- (deleteOptions?: SandboxDeleteOptions) => handle.onSandboxDelete(deleteOptions),- () => handle.onSandboxStop(),- );- opened = { handle, providerName, sandbox };- return sandbox;- }-- async function resumePersisted(context: SandboxProviderSessionContext) {+ async function resumePersisted(context: SandboxSessionContext) {if (persisted === null) throw new Error("Sandbox session state is missing.");const provider = getSandboxEnvironmentRuntime(activeDefinition().environment);// State another provider or protocol recorded cannot resume here, for example@@ -257,33 +248,34 @@ export async function ensureSandboxAccess();}const artifact = await loadArtifact(provider);+ const state = persisted.state;opening = provider.implementation- .resume(context, artifact, persisted.state)+ .resume(context, artifact, state)+ .then((connection) => openSandbox(provider, context, connection, state)).catch((error: unknown) => {opening = undefined;throw error;});- const handle = await opening;- installHandle(provider.providerName, handle);- track({- handle,- providerName: provider.providerName,- sessionId: input.sessionId,- });- return handle;+ opened = await opening;+ track(opened);+ return opened;}- async function resolveHandle(): Promise<SandboxProviderHandle> {+ async function resolveOpened(): Promise<OpenedSandbox> {const definition = activeDefinition();+ const provider = getSandboxEnvironmentRuntime(definition.environment);+ const context = providerContext("sandbox-initialization");+ if (context.kind === "tool-session" && provider.implementation.toolSessions !== true) {+ throw new ToolSessionSandboxUnsupportedError(provider.providerName);+ }if (isEveDevEnvironment() && input.compiledArtifactsSource.kind === "disk") {await ensureDevelopmentSandboxesPrepared({compiledArtifactsSource: input.compiledArtifactsSource,nodeId: ownerNodeId,- providerName: getSandboxEnvironmentRuntime(definition.environment).providerName,+ providerName: provider.providerName,});}- const context = providerContext("sandbox-initialization");if (persisted !== null) {try {return await resumePersisted(context);@@ -308,7 +300,7 @@ export async function ensureSandboxAccess(concurrentStart = pendingSandboxStarts.get(startKey);}- const starting = startHandle(context);+ const starting = startOpened(context);const sharedStart = starting.then(() => persisted,() => null,@@ -328,7 +320,7 @@ export async function ensureSandboxAccess(* parent's sandbox is the parent's: whichever session opens the sandbox* first creates it with the same options and initialization.*/- async function startHandle(context: SandboxProviderSessionContext) {+ async function startOpened(context: SandboxSessionContext) {const definition = activeDefinition();try {const selected = await runWithSandboxConstructorRuntime(@@ -344,38 +336,50 @@ export async function ensureSandboxAccess(} catch (error) {// The sandbox stays: another session or call may share it, and the// next access runs the selector again on it. Session end removes it.+ await opened?.close().catch(() => undefined);opened = undefined;opening = undefined;persisted = null;throw error;}- track({- handle: opened.handle,- providerName: opened.providerName,- sessionId: input.sessionId,- });- return opened.handle;+ track(opened);+ return opened;}- function requireHandle(): Promise<SandboxProviderHandle> {+ function requireOpened(): Promise<OpenedSandbox> {if (requiring !== undefined) return requiring;- requiring = resolveHandle().catch((error: unknown) => {+ requiring = resolveOpened().catch((error: unknown) => {requiring = undefined;throw error;});return requiring;}- function forgetHandle() {+ function track(current: OpenedSandbox) {+ if (tracking === "none") return;+ trackActiveSandboxConnection({+ connection: current,+ providerName: current.providerName,+ sessionId: input.sessionId,+ });+ }++ function forgetOpened() {const current = opened;- if (tracked !== undefined) untrackActiveSandboxHandle(tracked);- tracked = undefined;opened = undefined;opening = undefined;requiring = undefined;return current;}+ /** The sandbox is gone, so shutdown has nothing left to stop for the session. */+ function forgetSandbox(providerName: string) {+ forgetOpened();+ stopped = undefined;+ untrackActiveSandboxConnection({ providerName, sessionId: input.sessionId });+ persisted = null;+ }+return {environment: ownerDefinition.kind === "independent" ? ownerDefinition.environment : undefined,async captureState() {@@ -385,19 +389,20 @@ export async function ensureSandboxAccess(async delete(deleteOptions) {if (input.ownsSandbox === false)throw new Error("Only the owning session can delete this sandbox.");- const current = await requireHandle();- await current.onSandboxDelete(deleteOptions);- forgetHandle();- persisted = null;- },- async detach() {- // A failed open left nothing to let go of.- if (requiring !== undefined) await requiring.catch(() => undefined);- return forgetHandle()?.handle;+ const current = await requireOpened();+ await current.delete(deleteOptions);+ forgetSandbox(current.providerName);},async end(reason: SandboxSessionEndReason) {if (input.ownsSandbox === false) return;if (requiring !== undefined) await requiring.catch(() => undefined);+ // A failed close of a process-local resource must not block deleting the sandbox.+ await opened?.close().catch((error: unknown) => {+ log.warn("failed to close a sandbox connection at session end", {+ error,+ sessionId: input.sessionId,+ });+ });// A failed step or process loss can create a sandbox without committing// any state. The previous checkpoint cannot prove that the key is unused.const provider = getSandboxEnvironmentRuntime(activeDefinition().environment);@@ -415,24 +420,123 @@ export async function ensureSandboxAccess(} else {const artifact = await loadSandboxPreparedArtifact({compiledArtifactsSource: input.compiledArtifactsSource,- nodeId: registered.inheritance?.nodeId ?? input.nodeId,+ nodeId: ownerNodeId,providerName: provider.providerName,});await endWithArtifact(context, state, { artifact, reason });}- forgetHandle();- persisted = null;+ forgetSandbox(provider.providerName);},async get() {- await requireHandle();- return opened?.sandbox ?? null;+ return (await requireOpened()).sandbox;+ },+ async release() {+ // A failed open left nothing to let go of.+ if (requiring !== undefined) await requiring.catch(() => undefined);+ const current = forgetOpened();+ // A keyed call never ends, so it drops a connection it stopped instead of keeping it for shutdown.+ if (stopped !== undefined && tracking !== "session") {+ untrackActiveSandboxConnection({+ connection: stopped,+ providerName: stopped.providerName,+ sessionId: input.sessionId,+ });+ stopped = undefined;+ }+ // Without `close()` there is nothing to free, and shutdown still stops the session's sandbox.+ if (current === undefined || (tracking === "session" && !current.closable)) return;+ untrackActiveSandboxConnection({+ connection: current,+ providerName: current.providerName,+ sessionId: input.sessionId,+ });+ await current.close();},async stop() {- const current = await requireHandle();- await current.onSandboxStop();- opened = undefined;- opening = undefined;- requiring = undefined;+ const current = await requireOpened();+ await current.stop();+ forgetOpened();+ if (!current.closable) {+ stopped = current;+ return;+ }+ // A closed connection cannot resume, so shutdown has nothing left to stop.+ untrackActiveSandboxConnection({+ connection: current,+ providerName: current.providerName,+ sessionId: input.sessionId,+ });},};++ async function openSandbox(+ provider: SandboxProviderRuntime,+ context: SandboxSessionContext,+ connection: SandboxConnection<object>,+ state: SandboxJson,+ ): Promise<OpenedSandbox> {+ let session: SandboxSession;+ try {+ session = createConnectionSession(connection);+ } catch (error) {+ await connection.close?.().catch((closeError: unknown) => {+ log.warn("failed to close a sandbox connection eve could not use", {+ error: closeError,+ sessionId: input.sessionId,+ });+ });+ throw error;+ }+ // A stopped connection can resume on its next use, so a later stop runs+ // again; only a stop already in flight is shared. Close runs once.+ const stopCompute = shared(() => connection.stop());+ const close = once(async () => await connection.close?.());+ const current: OpenedSandbox = {+ closable: connection.close !== undefined,+ close,+ async delete(options) {+ try {+ await close();+ } finally {+ await provider.implementation.onSessionEnd(context, state, {+ abortSignal: options?.abortSignal,+ reason: "deleted",+ });+ }+ },+ providerName: provider.providerName,+ sandbox: withRuntimeSandboxLifecycle(+ session,+ (options) => current.delete(options),+ () => current.stop(),+ ),+ async stop() {+ try {+ await stopCompute();+ } finally {+ await close();+ }+ },+ };+ return current;+ }+}++/** Runs `run` at most once at a time; a later call after it settles runs it again. */+function shared(run: () => Promise<void>): () => Promise<void> {+ let running: Promise<void> | undefined;+ return () =>+ (running ??= run().finally(() => {+ running = undefined;+ }));+}++/** Runs `run` at most once while it succeeds; a failed run can be retried. */+function once(run: () => Promise<void>): () => Promise<void> {+ let running: Promise<void> | undefined;+ return () =>+ (running ??= run().catch((error: unknown) => {+ running = undefined;+ throw error;+ }));}diff --git a/packages/eve/src/execution/sandbox/glob-tool.ts b/packages/eve/src/execution/sandbox/glob-tool.tsindex 1baffbf25..bc41df5eb 100644--- a/packages/eve/src/execution/sandbox/glob-tool.ts+++ b/packages/eve/src/execution/sandbox/glob-tool.ts@@ -11,7 +11,6 @@ import { MAX_OUTPUT_BYTES } from "#execution/sandbox/truncate-output.js";const DEFAULT_GLOB_LIMIT = 100;const MAX_GLOB_LIMIT = 1000;-const DEFAULT_PATH = "/workspace";// ---------------------------------------------------------------------------// Input / result shapes@@ -47,9 +46,7 @@ export async function executeGlobOnSandbox(sandbox: SandboxSession,args: GlobInput,): Promise<GlobResult> {- const effectivePath = args.path ?? DEFAULT_PATH;-- const resolvedPath = await resolveAbsoluteFilePath(sandbox, effectivePath);+ const resolvedPath = await resolveAbsoluteFilePath(sandbox, args.path ?? ".");const normalizedPath = normalizeModelPath(resolvedPath);const effectiveLimit = Math.min(Math.max(1, args.limit ?? DEFAULT_GLOB_LIMIT), MAX_GLOB_LIMIT);diff --git a/packages/eve/src/execution/sandbox/grep-tool.ts b/packages/eve/src/execution/sandbox/grep-tool.tsindex f06886548..ebf78251c 100644--- a/packages/eve/src/execution/sandbox/grep-tool.ts+++ b/packages/eve/src/execution/sandbox/grep-tool.ts@@ -11,7 +11,6 @@ import { capLineLength, MAX_OUTPUT_BYTES } from "#execution/sandbox/truncate-outconst DEFAULT_GREP_LIMIT = 100;const MAX_GREP_LIMIT = 1000;-const DEFAULT_PATH = "/workspace";// ---------------------------------------------------------------------------// Input / result shapes@@ -51,9 +50,7 @@ export async function executeGrepOnSandbox(sandbox: SandboxSession,args: GrepInput,): Promise<GrepResult> {- const effectivePath = args.path ?? DEFAULT_PATH;-- const resolvedPath = await resolveAbsoluteFilePath(sandbox, effectivePath);+ const resolvedPath = await resolveAbsoluteFilePath(sandbox, args.path ?? ".");const normalizedPath = normalizeModelPath(resolvedPath);const effectiveLimit = Math.min(Math.max(1, args.limit ?? DEFAULT_GREP_LIMIT), MAX_GREP_LIMIT);const contextLines = args.context !== undefined && args.context > 0 ? args.context : 0;diff --git a/packages/eve/src/execution/sandbox/prewarm.scenario.test.ts b/packages/eve/src/execution/sandbox/prewarm.scenario.test.tsindex 795697c18..7c1353178 100644--- a/packages/eve/src/execution/sandbox/prewarm.scenario.test.ts+++ b/packages/eve/src/execution/sandbox/prewarm.scenario.test.ts@@ -6,7 +6,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { compileAgentInWorkspace } from "#compiler/compile-agent.js";import { resolvePackageSourceFilePath } from "#internal/application/package.js";import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";-import type { SandboxProviderPrepareContext } from "#shared/sandbox-provider.js";+import { populatedPaths } from "#internal/testing/sandbox-provider-harness.js";+import type { SandboxPrepareContext } from "#sandbox/provider.js";import { prewarmAppSandboxes } from "#execution/sandbox/prewarm.js";import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";@@ -111,8 +112,8 @@ describe("prewarmAppSandboxes", () => {expect(events.seededTemplateCount).toBe(2);expect([...events.seededFilePaths].sort()).toEqual([- "$HOME/.agents/skills/research/SKILL.md",- "$HOME/.agents/skills/route-weather/SKILL.md",+ "/home/agent/.agents/skills/research/SKILL.md",+ "/home/agent/.agents/skills/route-weather/SKILL.md",]);});});@@ -193,23 +194,14 @@ async function createScenarioAppRoot(): Promise<string> {}function createRecordingDispatch(events: ReturnType<typeof createPrewarmEvents>) {- return async ({ context }: { context: SandboxProviderPrepareContext }) => {+ return async ({ context }: { context: SandboxPrepareContext }) => {events.templateKeys.push(context.storagePath);events.runtimeContextAppRoots.push(context.storagePath);- const resourceFiles = [- ...(context.resources.workspace?.files.map((file) => ({- ...file,- path: `${context.resources.workspace?.targetPath}/${file.relativePath}`,- })) ?? []),- ...(context.resources.skills?.files.map((file) => ({- ...file,- path: `${context.resources.skills?.targetPath}/${file.relativePath}`,- })) ?? []),- ];- if (resourceFiles.length > 0) {+ const paths = await populatedPaths(context);+ if (paths.length > 0) {events.seededTemplateCount += 1;- events.seededFilePaths.push(...resourceFiles.map((file) => file.path));+ events.seededFilePaths.push(...paths);}return { storagePath: context.storagePath };diff --git a/packages/eve/src/execution/sandbox/prewarm.test.ts b/packages/eve/src/execution/sandbox/prewarm.test.tsindex 89d8d95fc..7df7f07c6 100644--- a/packages/eve/src/execution/sandbox/prewarm.test.ts+++ b/packages/eve/src/execution/sandbox/prewarm.test.ts@@ -4,10 +4,7 @@ import {prewarmAppSandboxes,type SandboxPreparedArtifactStore,} from "#execution/sandbox/prewarm.js";-import {- defineLegacySandboxProvider,- type SandboxProviderPrepareContext,-} from "#shared/sandbox-provider.js";+import { defineSandboxProvider, type SandboxPrepareContext } from "#sandbox/provider.js";import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { ROOT_RUNTIME_AGENT_NODE_ID, type ResolvedAgentGraphBundle } from "#runtime/graph.js";import type { ResolvedSandboxDefinition } from "#runtime/types.js";@@ -33,8 +30,8 @@ describe("prewarmAppSandboxes", () => {const appRoot = process.cwd();const firstSnapshotRoot = `${appRoot}/.eve/dev-runtime/snapshots/one/app`;const secondSnapshotRoot = `${appRoot}/.eve/dev-runtime/snapshots/two/app`;- const firstInputs: SandboxProviderPrepareContext[] = [];- const secondInputs: SandboxProviderPrepareContext[] = [];+ const firstInputs: SandboxPrepareContext[] = [];+ const secondInputs: SandboxPrepareContext[] = [];const workspaceResourceRoot = {contentHash: "workspace-content-hash",logicalPath: "empty-resource-root",@@ -66,8 +63,8 @@ describe("prewarmAppSandboxes", () => {expect(secondInputs).toHaveLength(1);expect(firstInputs[0]?.storagePath).toBe(resolveSandboxCacheDirectory(appRoot));expect(secondInputs[0]?.storagePath).toBe(resolveSandboxCacheDirectory(appRoot));- expect(firstInputs[0]?.sourceRevision).toBe("sandbox-source-hash");- expect(secondInputs[0]?.sourceRevision).toBe("sandbox-source-hash");+ expect(firstInputs[0]?.resolveProjectPath(".")).toBe(appRoot);+ expect(secondInputs[0]?.templateKey({})).toBe(firstInputs[0]?.templateKey({}));});it("waits for other providers to finish before reporting a preparation failure", async () => {@@ -142,8 +139,8 @@ function createMemoryArtifactStore(): SandboxPreparedArtifactStore {return { async write() {} };}-function recordPrewarmInputs(inputs: SandboxProviderPrepareContext[]) {- return async ({ context }: { context: SandboxProviderPrepareContext }) => {+function recordPrewarmInputs(inputs: SandboxPrepareContext[]) {+ return async ({ context }: { context: SandboxPrepareContext }) => {inputs.push(context);return null;};@@ -159,7 +156,7 @@ function createGraph(};} = {},): ResolvedAgentGraphBundle {- const provider = defineLegacySandboxProvider({+ const provider = defineSandboxProvider({name: input.providerName ?? "test",environment: () => ({async onSessionEnd() {},diff --git a/packages/eve/src/execution/sandbox/prewarm.ts b/packages/eve/src/execution/sandbox/prewarm.tsindex 912a0aa9d..4bc7b9af1 100644--- a/packages/eve/src/execution/sandbox/prewarm.ts+++ b/packages/eve/src/execution/sandbox/prewarm.ts@@ -1,14 +1,21 @@import { join, relative, resolve } from "node:path";import type { CompiledWorkspaceResourceRoot } from "#compiler/manifest.js";+import { copyDirectoryAtomically } from "#execution/sandbox/bindings/local-provider-utils.js";+import { createLoggingSandboxSession } from "#execution/sandbox/logging-session.js";+import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";+import { createConnectionSession } from "#execution/sandbox/session.js";+import { shellQuote } from "#execution/sandbox/shell-quote.js";import { loadCompiledModuleMapFromAuthoredSource } from "#internal/authored-module-map-loader.js";import { createAuthoredSourceRuntimeCompiledArtifactsSource } from "#internal/application/runtime-compiled-artifacts-source.js";-import {- createSandboxProviderResources,- type SandboxPreparedArtifact,- type SandboxProviderPrepareContext,- type SandboxProviderResources,- type SandboxProviderRuntime,+import type {+ SandboxJson,+ SandboxPrepareContext,+ SandboxProviderRuntime,+} from "#sandbox/provider.js";+import type {+ SandboxProviderFiles,+ SandboxProviderResourceFile,} from "#shared/sandbox-provider.js";import {getRuntimeCompiledArtifactsSandboxAppRoot,@@ -24,7 +31,6 @@ import { loadCompiledManifest } from "#runtime/loaders/manifest.js";import { resolveRuntimeCompilerArtifactPaths } from "#runtime/loaders/artifact-paths.js";import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";import { createSandboxProviderFiles } from "#execution/sandbox/provider-files.js";-import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";import type { RuntimeRegisteredSandbox } from "#runtime/sandbox/registry.js";import type { SandboxPreparedArtifactEntry } from "#shared/sandbox-prepared-artifacts.js";@@ -32,6 +38,8 @@ import { writeSandboxPreparedArtifactsManifest } from "#runtime/sandbox/preparedimport { materializeWorkspaceDirectory } from "#runtime/workspace/seed-files.js";import { toErrorMessage } from "#shared/errors.js";import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";+import type { SandboxSession } from "#shared/sandbox-session.js";+import { MODEL_SKILL_ROOT, resolveSandboxModelPath } from "#shared/skill-paths.js";export interface SandboxPreparedArtifactStore {write(input: {@@ -47,10 +55,12 @@ const diskPreparedArtifactStore: SandboxPreparedArtifactStore = {};interface PrewarmTarget {- readonly context: SandboxProviderPrepareContext;+ readonly files: SandboxProviderFiles;readonly label: string;readonly nodeId: string;readonly provider: SandboxProviderRuntime;+ readonly resources: SandboxTemplateResources;+ readonly sourceRevision: string;}interface NodeSandbox extends RuntimeRegisteredSandbox {@@ -69,9 +79,9 @@ interface NodeSandbox extends RuntimeRegisteredSandbox {* them.*/type SandboxProviderPrepareDispatch = (input: {- readonly context: SandboxProviderPrepareContext;+ readonly context: SandboxPrepareContext;readonly provider: SandboxProviderRuntime;-}) => Promise<SandboxPreparedArtifact>;+}) => Promise<SandboxJson>;interface PrewarmSandboxesInput {readonly appRoot: string;@@ -105,17 +115,20 @@ async function prewarmSandboxes(input: PrewarmSandboxesInput): Promise<void> {input.log?.(`eve: initializing ${formatSandboxTemplateCount(targets.length)}...`);const results = await Promise.allSettled(- targets.map(async ({ context, label, nodeId, provider }) => {+ targets.map(async ({ label, nodeId, provider, ...target }) => {const logProviderProgress = (message: string) => {if (!shouldLogSandboxPrewarmProgress(message)) return;input.log?.(`eve: sandbox template "${label}" (${provider.providerName}): ${message}`);};try {const result = await dispatch({- context: {- ...context,- log: input.log === undefined ? undefined : logProviderProgress,- },+ context: createSandboxPrepareContext({+ ...target,+ appRoot: input.appRoot,+ log: logProviderProgress,+ provider,+ storagePath: resolveSandboxCacheDirectory(input.appRoot),+ }),provider,});return { nodeId, provider, result };@@ -213,16 +226,12 @@ async function collectPrewarmTargets(input: {workspaceResourceRoot,});targets.push({- context: {- files: createSandboxProviderFiles(sandboxRoot),- host: createSandboxProviderHost(input.appRoot),- resources,- sourceRevision: definition.revisionHash,- storagePath: resolveSandboxCacheDirectory(input.appRoot),- },+ files: createSandboxProviderFiles(sandboxRoot),label: formatLabel(nodeId),nodeId,provider,+ resources,+ sourceRevision: definition.revisionHash,});}),);@@ -239,15 +248,154 @@ async function collectPrewarmTargets(input: {async function loadSandboxProviderResources(input: {readonly compileDirectoryPath: string;readonly workspaceResourceRoot: CompiledWorkspaceResourceRoot;-}): Promise<SandboxProviderResources> {+}): Promise<SandboxTemplateResources> {const { contentHash, logicalPath } = input.workspaceResourceRoot;- if (contentHash === undefined) return createSandboxProviderResources({});+ if (contentHash === undefined) return {};const path = `${input.compileDirectoryPath}/${logicalPath}`;- return createSandboxProviderResources({- key: contentHash,- path,- ...(await materializeWorkspaceDirectory(path)),+ return { key: contentHash, path, ...(await materializeWorkspaceDirectory(path)) };+}++/** The compiled workspace and skill files one sandbox template seeds. */+export interface SandboxTemplateResources {+ /** The compiled resource tree's content hash; absent when the agent has none. */+ readonly key?: string;+ /** The compiled resource directory on the host, holding `workspace/` and `skills/`. */+ readonly path?: string;+ readonly skills?: readonly SandboxProviderResourceFile[];+ readonly workspace?: readonly SandboxProviderResourceFile[];+}++/** The context eve passes to a provider's `prepare()` for one template. */+export function createSandboxPrepareContext(input: {+ readonly appRoot: string;+ readonly files: SandboxProviderFiles;+ readonly log: (message: string) => void;+ readonly provider: Pick<SandboxProviderRuntime, "prepare" | "providerName">;+ readonly resources: SandboxTemplateResources;+ readonly sourceRevision: string;+ readonly storagePath: string;+}): SandboxPrepareContext {+ const { log, resources, storagePath } = input;+ const { prepare } = input.provider;+ const workspace = resources.workspace ?? [];+ const skills = resources.skills ?? [];+ const resourcesPath = resources.key === undefined ? undefined : resources.path;+ return {+ files: input.files,+ isEmpty: workspace.length === 0 && skills.length === 0 && prepare === undefined,+ log,+ async populate(connection, options) {+ const session = createConnectionSession(connection);+ // Without a resource directory there is nothing mounted to copy from.+ if (options?.mountedAt !== undefined && resourcesPath !== undefined) {+ log("copying workspace and skills from mounted resources");+ await copyMountedResources(session, shellQuote(options.mountedAt));+ } else if (workspace.length > 0 || skills.length > 0) {+ log("writing workspace and skills");+ const bytes = (file: SandboxProviderResourceFile) =>+ typeof file.content === "string" ? Buffer.from(file.content) : file.content;+ await session.writeFiles({+ files: [+ // A workspace file named like `$HOME/...` still lands under the workspace root.+ ...workspace.map((file) => ({+ content: bytes(file),+ path: session.resolvePath(file.relativePath),+ })),+ ...(await Promise.all(+ skills.map(async (file) => ({+ content: bytes(file),+ path: await resolveSandboxModelPath({+ path: `${MODEL_SKILL_ROOT}/${file.relativePath}`,+ sandbox: session,+ }),+ })),+ )),+ ],+ });+ }+ if (prepare === undefined) return;+ log("running sandbox preparation");+ await prepare(createLoggingSandboxSession({ log, session }));+ },+ resolveProjectPath: (path) => resolve(input.appRoot, path),+ async resourcesDirectory() {+ if (resources.key === undefined || resourcesPath === undefined) return undefined;+ const directory = join(storagePath, input.provider.providerName, "resources", resources.key);+ await copyDirectoryAtomically(resourcesPath, directory);+ return directory;+ },+ storagePath,+ templateKey(identity) {+ assertSandboxIdentity(identity, "identity", new WeakSet());+ for (const reserved of ["resources", "sourceRevision"]) {+ if (Object.hasOwn(identity, reserved)) {+ throw new Error(+ `ctx.templateKey() reserves "${reserved}": eve adds the workspace and skill files and the sandbox source revision itself. Rename that identity field.`,+ );+ }+ }+ const key = resources.key;+ return createSandboxProviderIdentity({+ ...identity,+ resources: {+ skills: key === undefined ? undefined : `${key}:skills`,+ workspace: key === undefined ? undefined : `${key}:workspace`,+ },+ sourceRevision: input.sourceRevision,+ });+ },+ };+}++/** `quotedRoot` is interpolated into the shell script, so callers pass it shell-quoted. */+async function copyMountedResources(session: SandboxSession, quotedRoot: string): Promise<void> {+ const workspace = shellQuote(session.resolvePath("."));+ const result = await session.run({+ command: [+ "set -e",+ `if [ -d ${quotedRoot}/workspace ]; then cp -a ${quotedRoot}/workspace/. ${workspace}/; fi`,+ `if [ -d ${quotedRoot}/skills ]; then`,+ ' mkdir -p "$HOME/.agents"',+ ' rm -rf "$HOME/.agents/skills"',+ ' mkdir -p "$HOME/.agents/skills"',+ ` cp -a ${quotedRoot}/skills/. "$HOME/.agents/skills/"`,+ "fi",+ ].join("\n"),});+ if (result.exitCode !== 0) {+ throw new Error(`Failed to hydrate sandbox resources: ${result.stderr || result.stdout}`);+ }+}++/**+ * Rejects what the template-key hasher cannot tell apart, such as a `Date` or+ * `Map` that would hash as `{}`, and circular values, before hashing.+ */+function assertSandboxIdentity(value: unknown, path: string, seen: WeakSet<object>): void {+ if (value === null || value === undefined || typeof value === "function") return;+ if (typeof value === "string" || typeof value === "boolean") return;+ if (typeof value === "number" && Number.isFinite(value)) return;+ const prototype = typeof value === "object" ? Object.getPrototypeOf(value) : undefined;+ const plain = Array.isArray(value) || prototype === Object.prototype || prototype === null;+ if (typeof value !== "object" || !plain) {+ throw new Error(+ `ctx.templateKey() accepts only JSON values, plain objects, arrays, and functions, but ${path} is ${describeIdentityValue(value)}. Pass a JSON form, such as a string.`,+ );+ }+ if (seen.has(value))+ throw new Error(`ctx.templateKey() cannot hash a circular value at ${path}.`);+ seen.add(value);+ for (const [key, entry] of Object.entries(value)) {+ assertSandboxIdentity(entry, Array.isArray(value) ? `${path}[${key}]` : `${path}.${key}`, seen);+ }+ seen.delete(value);+}++function describeIdentityValue(value: unknown): string {+ if (typeof value === "object" && value !== null) {+ return `a ${value.constructor?.name ?? "non-plain object"}`;+ }+ return typeof value === "number" ? String(value) : `a ${typeof value}`;}async function loadGraphFromArtifacts(input: {diff --git a/packages/eve/src/execution/sandbox/provider-host.ts b/packages/eve/src/execution/sandbox/provider-host.tsdeleted file mode 100644index 27784bc7f..000000000--- a/packages/eve/src/execution/sandbox/provider-host.ts+++ /dev/null@@ -1,16 +0,0 @@-import { resolve } from "node:path";--import { importOptionalEnginePackage } from "#internal/application/optional-package-import.js";-import type { SandboxProviderHost } from "#shared/sandbox-provider.js";--export function createSandboxProviderHost(appRoot: string): SandboxProviderHost {- return {- // Unused, but the extension contracts include this type; it goes with the legacy provider shape.- async loadOptionalPackage(input) {- return await importOptionalEnginePackage({ appRoot, ...input });- },- resolveProjectPath(path) {- return resolve(appRoot, path);- },- };-}diff --git a/packages/eve/src/execution/sandbox/read-file.ts b/packages/eve/src/execution/sandbox/read-file.tsindex b74a22b35..6d520df4d 100644--- a/packages/eve/src/execution/sandbox/read-file.ts+++ b/packages/eve/src/execution/sandbox/read-file.ts@@ -77,7 +77,7 @@ export async function executeReadFileOnSandbox(const bytes = await sandbox.readBinaryFile({ path: resolvedPath });if (bytes === null) {throw new Error(- `File not found: ${filePath}. Verify the path exists and is accessible in the sandbox.`,+ `File not found: ${normalizedPath}. Verify the path exists and is accessible in the sandbox.`,);}@@ -94,7 +94,7 @@ export async function executeReadFileOnSandbox(return buildFileReadResult(bytes, normalizedPath, imageMediaType);}throw new Error(- `File "${filePath}" appears to be a binary file. ` ++ `File "${normalizedPath}" appears to be a binary file. ` +"read_file only supports text files, PNG, JPEG, GIF, or WebP images, and PDFs.",);}diff --git a/packages/eve/src/execution/sandbox/require-sandbox.ts b/packages/eve/src/execution/sandbox/require-sandbox.tsindex 7ad895a54..090c06e1a 100644--- a/packages/eve/src/execution/sandbox/require-sandbox.ts+++ b/packages/eve/src/execution/sandbox/require-sandbox.ts@@ -2,8 +2,9 @@ import type { SandboxSession } from "#public/definitions/sandbox.js";import { resolveSandboxModelPath } from "#shared/skill-paths.js";/**- * Resolves a model-supplied `$HOME` prefix and validates that the resulting- * sandbox file path is absolute.+ * Resolves a model-supplied file path to an absolute sandbox path: a leading+ * `$HOME` through the sandbox's home, and a relative path from the workspace+ * root, where `bash` commands start.*/export async function resolveAbsoluteFilePath(sandbox: SandboxSession,@@ -11,12 +12,12 @@ export async function resolveAbsoluteFilePath(): Promise<string> {const resolvedPath = await resolveSandboxModelPath({ path: filePath, sandbox });- if (!resolvedPath.startsWith("/")) {+ if (resolvedPath === "$HOME" || resolvedPath.startsWith("$HOME/")) {throw new Error(- `filePath must be an absolute path. Received: "${filePath}". ` +- "Use an absolute path such as /workspace/foo.ts or a path beginning with $HOME/.",+ `Cannot resolve "${filePath}": the sandbox has no usable $HOME. ` ++ "Use an absolute path or a path relative to the workspace root.",);}- return resolvedPath;+ return sandbox.resolvePath(resolvedPath);}diff --git a/packages/eve/src/execution/sandbox/ripgrep-probe.ts b/packages/eve/src/execution/sandbox/ripgrep-probe.tsindex 9eeb7150c..09fd629ac 100644--- a/packages/eve/src/execution/sandbox/ripgrep-probe.ts+++ b/packages/eve/src/execution/sandbox/ripgrep-probe.ts@@ -1,9 +1,11 @@import type { SandboxSession } from "#public/definitions/sandbox.js";+// Searching an empty file checks that `rg` accepts eve's options (just-bash's+// `rg` does not) without walking a directory tree.const RIPGREP_PROBE_COMMAND ="command -v rg >/dev/null 2>&1 || exit 127; " +"rg --line-number --color=never --hidden --glob '!.git/*' --max-count 1 -- " +- "'__eve_ripgrep_probe_never_matches__' /workspace";+ "'__eve_ripgrep_probe_never_matches__' /dev/null";export async function ripgrepIsAvailable(session: SandboxSession): Promise<boolean> {try {diff --git a/packages/eve/src/execution/sandbox/session.test.ts b/packages/eve/src/execution/sandbox/session.test.tsindex 1d4cbb679..515f8c5d5 100644--- a/packages/eve/src/execution/sandbox/session.test.ts+++ b/packages/eve/src/execution/sandbox/session.test.ts@@ -1,22 +1,14 @@import { describe, expect, it, vi } from "vitest";-import type { InternalSandboxSession } from "#execution/sandbox/session.js";-import type { SandboxProcess } from "#shared/sandbox-session.js";-import { buildSandboxSession } from "#execution/sandbox/session.js";+import { createConnectionSession } from "#execution/sandbox/session.js";import { bufferToStream, streamToBuffer } from "#execution/sandbox/stream-utils.js";+import type { SandboxConnection } from "#sandbox/provider.js";+import type { SandboxProcess } from "#shared/sandbox-session.js";-function textStream(content: string): ReadableStream<Uint8Array> {- return bufferToStream(Buffer.from(content, "utf8"));-}--function syntheticProcess(input: {- exitCode?: number;- stdout?: string;- stderr?: string;-}): SandboxProcess {+function syntheticProcess(input: { exitCode?: number; stdout?: string }): SandboxProcess {return {stdout: bufferToStream(Buffer.from(input.stdout ?? "", "utf8")),- stderr: bufferToStream(Buffer.from(input.stderr ?? "", "utf8")),+ stderr: bufferToStream(new Uint8Array()),async wait() {return { exitCode: input.exitCode ?? 0 };},@@ -24,440 +16,146 @@ function syntheticProcess(input: {};}-function createTestPrimitives(- overrides: Partial<InternalSandboxSession> = {},-): InternalSandboxSession {- return {- readFile: overrides.readFile ?? vi.fn(async () => null),- removePath: overrides.removePath ?? vi.fn(async () => {}),- resolvePath: overrides.resolvePath ?? ((path: string) => `/resolved/${path}`),- spawn: overrides.spawn ?? vi.fn(async () => syntheticProcess({})),- writeFile: overrides.writeFile ?? vi.fn(async () => {}),- };-}--describe("buildSandboxSession", () => {- // ---------------------------------------------------------------------------- // setNetworkPolicy- // ----------------------------------------------------------------------------- it("forwards setNetworkPolicy to the supplied applier", async () => {- const apply = vi.fn(async () => {});- const session = buildSandboxSession(createTestPrimitives(), apply);- const policy = {- allow: {- "github.com": [{ transform: [{ headers: { authorization: "Basic abc" } }] }],- "*": [],+/** A connection over an in-memory file map; every primitive is a spy. */+function memoryConnection(initial: Record<string, string> = {}) {+ const files = new Map(Object.entries(initial).map(([path, text]) => [path, Buffer.from(text)]));+ const connection = {+ extensions: { ping: async () => "pong" },+ readFile: vi.fn(+ async ({ path }: { readonly path: string }): Promise<Uint8Array | null> =>+ files.get(path) ?? null,+ ),+ removePath: vi.fn(async () => {}),+ spawn: vi.fn(async () => syntheticProcess({ stdout: "hello" })),+ stop: vi.fn(async () => {}),+ writeFiles: vi.fn(+ async (options: { readonly files: readonly { content: Uint8Array; path: string }[] }) => {+ for (const file of options.files) files.set(file.path, Buffer.from(file.content));},- };-- await session.setNetworkPolicy(policy);-- expect(apply).toHaveBeenCalledWith(policy);- });-- it("returns the common session surface when no applier is supplied", () => {- expect(buildSandboxSession(createTestPrimitives())).not.toHaveProperty("setNetworkPolicy");- });-- // ---------------------------------------------------------------------------- // resolvePath- // ----------------------------------------------------------------------------- it("writes a batch through one primitive call, or several files at once without one", async () => {- const writeFiles = vi.fn(async () => {});- const files = Array.from({ length: 40 }, (_, i) => ({- content: new Uint8Array(),- path: `${i}.md`,- }));- await buildSandboxSession({ ...createTestPrimitives(), writeFiles }).writeFiles({ files });- expect(writeFiles).toHaveBeenCalledExactlyOnceWith({- abortSignal: undefined,- files: files.map((file) => ({ content: file.content, path: `/resolved/${file.path}` })),- });-- let inFlight = 0;- let maxInFlight = 0;- const writeFile = vi.fn(async () => {- maxInFlight = Math.max(maxInFlight, ++inFlight);- await Promise.resolve();- inFlight -= 1;- });- await buildSandboxSession(createTestPrimitives({ writeFile })).writeFiles({ files });- expect(writeFile).toHaveBeenCalledTimes(files.length);- expect(maxInFlight).toBeGreaterThan(1);- expect(maxInFlight).toBeLessThan(files.length);- });-- it("exposes resolvePath through the public session", () => {- const resolvePath = vi.fn((path: string) => `/resolved/${path}`);- const session = buildSandboxSession(createTestPrimitives({ resolvePath }));-- expect(session.resolvePath("notes/todo.txt")).toBe("/resolved/notes/todo.txt");- expect(resolvePath).toHaveBeenCalledWith("notes/todo.txt");- });-- // ---------------------------------------------------------------------------- // removePath- // ----------------------------------------------------------------------------- it("resolves removePath paths before delegating to the primitive", async () => {- const removePath = vi.fn(async () => {});- const session = buildSandboxSession(- createTestPrimitives({- removePath,- resolvePath: (path) => `/workspace/${path}`,- }),- );-- await session.removePath({ force: true, path: "skills/tenant", recursive: true });+ ),+ } satisfies SandboxConnection<{ ping(): Promise<string> }>;+ return { connection, files };+}- expect(removePath).toHaveBeenCalledWith({+describe("createConnectionSession", () => {+ it("resolves every path and working directory from /workspace", async () => {+ const { connection, files } = memoryConnection();+ const session = createConnectionSession(connection);++ await session.writeTextFile({ content: "hi", path: "notes/./a.txt" });+ await session.writeFiles({ files: [{ content: new Uint8Array([1]), path: "/tmp/b.bin" }] });+ await session.run({ command: "ls", workingDirectory: "src" });+ await session.run({ command: "pwd" });+ await session.removePath({ force: true, path: "../tmp/x", recursive: true });++ expect(session.resolvePath("notes/todo.txt")).toBe("/workspace/notes/todo.txt");+ expect([...files.keys()]).toEqual(["/workspace/notes/a.txt", "/tmp/b.bin"]);+ expect(connection.spawn.mock.calls).toEqual([+ [{ abortSignal: undefined, command: "ls", env: {}, workingDirectory: "/workspace/src" }],+ [{ abortSignal: undefined, command: "pwd", env: {}, workingDirectory: "/workspace" }],+ ]);+ expect(connection.removePath).toHaveBeenCalledWith({abortSignal: undefined,force: true,- path: "/workspace/skills/tenant",+ path: "/tmp/x",recursive: true,});});- // ---------------------------------------------------------------------------- // run / spawn- // ----------------------------------------------------------------------------- it("implements run by collecting stdout/stderr from the spawn primitive", async () => {- const spawn = vi.fn(async () => syntheticProcess({ exitCode: 0, stdout: "hello" }));- const session = buildSandboxSession(createTestPrimitives({ spawn }));- const result = await session.run({ command: "echo hello" });-- expect(spawn).toHaveBeenCalledWith({ command: "echo hello" });- expect(result).toEqual({ exitCode: 0, stderr: "", stdout: "hello" });- });-- it("does not pollute stderr with framework command progress logs", async () => {- const error = vi.spyOn(console, "error").mockImplementation(() => {});- const spawn = vi.fn(async () => syntheticProcess({ exitCode: 0, stdout: "hello" }));- const session = buildSandboxSession(createTestPrimitives({ spawn }));+ it("resolves from the connection's declared workspaceRoot, which must be absolute", async () => {+ const { connection, files } = memoryConnection();+ const session = createConnectionSession({ ...connection, workspaceRoot: "/srv/app/" });- try {- await session.run({ command: "echo hello" });- expect(error).not.toHaveBeenCalled();- } finally {- error.mockRestore();- }- });-- it("delegates spawn directly to the primitive", async () => {- const process = syntheticProcess({ exitCode: 7, stdout: "live", stderr: "warn" });- const spawn = vi.fn(async () => process);- const session = buildSandboxSession(createTestPrimitives({ spawn }));- const handle = await session.spawn({ command: "tail -f log" });-- expect(spawn).toHaveBeenCalledWith({ command: "tail -f log" });- expect(handle).toBe(process);- });-- // ---------------------------------------------------------------------------- // writeFile (stream)- // ---------------------------------------------------------------------------+ await session.writeTextFile({ content: "hi", path: "a.txt" });+ await session.run({ command: "pwd" });- it("resolves the path and forwards the stream verbatim to the primitive", async () => {- let capturedPath: string | undefined;- let capturedBytes: Buffer | undefined;- const session = buildSandboxSession(- createTestPrimitives({- resolvePath: (path) => `/workspace/${path}`,- writeFile: async ({ path, content }) => {- capturedPath = path;- capturedBytes = await streamToBuffer(content);- },- }),+ expect(session.resolvePath(".")).toBe("/srv/app");+ expect([...files.keys()]).toEqual(["/srv/app/a.txt"]);+ expect(connection.spawn).toHaveBeenCalledWith(+ expect.objectContaining({ workingDirectory: "/srv/app" }),);-- await session.writeFile({ content: textStream("buy milk"), path: "notes/todo.txt" });-- expect(capturedPath).toBe("/workspace/notes/todo.txt");- expect(capturedBytes?.toString("utf8")).toBe("buy milk");- });-- // ---------------------------------------------------------------------------- // writeBinaryFile- // ----------------------------------------------------------------------------- it("passes Uint8Array content through writeBinaryFile without lossy conversion", async () => {- let capturedBytes: Buffer | undefined;- const session = buildSandboxSession(- createTestPrimitives({- resolvePath: (path) => `/workspace/${path}`,- writeFile: async ({ content }) => {- capturedBytes = await streamToBuffer(content);- },- }),+ expect(() => createConnectionSession({ ...connection, workspaceRoot: "srv/app" })).toThrow(+ 'Sandbox connection workspaceRoot must be an absolute path, but received "srv/app".',);- const bytes = new Uint8Array([0x00, 0x01, 0x02, 0xff]);-- await session.writeBinaryFile({ content: bytes, path: "assets/binary.bin" });-- expect(capturedBytes).toEqual(Buffer.from(bytes));});- // ---------------------------------------------------------------------------- // writeTextFile- // ---------------------------------------------------------------------------+ it("implements run over spawn and merges the connection's extensions", async () => {+ const session = createConnectionSession(memoryConnection().connection);- it("encodes a string as utf-8 bytes through writeTextFile by default", async () => {- let capturedPath: string | undefined;- let capturedBytes: Buffer | undefined;- const session = buildSandboxSession(- createTestPrimitives({- resolvePath: (path) => `/workspace/${path}`,- writeFile: async ({ path, content }) => {- capturedPath = path;- capturedBytes = await streamToBuffer(content);- },- }),- );-- await session.writeTextFile({ content: "buy milk", path: "notes/todo.txt" });-- expect(capturedPath).toBe("/workspace/notes/todo.txt");- expect(capturedBytes).toEqual(Buffer.from("buy milk", "utf8"));- });-- // ---------------------------------------------------------------------------- // readBinaryFile- // ----------------------------------------------------------------------------- it("collects the readFile stream into a Uint8Array for readBinaryFile", async () => {- const bytes = Buffer.from([0x00, 0x01, 0x02, 0xff]);- const readFile = vi.fn(async () => bufferToStream(bytes));- const session = buildSandboxSession(- createTestPrimitives({- readFile,- resolvePath: (path) => `/workspace/${path}`,- }),- );-- const result = await session.readBinaryFile({ path: "assets/binary.bin" });-- expect(readFile).toHaveBeenCalledWith({- abortSignal: undefined,- path: "/workspace/assets/binary.bin",+ await expect(session.run({ command: "echo hello" })).resolves.toEqual({+ exitCode: 0,+ stderr: "",+ stdout: "hello",});- expect(result).toEqual(bytes);- });-- it("returns null when readBinaryFile target is missing", async () => {- const session = buildSandboxSession(createTestPrimitives({ readFile: async () => null }));-- await expect(session.readBinaryFile({ path: "missing.bin" })).resolves.toBeNull();+ await expect(session.ping()).resolves.toBe("pong");});- // ---------------------------------------------------------------------------- // readFile (stream)- // ----------------------------------------------------------------------------- it("returns the underlying stream from readFile verbatim", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("streamed content"),- }),+ it("rejects connection extensions that would replace a session member", () => {+ const { connection } = memoryConnection();+ expect(() =>+ createConnectionSession({ ...connection, extensions: { run: async () => "mine" } } as never),+ ).toThrow(+ "Sandbox connection extensions cannot replace the session members eve provides: run.",);-- const stream = await session.readFile({ path: "f.txt" });- expect(stream).not.toBeNull();- const buf = await streamToBuffer(stream as ReadableStream<Uint8Array>);- expect(buf.toString("utf8")).toBe("streamed content");});- // ---------------------------------------------------------------------------- // readTextFile — basic- // ----------------------------------------------------------------------------- it("returns null when the file does not exist", async () => {- const session = buildSandboxSession(createTestPrimitives());-- const result = await session.readTextFile({ path: "missing.txt" });-- expect(result).toBeNull();- });+ it("reads bytes or a stream from the connection in every read variant", async () => {+ const { connection } = memoryConnection({ "/workspace/a.bin": "\u0000\u0001" });+ const session = createConnectionSession(connection);- it("returns the full file content when no options are provided", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("line one\nline two\n"),- }),- );- const result = await session.readTextFile({ path: "file.txt" });-- expect(result).toBe("line one\nline two\n");- });-- it("resolves the path before reading", async () => {- const readFile = vi.fn(async () => textStream("content"));- const session = buildSandboxSession(- createTestPrimitives({- readFile,- resolvePath: (path) => `/cwd/${path}`,- }),- );-- await session.readTextFile({ path: "relative.txt" });-- expect(readFile).toHaveBeenCalledWith({ abortSignal: undefined, path: "/cwd/relative.txt" });- });-- // ---------------------------------------------------------------------------- // readTextFile — line ranges- // ----------------------------------------------------------------------------- it("returns a single line with startLine and endLine equal", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("alpha\nbeta\ngamma\n"),- }),- );- const result = await session.readTextFile({ endLine: 2, path: "f.txt", startLine: 2 });-- expect(result).toBe("beta\n");- });-- it("returns a range of lines", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("one\ntwo\nthree\nfour\n"),- }),- );- const result = await session.readTextFile({ endLine: 3, path: "f.txt", startLine: 2 });-- expect(result).toBe("two\nthree\n");- });-- it("returns from startLine through EOF when endLine is omitted", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("a\nb\nc"),- }),- );- const result = await session.readTextFile({ path: "f.txt", startLine: 2 });-- expect(result).toBe("b\nc");- });-- it("clamps endLine to EOF without error", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("a\nb\n"),- }),- );- const result = await session.readTextFile({ endLine: 999, path: "f.txt", startLine: 1 });-- expect(result).toBe("a\nb\n");- });-- it("returns empty string when startLine is past EOF", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("only\n"),- }),- );- const result = await session.readTextFile({ path: "f.txt", startLine: 5 });-- expect(result).toBe("");- });-- it("returns from line 1 through endLine when startLine is omitted", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("a\nb\nc\n"),- }),- );- const result = await session.readTextFile({ endLine: 2, path: "f.txt" });-- expect(result).toBe("a\nb\n");- });-- // ---------------------------------------------------------------------------- // readTextFile — preserves original line endings- // ----------------------------------------------------------------------------- it("preserves CRLF line endings in ranged reads", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("alpha\r\nbeta\r\ngamma\r\n"),- }),- );- const result = await session.readTextFile({ endLine: 2, path: "f.txt", startLine: 1 });-- expect(result).toBe("alpha\r\nbeta\r\n");- });-- it("preserves bare CR line endings in ranged reads", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("alpha\rbeta\rgamma\r"),- }),- );- const result = await session.readTextFile({ endLine: 2, path: "f.txt", startLine: 2 });-- expect(result).toBe("beta\r");- });-- it("handles file without trailing newline", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("first\nsecond"),- }),- );- const result = await session.readTextFile({ endLine: 2, path: "f.txt", startLine: 2 });-- expect(result).toBe("second");- });-- // ---------------------------------------------------------------------------- // readTextFile — validation- // ----------------------------------------------------------------------------- it("throws for non-integer startLine", async () => {- const session = buildSandboxSession(createTestPrimitives());-- await expect(session.readTextFile({ path: "f.txt", startLine: 1.5 })).rejects.toThrow(- "startLine must be a positive integer (1-based).",- );- });-- it("throws for zero startLine", async () => {- const session = buildSandboxSession(createTestPrimitives());-- await expect(session.readTextFile({ path: "f.txt", startLine: 0 })).rejects.toThrow(- "startLine must be a positive integer (1-based).",- );- });-- it("throws for negative endLine", async () => {- const session = buildSandboxSession(createTestPrimitives());-- await expect(session.readTextFile({ endLine: -1, path: "f.txt" })).rejects.toThrow(- "endLine must be a positive integer (1-based).",- );- });-- it("throws when startLine exceeds endLine", async () => {- const session = buildSandboxSession(createTestPrimitives());-- await expect(session.readTextFile({ endLine: 3, path: "f.txt", startLine: 5 })).rejects.toThrow(- "startLine must not be greater than endLine.",+ await expect(session.readBinaryFile({ path: "a.bin" })).resolves.toEqual(+ Buffer.from([0x00, 0x01]),);+ await expect(session.readBinaryFile({ path: "missing.bin" })).resolves.toBeNull();+ connection.readFile.mockResolvedValueOnce(new Blob(["streamed"]).stream() as never);+ await expect(session.readTextFile({ path: "b.txt" })).resolves.toBe("streamed");+ const stream = await session.readFile({ path: "a.bin" });+ expect(await streamToBuffer(stream!)).toEqual(Buffer.from([0x00, 0x01]));});- it("does not throw for valid range options", async () => {- const session = buildSandboxSession(- createTestPrimitives({- readFile: async () => textStream("a\nb\nc\n"),- }),- );+ it("writes stream, binary, and encoded text content as bytes", async () => {+ const { connection, files } = memoryConnection();+ const session = createConnectionSession(connection);+ const bytes = new Uint8Array([0x00, 0x01, 0x02, 0xff]);- await expect(session.readTextFile({ endLine: 3, path: "f.txt", startLine: 1 })).resolves.toBe(- "a\nb\nc\n",- );+ await session.writeFile({ content: bufferToStream(Buffer.from("buy milk")), path: "a.txt" });+ await session.writeBinaryFile({ content: bytes, path: "b.bin" });+ await session.writeTextFile({ content: "aGk=", encoding: "base64", path: "c.txt" });++ expect(files.get("/workspace/a.txt")?.toString()).toBe("buy milk");+ expect(files.get("/workspace/b.bin")).toEqual(Buffer.from(bytes));+ expect(files.get("/workspace/c.txt")?.toString()).toBe("hi");+ });++ it.each([+ ["one line", "alpha\nbeta\ngamma\n", { endLine: 2, startLine: 2 }, "beta\n"],+ ["a range", "one\ntwo\nthree\nfour\n", { endLine: 3, startLine: 2 }, "two\nthree\n"],+ ["through EOF", "a\nb\nc", { startLine: 2 }, "b\nc"],+ ["a clamped end", "a\nb\n", { endLine: 999, startLine: 1 }, "a\nb\n"],+ ["a start past EOF", "only\n", { startLine: 5 }, ""],+ ["from line 1", "a\nb\nc\n", { endLine: 2 }, "a\nb\n"],+ [+ "CRLF endings",+ "alpha\r\nbeta\r\ngamma\r\n",+ { endLine: 2, startLine: 1 },+ "alpha\r\nbeta\r\n",+ ],+ ["bare CR endings", "alpha\rbeta\rgamma\r", { endLine: 2, startLine: 2 }, "beta\r"],+ ["no trailing newline", "first\nsecond", { endLine: 2, startLine: 2 }, "second"],+ ])("reads %s of a text file", async (_, content, range, expected) => {+ const session = createConnectionSession(+ memoryConnection({ "/workspace/f.txt": content }).connection,+ );+ await expect(session.readTextFile({ path: "f.txt", ...range })).resolves.toBe(expected);+ });++ it.each([+ [{ startLine: 1.5 }, "startLine must be a positive integer (1-based)."],+ [{ startLine: 0 }, "startLine must be a positive integer (1-based)."],+ [{ endLine: -1 }, "endLine must be a positive integer (1-based)."],+ [{ endLine: 3, startLine: 5 }, "startLine must not be greater than endLine."],+ ])("rejects the line range %j", async (range, message) => {+ const session = createConnectionSession(memoryConnection().connection);+ await expect(session.readTextFile({ path: "f.txt", ...range })).rejects.toThrow(message);});});diff --git a/packages/eve/src/execution/sandbox/session.ts b/packages/eve/src/execution/sandbox/session.tsindex f554379b3..210fb1c98 100644--- a/packages/eve/src/execution/sandbox/session.ts+++ b/packages/eve/src/execution/sandbox/session.ts@@ -1,14 +1,12 @@-import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";-type NetworkPolicySandboxSession = SandboxSession & {- setNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void>;-};+import { posix } from "node:path";++import type { SandboxConnection } from "#sandbox/provider.js";+import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";import type {- InternalSandboxSession,- SandboxProcess,SandboxReadBinaryFileOptions,SandboxReadFileOptions,- SandboxRemovePathOptions,SandboxReadTextFileOptions,+ SandboxRemovePathOptions,SandboxRunOptions,SandboxSession,SandboxSpawnOptions,@@ -17,13 +15,8 @@ import type {SandboxWriteFilesOptions,SandboxWriteTextFileOptions,} from "#shared/sandbox-session.js";-import { mapWithConcurrency } from "#shared/map-with-concurrency.js";import { bufferToStream, streamToBuffer } from "./stream-utils.js";-export type { InternalSandboxSession };--const FALLBACK_WRITE_CONCURRENCY = 16;-/*** Tells agent-aware CLIs (such as `vercel`) that an automated agent runs* the command, so they skip interactive prompts. Providers apply it beneath@@ -32,122 +25,112 @@ const FALLBACK_WRITE_CONCURRENCY = 16;export const SANDBOX_AGENT_ENV: Readonly<Record<string, string>> = { AI_AGENT: "eve" };/**- * Builds a public {@link SandboxSession} from provider-specific primitives.- *- * Encoding handling, line-range slicing, and the binary/text/stream- * variants live here so each provider only has to implement byte-oriented- * read/write primitives. `run` is implemented as a thin wrapper over the- * provider's `spawn`: collect stdout/stderr to strings, await `wait()`,- * then return the combined result.- *- * Providers without mutable firewall support omit `setNetworkPolicy`; the- * dedicated Vercel provider wires it to `sandbox.update`.+ * Builds the {@link SandboxSession} eve hands out from a provider's+ * connection: every path and working directory resolves from the+ * connection's workspace root, `run` collects `spawn`, the read and write+ * variants share the connection's byte primitives, and the connection's+ * extensions merge on top.*/-export function buildSandboxSession(- primitives: InternalSandboxSession,- setNetworkPolicy: (policy: SandboxNetworkPolicy) => Promise<void>,-): NetworkPolicySandboxSession;-export function buildSandboxSession(primitives: InternalSandboxSession): SandboxSession;-export function buildSandboxSession(- primitives: InternalSandboxSession,- setNetworkPolicy?: (policy: SandboxNetworkPolicy) => Promise<void>,-): SandboxSession {- async function run(options: SandboxRunOptions) {- const process = await primitives.spawn(options);- const [stdout, stderr, { exitCode }] = await Promise.all([- collectStreamToString(process.stdout),- collectStreamToString(process.stderr),- process.wait(),- ]);- return { exitCode, stderr, stdout };+export function createConnectionSession<Extensions extends object>(+ connection: SandboxConnection<Extensions>,+): SandboxSession & Extensions {+ const workspaceRoot = connection.workspaceRoot ?? WORKSPACE_ROOT;+ if (!posix.isAbsolute(workspaceRoot)) {+ throw new Error(+ `Sandbox connection workspaceRoot must be an absolute path, but received "${workspaceRoot}".`,+ );}- const session: { -readonly [Key in keyof SandboxSession]: SandboxSession[Key] } = {- resolvePath(path: string): string {- return primitives.resolvePath(path);- },- run,- async spawn(options: SandboxSpawnOptions): Promise<SandboxProcess> {- return await primitives.spawn(options);+ const resolveSandboxPath = (path: string) => posix.resolve(workspaceRoot, path);+ async function read(options: { readonly abortSignal?: AbortSignal; readonly path: string }) {+ return await connection.readFile({+ abortSignal: options.abortSignal,+ path: resolveSandboxPath(options.path),+ });+ }+ async function readBytes(options: { readonly abortSignal?: AbortSignal; readonly path: string }) {+ const content = await read(options);+ if (content === null) return null;+ return ArrayBuffer.isView(content) ? Buffer.from(content) : await streamToBuffer(content);+ }+ async function write(+ options: { readonly abortSignal?: AbortSignal; readonly path: string },+ content: Uint8Array,+ ) {+ await connection.writeFiles({+ abortSignal: options.abortSignal,+ files: [{ content, path: resolveSandboxPath(options.path) }],+ });+ }+ async function spawn(options: SandboxSpawnOptions) {+ return await connection.spawn({+ abortSignal: options.abortSignal,+ command: options.command,+ env: options.env ?? {},+ workingDirectory: resolveSandboxPath(options.workingDirectory ?? "."),+ });+ }+ const session: SandboxSession = {+ resolvePath: resolveSandboxPath,+ async run(options: SandboxRunOptions) {+ const process = await spawn(options);+ const [stdout, stderr, { exitCode }] = await Promise.all([+ collectStreamToString(process.stdout),+ collectStreamToString(process.stderr),+ process.wait(),+ ]);+ return { exitCode, stderr, stdout };},+ spawn,async readFile(options: SandboxReadFileOptions) {- return await primitives.readFile({- abortSignal: options.abortSignal,- path: primitives.resolvePath(options.path),- });- },- async readBinaryFile(options: SandboxReadBinaryFileOptions) {- const stream = await primitives.readFile({- abortSignal: options.abortSignal,- path: primitives.resolvePath(options.path),- });- if (stream === null) {- return null;- }- return await streamToBuffer(stream);+ const content = await read(options);+ if (content === null || !ArrayBuffer.isView(content)) return content;+ return bufferToStream(new Uint8Array(content.buffer, content.byteOffset, content.byteLength));},+ readBinaryFile: (options: SandboxReadBinaryFileOptions) => readBytes(options),async readTextFile(options: SandboxReadTextFileOptions) {validateReadTextFileOptions(options);- const stream = await primitives.readFile({- abortSignal: options.abortSignal,- path: primitives.resolvePath(options.path),- });- if (stream === null) {- return null;- }- const buf = await streamToBuffer(stream);- const text = decodeBytes(buf, options.encoding ?? "utf-8");- return applyLineRange(text, options);+ const content = await readBytes(options);+ if (content === null) return null;+ return applyLineRange(decodeBytes(content, options.encoding ?? "utf-8"), options);},async writeFile(options: SandboxWriteFileOptions) {- await primitives.writeFile({- abortSignal: options.abortSignal,- content: options.content,- path: primitives.resolvePath(options.path),- });+ await write(options, await streamToBuffer(options.content));},async writeBinaryFile(options: SandboxWriteBinaryFileOptions) {- await primitives.writeFile({- abortSignal: options.abortSignal,- content: bufferToStream(options.content),- path: primitives.resolvePath(options.path),- });+ await write(options, Buffer.from(options.content));},async writeTextFile(options: SandboxWriteTextFileOptions) {- const buf = encodeString(options.content, options.encoding ?? "utf-8");- await primitives.writeFile({- abortSignal: options.abortSignal,- content: bufferToStream(buf),- path: primitives.resolvePath(options.path),- });+ const encoding = (options.encoding ?? "utf-8") as BufferEncoding;+ await write(options, Buffer.from(options.content, encoding));},async writeFiles(options: SandboxWriteFilesOptions) {- const files = options.files.map((file) => ({- content: file.content,- path: primitives.resolvePath(file.path),- }));- if (primitives.writeFiles !== undefined) {- await primitives.writeFiles({ abortSignal: options.abortSignal, files });- return;- }- await mapWithConcurrency(files, FALLBACK_WRITE_CONCURRENCY, async (file) => {- await primitives.writeFile({- abortSignal: options.abortSignal,- content: bufferToStream(file.content),- path: file.path,- });+ await connection.writeFiles({+ abortSignal: options.abortSignal,+ files: options.files.map((file) => ({+ content: file.content,+ path: resolveSandboxPath(file.path),+ })),});},async removePath(options: SandboxRemovePathOptions) {- await primitives.removePath({+ await connection.removePath({abortSignal: options.abortSignal,force: options.force,- path: primitives.resolvePath(options.path),+ path: resolveSandboxPath(options.path),recursive: options.recursive,});},};- if (setNetworkPolicy === undefined) return session;- return { ...session, setNetworkPolicy } as NetworkPolicySandboxSession;+ const extensions: object = connection.extensions ?? {};+ const collisions = Object.keys(extensions).filter(+ (key) => Object.hasOwn(session, key) || key === "delete" || key === "stop",+ );+ if (collisions.length > 0) {+ throw new Error(+ `Sandbox connection extensions cannot replace the session members eve provides: ${collisions.join(", ")}. Rename them.`,+ );+ }+ return { ...extensions, ...session } as SandboxSession & Extensions;}/**@@ -240,16 +223,3 @@ function decodeBytes(buf: Uint8Array, encoding: string): string {encoding as BufferEncoding,);}--/**- * Encodes a string to raw bytes using the given encoding.- *- * `"utf-8"` uses `TextEncoder`; other encodings fall back to- * `Buffer.from(str, encoding)`.- */-function encodeString(str: string, encoding: string): Uint8Array {- if (encoding === "utf-8" || encoding === "utf8") {- return new TextEncoder().encode(str);- }- return Buffer.from(str, encoding as BufferEncoding);-}diff --git a/packages/eve/src/execution/session-reset.integration.test.ts b/packages/eve/src/execution/session-reset.integration.test.tsindex efa8c2dd8..bb14effbe 100644--- a/packages/eve/src/execution/session-reset.integration.test.ts+++ b/packages/eve/src/execution/session-reset.integration.test.ts@@ -4,12 +4,12 @@ import { describe, expect, it, vi } from "vitest";import { ContextContainer } from "#context/container.js";import { SessionKey } from "#context/keys.js";import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";-import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";+import { shutdownActiveSandboxConnections } from "#execution/sandbox/active-connections.js";import { sessionCommandInboxWorkflow } from "#internal/testing/session-inbox-workflow.js";import { waitForHook, startSessionOwner } from "#internal/testing/workflow-test-helpers.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";-import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";+import { defineSandboxProvider } from "#sandbox/provider.js";import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";@@ -67,7 +67,7 @@ describe("session reset integration", () => {} finally {const status = await first.status;if (status === "pending" || status === "running") await first.cancel();- await shutdownActiveSandboxHandles();+ await shutdownActiveSandboxConnections();}});});@@ -76,30 +76,24 @@ function createSessionSandboxHarness() {const initializedSessionIds: string[] = [];const sessionKeys: string[] = [];let sandboxCount = 0;- const provider = defineLegacySandboxProvider({+ const provider = defineSandboxProvider({name: "session-reset-test",environment: () => ({async onSessionEnd() {},- async resume(context) {- return createHandle(context.session.id);- },async start(context) {sessionKeys.push(context.session.id);sandboxCount += 1;- const sandbox = mockSandbox({ id: `sandbox-${sandboxCount}` });- return { handle: createHandle(context.session.id, sandbox), state: null };+ return {+ connection: mockSandbox({ id: `sandbox-${sandboxCount}` }).connection,+ state: null,+ };+ },+ async resume(context) {+ return mockSandbox({ id: context.session.id }).connection;},prepare: async () => null,}),});- function createHandle(sessionId: string, value = mockSandbox({ id: sessionId })) {- return {- sandbox: value.session,- async onSandboxDelete() {},- async onSandboxStop() {},- async onRuntimeShutdown() {},- };- }const environment = provider.environment();const definition: ResolvedSandboxDefinition = {environment,diff --git a/packages/eve/src/execution/session.test.ts b/packages/eve/src/execution/session.test.tsindex db3c880b0..ae62c39ff 100644--- a/packages/eve/src/execution/session.test.ts+++ b/packages/eve/src/execution/session.test.ts@@ -111,7 +111,9 @@ describe("createSession", () => {});expect(session.agent.system).toContain("`$HOME/.agents/skills/<skill>/`");- expect(session.agent.system).toContain("`/workspace/skills/<skill>/` as the fallback");+ expect(session.agent.system).toContain(+ "`skills/<skill>/` under the workspace root as the fallback",+ );expect(session.agent.system).toContain("- research: Research topics. (path: $HOME/.agents/skills/research/SKILL.md)",);diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex 0a072d5d3..9edb2bf22 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -2252,7 +2252,11 @@ describe("turnStep", () => {installSessionStoreMocks([session]);vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(createTurnStepTestBundle());const sandbox = mockSandbox({ id: "sbx_cancelled" });- vi.mocked(ensureSandboxAccess).mockResolvedValueOnce(sandbox.access as never);+ vi.mocked(ensureSandboxAccess).mockResolvedValueOnce({+ ...sandbox.access,+ end: async () => {},+ release: async () => {},+ });const controller = new AbortController();controller.abort(new TurnCancelledError());diff --git a/packages/eve/src/execution/skills/instructions.test.ts b/packages/eve/src/execution/skills/instructions.test.tsindex b3d6533b8..b37de8fda 100644--- a/packages/eve/src/execution/skills/instructions.test.ts+++ b/packages/eve/src/execution/skills/instructions.test.ts@@ -36,7 +36,7 @@ describe("formatAvailableSkillsSection", () => {);expect(result).toContain("Skill files live under `$HOME/.agents/skills/<skill>/`");expect(result).toContain(- "`/workspace/skills/<skill>/` as the fallback when `$HOME` is unavailable",+ "`skills/<skill>/` under the workspace root as the fallback when `$HOME` is unavailable",);expect(result).toContain("resolve them relative to the directory containing that specific SKILL.md",diff --git a/packages/eve/src/execution/skills/instructions.ts b/packages/eve/src/execution/skills/instructions.tsindex 3dbd5ff49..61918880b 100644--- a/packages/eve/src/execution/skills/instructions.ts+++ b/packages/eve/src/execution/skills/instructions.ts@@ -1,7 +1,7 @@import type { DynamicSkillManifest } from "#context/keys.js";import type { Announcement } from "#harness/announcements.js";import { SKILL_TOOL_NAME } from "#protocol/catalog-tools.js";-import { FALLBACK_SKILL_ROOT, MODEL_SKILL_ROOT } from "#shared/skill-paths.js";+import { MODEL_SKILL_ROOT } from "#shared/skill-paths.js";export interface AvailableSkillDescription {readonly description: string;@@ -40,7 +40,7 @@ export function formatAvailableSkillsSection(`If the user names a skill or the request clearly matches one of the descriptions below, load it with ${SKILL_TOOL_NAME}({ name }) before proceeding.`,"If multiple skills match, activate the minimal set that covers the task. After activation, follow the returned instructions instead of improvising around them.","If activation fails, say so briefly and continue with the best available alternative.",- `Skill files live under \`${MODEL_SKILL_ROOT}/<skill>/\`, with \`${FALLBACK_SKILL_ROOT}/<skill>/\` as the fallback when \`$HOME\` is unavailable.`,+ `Skill files live under \`${MODEL_SKILL_ROOT}/<skill>/\`, with \`skills/<skill>/\` under the workspace root as the fallback when \`$HOME\` is unavailable.`,"When a loaded SKILL.md mentions sibling files such as `references/foo.md`, resolve them relative to the directory containing that specific SKILL.md.",...skills.map(formatAvailableSkillLine),];diff --git a/packages/eve/src/execution/tool-session/sandbox.ts b/packages/eve/src/execution/tool-session/sandbox.tsdeleted file mode 100644index 96fdd22e7..000000000--- a/packages/eve/src/execution/tool-session/sandbox.ts+++ /dev/null@@ -1,82 +0,0 @@-import {- owningSandboxDefinition,- type RuntimeRegisteredSandbox,- type RuntimeSandboxRegistry,-} from "#runtime/sandbox/registry.js";-import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";-import type { SandboxProviderHandle, SandboxProviderRuntime } from "#shared/sandbox-provider.js";--/*- * A keyed tool session has no end, so nothing ever runs its sandbox's- * session-end cleanup. Only eve's bindings whose kept sandboxes stay bounded- * opt in: Vercel's saved filesystems expire, and just-bash keeps only files on- * the local disk. Custom providers opt in with `toolSessions: true`, which- * `defineSandboxProvider()` turns into this marker.- */--/** What a binding that keeps tool-session sandboxes tells the calls that use them. */-export interface ToolSessionSandboxSupport {- /**- * Frees what a call's handle holds in this process once the call ends,- * leaving the session's sandbox for later and overlapping calls. Absent- * when a handle holds nothing of its own, such as a client to a remote- * sandbox.- */- releaseHandle?(handle: SandboxProviderHandle): Promise<void>;-}--const supported = new WeakMap<object, ToolSessionSandboxSupport>();--/** Marks a binding that can keep a tool-session sandbox between calls. */-export function withToolSessionSandboxes<Implementation extends object>(- implementation: Implementation,- support: ToolSessionSandboxSupport = {},-): Implementation {- supported.set(implementation, support);- return implementation;-}--/** What a binding marked with `withToolSessionSandboxes` supports, or `undefined` when unmarked. */-export function getToolSessionSandboxSupport(- implementation: object,-): ToolSessionSandboxSupport | undefined {- return supported.get(implementation);-}--/** Raised when a keyed tool session opens a sandbox on a provider that cannot keep it. */-export class ToolSessionSandboxUnsupportedError extends Error {- constructor(providerName: string) {- super(- `Sandbox provider "${providerName}" cannot keep a sandbox between invokeTool calls, ` +- "so a call with a key cannot open one. Call without a key for a sandbox that lasts " +- "one call, or use Vercel Sandbox, just-bash, or a custom provider that sets `toolSessions: true`.",- );- this.name = "ToolSessionSandboxUnsupportedError";- }-}--/** Throws unless the registry's sandbox provider can keep tool-session sandboxes. */-export function assertToolSessionSandboxSupport(registry: RuntimeSandboxRegistry): void {- const provider = registeredProvider(registry);- if (provider !== undefined && !supported.has(provider.implementation)) {- throw new ToolSessionSandboxUnsupportedError(provider.providerName);- }-}--/** Frees what a keyed call's handle holds in this process; the sandbox itself stays. */-export async function releaseToolSessionHandle(- registry: RuntimeSandboxRegistry,- handle: SandboxProviderHandle,-): Promise<void> {- const provider = registeredProvider(registry);- if (provider === undefined) return;- await supported.get(provider.implementation)?.releaseHandle?.(handle);-}--function registeredProvider(registry: RuntimeSandboxRegistry): SandboxProviderRuntime | undefined {- // Test runtimes without a sandbox cast a null registry.- const registered = registry.sandbox as RuntimeRegisteredSandbox | null | undefined;- const definition = registered ? owningSandboxDefinition(registered) : undefined;- if (definition?.kind !== "independent") return undefined;- return getSandboxEnvironmentRuntime(definition.environment);-}diff --git a/packages/eve/src/execution/tools/workflow/step-execution.test.ts b/packages/eve/src/execution/tools/workflow/step-execution.test.tsindex 91d92bbb5..b8c2647a4 100644--- a/packages/eve/src/execution/tools/workflow/step-execution.test.ts+++ b/packages/eve/src/execution/tools/workflow/step-execution.test.ts@@ -15,7 +15,7 @@ import type { WorkflowToolContext } from "#tools/workflow-definition.js";import type { AuthorizationDefinition } from "#shared/connection-types.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import { defineSandbox } from "#public/definitions/sandbox.js";-import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";+import { shutdownActiveSandboxConnections } from "#execution/sandbox/active-connections.js";import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";import { withDevelopmentWorkflowGeneration } from "#internal/workflow/development-generation-context.js";import {@@ -23,10 +23,7 @@ import {createDiskRuntimeCompiledArtifactsSource,} from "#runtime/compiled-artifacts-source.js";import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";-import {- defineLegacySandboxProvider,- type SandboxProviderSessionContext,-} from "#shared/sandbox-provider.js";+import { defineSandboxProvider } from "#sandbox/provider.js";const durable = vi.hoisted(() => ({attempt: 1,@@ -72,42 +69,42 @@ vi.mock("#internal/workflow/runtime.js", () => ({/*** A provider whose `start` upserts a sandbox by session id and whose* `onSessionEnd` deletes by it, as the provider contract requires. Each open- * hands out its own handle over the shared sandbox; `shutDown` records which- * ones the runtime's shutdown stopped.+ * hands out its own connection over the shared sandbox; `stopped` and+ * `closed` record which connections eve stopped and closed.*/function upsertSandboxes() {const live = new Map<string, ReturnType<typeof mockSandbox>>();const starts: string[] = [];- const handles: object[] = [];- const shutDown: object[] = [];- const stopped: Mock<() => Promise<void>> = vi.fn(async () => {});+ const connections: object[] = [];+ const stopped: object[] = [];+ const closed: object[] = [];const deleted: Mock<() => Promise<void>> = vi.fn(async () => {});- const handleFor = (key: string) => {+ const connect = (key: string) => {let sandbox = live.get(key);if (sandbox === undefined) {sandbox = mockSandbox();live.set(key, sandbox);}- const handle = {- sandbox: sandbox.session,- onRuntimeShutdown: async () => void shutDown.push(handle),- onSandboxDelete: deleted,- onSandboxStop: stopped,+ const connection = {+ ...sandbox.connection,+ close: async () => void closed.push(connection),+ stop: async () => void stopped.push(connection),};- handles.push(handle);- return handle;+ connections.push(connection);+ return connection;};- const provider = defineLegacySandboxProvider({+ const provider = defineSandboxProvider({name: "upsert",environment: () => ({- onSessionEnd: async (context: SandboxProviderSessionContext) =>- void live.delete(context.session.id),prepare: async () => null,- resume: async (_context: unknown, _artifact: unknown, state: { readonly key: string }) =>- handleFor(state.key),- start: async (context: SandboxProviderSessionContext) => {+ start: async (context) => {starts.push(context.session.id);- return { handle: handleFor(context.session.id), state: { key: context.session.id } };+ return { connection: connect(context.session.id), state: { key: context.session.id } };+ },+ resume: async (_context, _artifact, state) => connect(state.key),+ async onSessionEnd(context, _state, { reason }) {+ if (reason === "deleted") await deleted();+ live.delete(context.session.id);},}),});@@ -126,7 +123,7 @@ function upsertSandboxes() {workspaceResourceRoot: { logicalPath: "", rootEntries: [] },},};- return { deleted, handles, provider, registry, shutDown, starts, stopped };+ return { closed, connections, deleted, provider, registry, starts, stopped };}function context(user = "user-1", sessionId = "session-1"): WorkflowStepContext {@@ -170,7 +167,7 @@ describe("workflow step authorization", () => {durable.stepId = "step-1";durable.entries.clear();bundle.loadedFrom = [];- await shutdownActiveSandboxHandles();+ await shutdownActiveSandboxConnections();});afterEach(() => vi.unstubAllEnvs());it.each([@@ -228,8 +225,8 @@ describe("workflow step authorization", () => {expect(starts).toEqual(["owner-session"]);});- it("leaves the session's handle tracked for runtime shutdown after a step uses the sandbox", async () => {- const { handles, registry, shutDown } = upsertSandboxes();+ it("closes the step's connection and leaves the session's tracked for runtime shutdown", async () => {+ const { closed, connections, registry, stopped } = upsertSandboxes();bundle.registry = registry;// The session's turn opened its sandbox in this process.const session = await ensureSandboxAccess({@@ -240,14 +237,15 @@ describe("workflow step authorization", () => {state: null,});await session.get();- const sessionHandle = handles[0];await expect(runStep(async (ctx) => void (await ctx.getSandbox()))).resolves.toMatchObject({kind: "result",});- await shutdownActiveSandboxHandles();- // The step's handle neither replaced nor dropped the session's.- expect(handles).toHaveLength(2);- expect(shutDown).toEqual([sessionHandle]);+ const [sessionConnection, stepConnection] = connections;+ expect(closed).toEqual([stepConnection]);+ await shutdownActiveSandboxConnections();+ // The step's connection neither replaced nor dropped the session's.+ expect(connections).toHaveLength(2);+ expect(stopped).toEqual([sessionConnection]);});it("fails ctx.getSandbox() without retrying once its step has returned", async () => {@@ -274,7 +272,7 @@ describe("workflow step authorization", () => {return "opened";}),).resolves.toMatchObject({ output: "opened" });- const other = defineLegacySandboxProvider({+ const other = defineSandboxProvider({name: "other",environment: () => ({onSessionEnd: async () => {},@@ -294,7 +292,7 @@ describe("workflow step authorization", () => {message: expect.stringContaining(message),});}- expect(stopped).not.toHaveBeenCalled();+ expect(stopped).toEqual([]);expect(deleted).not.toHaveBeenCalled();});diff --git a/packages/eve/src/execution/tools/workflow/step-execution.ts b/packages/eve/src/execution/tools/workflow/step-execution.tsindex 540792f6c..e288e625a 100644--- a/packages/eve/src/execution/tools/workflow/step-execution.ts+++ b/packages/eve/src/execution/tools/workflow/step-execution.ts@@ -117,12 +117,13 @@ export function withWorkflowStepAuthorization(execute: (...args: never[]) => unk/*** The calling session's sandbox, opened on the step's first `ctx.getSandbox()`- * under the key of the session that owns it, and let go of when the step- * ends. Recorded state, when the call captured it, resumes the sandbox;- * without it, or when that sandbox is gone, the provider's `start` upserts- * it by that key with the owner's sandbox definition, so the session finds- * the same sandbox and its session-end cleanup removes it. The step never owns the sandbox: the- * session's turns may be using it, so the step can neither stop nor delete it.+ * under the key of the session that owns it, and closed when the step ends.+ * Recorded state, when the call captured it, resumes the sandbox; without+ * it, or when that sandbox is gone, the provider's `start` upserts it by that+ * key with the owner's sandbox definition, so the session finds the same+ * sandbox and its session-end cleanup removes it. The step never owns the+ * sandbox: the session's turns may be using it, so the step can neither stop+ * nor delete it.* A step that never asks for it loads nothing.*/function openStepSandbox(input: WorkflowStepContext) {@@ -147,7 +148,7 @@ function openStepSandbox(input: WorkflowStepContext) {registry: node.sandboxRegistry,sessionId,state: state ?? null,- borrowed: true,+ shutdownTracking: "none",});};const openOnce = (): Promise<EnsuredSandboxAccess> => {@@ -176,7 +177,7 @@ function openStepSandbox(input: WorkflowStepContext) {stop: () =>unavailableInStep("sandbox.stop()",- "The session's turns may be using the sandbox; eve lets go of the step's handle when the step ends.",+ "The session's turns may be using the sandbox; eve closes the step's connection when the step ends.",),};},@@ -184,7 +185,7 @@ function openStepSandbox(input: WorkflowStepContext) {released = true;const access = await opening?.catch(() => undefined);try {- await access?.detach();+ await access?.release();} catch (error) {logError(log, "failed to release a workflow step's sandbox", error, {sessionId,diff --git a/packages/eve/src/harness/attachment-staging.integration.test.ts b/packages/eve/src/harness/attachment-staging.integration.test.tsindex 85282e4a5..9b5febe47 100644--- a/packages/eve/src/harness/attachment-staging.integration.test.ts+++ b/packages/eve/src/harness/attachment-staging.integration.test.ts@@ -9,7 +9,6 @@ import { createTestRuntime } from "#internal/testing/app-harness.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import { mockTool } from "#internal/testing/mocks/mock-tool.js";import {- ATTACHMENTS_ROOT,hydrateSandboxAttachments,stageAttachmentsToSandbox,stageToolResultMedia,@@ -189,7 +188,7 @@ describe("stageAttachmentsToSandbox (integration)", () => {expect(staged).toHaveLength(2);const filePart = staged[1] as FilePart;expect(filePart.filename).toMatch(- new RegExp(`^${ATTACHMENTS_ROOT.replaceAll(".", "\\.")}/[0-9a-f]{16}/report\\.csv$`),+ /^\/workspace\/\.eve\/attachments\/[0-9a-f]{16}\/report\.csv$/,);// `data` is replaced with an eve-sandbox: ref — the bytes live in// the sandbox and are rehydrated at the model call site. Thediff --git a/packages/eve/src/harness/attachment-staging.test.ts b/packages/eve/src/harness/attachment-staging.test.tsindex 35b300fc1..173aad403 100644--- a/packages/eve/src/harness/attachment-staging.test.ts+++ b/packages/eve/src/harness/attachment-staging.test.ts@@ -7,7 +7,6 @@ import { SandboxKey } from "#context/keys.js";import { decodeSandboxRef, isSandboxRefUrl } from "#internal/attachments/sandbox-refs.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import {- ATTACHMENTS_ROOT,moveToolResultFilesToUserMessages,stageAttachmentsForAdapter,stageAttachmentsToSandbox,@@ -87,9 +86,7 @@ describe("stageAttachmentsForAdapter", () => {expect(sandbox.writes).toHaveLength(1);const write = sandbox.writes[0];- expect(write?.path).toMatch(- new RegExp(`^${ATTACHMENTS_ROOT.replaceAll(".", "\\.")}/[0-9a-f]{16}/quarterly\\.csv$`),- );+ expect(write?.path).toBe(ref.path);expect(write?.content).toEqual(data);});diff --git a/packages/eve/src/harness/attachment-staging.ts b/packages/eve/src/harness/attachment-staging.tsindex a66f49c37..7b0a73897 100644--- a/packages/eve/src/harness/attachment-staging.ts+++ b/packages/eve/src/harness/attachment-staging.ts@@ -33,12 +33,11 @@ import type { SandboxSession } from "#public/definitions/sandbox.js";import type { SandboxAccess } from "#sandbox/state.js";/**- * Sandbox directory where eve stages message attachments and tool-result- * files. It sits under eve's own dot-directory so it never collides with an- * agent's `/workspace/attachments`. Authored canonical path —- * {@link SandboxSession.writeFile} translates to the backend-native location.+ * Directory, relative to the workspace root, where eve stages message+ * attachments and tool-result files. It sits under eve's own dot-directory so+ * it never collides with an agent's own `attachments/`.*/-export const ATTACHMENTS_ROOT = "/workspace/.eve/attachments";+const ATTACHMENTS_ROOT = ".eve/attachments";const log = createLogger("harness.attachment-staging");diff --git a/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.ts b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.tsindex 3c95e7231..6368db166 100644--- a/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.ts+++ b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.test.ts@@ -1,9 +1,9 @@import { afterEach, describe, expect, it, vi } from "vitest";import {- shutdownActiveSandboxHandles,- trackActiveSandboxHandle,-} from "#execution/sandbox/active-handles.js";+ shutdownActiveSandboxConnections,+ trackActiveSandboxConnection,+} from "#execution/sandbox/active-connections.js";import {installSandboxShutdownHandlers,runSandboxShutdown,@@ -30,7 +30,7 @@ function createFakeProcess(env: Record<string, string | undefined> = {}) {}afterEach(async () => {- await shutdownActiveSandboxHandles();+ await shutdownActiveSandboxConnections();vi.unstubAllEnvs();});@@ -63,8 +63,8 @@ describe("installSandboxShutdownHandlers", () => {});it("stops tracked sandboxes and exits 143 on SIGTERM", async () => {- const handle = { onRuntimeShutdown: vi.fn(async () => {}) };- trackActiveSandboxHandle({ providerName: "docker", handle, sessionId: "session-1" });+ const connection = { stop: vi.fn(async () => {}) };+ trackActiveSandboxConnection({ providerName: "docker", connection, sessionId: "session-1" });const fakeProcess = createFakeProcess();installSandboxShutdownHandlers({ log: () => {}, process: fakeProcess });@@ -73,12 +73,12 @@ describe("installSandboxShutdownHandlers", () => {await vi.waitFor(() => {expect(fakeProcess.exit).toHaveBeenCalledWith(143);});- expect(handle.onRuntimeShutdown).toHaveBeenCalledTimes(1);+ expect(connection.stop).toHaveBeenCalledTimes(1);});it("stops tracked sandboxes and exits 130 on SIGINT", async () => {- const handle = { onRuntimeShutdown: vi.fn(async () => {}) };- trackActiveSandboxHandle({ providerName: "docker", handle, sessionId: "session-1" });+ const connection = { stop: vi.fn(async () => {}) };+ trackActiveSandboxConnection({ providerName: "docker", connection, sessionId: "session-1" });const fakeProcess = createFakeProcess();installSandboxShutdownHandlers({ log: () => {}, process: fakeProcess });@@ -87,12 +87,12 @@ describe("installSandboxShutdownHandlers", () => {await vi.waitFor(() => {expect(fakeProcess.exit).toHaveBeenCalledWith(130);});- expect(handle.onRuntimeShutdown).toHaveBeenCalledTimes(1);+ expect(connection.stop).toHaveBeenCalledTimes(1);});it("stops tracked sandboxes through the nitro close hook", async () => {- const handle = { onRuntimeShutdown: vi.fn(async () => {}) };- trackActiveSandboxHandle({ providerName: "docker", handle, sessionId: "session-1" });+ const connection = { stop: vi.fn(async () => {}) };+ trackActiveSandboxConnection({ providerName: "docker", connection, sessionId: "session-1" });let closeHandler: (() => Promise<void>) | undefined;const nitroApp = {hooks: {@@ -112,16 +112,16 @@ describe("installSandboxShutdownHandlers", () => {});await closeHandler?.();- expect(handle.onRuntimeShutdown).toHaveBeenCalledTimes(1);+ expect(connection.stop).toHaveBeenCalledTimes(1);});});describe("runSandboxShutdown", () => {- it("exits even when a handle shutdown never settles", async () => {+ it("exits even when a connection shutdown never settles", async () => {vi.useFakeTimers();try {- const handle = { onRuntimeShutdown: vi.fn(() => new Promise<void>(() => {})) };- trackActiveSandboxHandle({ providerName: "docker", handle, sessionId: "session-1" });+ const connection = { stop: vi.fn(() => new Promise<void>(() => {})) };+ trackActiveSandboxConnection({ providerName: "docker", connection, sessionId: "session-1" });const log = vi.fn();const shutdown = runSandboxShutdown(log);diff --git a/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.ts b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.tsindex 4e762fcfb..f9e150a3e 100644--- a/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.ts+++ b/packages/eve/src/internal/nitro/host/sandbox-shutdown-plugin.ts@@ -1,4 +1,4 @@-import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";+import { shutdownActiveSandboxConnections } from "#execution/sandbox/active-connections.js";import { isEveDevEnvironment } from "#internal/application/dev-environment.js";const SHUTDOWN_SIGNALS = ["SIGINT", "SIGTERM"] as const;@@ -62,7 +62,7 @@ export async function runSandboxShutdown(log: (message: string) => void): Promis});try {- await Promise.race([shutdownActiveSandboxHandles({ log }), deadline]);+ await Promise.race([shutdownActiveSandboxConnections({ log }), deadline]);} finally {clearTimeout(timer);}diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.tsindex 3b826be54..1fb321892 100644--- a/packages/eve/src/internal/testing/app-harness.ts+++ b/packages/eve/src/internal/testing/app-harness.ts@@ -20,10 +20,7 @@ import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";import { createNodeHarnessTools } from "#execution/node-step.js";import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";import { defineSandbox } from "#public/definitions/sandbox.js";-import {- defineLegacySandboxProvider,- type SandboxProviderSessionContext,-} from "#shared/sandbox-provider.js";+import { defineSandboxProvider } from "#sandbox/provider.js";import {buildActiveSessionContext,type ActiveSessionInit,@@ -158,44 +155,33 @@ function createTestSandboxProvider() {const endedSessionIds: string[] = [];const events: string[] = [];- function createHandle(sessionId: string) {+ function connect(sessionId: string) {let sandbox = sessionSandboxes.get(sessionId);if (sandbox === undefined) {sandbox = mockSandbox({ id: sessionId });sessionSandboxes.set(sessionId, sandbox);}- const opened = sandbox;- return {- sandbox: opened.session,- async onSandboxDelete(options?: import("#shared/sandbox-provider.js").SandboxDeleteOptions) {- events.push(`delete:${sessionId}`);- sessionSandboxes.delete(sessionId);- await opened.access.delete?.(options);- },- async onSandboxStop() {},- async onRuntimeShutdown() {},- };+ return sandbox.connection;}- const provider = defineLegacySandboxProvider({+ const provider = defineSandboxProvider({name: TEST_SANDBOX_PROVIDER_NAME,environment: () => ({- async onSessionEnd(context) {- endedSessionIds.push(context.session.id);- const sandbox = sessionSandboxes.get(context.session.id);+ async onSessionEnd(context, _state, { reason }) {+ if (reason === "deleted") events.push(`delete:${context.session.id}`);+ else endedSessionIds.push(context.session.id);sessionSandboxes.delete(context.session.id);- await sandbox?.access.delete?.();},async prepare() {return null;},- async resume(context: SandboxProviderSessionContext) {- events.push(`resume:${context.session.id}`);- return createHandle(context.session.id);- },- async start(context: SandboxProviderSessionContext) {+ async start(context) {events.push(`start:${context.session.id}`);- return { handle: createHandle(context.session.id), state: null };+ return { connection: connect(context.session.id), state: null };+ },+ async resume(context) {+ events.push(`resume:${context.session.id}`);+ return connect(context.session.id);},}),});diff --git a/packages/eve/src/internal/testing/docker-sandbox-runtime.ts b/packages/eve/src/internal/testing/docker-sandbox-runtime.tsindex 04d4a9370..ec05546a1 100644--- a/packages/eve/src/internal/testing/docker-sandbox-runtime.ts+++ b/packages/eve/src/internal/testing/docker-sandbox-runtime.ts@@ -1,28 +1,27 @@import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";+import { createSandboxEnvironmentHarness } from "#internal/testing/sandbox-provider-harness.js";import type { DockerSandboxSession } from "#public/sandbox/docker.js";import type {DockerSandboxEnvironmentOptions,DockerSandboxRuntimeOptions,} from "#public/sandbox/docker-sandbox.js";import { defineDockerSandboxProvider } from "#sandbox/providers/docker.js";-import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";-import type { LegacySandboxProviderImplementation } from "#shared/sandbox-provider.js";-/** What `DockerSandbox.environment(options)` gives core, over `cli`. */-export function createDockerSandboxRuntime(- options?: DockerSandboxEnvironmentOptions,- cli?: DockerCli,-): LegacySandboxProviderImplementation<- DockerSandboxRuntimeOptions,- { readonly imageReference: string },- { readonly containerName: string; readonly version: 2 },- DockerSandboxSession-> {- return getSandboxEnvironmentRuntime(defineDockerSandboxProvider(cli).environment(options ?? {}))- .implementation as LegacySandboxProviderImplementation<+/** A harness over `DockerSandbox.environment(options)`, run against `cli`. */+export function createDockerSandboxHarness(+ input: {+ readonly cli?: DockerCli;+ readonly options?: DockerSandboxEnvironmentOptions;+ readonly preparedArtifact?: () => { readonly imageReference: string };+ readonly runtimeOptions?: DockerSandboxRuntimeOptions;+ } = {},+) {+ return createSandboxEnvironmentHarness<DockerSandboxRuntimeOptions,{ readonly imageReference: string },{ readonly containerName: string; readonly version: 2 },DockerSandboxSession- >;+ >(defineDockerSandboxProvider(input.cli).environment(input.options ?? {}), input.runtimeOptions, {+ preparedArtifact: input.preparedArtifact,+ });}diff --git a/packages/eve/src/internal/testing/mocks/mock-sandbox.ts b/packages/eve/src/internal/testing/mocks/mock-sandbox.tsindex 074aa3687..84eb06c76 100644--- a/packages/eve/src/internal/testing/mocks/mock-sandbox.ts+++ b/packages/eve/src/internal/testing/mocks/mock-sandbox.ts@@ -13,6 +13,9 @@ import type {SandboxWriteFilesOptions,SandboxWriteTextFileOptions,} from "#public/definitions/sandbox.js";+import { posix } from "node:path";++import type { SandboxConnection } from "#sandbox/provider.js";import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";type NetworkPolicySandboxSession = SandboxSession & {readonly name: string;@@ -20,6 +23,7 @@ type NetworkPolicySandboxSession = SandboxSession & {};import type { SandboxAccess, SandboxState } from "#sandbox/state.js";import { bufferToStream, streamToBuffer } from "#execution/sandbox/stream-utils.js";+import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";/*** Declarative description of a mock sandbox surface.@@ -91,6 +95,8 @@ export interface MockSandbox {* want to call the session surface outside a `ctx` scope.*/readonly session: NetworkPolicySandboxSession;+ /** A provider connection over the same sandbox; its `stop` calls {@link MockSandboxInput.stop}. */+ readonly connection: SandboxConnection<Pick<NetworkPolicySandboxSession, "setNetworkPolicy">>;/** Ordered log of every command received through `run`/`spawn`. */readonly commandLog: readonly string[];/** Ordered log of every path received through `removePath`. */@@ -257,6 +263,16 @@ export function mockSandbox(input: MockSandboxInput = {}): MockSandbox {},};const session = baseSession;+ const connection: MockSandbox["connection"] = {+ extensions: { setNetworkPolicy: session.setNetworkPolicy },+ readFile: async ({ path }) => fileBytes.get(path) ?? null,+ removePath,+ spawn: session.spawn,+ async stop() {+ await input.stop?.();+ },+ writeFiles: session.writeFiles,+ };const access: SandboxAccess = {async captureState(): Promise<SandboxState> {@@ -276,6 +292,7 @@ export function mockSandbox(input: MockSandboxInput = {}): MockSandbox {return {access,commandLog,+ connection,fileBytes,files,networkPolicyUpdates,@@ -302,14 +319,6 @@ function synthesizeMockProcess(result: SandboxCommandResult): SandboxProcess {};}-/**- * Anchors a sandbox-relative path under `/workspace`, mirroring the real- * backend contract documented on {@link SandboxSession.resolvePath}.- */function resolveWorkspacePath(path: string): string {- if (path.startsWith("/")) {- return path;- }-- return `/workspace/${path}`;+ return posix.resolve(WORKSPACE_ROOT, path);}diff --git a/packages/eve/src/internal/testing/sandbox-provider-harness.ts b/packages/eve/src/internal/testing/sandbox-provider-harness.tsindex 0c1bd20f7..b522ab895 100644--- a/packages/eve/src/internal/testing/sandbox-provider-harness.ts+++ b/packages/eve/src/internal/testing/sandbox-provider-harness.ts@@ -1,48 +1,53 @@+import { resolve } from "node:path";++import { createSandboxPrepareContext } from "#execution/sandbox/prewarm.js";import { createSandboxProviderFiles } from "#execution/sandbox/provider-files.js";-import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";-import {- createSandboxProviderResources,- type SandboxPreparedArtifact,- type SandboxProviderHandle,- type LegacySandboxProviderImplementation,- type SandboxProviderResourceFile,-} from "#shared/sandbox-provider.js";-import type { SandboxSession } from "#shared/sandbox-session.js";+import { createConnectionSession } from "#execution/sandbox/session.js";+import { isToolSessionId } from "#execution/tool-session/id.js";+import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";+import type {+ SandboxConnection,+ SandboxJson,+ SandboxPrepareContext,+ SandboxProviderImplementation,+ SandboxSessionContext,+ SandboxSessionEndOptions,+} from "#sandbox/provider.js";import {getSandboxEnvironmentRuntime,type SandboxEnvironmentIdentity,} from "#shared/sandbox-environment.js";+import type { SandboxProviderResourceFile } from "#shared/sandbox-provider.js";+import type { SandboxSession } from "#shared/sandbox-session.js";-/** A harness over the provider implementation an environment carries. */-export function createSandboxEnvironmentHarness(environment: SandboxEnvironmentIdentity) {- return createSandboxProviderHarness(- getSandboxEnvironmentRuntime(environment).implementation,- undefined,- );-}--export function createSandboxProviderHarness<- Options extends object | undefined,- PreparedArtifact extends SandboxPreparedArtifact,- SessionState,- Session extends SandboxSession,+/**+ * Drives the lifecycle an environment's provider implements the way core+ * does, with eve's prepare context and derived session, without a runtime.+ * The type parameters name what the provider returns, which the environment+ * erases.+ */+export function createSandboxEnvironmentHarness<+ Options extends object | undefined = object | undefined,+ Artifact extends SandboxJson = SandboxJson,+ State extends SandboxJson = SandboxJson,+ Session extends SandboxSession = SandboxSession,>(- implementation: LegacySandboxProviderImplementation<- Options,- PreparedArtifact,- SessionState,- Session- >,- options: Options,- harnessOptions: {- readonly preparedArtifact?: () => PreparedArtifact;- } = {},+ environment: SandboxEnvironmentIdentity,+ options?: Options,+ harnessOptions: { readonly preparedArtifact?: () => Artifact } = {},) {- let preparedArtifact: PreparedArtifact | undefined;+ const runtime = getSandboxEnvironmentRuntime(environment);+ const implementation = runtime.implementation as SandboxProviderImplementation<+ Options,+ Artifact,+ State,+ object+ >;+ let preparedArtifact: Artifact | undefined;async function resolveArtifact(input: {readonly appRoot: string;- readonly prepared?: PreparedArtifact;- }): Promise<PreparedArtifact> {+ readonly prepared?: Artifact;+ }): Promise<Artifact> {return (input.prepared ??preparedArtifact ??@@ -51,28 +56,38 @@ export function createSandboxProviderHarness<);}- function sessionContext(appRoot: string, sandboxName: string) {+ function sessionContext(appRoot: string, sandboxName: string): SandboxSessionContext {return {- host: createSandboxProviderHost(appRoot),+ kind: isToolSessionId(sandboxName) ? "tool-session" : "session",+ resolveProjectPath: (path) => resolve(appRoot, path),session: {auth: { current: null, initiator: null },id: sandboxName,turn: { id: "test-turn", sequence: 0 },},storagePath: appRoot,- } as const;+ };+ }++ function opened(connection: SandboxConnection<object>) {+ return { connection, sandbox: createConnectionSession(connection) as Session };}const harness = {- async endSession(input: {- readonly appRoot: string;- readonly sandboxName: string;- readonly state: SessionState | null;- }): Promise<void> {+ async endSession(+ input: {+ readonly appRoot: string;+ readonly sandboxName: string;+ readonly state: State | null;+ } & Partial<SandboxSessionEndOptions>,+ ): Promise<void> {await implementation.onSessionEnd(sessionContext(input.appRoot, input.sandboxName),input.state,- { reason: "completed" },+ {+ abortSignal: input.abortSignal,+ reason: input.reason ?? "completed",+ },);},async prepare(input: {@@ -82,51 +97,67 @@ export function createSandboxProviderHarness<readonly resourcesPath?: string;readonly skills?: readonly SandboxProviderResourceFile[];readonly sourceRevision?: string;+ readonly storagePath?: string;readonly workspace?: readonly SandboxProviderResourceFile[];- }) {+ }): Promise<Artifact> {const hasFiles = (input.skills?.length ?? 0) + (input.workspace?.length ?? 0) > 0;- const artifact = await implementation.prepare({- files: createSandboxProviderFiles(`${input.appRoot}/sandbox`),- host: createSandboxProviderHost(input.appRoot),- log: input.log,- resources: createSandboxProviderResources({- key: input.resourcesKey ?? (hasFiles ? "test-resources" : undefined),- path: input.resourcesPath,- skills: input.skills,- workspace: input.workspace,+ const artifact = await implementation.prepare(+ createSandboxPrepareContext({+ appRoot: input.appRoot,+ files: createSandboxProviderFiles(`${input.appRoot}/sandbox`),+ log: input.log ?? (() => {}),+ provider: runtime,+ resources: {+ key: input.resourcesKey ?? (hasFiles ? "test-resources" : undefined),+ path: input.resourcesPath,+ skills: input.skills,+ workspace: input.workspace,+ },+ sourceRevision: input.sourceRevision ?? "test-source-revision",+ storagePath: input.storagePath ?? input.appRoot,}),- sourceRevision: input.sourceRevision ?? "test-source-revision",- storagePath: input.appRoot,- });+ );preparedArtifact = artifact;return artifact;},+ /** Resumes `existing` when given, or else starts the session's sandbox. */async openSession(input: {readonly appRoot: string;- readonly existing?: SessionState;- readonly prepared?: PreparedArtifact;+ readonly existing?: State;+ readonly prepared?: Artifact;readonly sandboxName: string;- }): Promise<SandboxProviderHandle<Session>> {+ }) {+ if (input.existing === undefined) return await harness.start(input);const artifact = await resolveArtifact(input);const context = sessionContext(input.appRoot, input.sandboxName);- if (input.existing === undefined) {- return (await implementation.start(context, options, artifact)).handle;- }- return await implementation.resume(context, artifact, input.existing);+ return opened(await implementation.resume(context, artifact, input.existing));},async start(input: {readonly appRoot: string;readonly options?: Options;- readonly prepared?: PreparedArtifact;+ readonly prepared?: Artifact;readonly sandboxName: string;}) {const artifact = await resolveArtifact(input);- return await implementation.start(+ const { connection, state } = await implementation.start(sessionContext(input.appRoot, input.sandboxName),input.options ?? options,artifact,);+ return { ...opened(connection), state };},};return harness;}++/**+ * Runs `ctx.populate()` against an in-memory sandbox whose home is+ * `/home/agent`, and returns the paths it wrote in order.+ */+export async function populatedPaths(context: SandboxPrepareContext): Promise<string[]> {+ const sandbox = mockSandbox({+ commands: { [`printf '%s\\n' "$HOME"`]: { exitCode: 0, stderr: "", stdout: "/home/agent\n" } },+ });+ await context.populate(sandbox.connection);+ return sandbox.writes.map((write) => write.path);+}diff --git a/packages/eve/src/public/channels/github/checkout.ts b/packages/eve/src/public/channels/github/checkout.tsindex cd29fc2f2..4a3907ab2 100644--- a/packages/eve/src/public/channels/github/checkout.ts+++ b/packages/eve/src/public/channels/github/checkout.ts@@ -16,7 +16,6 @@ import {import { gitHubGitBrokerNetworkPolicy, gitHubRemoteUrl, isFullGitSha } from "#shared/git.js";import { shellQuote } from "#shared/shell-quote.js";-const DEFAULT_CHECKOUT_PATH = "/workspace";const DEFAULT_CHECKOUT_DEPTH = 1;const GITHUB_CHECKOUT_NETWORK_HINT ="Verify the GitHub App installation has access to this repository.";@@ -73,7 +72,7 @@ export async function checkoutGitHubRepository(input: GitHubCheckoutInput,): Promise<GitHubCheckout> {const descriptor = await resolveCheckoutDescriptor(input);- const checkoutPath = sandbox.resolvePath(input.path ?? DEFAULT_CHECKOUT_PATH);+ const checkoutPath = sandbox.resolvePath(input.path ?? ".");const checkoutRef = resolveCheckoutRef(input.ref, descriptor);if (isFullGitSha(checkoutRef)) {diff --git a/packages/eve/src/public/sandbox/provider.ts b/packages/eve/src/public/sandbox/provider.tsindex 0f6e8a2f2..e7dee7727 100644--- a/packages/eve/src/public/sandbox/provider.ts+++ b/packages/eve/src/public/sandbox/provider.ts@@ -5,17 +5,14 @@ export {type SandboxJson,type SandboxPrepareContext,type SandboxPrepareOption,+ type SandboxProvider,type SandboxProviderDefinition,type SandboxProviderImplementation,type SandboxSessionContext,type SandboxSessionEndOptions,type WithPrepareOption,} from "#sandbox/provider.js";-export type {- SandboxDeleteOptions,- SandboxProvider,- SandboxProviderFiles,-} from "#shared/sandbox-provider.js";+export type { SandboxDeleteOptions, SandboxProviderFiles } from "#shared/sandbox-provider.js";export { SANDBOX_AGENT_ENV } from "#execution/sandbox/session.js";export { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";export { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";diff --git a/packages/eve/src/runtime/workspace/seed-files.scenario.test.ts b/packages/eve/src/runtime/workspace/seed-files.scenario.test.tsindex 69650c91c..019d8c662 100644--- a/packages/eve/src/runtime/workspace/seed-files.scenario.test.ts+++ b/packages/eve/src/runtime/workspace/seed-files.scenario.test.ts@@ -5,10 +5,8 @@ import { describe, expect, it } from "vitest";import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";import { materializeWorkspaceDirectory } from "#runtime/workspace/seed-files.js";-import {- createSandboxProviderResources,- providerResourceTargetFiles,-} from "#shared/sandbox-provider.js";+import { createSandboxPrepareContext } from "#execution/sandbox/prewarm.js";+import { populatedPaths } from "#internal/testing/sandbox-provider-harness.js";const createScratchDirectory = useTemporaryDirectories();@@ -29,45 +27,39 @@ describe("compiled resource root materialization", () => {await writeFile(join(resourceRoot, path), content);}- const resources = createSandboxProviderResources({- key: "resources-hash",- path: resourceRoot,- ...(await materializeWorkspaceDirectory(resourceRoot)),- });+ const trees = await materializeWorkspaceDirectory(resourceRoot);// Each tree is ordered by locale-aware relative path, not raw bytes.- expect(resources).toEqual({- skills: {- files: [- { content: Buffer.from("sources"), relativePath: "research/refs/sources.md" },- { content: Buffer.from("research skill"), relativePath: "research/SKILL.md" },- { content: Buffer.from("weather skill"), relativePath: "weather/SKILL.md" },- ],- key: "resources-hash:skills",- mountPath: "/eve/resources/skills",- targetPath: "$HOME/.agents/skills",- },- source: { key: "resources-hash", kind: "materialized", path: resourceRoot },- workspace: {- files: [- { content: Buffer.from("a"), relativePath: "data/a.csv" },- { content: Buffer.from("b"), relativePath: "data/b.csv" },- { content: Buffer.from("notes"), relativePath: "notes.md" },- { content: Buffer.from("readme"), relativePath: "README.md" },- ],- key: "resources-hash:workspace",- mountPath: "/eve/resources/workspace",- targetPath: "/workspace",- },+ expect(trees).toEqual({+ skills: [+ { content: Buffer.from("sources"), relativePath: "research/refs/sources.md" },+ { content: Buffer.from("research skill"), relativePath: "research/SKILL.md" },+ { content: Buffer.from("weather skill"), relativePath: "weather/SKILL.md" },+ ],+ workspace: [+ { content: Buffer.from("a"), relativePath: "data/a.csv" },+ { content: Buffer.from("b"), relativePath: "data/b.csv" },+ { content: Buffer.from("notes"), relativePath: "notes.md" },+ { content: Buffer.from("readme"), relativePath: "README.md" },+ ],+ });+ const context = createSandboxPrepareContext({+ appRoot: resourceRoot,+ files: { list: async () => [], read: async () => new Uint8Array(), readText: async () => "" },+ log: () => {},+ provider: { prepare: undefined, providerName: "test" },+ resources: { key: "resources-hash", path: resourceRoot, ...trees },+ sourceRevision: "revision",+ storagePath: resourceRoot,});- expect(providerResourceTargetFiles(resources).map((file) => file.path)).toEqual([+ expect(await populatedPaths(context)).toEqual(["/workspace/data/a.csv","/workspace/data/b.csv","/workspace/notes.md","/workspace/README.md",- "$HOME/.agents/skills/research/refs/sources.md",- "$HOME/.agents/skills/research/SKILL.md",- "$HOME/.agents/skills/weather/SKILL.md",+ "/home/agent/.agents/skills/research/refs/sources.md",+ "/home/agent/.agents/skills/research/SKILL.md",+ "/home/agent/.agents/skills/weather/SKILL.md",]);});});diff --git a/packages/eve/src/runtime/workspace/spec.ts b/packages/eve/src/runtime/workspace/spec.tsindex 5facca2f3..95ed40b43 100644--- a/packages/eve/src/runtime/workspace/spec.ts+++ b/packages/eve/src/runtime/workspace/spec.ts@@ -1,4 +1,4 @@-import { WORKSPACE_ROOT, type WorkspaceRuntimeSpec } from "#runtime/workspace/types.js";+import type { WorkspaceRuntimeSpec } from "#runtime/workspace/types.js";/*** Creates the authored-workspace prompt section that advertises the authored@@ -12,10 +12,9 @@ export function createWorkspacePromptSection(spec: WorkspaceRuntimeSpec): stringconst lines = ["Workspace","- You have access to authored files mounted at the workspace root for this run.",- `- The live workspace root visible to \`bash\` in this run is \`${WORKSPACE_ROOT}\`.`,- `- Root entries under ${WORKSPACE_ROOT}/:`,+ "- The workspace root is the directory where `bash` commands start; `pwd` prints its absolute path.",+ "- Root entries under the workspace root:",...spec.rootEntries.map((entry) => ` - ${entry}`),- `- Treat \`${WORKSPACE_ROOT}\` as the workspace root for this run unless a \`bash\` call shows otherwise.`,"- For questions about workspace paths or file availability, verify with `bash` first using commands like `pwd`, `ls`, and `find`.","- If the required `bash` verification fails, report that failure directly instead of answering from this overview.","- Use the `bash` tool with `ls`, `find`, and `rg` to inspect deeper contents when needed.",diff --git a/packages/eve/src/runtime/workspace/types.ts b/packages/eve/src/runtime/workspace/types.tsindex b1c2b79cd..d86957836 100644--- a/packages/eve/src/runtime/workspace/types.ts+++ b/packages/eve/src/runtime/workspace/types.ts@@ -1,10 +1,6 @@/**- * Stable root directory for every workspace eve exposes to agents and- * sandbox providers.- *- * This is both the model-facing logical path and the live `bash` cwd- * for every backend. Backends must initialize their filesystems so- * commands run at this path; there is no per-backend translation.+ * The default sandbox workspace root, used by every built-in provider and by+ * a connection that does not declare its own `workspaceRoot`.*/export const WORKSPACE_ROOT = "/workspace";diff --git a/packages/eve/src/sandbox/provider.test.ts b/packages/eve/src/sandbox/provider.test.tsindex 38755fbe9..df0c7dc77 100644--- a/packages/eve/src/sandbox/provider.test.ts+++ b/packages/eve/src/sandbox/provider.test.ts@@ -2,14 +2,16 @@ import type { Experimental_SandboxSession } from "ai";import { describe, expect, expectTypeOf, it, vi } from "vitest";import type * as Vercel from "#compiled/@vercel/sandbox/index.js";+import {+ createSandboxPrepareContext,+ type SandboxTemplateResources,+} from "#execution/sandbox/prewarm.js";import { defineSandboxProvider, type SandboxConnection } from "#sandbox/provider.js";-import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";-import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";import {- createSandboxProviderResources,- type SandboxProviderPrepareContext,- type SandboxProviderSessionContext,-} from "#shared/sandbox-provider.js";+ getSandboxEnvironmentRuntime,+ type SandboxEnvironmentIdentity,+} from "#shared/sandbox-environment.js";+import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";import type { SandboxSession } from "#shared/sandbox-session.js";const HOME_PROBE = `printf '%s\\n' "$HOME"`;@@ -19,7 +21,6 @@ function recordingConnection() {const files = new Map<string, Uint8Array>();const calls: string[] = [];const connection = {- close: vi.fn(async () => void calls.push("close")),extensions: { ping: async () => "pong" },async readFile({ path }: { readonly path: string }) {return files.get(path) ?? null;@@ -42,27 +43,23 @@ function recordingConnection() {return { calls, connection, files };}-function sessionContext(id = "session-1"): SandboxProviderSessionContext {- return {- host: { loadOptionalPackage: vi.fn(), resolveProjectPath: (path) => `/app/${path}` },- session: { auth: { current: null, initiator: null }, id, turn: { id: "turn", sequence: 0 } },- storagePath: "/app/.eve/sandbox",- };-}--type ResourceTrees = Pick<- Parameters<typeof createSandboxProviderResources>[0],- "skills" | "workspace"->;--function prepareContext(trees: ResourceTrees = {}, path?: string): SandboxProviderPrepareContext {- return {- files: { list: async () => [], read: vi.fn(), readText: vi.fn() },- host: sessionContext().host,- resources: createSandboxProviderResources({ key: "resources-key", path, ...trees }),- sourceRevision: "revision-1",- storagePath: "/app/.eve/sandbox",- };+/** Runs the environment's `prepare()` with the context eve builds during `eve build`. */+async function prepare(+ environment: SandboxEnvironmentIdentity,+ resources: Omit<SandboxTemplateResources, "key"> = {},+) {+ const runtime = getSandboxEnvironmentRuntime(environment);+ return await runtime.implementation.prepare(+ createSandboxPrepareContext({+ appRoot: "/app",+ files: { list: async () => [], read: vi.fn(), readText: vi.fn() },+ log: () => {},+ provider: runtime,+ resources: { key: "resources-key", ...resources },+ sourceRevision: "revision-1",+ storagePath: "/app/.eve/sandbox",+ }),+ );}/** A provider whose `prepare` populates `connection`, passing `mountedAt` through. */@@ -85,75 +82,6 @@ function bakingProvider(}describe("defineSandboxProvider", () => {- it("derives the session from the connection, resolving paths from /workspace", async () => {- const { connection, files } = recordingConnection();- const kinds: string[] = [];- const provider = defineSandboxProvider({- name: "recording",- environment: () => ({- prepare: async () => null,- async start(ctx) {- kinds.push(ctx.kind);- return { connection, state: null };- },- resume: async () => connection,- onSessionEnd: async () => {},- }),- });- const { implementation } = getSandboxEnvironmentRuntime(provider.environment());-- const { handle } = await implementation.start(sessionContext(), undefined, null);- await implementation.start(sessionContext("tool_session_abc"), undefined, null);- const sandbox = handle.sandbox as SandboxSession & { ping(): Promise<string> };- await sandbox.writeTextFile({ content: "hi", path: "notes/./a.txt" });- await sandbox.run({ command: "ls", workingDirectory: "src" });- await sandbox.removePath({ path: "../tmp/x", recursive: true });-- expect(kinds).toEqual(["session", "tool-session"]);- expect([...files.keys()]).toEqual(["/workspace/notes/a.txt"]);- expect(await sandbox.readTextFile({ path: "/workspace/notes/a.txt" })).toBe("hi");- expect(connection.spawn).toHaveBeenCalledWith({- abortSignal: undefined,- command: "ls",- env: {},- workingDirectory: "/workspace/src",- });- expect(connection.removePath).toHaveBeenCalledWith(- expect.objectContaining({ path: "/tmp/x", recursive: true }),- );- expect(await sandbox.ping()).toBe("pong");- // A backend may answer with a stream instead of bytes.- vi.spyOn(connection, "readFile").mockResolvedValueOnce(- new Blob(["streamed"]).stream() as never,- );- expect(await sandbox.readTextFile({ path: "b.txt" })).toBe("streamed");- expect(connection.readFile).toHaveBeenLastCalledWith({- abortSignal: undefined,- path: "/workspace/b.txt",- });- });-- it("rejects connection extensions that would replace a session member", async () => {- const { connection } = recordingConnection();- const provider = defineSandboxProvider({- name: "colliding",- environment: () => ({- prepare: async () => null,- start: async () => ({- connection: { ...connection, extensions: { run: async () => "mine" } } as never,- state: null,- }),- resume: async () => connection,- onSessionEnd: async () => {},- }),- });- const { implementation } = getSandboxEnvironmentRuntime(provider.environment());-- await expect(implementation.start(sessionContext(), undefined, null)).rejects.toThrow(- "Sandbox connection extensions cannot replace the session members eve provides: run.",- );- });-it("passes environment options to the provider without prepare, and {} when omitted", () => {const received: object[] = [];const provider = defineSandboxProvider({@@ -203,9 +131,7 @@ describe("defineSandboxProvider", () => {onSessionEnd: async () => {},}),});- const { implementation } = getSandboxEnvironmentRuntime(provider.environment());-- await implementation.prepare(prepareContext());+ await prepare(provider.environment());// Golden value: if it changes, every custom provider's template keys change with it.expect(keys).toEqual(["d02550d7328ec5806580c8cd02c0c2b0b3e9a90bbbec7f552938442d79ffd8e1"]);@@ -221,42 +147,40 @@ describe("defineSandboxProvider", () => {});const artifacts = [- await getSandboxEnvironmentRuntime(environment).implementation.prepare(- prepareContext({- skills: [{ content: "# Skill", relativePath: "review/SKILL.md" }],- workspace: [{ content: "seed", relativePath: "seed.txt" }],- }),- ),- await getSandboxEnvironmentRuntime(provider.environment()).implementation.prepare(- prepareContext(),- ),+ await prepare(environment, {+ skills: [{ content: "# Skill", relativePath: "review/SKILL.md" }],+ workspace: [+ { content: "seed", relativePath: "seed.txt" },+ { content: "literal", relativePath: "$HOME/notes.txt" },+ ],+ }),+ await prepare(provider.environment()),];expect(artifacts).toEqual([{ empty: false }, { empty: true }]);expect(calls).toEqual([- "write /workspace/seed.txt /home/agent/.agents/skills/review/SKILL.md",+ "write /workspace/seed.txt /workspace/$HOME/notes.txt /home/agent/.agents/skills/review/SKILL.md","write /workspace/prepared.txt",]);});- it("copies from mounted resources, and writes files when there is no resource directory", async () => {+ it("seeds the connection's workspace root from mounted resources, or by writing files without a resource directory", async () => {const seed = { workspace: [{ content: "seed", relativePath: "seed.txt" }] };const mounted = recordingConnection();- await getSandboxEnvironmentRuntime(- bakingProvider(mounted.connection, "/eve/res ources").environment(),- ).implementation.prepare(prepareContext(seed, "/app/.eve/compile/resources"));+ const mountedConnection = { ...mounted.connection, workspaceRoot: "/srv/app" };+ await prepare(bakingProvider(mountedConnection, "/eve/res ources").environment(), {+ ...seed,+ path: "/app/.eve/compile/resources",+ });const inline = recordingConnection();- await getSandboxEnvironmentRuntime(- bakingProvider(inline.connection, "/eve/resources").environment(),- ).implementation.prepare(prepareContext(seed));+ const inlineConnection = { ...inline.connection, workspaceRoot: "/srv/app" };+ await prepare(bakingProvider(inlineConnection, "/eve/resources").environment(), seed);expect(mounted.calls).toEqual([]);- expect(mounted.connection.spawn).toHaveBeenCalledWith(- expect.objectContaining({- command: expect.stringContaining("cp -a '/eve/res ources'/workspace/. /workspace/"),- }),- );- expect(inline.calls).toEqual(["write /workspace/seed.txt"]);+ const copy = mounted.connection.spawn.mock.calls[0]?.[0].command;+ expect(copy).toContain("cp -a '/eve/res ources'/workspace/. '/srv/app'/");+ expect(copy).toContain(`cp -a '/eve/res ources'/skills/. "$HOME/.agents/skills/"`);+ expect(inline.calls).toEqual(["write /srv/app/seed.txt"]);});});diff --git a/packages/eve/src/sandbox/provider.ts b/packages/eve/src/sandbox/provider.tsindex 779999012..9617e02fe 100644--- a/packages/eve/src/sandbox/provider.ts+++ b/packages/eve/src/sandbox/provider.ts@@ -1,37 +1,15 @@-import { posix } from "node:path";--import {- hydrateSandboxFromImmutableResources,- prepareImmutableResources,-} from "#execution/sandbox/bindings/immutable-resources.js";-import { createLoggingSandboxSession } from "#execution/sandbox/logging-session.js";-import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";-import { buildSandboxSession } from "#execution/sandbox/session.js";-import { shellQuote } from "#execution/sandbox/shell-quote.js";-import { bufferToStream, streamToBuffer } from "#execution/sandbox/stream-utils.js";-import { isToolSessionId } from "#execution/tool-session/id.js";-import { withToolSessionSandboxes } from "#execution/tool-session/sandbox.js";-import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";-import type { SandboxSelectorContext } from "#shared/sandbox-environment.js";import {- defineLegacySandboxProvider,- providerResourceTargetFiles,- sandboxProviderResourceIdentity,- type LegacySandboxProviderImplementation,- type SandboxPreparedArtifact,- type SandboxProvider,- type SandboxProviderFiles,- type SandboxProviderHandle,- type SandboxProviderPrepareContext,- type SandboxProviderSessionContext,-} from "#shared/sandbox-provider.js";+ createSandboxEnvironment,+ type SandboxEnvironment,+ type SandboxSelectorContext,+} from "#shared/sandbox-environment.js";+import type { SandboxPreparedArtifact, SandboxProviderFiles } from "#shared/sandbox-provider.js";import type {SandboxProcess,SandboxRemovePathOptions,SandboxSession,SandboxWriteFilesOptions,} from "#shared/sandbox-session.js";-import { resolveSandboxModelPath } from "#shared/skill-paths.js";/** A JSON-compatible value: what a provider may return as an artifact or session state. */export type SandboxJson = SandboxPreparedArtifact;@@ -44,9 +22,15 @@ type ReservedSessionMember = keyof SandboxSession | "delete" | "stop";* derives the full {@link SandboxSession} from it.** Every path a connection receives is absolute, and `workingDirectory` is- * always set: eve resolves relative paths from `/workspace`.+ * always set: eve resolves relative paths from {@link workspaceRoot}.*/export interface SandboxConnection<Extensions extends object = {}> {+ /**+ * The absolute sandbox directory that relative paths resolve from and+ * commands start in by default. Defaults to `/workspace`. The directory+ * must exist when eve first runs a command.+ */+ readonly workspaceRoot?: string;/*** Runs `command` as a Bash login-shell script (`bash -lc`) in* `workingDirectory`, with the sandbox's environment plus `env`. `env`@@ -119,10 +103,11 @@ export interface SandboxPrepareContext {/** Reports build progress, such as `eve build` output. */log(message: string): void;/**- * Seeds `/workspace` and `$HOME/.agents/skills`, then runs the authored- * `prepare` with a session over `connection`. With `mountedAt`, the- * provider has mounted {@link resourcesDirectory} read-only at that- * sandbox path, and eve copies from it instead of writing every file.+ * Seeds the connection's workspace root and `$HOME/.agents/skills`, then+ * runs the authored `prepare` with a session over `connection`. With+ * `mountedAt`, the provider has mounted {@link resourcesDirectory}+ * read-only at that sandbox path, and eve copies from it instead of+ * writing every file.*/populate(connection: SandboxConnection<object>,@@ -223,6 +208,37 @@ export interface SandboxProviderDefinition<): SandboxProviderImplementation<OpenOptions, Artifact, State, Extensions>;}+type SandboxOptionArguments<Options extends object | undefined> = Options extends undefined+ ? [options?: undefined]+ : Record<never, never> extends Options+ ? [options?: Readonly<Options>]+ : [options: Readonly<Options>];++export interface SandboxProvider<+ EnvironmentOptions extends object | undefined,+ OpenOptions extends object | undefined,+ Session extends SandboxSession,+> {+ readonly name: string;+ environment(+ ...args: SandboxOptionArguments<EnvironmentOptions>+ ): SandboxEnvironment<OpenOptions, Session>;+}++/** What core runs for one environment: the provider's lifecycle with its types erased. */+export interface SandboxProviderRuntime {+ readonly implementation: SandboxProviderImplementation<+ object | undefined,+ SandboxJson,+ SandboxJson,+ object+ >;+ /** The authored `prepare` option, which eve runs in `ctx.populate()`. */+ readonly prepare: ((sandbox: SandboxSession) => void | Promise<void>) | undefined;+ readonly providerName: string;+ readonly stateProtocolVersion: number;+}+/** Defines a sandbox provider from a connection and a lifecycle. */export function defineSandboxProvider<EnvironmentOptions extends object = {},@@ -244,284 +260,19 @@ export function defineSandboxProvider<SandboxSession & Extensions> {type Session = SandboxSession & Extensions;- const provider = defineLegacySandboxProvider<- SandboxPrepareOption<Session> | undefined,- OpenOptions,- Artifact,- State,- Session- >({+ return {name: definition.name,- stateProtocolVersion: definition.stateProtocolVersion,- environment(options) {+ environment(options?: WithPrepareOption<EnvironmentOptions, Session>) {const { prepare, ...environmentOptions } = options ?? {};- const implementation = definition.environment(environmentOptions as EnvironmentOptions);- return adaptSandboxProvider(definition.name, implementation, prepare);- },- });- return provider as SandboxProvider<- WithPrepareOption<EnvironmentOptions, Session>,- OpenOptions,- Session- >;-}--function adaptSandboxProvider<- OpenOptions extends object | undefined,- Artifact extends SandboxJson,- State extends SandboxJson,- Extensions extends object,->(- providerName: string,- implementation: SandboxProviderImplementation<OpenOptions, Artifact, State, Extensions>,- prepare: ((sandbox: SandboxSession & Extensions) => void | Promise<void>) | undefined,-): LegacySandboxProviderImplementation<OpenOptions, Artifact, State, SandboxSession & Extensions> {- const closers = new WeakMap<SandboxProviderHandle, () => Promise<void>>();- // Closable connections this process holds per session, so terminal cleanup can close them.- const open = new Map<string, Set<() => Promise<void>>>();-- function createHandle(- context: SandboxSessionContext,- connection: SandboxConnection<Extensions>,- state: Readonly<State>,- ): SandboxProviderHandle<SandboxSession & Extensions> {- const sessionId = context.session.id;- // A stopped connection can resume on its next use, so a later stop runs- // again; only a stop already in flight is shared. Close runs once.- const stop = shared(() => connection.stop());- const close = once(async () => {- const remaining = open.get(sessionId);- remaining?.delete(close);- if (remaining?.size === 0) open.delete(sessionId);- await connection.close?.();- });- if (connection.close !== undefined) {- let sessionClosers = open.get(sessionId);- if (sessionClosers === undefined) open.set(sessionId, (sessionClosers = new Set()));- sessionClosers.add(close);- }- const release = async () => {- try {- await stop();- } finally {- await close();- }- };- const handle: SandboxProviderHandle<SandboxSession & Extensions> = {- sandbox: createConnectionSession(connection),- onRuntimeShutdown: release,- async onSandboxDelete(options) {- try {- await close();- } finally {- await implementation.onSessionEnd(context, state, {- abortSignal: options?.abortSignal,- reason: "deleted",- });- }- },- onSandboxStop: release,- };- closers.set(handle, close);- return handle;- }-- async function closeSession(sessionId: string): Promise<void> {- const sessionClosers = [...(open.get(sessionId) ?? [])];- open.delete(sessionId);- await Promise.allSettled(sessionClosers.map((close) => close()));- }-- const adapted: LegacySandboxProviderImplementation<- OpenOptions,- Artifact,- State,- SandboxSession & Extensions- > = {- async onSessionEnd(context, state, { reason }) {- // A failed close of a process-local resource must not block deleting the sandbox.- await closeSession(context.session.id);- await implementation.onSessionEnd(createSessionContext(context), state, { reason });- },- async prepare(context) {- return await implementation.prepare(createPrepareContext(providerName, context, prepare));- },- async resume(context, artifact, state) {- const sessionContext = createSessionContext(context);- const connection = await implementation.resume(sessionContext, artifact, state);- return createHandle(sessionContext, connection, state);- },- async start(context, options, artifact) {- const sessionContext = createSessionContext(context);- const { connection, state } = await implementation.start(sessionContext, options, artifact);- return { handle: createHandle(sessionContext, connection, state), state };- },- };- if (implementation.toolSessions !== true) return adapted;- return withToolSessionSandboxes(adapted, {- releaseHandle: async (handle) => await closers.get(handle)?.(),- });-}--function createSessionContext(context: SandboxProviderSessionContext): SandboxSessionContext {- return {- kind: isToolSessionId(context.session.id) ? "tool-session" : "session",- resolveProjectPath: (path) => context.host.resolveProjectPath(path),- session: context.session,- storagePath: context.storagePath,- };-}--function createPrepareContext<Extensions extends object>(- providerName: string,- context: SandboxProviderPrepareContext,- prepare: ((sandbox: SandboxSession & Extensions) => void | Promise<void>) | undefined,-): SandboxPrepareContext {- const files = providerResourceTargetFiles(context.resources);- const log = (message: string) => context.log?.(message);- return {- files: context.files,- isEmpty: files.length === 0 && prepare === undefined,- log,- async populate(connection, options) {- const session = createConnectionSession(connection);- // Without a resource directory there is nothing mounted to copy from.- if (options?.mountedAt !== undefined && context.resources.source.kind === "materialized") {- log("copying workspace and skills from mounted resources");- await hydrateSandboxFromImmutableResources(session, shellQuote(options.mountedAt));- } else if (files.length > 0) {- log("writing workspace and skills");- await session.writeFiles({- files: await Promise.all(- files.map(async (file) => ({- content: typeof file.content === "string" ? Buffer.from(file.content) : file.content,- path: await resolveSandboxModelPath({ path: file.path, sandbox: session }),- })),- ),- });- }- if (prepare === undefined) return;- log("running sandbox preparation");- // The provider builds the template with the connection type its sessions use.- await prepare(createLoggingSandboxSession({ log, session }) as SandboxSession & Extensions);- },- resolveProjectPath: (path) => context.host.resolveProjectPath(path),- async resourcesDirectory() {- const source = context.resources.source;- if (source.kind !== "materialized") return undefined;- return await prepareImmutableResources({- provider: providerName,- resourcesKey: source.key,- sourcePath: source.path,- storagePath: context.storagePath,- });- },- storagePath: context.storagePath,- templateKey(identity) {- assertSandboxIdentity(identity, "identity", new WeakSet());- for (const reserved of ["resources", "sourceRevision"]) {- if (Object.hasOwn(identity, reserved)) {- throw new Error(- `ctx.templateKey() reserves "${reserved}": eve adds the workspace and skill files and the sandbox source revision itself. Rename that identity field.`,- );- }- }- return createSandboxProviderIdentity({- ...identity,- resources: sandboxProviderResourceIdentity(context.resources),- sourceRevision: context.sourceRevision,- });- },- };-}--function createConnectionSession<Extensions extends object>(- connection: SandboxConnection<Extensions>,-): SandboxSession & Extensions {- const session = buildSandboxSession({- async readFile(options) {- const content = await connection.readFile(options);- if (content === null || !ArrayBuffer.isView(content)) return content;- return bufferToStream(new Uint8Array(content.buffer, content.byteOffset, content.byteLength));- },- removePath: (options) => connection.removePath(options),- resolvePath: resolveSandboxPath,- spawn: (options) =>- connection.spawn({- abortSignal: options.abortSignal,- command: options.command,- env: options.env ?? {},- workingDirectory: resolveSandboxPath(options.workingDirectory ?? WORKSPACE_ROOT),- }),- async writeFile(options) {- await connection.writeFiles({- abortSignal: options.abortSignal,- files: [{ content: await streamToBuffer(options.content), path: options.path }],+ return createSandboxEnvironment<OpenOptions, Session>({+ // The provider's own types are erased: core passes it only what it returned.+ implementation: definition.environment(+ environmentOptions as EnvironmentOptions,+ ) as SandboxProviderRuntime["implementation"],+ prepare: prepare as SandboxProviderRuntime["prepare"],+ providerName: definition.name,+ stateProtocolVersion: definition.stateProtocolVersion ?? 1,});},- writeFiles: (options) => connection.writeFiles(options),- });- const extensions: object = connection.extensions ?? {};- const collisions = Object.keys(extensions).filter(- (key) => Object.hasOwn(session, key) || key === "delete" || key === "stop",- );- if (collisions.length > 0) {- throw new Error(- `Sandbox connection extensions cannot replace the session members eve provides: ${collisions.join(", ")}. Rename them.`,- );- }- return { ...extensions, ...session } as SandboxSession & Extensions;-}--/** Runs `run` at most once while it succeeds; a failed run can be retried. */-function shared(run: () => Promise<void>): () => Promise<void> {- let running: Promise<void> | undefined;- return () =>- (running ??= run().finally(() => {- running = undefined;- }));-}--function once(run: () => Promise<void>): () => Promise<void> {- let running: Promise<void> | undefined;- return () =>- (running ??= run().catch((error: unknown) => {- running = undefined;- throw error;- }));-}--/**- * Rejects what the template-key hasher cannot tell apart, such as a `Date` or- * `Map` that would hash as `{}`, and circular values, before hashing.- */-function assertSandboxIdentity(value: unknown, path: string, seen: WeakSet<object>): void {- if (value === null || value === undefined || typeof value === "function") return;- if (typeof value === "string" || typeof value === "boolean") return;- if (typeof value === "number" && Number.isFinite(value)) return;- const prototype = typeof value === "object" ? Object.getPrototypeOf(value) : undefined;- const plain = Array.isArray(value) || prototype === Object.prototype || prototype === null;- if (typeof value !== "object" || !plain) {- throw new Error(- `ctx.templateKey() accepts only JSON values, plain objects, arrays, and functions, but ${path} is ${describeIdentityValue(value)}. Pass a JSON form, such as a string.`,- );- }- if (seen.has(value))- throw new Error(`ctx.templateKey() cannot hash a circular value at ${path}.`);- seen.add(value);- for (const [key, entry] of Object.entries(value)) {- assertSandboxIdentity(entry, Array.isArray(value) ? `${path}[${key}]` : `${path}.${key}`, seen);- }- seen.delete(value);-}--function describeIdentityValue(value: unknown): string {- if (typeof value === "object" && value !== null) {- return `a ${value.constructor?.name ?? "non-plain object"}`;- }- return typeof value === "number" ? String(value) : `a ${typeof value}`;-}--function resolveSandboxPath(path: string): string {- return posix.resolve(WORKSPACE_ROOT, path);+ } as SandboxProvider<WithPrepareOption<EnvironmentOptions, Session>, OpenOptions, Session>;}diff --git a/packages/eve/src/sandbox/providers/default.integration.test.ts b/packages/eve/src/sandbox/providers/default.integration.test.tsindex ec6569fe9..22a0eae0d 100644--- a/packages/eve/src/sandbox/providers/default.integration.test.ts+++ b/packages/eve/src/sandbox/providers/default.integration.test.ts@@ -1,12 +1,14 @@import { mkdir } from "node:fs/promises";+import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";-import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";+import { shutdownActiveSandboxConnections } from "#execution/sandbox/active-connections.js";import { isLinuxDockerDaemonAvailableSync } from "#execution/sandbox/bindings/local.js";import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";+import { createSandboxPrepareContext } from "#execution/sandbox/prewarm.js";import { createSandboxProviderFiles } from "#execution/sandbox/provider-files.js";-import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";+import { TOOL_SESSION_ID_PREFIX } from "#execution/tool-session/id.js";import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";import { defineSandbox } from "#public/definitions/sandbox.js";@@ -17,7 +19,6 @@ import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";import { DefaultSandbox, type DefaultSandboxSession } from "#sandbox/providers/default.js";import type { SandboxState } from "#sandbox/state.js";import { getSandboxEnvironmentRuntime, type SandboxSelector } from "#shared/sandbox-environment.js";-import { createSandboxProviderResources } from "#shared/sandbox-provider.js";vi.mock("#execution/sandbox/bindings/local.js", async (importOriginal) => ({...(await importOriginal<typeof import("#execution/sandbox/bindings/local.js")>()),@@ -27,7 +28,7 @@ vi.mock("#execution/sandbox/bindings/local.js", async (importOriginal) => ({const createScratchDirectory = useTemporaryDirectories();afterEach(async () => {- await shutdownActiveSandboxHandles();+ await shutdownActiveSandboxConnections();vi.unstubAllEnvs();vi.mocked(isLinuxDockerDaemonAvailableSync).mockClear();});@@ -38,14 +39,18 @@ async function build(environment: ReturnType<typeof DefaultSandbox.environment>,const log = vi.fn();vi.stubEnv("VERCEL", "");vi.stubEnv("EVE_DEV", dev ? "1" : "");- const artifact = await getSandboxEnvironmentRuntime(environment).implementation.prepare({- files: createSandboxProviderFiles(`${appRoot}/agent/sandbox`),- host: createSandboxProviderHost(appRoot),- log,- resources: createSandboxProviderResources({}),- sourceRevision: "revision",- storagePath: resolveSandboxCacheDirectory(appRoot),- });+ const runtime = getSandboxEnvironmentRuntime(environment);+ const artifact = await runtime.implementation.prepare(+ createSandboxPrepareContext({+ appRoot,+ files: createSandboxProviderFiles(`${appRoot}/agent/sandbox`),+ log,+ provider: runtime,+ resources: {},+ sourceRevision: "revision",+ storagePath: resolveSandboxCacheDirectory(appRoot),+ }),+ );const { compileDirectoryPath } = resolveRuntimeCompilerArtifactPaths(appRoot);await mkdir(compileDirectoryPath, { recursive: true });await writeSandboxPreparedArtifactsManifest({@@ -60,6 +65,7 @@ async function access(input: {readonly appRoot: string;readonly environment: ReturnType<typeof DefaultSandbox.environment>;readonly selector: SandboxSelector;+ readonly sessionId?: string;readonly state?: SandboxState;}) {const registry: RuntimeSandboxRegistry = {@@ -80,7 +86,7 @@ async function access(input: {compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(input.appRoot),nodeId: "__root__",registry,- sessionId: "session-1",+ sessionId: input.sessionId ?? "session-1",state: input.state ?? null,});}@@ -147,6 +153,53 @@ describe("DefaultSandbox", () => {await expect(opened?.setNetworkPolicy("deny-all")).rejects.toThrow(/just-bash/);});+ // Recorded from DefaultSandbox before it moved to the public provider API.+ // Deployed builds and running sessions depend on them, so they must never change.+ it("records the same artifact and session state as earlier releases", async () => {+ const environment = DefaultSandbox.environment();+ const { appRoot, artifact } = await build(environment, true);+ expect(artifact).toEqual({+ artifact: { templateKey: "f8ea3d0c5299b20a1228522b" },+ provider: "just-bash",+ });++ const sandbox = await access({+ appRoot,+ environment,+ selector: defineSandbox(() => environment.open()),+ });+ await sandbox.get();+ await expect(sandbox.captureState()).resolves.toMatchObject({+ session: {+ providerName: "default",+ state: {+ provider: "just-bash",+ state: {+ rootPath: join(+ resolveSandboxCacheDirectory(appRoot),+ "just-bash/sessions/7ee62ad93371e90cea6827d5",+ ),+ version: 2,+ },+ stateProtocolVersion: 1,+ },+ stateProtocolVersion: 1,+ },+ });+ });++ it("keeps a keyed tool call's sandbox when the selected provider can", async () => {+ const environment = DefaultSandbox.environment();+ const { appRoot } = await build(environment, true);+ const selector = defineSandbox(() => environment.open());+ const sessionId = `${TOOL_SESSION_ID_PREFIX}desk`;++ const first = await access({ appRoot, environment, selector, sessionId });+ await (await first.get())?.writeTextFile({ content: "kept", path: "marker.txt" });+ const second = await access({ appRoot, environment, selector, sessionId });+ await expect((await second.get())?.readTextFile({ path: "marker.txt" })).resolves.toBe("kept");+ });+it("ends a sandbox no checkpoint recorded through the provider its build selected", async () => {const environment = DefaultSandbox.environment();const { appRoot } = await build(environment, true);diff --git a/packages/eve/src/sandbox/providers/default.ts b/packages/eve/src/sandbox/providers/default.tsindex a220080f7..5b5c7767c 100644--- a/packages/eve/src/sandbox/providers/default.ts+++ b/packages/eve/src/sandbox/providers/default.ts@@ -1,36 +1,29 @@import { isLinuxDockerDaemonAvailableSync } from "#execution/sandbox/bindings/local.js";-import { isToolSessionId } from "#execution/tool-session/id.js";-import {- getToolSessionSandboxSupport,- ToolSessionSandboxUnsupportedError,- withToolSessionSandboxes,-} from "#execution/tool-session/sandbox.js";import { isEveDevEnvironment } from "#internal/application/dev-environment.js";import type { DockerSandboxEnvironmentOptions } from "#public/sandbox/docker-sandbox.js";-import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.js";+import type { SandboxSession } from "#public/sandbox/index.js";import {- type SandboxSessionEndWithArtifact,- withAdoptedSandboxSessionStates,- withSessionEndArtifact,-} from "#sandbox/state.js";+ defineSandboxProvider,+ SandboxSessionGoneError,+ type SandboxConnection,+ type SandboxJson,+ type SandboxProvider,+ type SandboxProviderImplementation,+ type SandboxSessionContext,+ type SandboxSessionEndOptions,+} from "#public/sandbox/provider.js";+import type { VercelSandboxCreateOptions } from "#public/sandbox/vercel-sandbox.js";+import { withAdoptedSandboxSessionStates, withSessionEndArtifact } from "#sandbox/state.js";import { DockerSandbox } from "#sandbox/providers/docker.js";import { JustBashSandbox, type JustBashEnvironmentOptions } from "#sandbox/providers/just-bash.js";import { VercelSandbox } from "#sandbox/providers/vercel.js";+import { isObject } from "#shared/guards.js";import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";import type {SandboxNetworkOptions,SandboxNetworkPolicy,} from "#shared/sandbox-network-policy.js";-import {- defineLegacySandboxProvider,- isSandboxPreparedArtifactRecord,- type SandboxPreparedArtifact,- type SandboxProviderHandle,- type LegacySandboxProviderImplementation,- type SandboxProviderRuntime,-} from "#shared/sandbox-provider.js";-import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";-import type { SandboxSession } from "#shared/sandbox-session.js";+import { ToolSessionSandboxUnsupportedError } from "#shared/sandbox-tool-session-error.js";export interface DefaultSandboxEnvironmentOptions {readonly docker?: DockerSandboxEnvironmentOptions;@@ -54,16 +47,18 @@ export interface DefaultSandboxSession extends SandboxSession {type SelectedProvider = "docker" | "just-bash" | "vercel";type DefaultSandboxPreparedArtifact =- | { readonly artifact: SandboxPreparedArtifact; readonly provider: SelectedProvider }+ | { readonly artifact: SandboxJson; readonly provider: SelectedProvider }| { readonly provider: null };type DefaultSandboxSessionState = {readonly provider: SelectedProvider;- readonly state: SandboxPreparedArtifact;+ readonly state: SandboxJson;/** The selected provider's state protocol when it recorded `state`. */readonly stateProtocolVersion: number;};+type NetworkPolicyExtensions = Pick<DefaultSandboxSession, "setNetworkPolicy">;+const SELECTED_PROVIDERS: readonly SelectedProvider[] = ["docker", "just-bash", "vercel"];const NO_PROVIDER_MESSAGE =@@ -82,17 +77,15 @@ const JUST_BASH_NETWORK_POLICY_MESSAGE =* just-bash in development. Preparation records the choice, so the runtime* uses the provider the build selected and never probes the host.*/-export const DefaultSandbox = defineLegacySandboxProvider<+export const DefaultSandbox: SandboxProvider<DefaultSandboxEnvironmentOptions,DefaultSandboxRuntimeOptions,- DefaultSandboxPreparedArtifact,- DefaultSandboxSessionState,DefaultSandboxSession->({+> = defineSandboxProvider({name: "default",- environment(options = {}) {+ environment(options: Omit<DefaultSandboxEnvironmentOptions, "prepare">) {// Created on first use, so a hosted bundle never constructs the local providers it prunes.- const providers = new Map<SelectedProvider, SandboxProviderRuntime>();+ const providers = new Map<SelectedProvider, ReturnType<typeof getSandboxEnvironmentRuntime>>();const provider = (name: SelectedProvider) => {let runtime = providers.get(name);if (runtime === undefined) {@@ -101,95 +94,56 @@ export const DefaultSandbox = defineLegacySandboxProvider<}return runtime;};- const releases = new WeakMap<SandboxProviderHandle, () => Promise<void>>();- function wrapHandle(- inner: SandboxProviderRuntime,- handle: SandboxProviderHandle,- ): SandboxProviderHandle<DefaultSandboxSession> {- const wrapped: SandboxProviderHandle<DefaultSandboxSession> = {- sandbox: hasNetworkPolicy(handle.sandbox)- ? handle.sandbox- : { ...handle.sandbox, setNetworkPolicy: rejectJustBashNetworkPolicy },- onRuntimeShutdown: () => handle.onRuntimeShutdown(),- onSandboxDelete: (deleteOptions) => handle.onSandboxDelete(deleteOptions),- onSandboxStop: () => handle.onSandboxStop(),- };- const release = getToolSessionSandboxSupport(inner.implementation)?.releaseHandle;- if (release !== undefined) releases.set(wrapped, () => release(handle));- return wrapped;- }-- function requireProvider(name: SelectedProvider, sessionId: string) {+ function requireProvider(name: SelectedProvider, kind: "session" | "tool-session") {const inner = provider(name);- if (- isToolSessionId(sessionId) &&- getToolSessionSandboxSupport(inner.implementation) === undefined- ) {+ if (kind === "tool-session" && inner.implementation.toolSessions !== true) {throw new ToolSessionSandboxUnsupportedError(name);}return inner;}// Routes to the provider that recorded the state, or else the one this build selected.- const endSession = async (- context: Parameters<SandboxSessionEndWithArtifact>[0],- state: Readonly<DefaultSandboxSessionState> | null,- options: {- readonly artifact: DefaultSandboxPreparedArtifact | undefined;- readonly reason: Parameters<SandboxSessionEndWithArtifact>[2]["reason"];- },- ) => {- const name = state?.provider ?? options.artifact?.provider ?? null;+ async function endSession(+ context: SandboxSessionContext,+ state: DefaultSandboxSessionState | null,+ artifact: DefaultSandboxPreparedArtifact | undefined,+ endOptions: SandboxSessionEndOptions,+ ) {+ const name = state?.provider ?? artifact?.provider ?? null;if (name === null) return;const inner = provider(name);const innerState =state?.stateProtocolVersion === inner.stateProtocolVersion ? state.state : null;- await inner.implementation.onSessionEnd(context, innerState, { reason: options.reason });- };+ await inner.implementation.onSessionEnd(context, innerState, endOptions);+ }- const implementation: LegacySandboxProviderImplementation<+ const implementation: SandboxProviderImplementation<DefaultSandboxRuntimeOptions,DefaultSandboxPreparedArtifact,DefaultSandboxSessionState,- DefaultSandboxSession+ NetworkPolicyExtensions> = {- async onSessionEnd(context, state, { reason }) {- await endSession(context, state, { artifact: undefined, reason });- },+ onSessionEnd: (context, state, endOptions) =>+ endSession(context, state, undefined, endOptions),async prepare(context) {const name = selectProvider();if (name === null) {- context.log?.(NO_PROVIDER_MESSAGE);+ context.log(NO_PROVIDER_MESSAGE);return { provider: null };}return { artifact: await provider(name).implementation.prepare(context), provider: name };},- async resume(context, artifact, state) {- if (artifact.provider === null || artifact.provider !== state.provider) {- throw new SandboxSessionGoneError(- `The session's ${state.provider} sandbox cannot resume because this build selected ${artifact.provider ?? "no provider"}.`,- );- }- const inner = requireProvider(state.provider, context.session.id);- if (state.stateProtocolVersion !== inner.stateProtocolVersion) {- throw new SandboxSessionGoneError(- `The session's ${state.provider} sandbox state uses protocol ${state.stateProtocolVersion}, not ${inner.stateProtocolVersion}.`,- );- }- const handle = await inner.implementation.resume(context, artifact.artifact, state.state);- return wrapHandle(inner, handle);- },- async start(context, options, artifact) {+ async start(context, openOptions, artifact) {if (artifact.provider === null) throw new Error(NO_PROVIDER_MESSAGE);- const inner = requireProvider(artifact.provider, context.session.id);+ const inner = requireProvider(artifact.provider, context.kind);const result = await inner.implementation.start(context,- openOptions(artifact.provider, options),+ innerOpenOptions(artifact.provider, openOptions),artifact.artifact,);return {- handle: wrapHandle(inner, result.handle),+ connection: withNetworkPolicy(result.connection),state: {provider: artifact.provider,state: result.state,@@ -197,16 +151,33 @@ export const DefaultSandbox = defineLegacySandboxProvider<},};},+ async resume(context, artifact, state) {+ if (artifact.provider === null || artifact.provider !== state.provider) {+ throw new SandboxSessionGoneError(+ `The session's ${state.provider} sandbox cannot resume because this build selected ${artifact.provider ?? "no provider"}.`,+ );+ }+ const inner = requireProvider(state.provider, context.kind);+ if (state.stateProtocolVersion !== inner.stateProtocolVersion) {+ throw new SandboxSessionGoneError(+ `The session's ${state.provider} sandbox state uses protocol ${state.stateProtocolVersion}, not ${inner.stateProtocolVersion}.`,+ );+ }+ return withNetworkPolicy(+ await inner.implementation.resume(context, artifact.artifact, state.state),+ );+ },+ // `requireProvider` rejects a keyed call when the selected provider cannot keep its sandbox.+ toolSessions: true,};- withToolSessionSandboxes(implementation, {- releaseHandle: async (handle) => await releases.get(handle)?.(),- });- withSessionEndArtifact(implementation, async (context, state, options) => {- await endSession(context, isDefaultSandboxSessionState(state) ? state : null, {- artifact: isDefaultSandboxPreparedArtifact(options.artifact) ? options.artifact : undefined,- reason: options.reason,- });+ withSessionEndArtifact(implementation, async (context, state, { artifact, reason }) => {+ await endSession(+ context,+ isDefaultSandboxSessionState(state) ? state : null,+ isDefaultSandboxPreparedArtifact(artifact) ? artifact : undefined,+ { reason },+ );});// Sessions saved before DefaultSandbox recorded its own state hold the state// of the provider it picked. Remove this once eve stops resuming sessions@@ -230,19 +201,22 @@ function selectProvider(): SelectedProvider | null {return isEveDevEnvironment() ? "just-bash" : null;}-function createEnvironment(name: SelectedProvider, options: DefaultSandboxEnvironmentOptions) {- const prepare = options.prepare === undefined ? {} : { prepare: options.prepare };+// eve runs the authored `prepare` itself through `ctx.populate()`, so the inner environments omit it.+function createEnvironment(+ name: SelectedProvider,+ options: Omit<DefaultSandboxEnvironmentOptions, "prepare">,+) {switch (name) {case "docker":- return DockerSandbox.environment({ ...options.docker, ...prepare });+ return DockerSandbox.environment(options.docker ?? {});case "just-bash":- return JustBashSandbox.environment({ ...options.justBash, ...prepare });+ return JustBashSandbox.environment(options.justBash ?? {});case "vercel":- return VercelSandbox.environment({ ...options.vercel, ...prepare });+ return VercelSandbox.environment(options.vercel ?? {});}}-function openOptions(+function innerOpenOptions(name: SelectedProvider,options: Readonly<DefaultSandboxRuntimeOptions> | undefined,): Readonly<DefaultSandboxRuntimeOptions> | undefined {@@ -253,12 +227,20 @@ function openOptions(return undefined;}-async function rejectJustBashNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void> {- if (policy !== "allow-all") throw new Error(JUST_BASH_NETWORK_POLICY_MESSAGE);+/** Gives a just-bash connection the `setNetworkPolicy` the other providers have. */+function withNetworkPolicy(connection: SandboxConnection<object>) {+ const extensions: object = connection.extensions ?? {};+ if (typeof Reflect.get(extensions, "setNetworkPolicy") === "function") {+ return connection as SandboxConnection<NetworkPolicyExtensions>;+ }+ return {+ ...connection,+ extensions: { ...extensions, setNetworkPolicy: rejectJustBashNetworkPolicy },+ } as SandboxConnection<NetworkPolicyExtensions>;}-function hasNetworkPolicy(session: SandboxSession): session is DefaultSandboxSession {- return typeof Reflect.get(session, "setNetworkPolicy") === "function";+async function rejectJustBashNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void> {+ if (policy !== "allow-all") throw new Error(JUST_BASH_NETWORK_POLICY_MESSAGE);}function isSelectedProvider(value: unknown): value is SelectedProvider {@@ -266,10 +248,10 @@ function isSelectedProvider(value: unknown): value is SelectedProvider {}function isDefaultSandboxSessionState(- value: SandboxPreparedArtifact | null,+ value: SandboxJson | null,): value is DefaultSandboxSessionState {return (- isSandboxPreparedArtifactRecord(value) &&+ isObject(value) &&isSelectedProvider(value.provider) &&typeof value.stateProtocolVersion === "number" &&"state" in value@@ -277,10 +259,10 @@ function isDefaultSandboxSessionState(}function isDefaultSandboxPreparedArtifact(- value: SandboxPreparedArtifact | undefined,+ value: SandboxJson | undefined,): value is DefaultSandboxPreparedArtifact {return (- isSandboxPreparedArtifactRecord(value) &&+ isObject(value) &&(value.provider === null || (isSelectedProvider(value.provider) && "artifact" in value)));}diff --git a/packages/eve/src/sandbox/providers/just-bash.ts b/packages/eve/src/sandbox/providers/just-bash.tsindex e017a8914..2e46921bf 100644--- a/packages/eve/src/sandbox/providers/just-bash.ts+++ b/packages/eve/src/sandbox/providers/just-bash.ts@@ -1,7 +1,7 @@import { createJustBashSandboxProvider } from "#execution/sandbox/bindings/local.js";import type { JustBashSandboxCreateOptions } from "#public/sandbox/just-bash-sandbox.js";import { defineSandboxProvider, type WithPrepareOption } from "#public/sandbox/provider.js";-import type { SandboxSession } from "#shared/sandbox-session.js";+import type { SandboxSession } from "#public/sandbox/index.js";export type JustBashEnvironmentOptions = WithPrepareOption<JustBashSandboxCreateOptions,diff --git a/packages/eve/src/sandbox/state.ts b/packages/eve/src/sandbox/state.tsindex 94ae88985..fb5a7eb78 100644--- a/packages/eve/src/sandbox/state.ts+++ b/packages/eve/src/sandbox/state.ts@@ -1,11 +1,7 @@import type { SandboxSession } from "#public/definitions/sandbox.js";+import type { SandboxProviderRuntime, SandboxSessionContext } from "#sandbox/provider.js";import type { SandboxEnvironmentIdentity } from "#shared/sandbox-environment.js";-import type {- SandboxDeleteOptions,- SandboxPreparedArtifact,- SandboxProviderRuntime,- SandboxProviderSessionContext,-} from "#shared/sandbox-provider.js";+import type { SandboxDeleteOptions, SandboxPreparedArtifact } from "#shared/sandbox-provider.js";export type SandboxSessionEndReason = "completed" | "expired" | "failed";@@ -81,8 +77,8 @@ export function resolvePersistedSandboxSessionState(}/** Session-end cleanup that also needs the current build's prepared artifact. */-export type SandboxSessionEndWithArtifact = (- context: SandboxProviderSessionContext,+type SandboxSessionEndWithArtifact = (+ context: SandboxSessionContext,state: SandboxPreparedArtifact | null,options: {readonly artifact: SandboxPreparedArtifact | undefined;diff --git a/packages/eve/src/self-modification/deployed-sandbox.test.ts b/packages/eve/src/self-modification/deployed-sandbox.test.tsindex 16f803eb6..a6d480547 100644--- a/packages/eve/src/self-modification/deployed-sandbox.test.ts+++ b/packages/eve/src/self-modification/deployed-sandbox.test.ts@@ -5,10 +5,7 @@ import {getSandboxEnvironmentRuntime,type SandboxSelectorContext,} from "#shared/sandbox-environment.js";-import {- createSandboxProviderResources,- type SandboxProviderPrepareContext,-} from "#shared/sandbox-provider.js";+import { createSandboxPrepareContext } from "#execution/sandbox/prewarm.js";import type { DeployedSelfModificationConfig } from "./remote/config.js";import { defineDeployedSelfModificationSandbox } from "./deployed-sandbox.js";@@ -32,12 +29,17 @@ describe("deployed self-modification sandbox", () => {);expect(environment?.provider).toBe("vercel");- const prepareContext = {- resources: createSandboxProviderResources({}),- } as SandboxProviderPrepareContext;- await expect(- getSandboxEnvironmentRuntime(environment!).implementation.prepare(prepareContext),- ).resolves.toEqual({});+ const runtime = getSandboxEnvironmentRuntime(environment!);+ const prepareContext = createSandboxPrepareContext({+ appRoot: "/app",+ files: { list: async () => [], read: vi.fn(), readText: vi.fn() },+ log: () => {},+ provider: runtime,+ resources: {},+ sourceRevision: "revision",+ storagePath: "/app/.eve/sandbox",+ });+ await expect(runtime.implementation.prepare(prepareContext)).resolves.toEqual({});expect(isDeployedOnVercel).not.toHaveBeenCalled();});diff --git a/packages/eve/src/shared/sandbox-environment.ts b/packages/eve/src/shared/sandbox-environment.tsindex 1391ff0b7..0b173873a 100644--- a/packages/eve/src/shared/sandbox-environment.ts+++ b/packages/eve/src/shared/sandbox-environment.ts@@ -1,8 +1,6 @@-import { createHash } from "node:crypto";-import { ContextContainer, contextStorage, type AlsContext } from "#context/container.js";import type { SessionAuth, SessionParent, SessionTurn } from "#context/keys.js";-import type { SandboxProviderRuntime } from "#shared/sandbox-provider.js";+import type { SandboxProviderRuntime } from "#sandbox/provider.js";import type {RuntimeSandboxSession,RuntimeSandboxSessionFor,@@ -11,7 +9,6 @@ import type {const ENVIRONMENT = Symbol.for("eve.sandbox-environment");const PROVIDER_RUNTIME = Symbol.for("eve.sandbox-provider-runtime");-const CONFIGURATION_HASH = Symbol.for("eve.sandbox-environment-configuration-hash");const SELECTOR_ENVIRONMENT = Symbol.for("eve.sandbox-selector-environment");export interface SandboxSelectorContext {@@ -34,9 +31,9 @@ export type SandboxOpenArguments<Options> = Options extends undefined: [options: Options];export interface SandboxEnvironmentIdentity {- readonly [CONFIGURATION_HASH]: string;readonly [ENVIRONMENT]: true;- readonly [PROVIDER_RUNTIME]: SandboxProviderRuntime;+ /** A {@link SandboxProviderRuntime}, opaque so the public type does not carry core internals. */+ readonly [PROVIDER_RUNTIME]: unknown;readonly provider: string;}@@ -49,9 +46,7 @@ export interface SandboxEnvironment<interface ConstructorRuntime {open(input: {- readonly configurationHash: string;readonly environment: object;- readonly environmentConfigurationHash: string;readonly options: object | undefined;readonly provider: SandboxProviderRuntime;}): Promise<RuntimeSandboxSession>;@@ -66,76 +61,35 @@ const runtimes = (globals[RUNTIMES] ??= new WeakMap<AlsContext, ConstructorRuntiexport function createSandboxEnvironment<Options extends object | undefined = object,Session extends SandboxSession = SandboxSession,->(input: {- readonly configuration?: unknown;- readonly runtime: SandboxProviderRuntime;-}): SandboxEnvironment<Options, Session> {- let environment: SandboxEnvironment<Options, Session>;-- environment = {- [CONFIGURATION_HASH]: hashConstructorOptions({ environment: input.configuration, sandbox: {} }),+>(runtime: SandboxProviderRuntime): SandboxEnvironment<Options, Session> {+ const environment: SandboxEnvironment<Options, Session> = {[ENVIRONMENT]: true,- [PROVIDER_RUNTIME]: input.runtime,- provider: input.runtime.providerName,+ [PROVIDER_RUNTIME]: runtime,+ provider: runtime.providerName,async open(...args: SandboxOpenArguments<Options>) {const options = args[0] as object | undefined;const context = contextStorage.getStore();- const runtime = context === undefined ? undefined : runtimes.get(context);- if (runtime === undefined) {+ const opener = context === undefined ? undefined : runtimes.get(context);+ if (opener === undefined) {throw new Error("Sandbox environments can only open sandboxes inside defineSandbox(). " +"Use `ctx.getSandbox()` to reach the session's sandbox from tools and other runtime code.",);}- return (await runtime.open({- configurationHash: hashConstructorOptions({- environment: input.configuration,- sandbox: options,- }),+ return (await opener.open({environment,- environmentConfigurationHash: environment[CONFIGURATION_HASH],options,- provider: input.runtime,+ provider: runtime,})) as RuntimeSandboxSessionFor<Session>;},};return environment;}-function hashConstructorOptions(options: unknown): string {- return createHash("sha256").update(stableSerialize(options)).digest("hex");-}--function stableSerialize(value: unknown, seen = new WeakSet<object>()): string {- if (- value === null ||- typeof value === "boolean" ||- typeof value === "number" ||- typeof value === "string"- ) {- return JSON.stringify(value);- }- if (typeof value === "function") return `function:${value.toString()}`;- if (Array.isArray(value))- return `[${value.map((entry) => stableSerialize(entry, seen)).join(",")}]`;- if (typeof value === "object") {- if (seen.has(value)) return "[circular]";- seen.add(value);- const constructorName = value.constructor?.name ?? "Object";- const serialized = `{${Object.entries(value)- .sort(([left], [right]) => left.localeCompare(right))- .map(([key, entry]) => `${JSON.stringify(key)}:${stableSerialize(entry, seen)}`)- .join(",")}}`;- seen.delete(value);- return `${constructorName}:${serialized}`;- }- return typeof value;-}-export function getSandboxEnvironmentRuntime(environment: SandboxEnvironmentIdentity,): SandboxProviderRuntime {- return environment[PROVIDER_RUNTIME];+ return environment[PROVIDER_RUNTIME] as SandboxProviderRuntime;}export function bindSandboxEnvironment(diff --git a/packages/eve/src/shared/sandbox-provider.test.ts b/packages/eve/src/shared/sandbox-provider.test.tsdeleted file mode 100644index ca902aad3..000000000--- a/packages/eve/src/shared/sandbox-provider.test.ts+++ /dev/null@@ -1,79 +0,0 @@-import { describe, expect, expectTypeOf, it, vi } from "vitest";--import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";-import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";--const provider = defineLegacySandboxProvider<- { readonly image?: string },- { readonly networkPolicy?: "allow-all" | "deny-all" },- { readonly templateId: string },- { readonly nativeId: string; readonly version: 1 }->({- name: "test-provider",- stateProtocolVersion: 4,- environment: (environmentOptions) => ({- async onSessionEnd() {},- async prepare() {- return { templateId: environmentOptions?.image ?? "default" };- },- async resume(_context, _artifact, state) {- return handle(state.nativeId);- },- async start(context) {- const nativeId = `native-${context.session.id}`;- return { handle: handle(nativeId), state: { nativeId, version: 1 } };- },- }),-});--function handle(nativeId: string) {- return {- sandbox: {- resolvePath: (path: string) => path,- run: vi.fn(),- spawn: vi.fn(),- readFile: vi.fn(),- readBinaryFile: vi.fn(),- readTextFile: vi.fn(),- writeFile: vi.fn(),- writeBinaryFile: vi.fn(),- writeFiles: vi.fn(),- writeTextFile: vi.fn(),- removePath: vi.fn(),- },- onRuntimeShutdown: vi.fn(async () => {}),- onSandboxDelete: vi.fn(async () => {}),- onSandboxStop: vi.fn(async () => {}),- nativeId,- };-}--describe("defineLegacySandboxProvider", () => {- it("preserves provider-owned environment and open option types", () => {- const environment = provider.environment({ image: "node:24" });- expect(environment.provider).toBe("test-provider");- expect(getSandboxEnvironmentRuntime(environment).stateProtocolVersion).toBe(4);- expectTypeOf(environment.open).parameter(0).toEqualTypeOf<- | {- readonly networkPolicy?: "allow-all" | "deny-all";- }- | undefined- >();- });-- it("stores one direct implementation without extracting provider options", async () => {- const environment = provider.environment({ image: "node:24" });- const implementation = getSandboxEnvironmentRuntime(environment).implementation;- const artifact = await implementation.prepare({- files: { list: async () => [], read: async () => new Uint8Array(), readText: async () => "" },- host: {- loadOptionalPackage: async ({ importModule }) => await importModule(),- resolveProjectPath: (path) => path,- },- resources: { source: { kind: "none" } },- sourceRevision: "test-source-revision",- storagePath: "/tmp/test",- });- expect(artifact).toEqual({ templateId: "node:24" });- });-});diff --git a/packages/eve/src/shared/sandbox-provider.ts b/packages/eve/src/shared/sandbox-provider.tsindex 6ffccf9e1..9326c72fb 100644--- a/packages/eve/src/shared/sandbox-provider.ts+++ b/packages/eve/src/shared/sandbox-provider.ts@@ -1,10 +1,3 @@-import {- createSandboxEnvironment,- type SandboxEnvironment,- type SandboxSelectorContext,-} from "#shared/sandbox-environment.js";-import type { SandboxSession } from "#shared/sandbox-session.js";-export interface SandboxDeleteOptions {readonly abortSignal?: AbortSignal;}@@ -14,49 +7,6 @@ export interface SandboxProviderResourceFile {readonly relativePath: string;}-export interface SandboxProviderResourceTree {- readonly files: readonly SandboxProviderResourceFile[];- readonly key: string;- readonly mountPath: string;- readonly targetPath: string;-}--export type SandboxProviderResourceSource =- | { readonly kind: "none" }- | { readonly key: string; readonly kind: "inline" }- | { readonly key: string; readonly kind: "materialized"; readonly path: string };--export interface SandboxProviderResources {- readonly skills?: SandboxProviderResourceTree;- readonly source: SandboxProviderResourceSource;- readonly workspace?: SandboxProviderResourceTree;-}--export function sandboxProviderResourceIdentity(resources: SandboxProviderResources): object {- return {- skills: resources.skills?.key,- workspace: resources.workspace?.key,- };-}--export interface SandboxProviderTargetFile {- readonly content: string | Uint8Array;- readonly path: string;-}--export function providerResourceTargetFiles(- resources: SandboxProviderResources,-): SandboxProviderTargetFile[] {- return [resources.workspace, resources.skills].flatMap((resource) =>- resource === undefined- ? []- : resource.files.map((file) => ({- content: file.content,- path: `${resource.targetPath}/${file.relativePath}`,- })),- );-}-export type SandboxPreparedArtifact =| null| boolean@@ -82,203 +32,8 @@ export function isSandboxPreparedArtifact(value: unknown): value is SandboxPrepa);}-export function isSandboxPreparedArtifactRecord(- artifact: unknown,-): artifact is { readonly [key: string]: SandboxPreparedArtifact } {- return typeof artifact === "object" && artifact !== null && !Array.isArray(artifact);-}-export interface SandboxProviderFiles {list(): Promise<readonly string[]>;read(path: string): Promise<Uint8Array>;readText(path: string): Promise<string>;}--export interface SandboxProviderHost {- loadOptionalPackage<T>(input: {- readonly autoInstall: boolean;- readonly importModule: () => Promise<T>;- readonly installPackageName?: string;- readonly ignoredOptionalDependencies?: readonly string[];- readonly missingMessage: string;- readonly packageName: string;- }): Promise<T>;- resolveProjectPath(path: string): string;-}--export interface SandboxProviderPrepareContext {- readonly files: SandboxProviderFiles;- readonly host: SandboxProviderHost;- readonly log?: (message: string) => void;- readonly resources: SandboxProviderResources;- readonly sourceRevision: string;- readonly storagePath: string;-}--export interface SandboxProviderSessionContext {- readonly host: SandboxProviderHost;- readonly session: SandboxSelectorContext["session"];- readonly storagePath: string;-}--export interface SandboxProviderHandle<Session extends SandboxSession = SandboxSession> {- readonly sandbox: Session;- onRuntimeShutdown(): Promise<void>;- onSandboxDelete(options?: SandboxDeleteOptions): Promise<void>;- onSandboxStop(): Promise<void>;-}--export interface LegacySandboxProviderImplementation<- OpenOptions extends object | undefined,- PreparedArtifact extends SandboxPreparedArtifact,- SessionState,- Session extends SandboxSession = SandboxSession,-> {- /**- * Permanently deletes the sandbox for `context.session.id` after the session's terminal- * outcome. `state` is what `start()` returned when the session recorded it, or `null` when- * the session never did, for example because a subagent that shares the sandbox opened it.- * Find the sandbox from the key when `state` is `null`. Must succeed when no sandbox exists- * and be idempotent, because the cleanup step may retry.- */- onSessionEnd(- context: SandboxProviderSessionContext,- state: Readonly<SessionState> | null,- options: { readonly reason: "completed" | "expired" | "failed" },- ): Promise<void>;- prepare(context: SandboxProviderPrepareContext): Promise<PreparedArtifact>;- resume(- context: SandboxProviderSessionContext,- artifact: Readonly<PreparedArtifact>,- state: Readonly<SessionState>,- ): Promise<SandboxProviderHandle<Session>>;- /**- * Returns the live sandbox for `context.session.id`, creating it when none exists. This- * must be an idempotent upsert on that key: repeated and concurrent calls, from any process- * or deployment, return the same sandbox while it exists. Derive the sandbox's identity- * from the key and a provider-level namespace only, never from `options` or `artifact`,- * which apply only when this call creates the sandbox.- */- start(- context: SandboxProviderSessionContext,- options: Readonly<OpenOptions> | undefined,- artifact: Readonly<PreparedArtifact>,- ): Promise<{ readonly handle: SandboxProviderHandle<Session>; readonly state: SessionState }>;-}--type SandboxOptionArguments<Options extends object | undefined> = Options extends undefined- ? [options?: undefined]- : Record<never, never> extends Options- ? [options?: Readonly<Options>]- : [options: Readonly<Options>];--export type LegacySandboxProviderDefinition<- EnvironmentOptions extends object | undefined,- OpenOptions extends object | undefined,- PreparedArtifact extends SandboxPreparedArtifact,- SessionState,- Session extends SandboxSession,-> = {- readonly name: string;- readonly stateProtocolVersion?: number;- environment(- ...args: SandboxOptionArguments<EnvironmentOptions>- ): LegacySandboxProviderImplementation<OpenOptions, PreparedArtifact, SessionState, Session>;-};--export interface SandboxProvider<- EnvironmentOptions extends object | undefined,- OpenOptions extends object | undefined,- Session extends SandboxSession,-> {- readonly name: string;- environment(- ...args: SandboxOptionArguments<EnvironmentOptions>- ): SandboxEnvironment<OpenOptions, Session>;-}--type ErasedSandboxProviderImplementation = LegacySandboxProviderImplementation<- object | undefined,- SandboxPreparedArtifact,- SandboxPreparedArtifact,- SandboxSession->;--export interface SandboxProviderRuntime {- readonly implementation: ErasedSandboxProviderImplementation;- readonly providerName: string;- readonly stateProtocolVersion: number;-}--/**- * Defines a provider on the handle-based contract that eve's built-in- * providers still implement and core runs. Internal: the public- * `defineSandboxProvider()` in `#sandbox/provider.js` compiles the- * connection-based contract onto it until every built-in migrates.- */-export function defineLegacySandboxProvider<- EnvironmentOptions extends object | undefined = undefined,- OpenOptions extends object | undefined = undefined,- PreparedArtifact extends SandboxPreparedArtifact = SandboxPreparedArtifact,- SessionState = SandboxPreparedArtifact,- Session extends SandboxSession = SandboxSession,->(- definition: LegacySandboxProviderDefinition<- EnvironmentOptions,- OpenOptions,- PreparedArtifact,- SessionState,- Session- >,-): SandboxProvider<EnvironmentOptions, OpenOptions, Session> {- const stateProtocolVersion = definition.stateProtocolVersion ?? 1;- return {- name: definition.name,- environment(...args: SandboxOptionArguments<EnvironmentOptions>) {- return createSandboxEnvironment<OpenOptions, Session>({- configuration: args[0],- runtime: {- implementation: eraseSandboxProviderImplementation(definition.environment(...args)),- providerName: definition.name,- stateProtocolVersion,- },- });- },- };-}--function eraseSandboxProviderImplementation<- Options extends object | undefined,- Artifact extends SandboxPreparedArtifact,- SessionState,- Session extends SandboxSession,->(- implementation: LegacySandboxProviderImplementation<Options, Artifact, SessionState, Session>,-): ErasedSandboxProviderImplementation {- return implementation as ErasedSandboxProviderImplementation;-}--export function createSandboxProviderResources(input: {- readonly key?: string;- readonly path?: string;- readonly skills?: readonly SandboxProviderResourceFile[];- readonly workspace?: readonly SandboxProviderResourceFile[];-}): SandboxProviderResources {- const { key, path } = input;- if (key === undefined) return { source: { kind: "none" } };- return {- skills: {- files: input.skills ?? [],- key: `${key}:skills`,- mountPath: "/eve/resources/skills",- targetPath: "$HOME/.agents/skills",- },- source: path === undefined ? { key, kind: "inline" } : { key, kind: "materialized", path },- workspace: {- files: input.workspace ?? [],- key: `${key}:workspace`,- mountPath: "/eve/resources/workspace",- targetPath: "/workspace",- },- };-}diff --git a/packages/eve/src/shared/sandbox-session.ts b/packages/eve/src/shared/sandbox-session.tsindex 624134b7b..2b60f63a0 100644--- a/packages/eve/src/shared/sandbox-session.ts+++ b/packages/eve/src/shared/sandbox-session.ts@@ -9,7 +9,7 @@ export interface SandboxRunOptions {readonly abortSignal?: AbortSignal;readonly command: string;readonly env?: Readonly<Record<string, string>>;- /** Relative directories resolve from `/workspace`, which is also the default. */+ /** Relative directories resolve from the workspace root, which is also the default. */readonly workingDirectory?: string;}@@ -89,7 +89,7 @@ export interface SandboxWriteFilesOptions {/*** Options for removing a path from a sandbox.*- * Relative paths resolve from `/workspace`; absolute paths pass through.+ * Relative paths resolve from the workspace root; absolute paths pass through.* `force` ignores missing paths. `recursive` permits removing non-empty* directories.*/@@ -103,10 +103,10 @@ export interface SandboxRemovePathOptions {/*** The sandbox session that authored tools, hooks, and `prepare` receive.*- * Relative paths resolve from `/workspace`, the live working directory for- * every provider. Absolute paths pass through unchanged. Writes create- * missing parent directories and overwrite existing files. Reads resolve to- * `null` only when the path does not exist.+ * Relative paths resolve from the workspace root, where commands start by+ * default: `/workspace` on every built-in provider. Absolute paths pass+ * through unchanged. Writes create missing parent directories and overwrite+ * existing files. Reads resolve to `null` only when the path does not exist.** The method set stays assignable to the AI SDK's* `Experimental_SandboxSession`, apart from its `description`.@@ -126,8 +126,9 @@ export interface SandboxSession {*/writeFiles(options: SandboxWriteFilesOptions): Promise<void>;/**- * Anchors a sandbox-relative path to `/workspace` and returns the- * resulting absolute path. The read and write methods already apply it.+ * Anchors a sandbox-relative path to the workspace root and returns the+ * resulting absolute path, so `resolvePath(".")` is the root itself. The+ * read and write methods already apply it.*/resolvePath(path: string): string;/** Removes one file or directory from the sandbox filesystem. */@@ -147,23 +148,3 @@ export interface RuntimeSandboxSession extends SandboxSession {export type RuntimeSandboxSessionFor<Session extends SandboxSession> = Session &Pick<RuntimeSandboxSession, "delete" | "stop">;--/**- * Byte-level primitives a built-in provider implements; `buildSandboxSession`- * derives the public {@link SandboxSession} from them. Paths are already- * resolved.- */-export interface InternalSandboxSession {- readFile(options: SandboxReadFileOptions): Promise<ReadableStream<Uint8Array> | null>;- /** Removes an already-resolved path from the provider filesystem. */- removePath(options: SandboxRemovePathOptions): Promise<void>;- /** Translates a user-facing path to the provider's native path. */- resolvePath(path: string): string;- spawn(options: SandboxSpawnOptions): Promise<SandboxProcess>;- writeFile(options: SandboxWriteFileOptions): Promise<void>;- /**- * Writes several already-resolved files in one provider call. Providers that- * omit it get one `writeFile` per file.- */- writeFiles?(options: SandboxWriteFilesOptions): Promise<void>;-}diff --git a/packages/eve/src/shared/sandbox-tool-session-error.ts b/packages/eve/src/shared/sandbox-tool-session-error.tsnew file mode 100644index 000000000..15383ecf3--- /dev/null+++ b/packages/eve/src/shared/sandbox-tool-session-error.ts@@ -0,0 +1,11 @@+/** Raised when a keyed tool session opens a sandbox on a provider that cannot keep it. */+export class ToolSessionSandboxUnsupportedError extends Error {+ constructor(providerName: string) {+ super(+ `Sandbox provider "${providerName}" cannot keep a sandbox between invokeTool calls, ` ++ "so a call with a key cannot open one. Call without a key for a sandbox that lasts " ++ "one call, or use Vercel Sandbox, just-bash, or a custom provider that sets `toolSessions: true`.",+ );+ this.name = "ToolSessionSandboxUnsupportedError";+ }+}diff --git a/packages/eve/src/shared/skill-paths.test.ts b/packages/eve/src/shared/skill-paths.test.tsindex 956c437db..0961c7c56 100644--- a/packages/eve/src/shared/skill-paths.test.ts+++ b/packages/eve/src/shared/skill-paths.test.ts@@ -1,8 +1,9 @@+import { posix } from "node:path";+import { describe, expect, it } from "vitest";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import {- FALLBACK_SKILL_ROOT,MODEL_SKILL_ROOT,resolveSandboxModelPath,resolveSandboxSkillRoot,@@ -55,22 +56,21 @@ describe("skill path helpers", () => {expect(sandbox.commandLog).toEqual([]);});- it("falls back to /workspace/skills when HOME is unusable", async () => {- const sandbox = mockSandbox({+ it("falls back to skills/ under the workspace root when HOME is unusable", async () => {+ const { session } = mockSandbox({commands: {[HOME_PROBE_COMMAND]: { exitCode: 0, stderr: "", stdout: "\n" },},});+ const sandbox = { ...session, resolvePath: (path: string) => posix.resolve("/srv/app", path) };- await expect(resolveSandboxSkillRoot({ sandbox: sandbox.session })).resolves.toBe(- FALLBACK_SKILL_ROOT,- );+ await expect(resolveSandboxSkillRoot({ sandbox })).resolves.toBe("/srv/app/skills");await expect(resolveSandboxModelPath({path: `${MODEL_SKILL_ROOT}/research/references/catalog.md`,- sandbox: sandbox.session,+ sandbox,}),- ).resolves.toBe("/workspace/skills/research/references/catalog.md");+ ).resolves.toBe("/srv/app/skills/research/references/catalog.md");});it("resolves model-facing seed paths before writing to the sandbox", async () => {diff --git a/packages/eve/src/shared/skill-paths.ts b/packages/eve/src/shared/skill-paths.tsindex 46dc386dd..54cdbc82b 100644--- a/packages/eve/src/shared/skill-paths.ts+++ b/packages/eve/src/shared/skill-paths.ts@@ -3,14 +3,13 @@ import type { SandboxSession } from "#shared/sandbox-session.js";const MODEL_HOME_ROOT = "$HOME";export const MODEL_SKILL_ROOT = `${MODEL_HOME_ROOT}/.agents/skills`;-export const FALLBACK_SKILL_ROOT = "/workspace/skills";const HOME_PROBE_COMMAND = `printf '%s\\n' "$HOME"`;const sandboxHomeCache = new WeakMap<SandboxSession, Promise<string | null>>();/*** Resolves where skills live in the sandbox: under the probed home when it has- * one, and under {@link FALLBACK_SKILL_ROOT} when it does not.+ * one, and under `skills/` in the workspace root when it does not.*/export async function resolveSandboxSkillRoot(input: {readonly sandbox: SandboxSession;@@ -20,9 +19,9 @@ export async function resolveSandboxSkillRoot(input: {/*** Resolves a leading `$HOME` in a model-supplied sandbox path without- * evaluating any other shell syntax. Skill paths retain their documented- * `/workspace/skills` fallback when the sandbox does not expose a usable- * home directory.+ * evaluating any other shell syntax. Skill paths fall back to `skills/` in+ * the workspace root when the sandbox does not expose a usable home+ * directory.*/export async function resolveSandboxModelPath(input: {readonly path: string;@@ -39,7 +38,7 @@ export async function resolveSandboxModelPath(input: {}if (isModelSkillPath(input.path)) {- return `${FALLBACK_SKILL_ROOT}${input.path.slice(MODEL_SKILL_ROOT.length)}`;+ return input.sandbox.resolvePath(`skills${input.path.slice(MODEL_SKILL_ROOT.length)}`);}return input.path;diff --git a/packages/eve/src/tools/provided/glob.ts b/packages/eve/src/tools/provided/glob.tsindex d9048ef71..4a5811519 100644--- a/packages/eve/src/tools/provided/glob.ts+++ b/packages/eve/src/tools/provided/glob.ts@@ -31,8 +31,8 @@ export const GLOB_INPUT_SCHEMA = defineJsonSchema<GlobToolInput>({path: {type: "string",description:- "The directory to search in. Defaults to /workspace. " +- "Must be an absolute path or begin with $HOME/. Omit to use the default.",+ "The directory to search in: absolute, relative to the workspace root, or beginning with $HOME/. " ++ "Omit to search the workspace root.",},pattern: {type: "string",diff --git a/packages/eve/src/tools/provided/grep.ts b/packages/eve/src/tools/provided/grep.tsindex a0fbb0aca..3fc3603ee 100644--- a/packages/eve/src/tools/provided/grep.ts+++ b/packages/eve/src/tools/provided/grep.ts@@ -54,8 +54,8 @@ export const GREP_INPUT_SCHEMA = defineJsonSchema<GrepToolInput>({path: {type: "string",description:- "The directory or file to search in. Defaults to /workspace. " +- "Must be an absolute path or begin with $HOME/. Omit to use the default.",+ "The directory or file to search in: absolute, relative to the workspace root, or beginning with $HOME/. " ++ "Omit to search the workspace root.",},pattern: {type: "string",diff --git a/packages/eve/src/tools/provided/read-file.ts b/packages/eve/src/tools/provided/read-file.tsindex a4ee2dbcc..99fb3ff27 100644--- a/packages/eve/src/tools/provided/read-file.ts+++ b/packages/eve/src/tools/provided/read-file.ts@@ -39,7 +39,8 @@ export const READ_FILE_INPUT_SCHEMA = defineJsonSchema<ReadFileToolInput>({properties: {filePath: {type: "string",- description: "The absolute path to the file to read. A leading $HOME is supported.",+ description:+ "The path to the file to read: absolute, relative to the workspace root, or beginning with $HOME/.",},limit: {type: "integer",@@ -94,7 +95,7 @@ export const readFile: ToolDefinition<ReadFileToolInput, ReadFileToolOutput> = f"Read a file from the local filesystem. If the path does not exist, an error is returned.","","Usage:",- "- The filePath parameter should be an absolute path or begin with $HOME/.",+ "- The filePath parameter is an absolute path, a path relative to the workspace root (where `bash` commands start), or a path beginning with $HOME/.","- By default, this tool returns up to 2000 lines from the start of the file.","- The offset parameter is the line number to start from (1-indexed).","- To read later sections, call this tool again with a larger offset.",diff --git a/packages/eve/src/tools/provided/write-file.ts b/packages/eve/src/tools/provided/write-file.tsindex c8cc794a5..fb3758c58 100644--- a/packages/eve/src/tools/provided/write-file.ts+++ b/packages/eve/src/tools/provided/write-file.ts@@ -22,7 +22,8 @@ export const WRITE_FILE_INPUT_SCHEMA = defineJsonSchema<WriteFileToolInput>({content: { type: "string", description: "Complete replacement file contents." },filePath: {type: "string",- description: "The absolute path to the file to write. A leading $HOME is supported.",+ description:+ "The path to the file to write: absolute, relative to the workspace root, or beginning with $HOME/.",},},required: ["content", "filePath"],diff --git a/packages/eve/test/glob-tool.test.ts b/packages/eve/test/glob-tool.test.tsindex c973559a3..b2ce5f1f8 100644--- a/packages/eve/test/glob-tool.test.ts+++ b/packages/eve/test/glob-tool.test.ts@@ -1,3 +1,5 @@+import { posix } from "node:path";+import { describe, expect, it } from "vitest";import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";@@ -13,7 +15,6 @@ import type { SandboxSession } from "../src/shared/sandbox-session.js";// ---------------------------------------------------------------------------interface FakeAccessOptions {- readonly pathResolver?: (path: string) => string;/*** Exit code returned by the ripgrep capability probe that runs before* each glob call. Defaults to `0` (ripgrep is available) so tests@@ -26,7 +27,7 @@ interface FakeAccessOptions {const PROBE_COMMAND ="command -v rg >/dev/null 2>&1 || exit 127; " +"rg --line-number --color=never --hidden --glob '!.git/*' --max-count 1 -- " +- "'__eve_ripgrep_probe_never_matches__' /workspace";+ "'__eve_ripgrep_probe_never_matches__' /dev/null";const HOME_PROBE_COMMAND = `printf '%s\\n' "$HOME"`;function createFakeAccess(@@ -58,7 +59,7 @@ function createFakeAccess(async setNetworkPolicy() {},async removePath() {},resolvePath(path: string) {- return options.pathResolver ? options.pathResolver(path) : path;+ return posix.resolve("/workspace", path);},async run({ command }: { command: string }) {if (command === HOME_PROBE_COMMAND) {@@ -102,7 +103,7 @@ describe("executeGlobOnSandbox", () => {// Default behavior// ---------------------------------------------------------------------------- it("uses /workspace as default path when path omitted", async () => {+ it("searches the workspace root when path is omitted", async () => {let capturedCommand = "";const result = (await runInContext((cmd) => {@@ -136,15 +137,6 @@ describe("executeGlobOnSandbox", () => {// Path validation// ---------------------------------------------------------------------------- it("rejects relative paths", async () => {- await expect(- runInContext(- () => ({ exitCode: 0, stderr: "", stdout: "" }),- (sandbox) => executeGlobOnSandbox(sandbox, { pattern: "*.ts", path: "src" }),- ),- ).rejects.toThrow("filePath must be an absolute path");- });-it("expands a leading $HOME before searching", async () => {let capturedCommand = "";const result = (await runInContext(diff --git a/packages/eve/test/grep-tool.test.ts b/packages/eve/test/grep-tool.test.tsindex ea6ff499a..6be39f83b 100644--- a/packages/eve/test/grep-tool.test.ts+++ b/packages/eve/test/grep-tool.test.ts@@ -1,3 +1,5 @@+import { posix } from "node:path";+import { describe, expect, it } from "vitest";import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";@@ -13,7 +15,6 @@ import type { SandboxSession } from "../src/shared/sandbox-session.js";// ---------------------------------------------------------------------------interface FakeAccessOptions {- readonly pathResolver?: (path: string) => string;/*** Exit code returned by the ripgrep capability probe that runs before* each grep call. Defaults to `0` (ripgrep is available) so the@@ -26,7 +27,7 @@ interface FakeAccessOptions {const PROBE_COMMAND ="command -v rg >/dev/null 2>&1 || exit 127; " +"rg --line-number --color=never --hidden --glob '!.git/*' --max-count 1 -- " +- "'__eve_ripgrep_probe_never_matches__' /workspace";+ "'__eve_ripgrep_probe_never_matches__' /dev/null";const HOME_PROBE_COMMAND = `printf '%s\\n' "$HOME"`;function createFakeAccess(@@ -58,7 +59,7 @@ function createFakeAccess(async setNetworkPolicy() {},async removePath() {},resolvePath(path: string) {- return options.pathResolver ? options.pathResolver(path) : path;+ return posix.resolve("/workspace", path);},async run({ command }: { command: string }) {if (command === HOME_PROBE_COMMAND) {@@ -102,7 +103,7 @@ describe("executeGrepOnSandbox", () => {// Default behavior// ---------------------------------------------------------------------------- it("uses /workspace as default path when path omitted", async () => {+ it("searches the workspace root when path is omitted", async () => {let capturedCommand = "";const result = (await runInContext((cmd) => {@@ -138,15 +139,6 @@ describe("executeGrepOnSandbox", () => {// Path validation// ---------------------------------------------------------------------------- it("rejects relative paths", async () => {- await expect(- runInContext(- () => ({ exitCode: 0, stderr: "", stdout: "" }),- (sandbox) => executeGrepOnSandbox(sandbox, { pattern: "foo", path: "src" }),- ),- ).rejects.toThrow("filePath must be an absolute path");- });-it("expands a leading $HOME before searching", async () => {let capturedCommand = "";const result = (await runInContext(diff --git a/packages/eve/test/read-file-tool.test.ts b/packages/eve/test/read-file-tool.test.tsindex 03c1f0117..c56e422dc 100644--- a/packages/eve/test/read-file-tool.test.ts+++ b/packages/eve/test/read-file-tool.test.ts@@ -1,3 +1,5 @@+import { posix } from "node:path";+import { describe, expect, it } from "vitest";import { stubSpawnProcess } from "./_helpers/sandbox-session-stub.js";@@ -42,7 +44,7 @@ function createFakeAccess(files: Record<string, string | null>): SandboxAccess {async setNetworkPolicy() {},async removePath() {},resolvePath(path: string) {- return path;+ return posix.resolve("/workspace", path);},async run({ command }: { command: string }) {if (command === HOME_PROBE_COMMAND) {@@ -233,12 +235,27 @@ describe("executeReadFileOnSandbox", () => {// Path validation// ---------------------------------------------------------------------------- it("rejects relative paths", async () => {+ it("resolves relative paths from the sandbox's workspace root", async () => {+ const result = (await runInContext({ "/srv/app/notes.md": "hello\n" }, (sandbox) =>+ executeReadFileOnSandbox(+ { ...sandbox, resolvePath: (path) => posix.resolve("/srv/app", path) },+ { filePath: "src/../notes.md" },+ ),+ )) as ReadFileResult;++ expect(result.path).toBe("/srv/app/notes.md");+ expect(result.content).toContain("1: hello");+ });++ it("rejects a $HOME path when the sandbox has no usable home", async () => {await expect(- runInContext({ "/workspace/foo.ts": "content" }, (sandbox) =>- executeReadFileOnSandbox(sandbox, { filePath: "foo.ts" }),+ runInContext({}, (sandbox) =>+ executeReadFileOnSandbox(+ { ...sandbox, run: async () => ({ exitCode: 0, stderr: "", stdout: "\n" }) },+ { filePath: "$HOME/notes.md" },+ ),),- ).rejects.toThrow("filePath must be an absolute path");+ ).rejects.toThrow('Cannot resolve "$HOME/notes.md": the sandbox has no usable $HOME.');});it("reads skill files through the model-facing $HOME path", async () => {@@ -306,7 +323,7 @@ describe("executeReadFileOnSandbox", () => {// ---------------------------------------------------------------------------it("canonicalizes paths with dot segments", async () => {- const access = createFakeAccess({ "/workspace/./foo.ts": "hello\n" });+ const access = createFakeAccess({ "/workspace/foo.ts": "hello\n" });const sandbox = (await access.get())!;const ctx = new ContextContainer();diff --git a/packages/eve/test/runtime-prompt-compose.test.ts b/packages/eve/test/runtime-prompt-compose.test.tsindex c88ffcfdf..9b459ddc3 100644--- a/packages/eve/test/runtime-prompt-compose.test.ts+++ b/packages/eve/test/runtime-prompt-compose.test.ts@@ -125,10 +125,9 @@ describe("composeRuntimeBasePrompt", () => {["Workspace","- You have access to authored files mounted at the workspace root for this run.",- "- The live workspace root visible to `bash` in this run is `/workspace`.",- "- Root entries under /workspace/:",+ "- The workspace root is the directory where `bash` commands start; `pwd` prints its absolute path.",+ "- Root entries under the workspace root:"," - skills/",- "- Treat `/workspace` as the workspace root for this run unless a `bash` call shows otherwise.","- For questions about workspace paths or file availability, verify with `bash` first using commands like `pwd`, `ls`, and `find`.","- If the required `bash` verification fails, report that failure directly instead of answering from this overview.","- Use the `bash` tool with `ls`, `find`, and `rg` to inspect deeper contents when needed.",@@ -151,10 +150,9 @@ describe("composeRuntimeBasePrompt", () => {["Workspace","- You have access to authored files mounted at the workspace root for this run.",- "- The live workspace root visible to `bash` in this run is `/workspace`.",- "- Root entries under /workspace/:",+ "- The workspace root is the directory where `bash` commands start; `pwd` prints its absolute path.",+ "- Root entries under the workspace root:"," - skills/",- "- Treat `/workspace` as the workspace root for this run unless a `bash` call shows otherwise.","- For questions about workspace paths or file availability, verify with `bash` first using commands like `pwd`, `ls`, and `find`.","- If the required `bash` verification fails, report that failure directly instead of answering from this overview.","- Use the `bash` tool with `ls`, `find`, and `rg` to inspect deeper contents when needed.",diff --git a/packages/eve/test/scenarios/eval-command-environment.scenario.test.ts b/packages/eve/test/scenarios/eval-command-environment.scenario.test.tsindex da13bcd90..18b8c6933 100644--- a/packages/eve/test/scenarios/eval-command-environment.scenario.test.ts+++ b/packages/eve/test/scenarios/eval-command-environment.scenario.test.ts@@ -8,9 +8,9 @@ import { defineEval } from "../../src/evals/define-eval.js";import { runCli } from "../../src/cli/run.js";import {- shutdownActiveSandboxHandles,- trackActiveSandboxHandle,-} from "../../src/execution/sandbox/active-handles.js";+ shutdownActiveSandboxConnections,+ trackActiveSandboxConnection,+} from "../../src/execution/sandbox/active-connections.js";import { useTemporaryDirectories } from "../../src/internal/testing/use-temporary-app-roots.js";const mockedEvalDependencies = vi.hoisted(() => ({@@ -100,7 +100,7 @@ afterEach(async () => {clearDevelopmentEnvironment();process.exitCode = undefined;vi.restoreAllMocks();- await shutdownActiveSandboxHandles();+ await shutdownActiveSandboxConnections();mockedEvalDependencies.createDevelopmentServer.mockReset();mockedEvalDependencies.discoverAndImportEvals.mockReset();mockedEvalDependencies.discoverEvalConfig.mockReset();@@ -360,7 +360,7 @@ describe("eve eval environment loading", () => {expect(exit).toHaveBeenCalledWith(0);});- it("shuts down tracked sandbox handles after a local eval run", async () => {+ it("shuts down tracked sandbox connections after a local eval run", async () => {const fixtureRoot = await createEnvironmentFixture();const previousCwd = process.cwd();const logger = {@@ -369,10 +369,10 @@ describe("eve eval environment loading", () => {};const exit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);const close = vi.fn(async () => {});- const handle = { onRuntimeShutdown: vi.fn(async () => {}) };+ const connection = { stop: vi.fn(async () => {}) };const evaluation = makeEvaluation("local");- trackActiveSandboxHandle({ providerName: "docker", handle, sessionId: "session-1" });+ trackActiveSandboxConnection({ providerName: "docker", connection, sessionId: "session-1" });process.chdir(fixtureRoot);mockedEvalDependencies.createDevelopmentServer.mockReturnValue({close,@@ -401,7 +401,7 @@ describe("eve eval environment loading", () => {}expect(close).toHaveBeenCalledTimes(1);- expect(handle.onRuntimeShutdown).toHaveBeenCalledTimes(1);+ expect(connection.stop).toHaveBeenCalledTimes(1);expect(process.env.EVE_EVALUATION).toBe("1");expect(process.env.EVE_EVALUATION_RUN_ID).toMatch(/^[0-9a-f-]{36}$/u);expect(exit).toHaveBeenCalledWith(0);diff --git a/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts b/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.tsindex 0a4e246eb..bb9137900 100644--- a/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts+++ b/packages/eve/test/scenarios/sandbox-workspace-folders.scenario.test.ts@@ -64,7 +64,7 @@ describe("sandbox workspace folder convention", () => {const roundTrip = await handle.sandbox.readTextFile({ path: "/workspace/authored.txt" });expect(roundTrip).toBe("round-trip");- await handle.onRuntimeShutdown();+ await handle.connection.stop();});it("opens an empty prewarmed template when the sandbox has no authored workspace files", async () => {@@ -89,7 +89,7 @@ describe("sandbox workspace folder convention", () => {expect(result.exitCode).toBe(0);expect(Number(result.stdout.trim())).toBe(0);- await handle.onRuntimeShutdown();+ await handle.connection.stop();});it("materializes a fixture default workspace folder into a deterministic file list", async () => {diff --git a/packages/eve/test/scenarios/vercel-build-prewarm.scenario.test.ts b/packages/eve/test/scenarios/vercel-build-prewarm.scenario.test.tsindex 6d0acf947..ae06df5b5 100644--- a/packages/eve/test/scenarios/vercel-build-prewarm.scenario.test.ts+++ b/packages/eve/test/scenarios/vercel-build-prewarm.scenario.test.ts@@ -6,7 +6,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { compileAgent } from "../../src/compiler/compile-agent.js";import { prewarmAppSandboxes } from "../../src/execution/sandbox/prewarm.js";import { runVercelBuildPrewarm } from "../../src/internal/nitro/host/vercel-build-prewarm.js";-import type { SandboxProviderPrepareContext } from "../../src/shared/sandbox-provider.js";+import { populatedPaths } from "../../src/internal/testing/sandbox-provider-harness.js";+import type { SandboxPrepareContext } from "../../src/sandbox/provider.js";import { useTemporaryDirectories } from "../../src/internal/testing/use-temporary-app-roots.js";const createScratchDirectory = useTemporaryDirectories();@@ -85,8 +86,8 @@ describe("Vercel build-time sandbox prewarm", () => {expect(events.seededTemplates).toEqual(["default", "default"]);expect([...events.writtenFilePaths].sort()).toEqual([- "$HOME/.agents/skills/research/SKILL.md",- "$HOME/.agents/skills/route-weather/SKILL.md",+ "/home/agent/.agents/skills/research/SKILL.md",+ "/home/agent/.agents/skills/route-weather/SKILL.md",]);});});@@ -181,19 +182,12 @@ function preparedSandboxSource(command: string): string {}function createRecordingDispatch(events: ReturnType<typeof createPrewarmEvents>) {- return async ({ context }: { context: SandboxProviderPrepareContext }) => {+ return async ({ context }: { context: SandboxPrepareContext }) => {events.templateKeys.push(context.storagePath);- const files = [- ...(context.resources.workspace?.files.map((file) => ({- path: `${context.resources.workspace?.targetPath}/${file.relativePath}`,- })) ?? []),- ...(context.resources.skills?.files.map((file) => ({- path: `${context.resources.skills?.targetPath}/${file.relativePath}`,- })) ?? []),- ];- if (files.length > 0) {+ const paths = await populatedPaths(context);+ if (paths.length > 0) {events.seededTemplates.push("default");- events.writtenFilePaths.push(...files.map((file) => file.path));+ events.writtenFilePaths.push(...paths);}return { storagePath: context.storagePath };diff --git a/packages/eve/test/write-file-tool.test.ts b/packages/eve/test/write-file-tool.test.tsindex fc3a30db7..9fd10434f 100644--- a/packages/eve/test/write-file-tool.test.ts+++ b/packages/eve/test/write-file-tool.test.ts@@ -289,23 +289,6 @@ describe("executeWriteFileOnSandbox", () => {// Path validation// ---------------------------------------------------------------------------- it("rejects relative paths", async () => {- const { access, session } = createFakeAccess({});-- const ctx = new ContextContainer();- ctx.set(SandboxKey, access);- ctx.set(ReadFileStateKey, { byTarget: {} });-- await expect(- contextStorage.run(ctx, () =>- executeWriteFileOnSandbox(session, {- filePath: "foo.ts",- content: "hello",- }),- ),- ).rejects.toThrow("filePath must be an absolute path");- });-it("shares read-before-write state with the resolved form of a $HOME path", async () => {const filePath = "/home/agent/.agents/skills/research/references/catalog.md";const { access, files, session } = createFakeAccess({ [filePath]: "original" });diff --git a/research/sandbox-provider-api.md b/research/sandbox-provider-api.mdindex b1f23bfb5..a7a89c653 100644--- a/research/sandbox-provider-api.md+++ b/research/sandbox-provider-api.md@@ -111,6 +111,8 @@ validator accepts. The Vercel provider type-checks it against```tsexport interface SandboxConnection<Extensions extends object = {}> {+ /** Absolute; relative paths resolve from it and commands start in it. Defaults to `/workspace`. */+ readonly workspaceRoot?: string;spawn(options: {readonly command: string;readonly workingDirectory: string;@@ -145,8 +147,9 @@ Each method has a fixed contract:before sending it, so a bytes-only primitive does not regress them.- Every path a connection receives is absolute, and `workingDirectory` isalways set. eve is the only owner of path resolution: relative paths and a- relative or missing `workingDirectory` resolve from `/workspace`, which every- built-in's `resolvePath` already does.+ relative or missing `workingDirectory` resolve from the connection's+ `workspaceRoot`, `/workspace` unless the connection declares another+ absolute directory. Every built-in keeps the default.eve derives the rest of `SandboxSession`: `run` over `spawn`, binary and textvariants, encodings and line ranges, single-file writes over `writeFiles`, path@@ -217,7 +220,7 @@ export interface SandboxPrepareContext {templateKey(identity: SandboxIdentity): string;/** A stable read-only host directory with `workspace/` and `skills/`, when one exists. */resourcesDirectory(): Promise<string | undefined>;- /** Seeds `/workspace` and `$HOME/.agents/skills`, then runs authored `prepare`. */+ /** Seeds the connection's workspace root and `$HOME/.agents/skills`, then runs authored `prepare`. */populate(connection: SandboxConnection<object>,options?: { readonly mountedAt?: string },@@ -267,7 +270,7 @@ reproducible.`populate()` writes the workspace and skill files through`connection.writeFiles()` in one batch. With `mountedAt`, the provider hasmounted `resourcesDirectory()` read-only at that sandbox path, and `populate()`-copies `<mountedAt>/workspace/.` into `/workspace` and `<mountedAt>/skills/.`+copies `<mountedAt>/workspace/.` into the workspace root and `<mountedAt>/skills/.`into `$HOME/.agents/skills` instead of writing them, as Docker does today.Either way, authored `prepare` runs next, with a logging session over the sameconnection.@@ -311,8 +314,8 @@ wiring, and Docker CLI and Vercel SDK glue stay internal.```textbuild (eve build, or first access in eve dev)eve ─ prepare(ctx) ─▶ provider: create build instance → connection- ctx.populate(connection) ─▶ eve: write /workspace and- $HOME/.agents/skills, then run authored prepare+ ctx.populate(connection) ─▶ eve: write the workspace root+ and $HOME/.agents/skills, then run authored prepareprovider: capture image or snapshot → artifact (JSON)eve: store artifact in sandbox-prepared-artifacts.json (ships with deployment)@@ -322,12 +325,16 @@ runtimeeve checkpoints { providerName, state, stateProtocolVersion }later step ─ resume(ctx, artifact, state) → connection└─ throws SandboxSessionGoneError → eve clears state, reruns selector+ step ends → connection.close?() (a turn's step, a "use step" function, or an+ invokeTool call; the next step resumes through a new connection)sandbox.stop() → connection.stop(), connection.close?()sandbox.delete() → connection.close?(), onSessionEnd(ctx, state, { reason: "deleted" }),eve clears state- process exit → connection.stop(), connection.close?() (failures logged, not thrown)- keyed call ends → connection.close?()- terminal outcome → connection.close?() for this process's connections,+ process exit → connection.stop(), connection.close?() on the connections the process+ still holds: any connection mid-step, and each session's latest+ connection without close() (failures logged, not thrown); a provider+ with close() and remote compute bounds idle compute itself+ terminal outcome → connection.close?() for a connection the ending step holds,onSessionEnd(ctx, state | null, { reason })(close runs at most once per connection; stop is idempotent and may run again afterthe connection resumes; a failed close never blocks deletion)@@ -364,8 +371,10 @@ runtimeTemplate retention and pruning stay with the provider.- **Seeding.** `populate()` writes workspace and skill files before authored`prepare`, and runs only at build time. Runtime never seeds.-- **Paths.** Relative paths and working directories resolve from `/workspace`;- eve resolves `$HOME` in skill targets. This changes one behavior: Vercel+- **Paths.** Relative paths and working directories resolve from the+ connection's workspace root; eve resolves `$HOME` in skill targets.+ `session.resolvePath(".")` returns the root, which is how the file tools,+ attachment staging, and GitHub checkouts find it. This changes one behavior: Vercelpasses a relative `workingDirectory` to the SDK unchanged today, while Dockerand just-bash already resolve it from `/workspace`. The Vercel migration PRstates this in its changeset.@@ -399,7 +408,7 @@ Docker mounts `await ctx.resourcesDirectory()` and calls`ctx.populate(connection, { mountedAt: "/eve/resources" })`. Vercel skipspreparation when `ctx.isEmpty` and no `source` is set, in`VercelSandbox.environment()` itself and therefore under `DefaultSandbox` too.-Vercel and just-bash set `toolSessions: true`; only just-bash needs `close()`.+Vercel and just-bash set `toolSessions: true`; no built-in needs `close()`.## Custom provider example@@ -532,8 +541,25 @@ the last step. There are no public dual-shape overloads.`#execution/tool-session/*`, `#runtime/sandbox/*`, or`#shared/sandbox-{provider,session,write-files}.js`). Engine helpers suchas other binding modules, stream utilities, and the optional-package loader- stay allowed.-6. Later: a host provider on the same contract.+ stay allowed. Implemented: `ensureSandboxAccess` runs the implementation and+ its connections directly, `createConnectionSession()` in+ `execution/sandbox/session.ts` derives every session, and `prewarm.ts`+ builds the prepare context. A workflow step, a turn's step, and a keyed or+ unkeyed `invokeTool` call close their connection when they end; after a+ turn's step, a connection without `close()` stays registered for server+ shutdown. `DefaultSandbox` is a `defineSandboxProvider()` selector over the+ three built-ins and keeps its two internal hooks: session end receives the+ prepared artifact, and records the picked provider wrote still resume. The+ guard is rule 44. The opaque provider runtime on `SandboxEnvironment` bumped+ six extension contract epochs, all retained.+6. Workspace-root paths. Implemented: `SandboxConnection.workspaceRoot`+ declares the root, defaulting to `/workspace`; eve rejects a relative one+ when it opens the connection. The built-in file tools accept paths+ relative to the root, `glob` and `grep` search it by default, and+ model-facing prompts no longer name `/workspace`, because they are+ composed before any sandbox opens. The skill root stays+ `$HOME/.agents/skills`, falling back to `skills/` under the workspace root.+7. Later: a host provider on the same contract.## Open questionsdiff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjsindex 9967075b5..f5a8d9c06 100644--- a/scripts/guard-invariants.mjs+++ b/scripts/guard-invariants.mjs@@ -95,11 +95,19 @@* executor. The generic inbox and state cursor must not* import subagent modules; session/turn composition roots may* compose built-in executors directly.- * rule 44 — Every concrete built-in sandbox provider is defined through- * `defineSandboxProvider()`, or the internal- * `defineLegacySandboxProvider()` until it migrates to the- * connection contract, and does not import sandbox runtime- * orchestration, registries, key derivation, or session state.+ * rule 44 — Sandbox providers are built on the public provider contract.+ * Files under `src/execution/sandbox/bindings/` and+ * `src/sandbox/providers/` reach the contract only through+ * `#public/sandbox/*` and never import core sandbox modules+ * (session construction, ensure, prewarm, sandbox state, the+ * shutdown registry, tool sessions, the runtime sandbox+ * registry, or the shared provider and session internals).+ * `sandbox/providers/default.ts` may import `#sandbox/state.js`+ * for `DefaultSandbox`'s two internal state hooks. Engine+ * helpers such as other binding modules,+ * stream utilities, and the optional-package loader stay+ * allowed. Every concrete built-in under `src/sandbox/providers/`+ * is defined through `defineSandboxProvider()`.* rule 45 — Provided tools under `packages/eve/src/tools/provided/**` and* the body of every agent tool import only public eve entry* points (the `#` specifiers of the package's `exports`), the@@ -142,6 +150,10 @@* itself and external packages. eve reaches it only through the* vendored root, delegation, otel, and ai-sdk entrypoints under* `#compiled/@vercel/agent-runs/`, never the workspace package itself.+ * rule 53 — Legacy session snapshots are read only at ingress. Outside+ * `execution/legacy-session/`, only the ingress files that import+ * protocol-1 sessions may import it, so current execution+ * consumes only normalized session state.** Baselines for rules with pre-existing violations live in* `guard-invariants-baseline.json`. Counts and allowlists in that file@@ -264,6 +276,7 @@ function isTsLike(relPath) {* rule50: Violation[];* rule51: Violation[];* rule52: Violation[];+ * rule53: Violation[];* symlinks: string[];* }} state*/@@ -293,6 +306,7 @@ async function scanRepo(state) {checkRule37(posix, content, state.rule37);checkRule43(posix, lines, state.rule43);checkRule44(posix, lines, state.rule44);+ checkRule53(posix, lines, state.rule53);checkRule45(posix, lines, state.rule45);checkRule46(posix, lines, state.rule46);checkRule47(posix, lines, state.rule47);@@ -387,7 +401,7 @@ const LEGACY_INGRESS_FILES = new Set(["packages/eve/src/eve-channel/index.ts",]);/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */-function checkRule44(posix, lines, violations) {+function checkRule53(posix, lines, violations) {if (posix.includes("/execution/legacy-session/") ||posix.includes("/internal/testing/") ||@@ -401,7 +415,7 @@ function checkRule44(posix, lines, violations) {/import\(["'][^"']*legacy-session\//.test(line))violations.push({- rule: 44,+ rule: 53,file: posix,line: index + 1,message:@@ -410,6 +424,54 @@ function checkRule44(posix, lines, violations) {});}+// ---------- Rule 44: sandbox providers use the public provider contract ----------++const SANDBOX_PROVIDER_DIRS = [+ "packages/eve/src/execution/sandbox/bindings/",+ "packages/eve/src/sandbox/providers/",+];++const SANDBOX_CORE_IMPORT_RE =+ /(?:from\s+|import\s*\()["']#(?:sandbox\/(?:provider|state)|execution\/sandbox\/(?:active-connections|ensure|prewarm|session|logging-session)|execution\/tool-session\/[^"']*|runtime\/sandbox\/[^"']*|shared\/sandbox-(?:provider|session|write-files))\.js["']/;++const SANDBOX_CORE_IMPORT_EXEMPTIONS = new Map([+ ["packages/eve/src/sandbox/providers/default.ts", /["']#sandbox\/state\.js["']/],+]);++/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */+function checkRule44(posix, lines, violations) {+ if (!SANDBOX_PROVIDER_DIRS.some((dir) => posix.startsWith(dir))) return;+ if (posix.endsWith(".test.ts")) return;+ const exemption = SANDBOX_CORE_IMPORT_EXEMPTIONS.get(posix);+ lines.forEach((line, index) => {+ if (!SANDBOX_CORE_IMPORT_RE.test(line) || exemption?.test(line)) return;+ violations.push({+ rule: 44,+ file: posix,+ line: index + 1,+ message:+ "Sandbox providers reach the provider contract only through #public/sandbox/* and may not import core sandbox modules. Use the public contract, or an engine helper such as another binding module.",+ });+ });+ if (!posix.startsWith("packages/eve/src/sandbox/providers/")) return;+ const source = lines.join("\n");+ if (!/\bdefineSandboxProvider\(/.test(source)) {+ violations.push({+ rule: 44,+ file: posix,+ message: "Built-in sandbox providers must use defineSandboxProvider().",+ });+ }+ if (source.includes("createSandboxEnvironment")) {+ violations.push({+ rule: 44,+ file: posix,+ message:+ "Built-in sandbox providers must not bypass defineSandboxProvider() through createSandboxEnvironment().",+ });+ }+}+// ---------- Rule 45: provided tools use only public entry points ----------const PROVIDED_TOOLS_DIR = "packages/eve/src/tools/provided/";@@ -1684,43 +1746,6 @@ function diffCounts(current, baseline) {// ---------- Entry point -----------async function checkRule44SandboxProviders() {- const providerNames = ["docker", "just-bash", "vercel"];- const forbidden = [- "#execution/sandbox/ensure.js",- "#execution/sandbox/prewarm.js",- "#runtime/sandbox/registry.js",- "#sandbox/state.js",- ];- const issues = [];- for (const name of providerNames) {- const file = `packages/eve/src/sandbox/providers/${name}.ts`;- const source = await readFile(join(REPO_ROOT, file), "utf8");- if (!/\bdefine(Legacy)?SandboxProvider\b/.test(source)) {- issues.push({- file,- message: "Built-in sandbox providers must use defineSandboxProvider().",- });- }- if (source.includes("createSandboxEnvironment")) {- issues.push({- file,- message:- "Built-in sandbox providers must not bypass defineSandboxProvider() through createSandboxEnvironment().",- });- }- for (const specifier of forbidden) {- if (source.includes(specifier)) {- issues.push({- file,- message: `Built-in sandbox providers may not bypass the provider contract through ${specifier}.`,- });- }- }- }- return issues;-}-async function main() {const baselineRaw = await readFile(BASELINE_PATH, "utf8");const baseline = JSON.parse(baselineRaw);@@ -1748,6 +1773,7 @@ async function main() {rule37: /** @type {Violation[]} */ ([]),rule43: /** @type {Violation[]} */ ([]),rule44: /** @type {Violation[]} */ ([]),+ rule53: /** @type {Violation[]} */ ([]),rule45: {allowlist: new Set(baseline.rule45_providedToolPrivateImportAllowlist),violations: /** @type {Violation[]} */ ([]),@@ -1856,12 +1882,9 @@ async function main() {// Rule 43violations.push(...state.rule43);- violations.push(...state.rule44);// Rule 44- for (const issue of await checkRule44SandboxProviders()) {- violations.push({ rule: 44, ...issue });- }+ violations.push(...state.rule44);// Rule 45violations.push(...state.rule45.violations);@@ -1876,6 +1899,7 @@ async function main() {violations.push(...state.rule50);violations.push(...state.rule51);violations.push(...state.rule52);+ violations.push(...state.rule53);if (violations.length === 0) {process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");