The Open Framework for Building Agents
refactor(sandbox): build the Docker provider on the public provider API (#5273)
Andrew Barba4db529f901e3
diff --git a/.changeset/docker-public-provider-api.md b/.changeset/docker-public-provider-api.mdnew file mode 100644index 000000000..9557d1895--- /dev/null+++ b/.changeset/docker-public-provider-api.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`DockerSandbox` now runs on the public `defineSandboxProvider()` contract. Container names, recorded session state, and template image references stay the same, so running sessions and prepared images from earlier builds keep working. A few behaviors change: `sandbox.delete()` removes the session's container by its session-derived name, honors the caller's `abortSignal`, and succeeds when the container is already gone; eve normalizes relative paths such as `logs/../out.txt` to `/workspace/out.txt` before they reach the container; and a Docker environment's `prepare` callback is typed with `DockerSandboxSession`.diff --git a/docs/sandbox/docker.mdx b/docs/sandbox/docker.mdxindex cccc25ee2..90b9331ce 100644--- a/docs/sandbox/docker.mdx+++ b/docs/sandbox/docker.mdx@@ -30,12 +30,12 @@ When `agent/sandbox/Dockerfile` exists, eve builds it during preparation and use## Environment options-Image, pull policy, environment variables, and `prepare` belong to the reusable environment. During preparation, eve starts a temporary container, hydrates managed resources, runs authored preparation, and commits the result as the recorded template image.+Image, pull policy, environment variables, and `prepare` belong to the reusable environment. During preparation, eve starts a temporary container, seeds workspace and skill files, runs your `prepare`, and commits the result as the recorded template image.## Live container optionsPass `networkPolicy` to `open()`. Docker supports only `"allow-all"` and `"deny-all"`. The policy applies to the live container, not the prepared image.-A session-owned container keeps writable `/workspace` state in its container filesystem. A stopped container restarts with that state.+A session-owned container keeps writable `/workspace` state in its container filesystem. A stopped container restarts with that state. `sandbox.delete()` removes the session's container by name and succeeds when the container is already gone.See the [sandbox overview](/docs/sandbox) for managed workspace, skills, parent inheritance, and custom providers.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.tsnew file mode 100644index 000000000..7e2e882bc--- /dev/null+++ b/packages/eve/src/execution/sandbox/bindings/docker-compat.integration.test.ts@@ -0,0 +1,276 @@+import { mkdir, writeFile } from "node:fs/promises";+import { join } from "node:path";++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 {+ createFakeDockerCli,+ fakeDockerContainerIdentity,+ findCall,+ 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,+ DockerSandboxRuntimeOptions,+} from "#public/sandbox/docker-sandbox.js";++const createScratchDirectory = useTemporaryDirectories();++function createEngine(input: {+ readonly cli: DockerCli;+ readonly options?: DockerSandboxEnvironmentOptions;+ readonly runtimeOptions?: DockerSandboxRuntimeOptions;+}) {+ return createSandboxProviderHarness(+ createDockerSandboxRuntime(input.options, input.cli),+ input.runtimeOptions ?? {},+ );+}++// Literal values recorded from the previous release. Running sessions persist+// container names and state, and deployments ship image references, so these+// must stay byte-identical across provider refactors.+describe("Docker provider compatibility with the previous release", () => {+ const ALICE_STORAGE = "/srv/alice-app/.eve/sandbox";+ const PREVIOUS_ARTIFACT = { imageReference: "eve-sandbox-template:previous-release" };+ const ALICE_CONTAINER = "eve-sbx-9b576ac2a11e0d99ef5520deef1b41fa";++ // `eve dev` labels containers with its run id; the recorded arguments predate it.+ beforeEach(() => {+ vi.stubEnv(EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV, undefined);+ });+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ function respondRunning(running: boolean) {+ return (args: readonly string[]): FakeResponse | undefined => {+ if (isContainerInspect(args) && args[3] === "{{.State.Running}}") {+ return running+ ? { exitCode: 0, stdout: "true\n" }+ : { exitCode: 1, stderr: "Error: No such container" };+ }+ return undefined;+ };+ }++ it("derives the same container name and state from the storage path and session id", async () => {+ const engine = createEngine({ cli: createFakeDockerCli(respondRunning(true)).cli });+ const start = (appRoot: string) =>+ engine.start({ appRoot, prepared: PREVIOUS_ARTIFACT, sandboxName: "ses_alice" });++ expect(JSON.stringify((await start(ALICE_STORAGE)).state)).toBe(+ `{"containerName":"${ALICE_CONTAINER}","version":2}`,+ );+ expect(JSON.stringify((await start("/srv/bob-app/.eve/sandbox")).state)).toBe(+ '{"containerName":"eve-sbx-a5c2666363bfc0bdb9e2f99bb7812b6c","version":2}',+ );+ });++ it("creates the session container with the same docker run arguments", async () => {+ const { calls, cli } = createFakeDockerCli(respondRunning(false));+ await createEngine({+ cli,+ options: { env: { FOO: "bar" } },+ runtimeOptions: { networkPolicy: "deny-all" },+ }).start({ appRoot: ALICE_STORAGE, prepared: PREVIOUS_ARTIFACT, sandboxName: "ses_alice" });++ expect(findCall(calls, (args) => args[0] === "run")?.args).toEqual([+ "run",+ "-d",+ "--name",+ ALICE_CONTAINER,+ "--label",+ "eve.sandbox=1",+ "--label",+ "eve.sandbox.role=session",+ "--label",+ "eve.sandbox.tag.agent=ses_alice",+ "--label",+ "eve.sandbox.tag.sessionId=ses_alice",+ "-e",+ "AI_AGENT=eve",+ "-e",+ "FOO=bar",+ "--network",+ "none",+ "--workdir",+ "/workspace",+ "--entrypoint",+ "/bin/sh",+ "eve-sandbox-template:previous-release",+ "-c",+ "sleep 2147483647",+ ]);+ });++ it("resumes a container from state the previous release recorded", async () => {+ const { calls, cli } = createFakeDockerCli(respondRunning(true));+ const handle = await createEngine({ cli }).openSession({+ appRoot: ALICE_STORAGE,+ existing: { containerName: ALICE_CONTAINER, version: 2 },+ prepared: PREVIOUS_ARTIFACT,+ sandboxName: "ses_alice",+ });+ await handle.sandbox.run({ command: "true" });++ expect(calls.filter(({ args }) => isContainerInspect(args)).map(({ args }) => args)).toEqual([+ ["container", "inspect", "--format", "{{.State.Running}}", ALICE_CONTAINER],+ ["container", "inspect", "--format", "{{.Id}}", ALICE_CONTAINER],+ ]);+ expect(findCall(calls, (args) => args[0] === "exec")?.args.slice(0, 4)).toEqual([+ "exec",+ "-w",+ "/workspace",+ fakeDockerContainerIdentity(ALICE_CONTAINER),+ ]);+ expect(findCall(calls, (args) => args[0] === "run" || args[0] === "start")).toBeUndefined();+ });++ it("reuses an existing template image under the same reference", async () => {+ const reference = "eve-sandbox-template:cbe866eb1c12526f7d05ae99-9f22a0e294ab3200fb39";+ const { calls, cli } = createFakeDockerCli();+ const appRoot = await createScratchDirectory("eve-docker-golden-");++ await expect(+ createEngine({ cli, options: { image: "alpine:3.21" } }).prepare({+ appRoot,+ sourceRevision: "golden-revision",+ }),+ ).resolves.toEqual({ imageReference: reference });+ expect(+ findCall(calls, (args) => ["build", "commit", "pull", "run"].includes(args[0] ?? "")),+ ).toBeUndefined();+ });++ it.each([+ {+ name: "a base image",+ artifact: "eve-sandbox-template:cbe866eb1c12526f7d05ae99-9f22a0e294ab3200fb39",+ baseImage: "alpine:3.21",+ runOptions: () => ["-e", "AI_AGENT=eve"],+ templateKey: "cbe866eb1c12526f7d05ae99",+ },+ {+ name: "custom options with workspace and skill files",+ artifact: "eve-sandbox-template:29da3fc1447dbbd1d40ca174-c22499590fe4cda16117",+ baseImage: "alpine:3.21",+ options: {+ env: { FOO: "bar" },+ image: "alpine:3.21",+ pullPolicy: "always",+ } satisfies DockerSandboxEnvironmentOptions,+ runOptions: () => ["-e", "AI_AGENT=eve", "-e", "FOO=bar"],+ seeded: [+ ["/home/agent/.agents/skills/weather/SKILL.md", "# Weather\n"],+ ["/workspace/README.md", "hello\n"],+ ],+ skills: [{ content: "# Weather\n", relativePath: "weather/SKILL.md" }],+ templateKey: "29da3fc1447dbbd1d40ca174",+ workspace: [{ content: "hello\n", relativePath: "README.md" }],+ },+ {+ name: "a sandbox Dockerfile",+ artifact: "eve-sandbox-template:6fb11595f3665a922c1175ad-9f22a0e294ab3200fb39",+ baseImage: "eve-sandbox-dockerfile:e96fef6018c802ba66c9c039",+ dockerfile: "FROM alpine:3.21\n",+ runOptions: () => ["-e", "AI_AGENT=eve"],+ templateKey: "6fb11595f3665a922c1175ad",+ },+ {+ name: "materialized resources",+ artifact: "eve-sandbox-template:8022e5c008de8d0002ed9faf-9f22a0e294ab3200fb39",+ baseImage: "alpine:3.21",+ materialized: true,+ runOptions: (appRoot: string) => [+ "-e",+ "AI_AGENT=eve",+ "--mount",+ `type=bind,src=${join(appRoot, "docker", "resources", "golden-resources")},dst=/eve/resources,readonly`,+ ],+ templateKey: "8022e5c008de8d0002ed9faf",+ },+ ])("builds the template image with $name under the same references", async (golden) => {+ const appRoot = await createScratchDirectory("eve-docker-golden-");+ if (golden.dockerfile !== undefined) {+ await mkdir(join(appRoot, "sandbox"), { recursive: true });+ await writeFile(join(appRoot, "sandbox", "Dockerfile"), golden.dockerfile);+ }+ let resourcesPath: string | undefined;+ if (golden.materialized === true) {+ resourcesPath = join(appRoot, "compiled-resources");+ await mkdir(join(resourcesPath, "workspace"), { recursive: true });+ await writeFile(join(resourcesPath, "workspace", "README.md"), "hello\n");+ }+ const { calls, cli } = createFakeDockerCli((args) => {+ if (args[0] === "image" && args[1] === "inspect") {+ return { exitCode: 1, stderr: "No such image" };+ }+ if (args[0] === "exec" && String(args.at(-1)).includes('"$HOME"')) {+ return { streamStdout: "/home/agent\n" };+ }+ return undefined;+ });++ const artifact = await createEngine({+ cli,+ options: golden.options ?? { image: "alpine:3.21" },+ }).prepare({+ appRoot,+ resourcesKey: resourcesPath === undefined ? undefined : "golden-resources",+ resourcesPath,+ skills: golden.skills,+ sourceRevision: "golden-revision",+ workspace: golden.workspace,+ });++ expect(artifact).toEqual({ imageReference: golden.artifact });+ const run = findCall(calls, (args) => args[0] === "run")?.args ?? [];+ const buildContainer = run[3] ?? "";+ expect(buildContainer).toMatch(new RegExp(`^${golden.templateKey}-build-[0-9a-f]{8}$`, "u"));+ expect(run).toEqual([+ "run",+ "-d",+ "--name",+ buildContainer,+ "--label",+ "eve.sandbox=1",+ "--label",+ "eve.sandbox.role=template-build",+ ...golden.runOptions(appRoot),+ "--workdir",+ "/workspace",+ "--entrypoint",+ "/bin/sh",+ golden.baseImage,+ "-c",+ "sleep 2147483647",+ ]);+ expect(findCall(calls, (args) => args[0] === "commit")?.args).toEqual([+ "commit",+ "--change",+ "LABEL eve.sandbox=1",+ "--change",+ "LABEL eve.sandbox.role=template",+ "--change",+ `LABEL eve.sandbox.template-key=${golden.templateKey}`,+ fakeDockerContainerIdentity(buildContainer),+ golden.artifact,+ ]);+ const seeded = calls+ .filter(({ args }) => args[0] === "exec" && args[1] === "-i")+ .map(({ args, stdin }) => [/cat > '(.+)'$/u.exec(String(args.at(-1)))?.[1], String(stdin)])+ .sort();+ expect(seeded).toEqual(golden.seeded ?? []);+ if (golden.dockerfile !== undefined) {+ expect(findCall(calls, (args) => args[0] === "build")?.args[4]).toBe(golden.baseImage);+ expect(findCall(calls, (args) => args[0] === "rmi")?.args).toEqual(["rmi", golden.baseImage]);+ }+ });+});diff --git a/packages/eve/src/execution/sandbox/bindings/docker-session.ts b/packages/eve/src/execution/sandbox/bindings/docker-connection.tssimilarity index 70%rename from packages/eve/src/execution/sandbox/bindings/docker-session.tsrename to packages/eve/src/execution/sandbox/bindings/docker-connection.tsindex 348d5202f..fb92b4498 100644--- a/packages/eve/src/execution/sandbox/bindings/docker-session.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker-connection.ts@@ -2,18 +2,14 @@ import { randomUUID } from "node:crypto";import { dirname as posixDirname } from "node:path/posix";import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";+import { stopDockerContainerIfRunning } from "#execution/sandbox/bindings/docker-container.js";+import { setDockerNetworkPolicy } from "#execution/sandbox/bindings/docker-network.js";import { expectDockerSuccess } from "#execution/sandbox/bindings/docker-utils.js";-import { resolveWorkspacePath } from "#execution/sandbox/bindings/local-provider-utils.js";import { shellQuote } from "#execution/sandbox/shell-quote.js";-import { bufferToStream, streamToBuffer } from "#execution/sandbox/stream-utils.js";-import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";-import type {- InternalSandboxSession,- SandboxReadFileOptions,- SandboxRemovePathOptions,- SandboxSpawnOptions,- SandboxWriteFileOptions,-} from "#shared/sandbox-session.js";+import type { DockerSandboxSession } from "#public/sandbox/docker.js";+import type { SandboxConnection } from "#public/sandbox/provider.js";++export type DockerSandboxExtensions = Pick<DockerSandboxSession, "setNetworkPolicy">;const DOCKER_SPAWN_PID_FILE_PREFIX = "/tmp/.eve-sbx-spawn-";@@ -48,10 +44,17 @@ const DOCKER_KILL_TREE_SCRIPT = ["exit 0",].join("\n");-export function createDockerInternalSession(input: {+/**+ * A connection bound to one container's identity rather than its name, so a+ * stale connection's commands, file operations, network policy changes, and+ * stop never reach a later container that reuses the session's name.+ * Deletion is the exception: `onSessionEnd` removes by session name, because+ * it is the single deletion path and must work without an open connection.+ */+export function createDockerConnection(input: {readonly cli: DockerCli;readonly containerIdentity: string;-}): InternalSandboxSession {+}): SandboxConnection<DockerSandboxExtensions> {const { cli, containerIdentity } = input;async function killSpawnTree(pidFilePath: string): Promise<void> {@@ -71,10 +74,12 @@ export function createDockerInternalSession(input: {}return {- resolvePath: resolveWorkspacePath,- async spawn(options: SandboxSpawnOptions) {- const args = ["exec", "-w", resolveWorkspacePath(options.workingDirectory ?? WORKSPACE_ROOT)];- for (const [key, value] of Object.entries(options.env ?? {})) {+ extensions: {+ setNetworkPolicy: (policy) => setDockerNetworkPolicy(cli, containerIdentity, policy),+ },+ async spawn(options) {+ const args = ["exec", "-w", options.workingDirectory];+ for (const [key, value] of Object.entries(options.env)) {args.push("-e", `${key}=${value}`);}// `docker exec` cannot deliver signals to the exec'd process, so@@ -108,7 +113,7 @@ export function createDockerInternalSession(input: {},};},- async readFile(options: SandboxReadFileOptions) {+ async readFile(options) {const quoted = shellQuote(options.path);const result = await cli.run([@@ -126,9 +131,9 @@ export function createDockerInternalSession(input: {return null;}expectDockerSuccess(result, `read "${options.path}" from sandbox container`);- return bufferToStream(result.stdoutBytes);+ return result.stdoutBytes;},- async removePath(options: SandboxRemovePathOptions) {+ async removePath(options) {const flags = `${options.recursive === true ? "r" : ""}${options.force === true ? "f" : ""}`;const args = ["exec",@@ -141,20 +146,22 @@ export function createDockerInternalSession(input: {const result = await cli.run(args, { signal: options.abortSignal });expectDockerSuccess(result, `remove "${options.path}" from sandbox container`);},- async writeFile(options: SandboxWriteFileOptions) {- const bytes = await streamToBuffer(options.content);- const result = await cli.run(- [- "exec",- "-i",- containerIdentity,- "bash",- "-lc",- `mkdir -p ${shellQuote(posixDirname(options.path))} && cat > ${shellQuote(options.path)}`,- ],- { signal: options.abortSignal, stdin: bytes },- );- expectDockerSuccess(result, `write "${options.path}" into sandbox container`);+ stop: () => stopDockerContainerIfRunning(cli, containerIdentity),+ async writeFiles(options) {+ for (const file of options.files) {+ const result = await cli.run(+ [+ "exec",+ "-i",+ containerIdentity,+ "bash",+ "-lc",+ `mkdir -p ${shellQuote(posixDirname(file.path))} && cat > ${shellQuote(file.path)}`,+ ],+ { signal: options.abortSignal, stdin: file.content },+ );+ expectDockerSuccess(result, `write "${file.path}" into sandbox container`);+ }},};}diff --git a/packages/eve/src/execution/sandbox/bindings/docker-container.ts b/packages/eve/src/execution/sandbox/bindings/docker-container.tsindex 0b144293e..cbaeae8d4 100644--- a/packages/eve/src/execution/sandbox/bindings/docker-container.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker-container.ts@@ -3,12 +3,15 @@ import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";import type { ResolvedDockerSandboxOptions } from "#execution/sandbox/bindings/docker-options.js";import { expectDockerSuccess } from "#execution/sandbox/bindings/docker-utils.js";import { withDevelopmentSandboxTags } from "#execution/sandbox/development-run.js";-import { SANDBOX_AGENT_ENV } from "#execution/sandbox/session.js";import type { DockerSandboxNetworkPolicy } from "#public/sandbox/docker-sandbox.js";+import { SANDBOX_AGENT_ENV } from "#public/sandbox/provider.js";import { WORKSPACE_ROOT } from "#runtime/workspace/types.js";export const DOCKER_SANDBOX_LABEL = "eve.sandbox";+/** Where a template build container mounts the read-only workspace and skill resources. */+export const DOCKER_RESOURCES_MOUNT_PATH = "/eve/resources";+// PID 1 must outlive every exec'd command; the largest portable sleep// argument keeps the container alive without depending on GNU// `sleep infinity` being present in the image.@@ -45,7 +48,10 @@ export async function startDockerContainer(input: {args.push("--network", "none");}if (input.resourcesPath !== undefined) {- args.push("--mount", `type=bind,src=${input.resourcesPath},dst=/eve/resources,readonly`);+ args.push(+ "--mount",+ `type=bind,src=${input.resourcesPath},dst=${DOCKER_RESOURCES_MOUNT_PATH},readonly`,+ );}args.push(diff --git a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.tsindex bc54277d0..dba58e225 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.integration.test.ts@@ -6,13 +6,8 @@ import { describe, expect, it } from "vitest";import {DockerDaemonUnavailableError,type DockerCli,- type DockerCommandResult,- type DockerProcess,} from "#execution/sandbox/bindings/docker-cli.js";-import {- createDockerSandboxProvider,- pruneDockerSandboxTemplates,-} from "#execution/sandbox/bindings/docker.js";+import { pruneDockerSandboxTemplates } from "#execution/sandbox/bindings/docker.js";import { EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV } from "#execution/sandbox/development-run.js";import {createDockerSandboxOptionsHash,@@ -26,9 +21,16 @@ 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 {+ createFakeDockerCli,+ fakeDockerContainerIdentity,+ findCall,+ 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 { bufferToStream } from "#execution/sandbox/stream-utils.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";@@ -37,105 +39,22 @@ import { createSandboxProviderResources } from "#shared/sandbox-provider.js";const createScratchDirectory = useTemporaryDirectories();-type FakeResponse = Partial<DockerCommandResult> & {- readonly streamStdout?: string;-};--interface FakeDockerCall {- readonly args: readonly string[];- readonly stdin?: Buffer;-}--function createFakeDockerCli(- respond: (args: readonly string[]) => FakeResponse | undefined = () => undefined,-): { calls: FakeDockerCall[]; cli: DockerCli; killedStreams: (readonly string[])[] } {- const calls: FakeDockerCall[] = [];- const createdContainerNames = new Set<string>();- const killedStreams: (readonly string[])[] = [];-- function resolve(args: readonly string[]): DockerCommandResult {- let partial = respond(args) ?? {};- if (args[0] === "container" && args[1] === "inspect" && args[3] === "{{.Id}}") {- const containerName = args.at(-1) ?? "unknown";- if (createdContainerNames.has(containerName) || (partial.exitCode ?? 0) === 0) {- partial = { ...partial, exitCode: 0, stdout: fakeDockerContainerIdentity(containerName) };- }- }- const stdout = partial.stdout ?? "";- const result = {- exitCode: partial.exitCode ?? 0,- stderr: partial.stderr ?? "",- stdout,- stdoutBytes: partial.stdoutBytes ?? Buffer.from(stdout, "utf8"),- };- if (args[0] === "run" && result.exitCode === 0) {- const nameIndex = args.indexOf("--name");- const containerName = nameIndex === -1 ? undefined : args[nameIndex + 1];- if (containerName !== undefined) createdContainerNames.add(containerName);- }- return result;- }-- return {- calls,- killedStreams,- cli: {- async run(args, options) {- calls.push({- args: [...args],- stdin: options?.stdin === undefined ? undefined : Buffer.from(options.stdin),- });- return resolve(args);- },- stream(args): DockerProcess {- calls.push({ args: [...args] });- const partial = respond(args) ?? {};- return {- stdout: bufferToStream(Buffer.from(partial.streamStdout ?? "", "utf8")),- stderr: bufferToStream(Buffer.alloc(0)),- async wait() {- return { exitCode: partial.exitCode ?? 0 };- },- async kill() {- killedStreams.push([...args]);- },- };- },- },- };-}-function createEngine(input: {readonly cli: DockerCli;readonly options?: DockerSandboxEnvironmentOptions;readonly runtimeOptions?: DockerSandboxRuntimeOptions;}) {return createSandboxProviderHarness(- createDockerSandboxProvider(input.options, input.cli),+ createDockerSandboxRuntime(input.options, input.cli),input.runtimeOptions ?? {},{ preparedArtifact: () => ({ imageReference: TEMPLATE_IMAGE }) },);}-function findCall(- calls: readonly FakeDockerCall[],- predicate: (args: readonly string[]) => boolean,-): FakeDockerCall | undefined {- return calls.find((call) => predicate(call.args));-}-function isImageInspect(args: readonly string[], reference: string): boolean {return args[0] === "image" && args[1] === "inspect" && args.at(-1) === reference;}-function isContainerInspect(args: readonly string[]): boolean {- return args[0] === "container" && args[1] === "inspect";-}--function fakeDockerContainerIdentity(containerName: string): string {- return `sha256:${containerName}`;-}-const TEMPLATE_KEY = "eve-sbx-tpl-local-abc123";const DEFAULT_DOCKER_OPTIONS_HASH = createDockerSandboxOptionsHash(resolveDockerSandboxOptions());const TEMPLATE_IMAGE = dockerTemplateImageReference({@@ -356,7 +275,8 @@ describe("Docker provider prewarm", () => {calls,(args) =>args[0] === "exec" &&- (args.at(-1) ?? "").includes("cp -a /eve/resources/workspace/. /workspace/"),+ // The spawn wrapper re-quotes the script for `bash -lc`, escaping its quoted root.+ (args.at(-1) ?? "").includes("cp -a '\\''/eve/resources'\\''/workspace/. /workspace/"),),).toBeDefined();});@@ -758,7 +678,8 @@ describe("Docker provider create", () => {it("rejects domain-level network policies with guidance toward the Vercel provider", async () => {const { handle } = await createRunningSessionHandle({});- await expect(handle.sandbox.setNetworkPolicy({ allow: { "*": [] } })).rejects.toThrow(+ // DefaultSandbox forwards the shared network policy type unchanged.+ await expect(handle.sandbox.setNetworkPolicy({ allow: { "*": [] } } as never)).rejects.toThrow(/Vercel provider/,);});@@ -784,7 +705,7 @@ describe("Docker template prune", () => {// Mirrors how prewarm and session start build the provider context.async function prepareLikeDevelopment(appRoot: string, cli: DockerCli) {- return await createDockerSandboxProvider(undefined, cli).prepare({+ return await createDockerSandboxRuntime(undefined, cli).prepare({files: createSandboxProviderFiles(join(appRoot, "sandbox")),host: createSandboxProviderHost(appRoot),resources: createSandboxProviderResources({}),diff --git a/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts b/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.tsindex f42359c81..46189acc1 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.scenario.test.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from "vitest";import { DockerUnavailableError } from "#execution/sandbox/bindings/docker-cli.js";-import { createDockerSandboxProvider } from "#execution/sandbox/bindings/docker.js";+import { createDockerSandboxRuntime } from "#internal/testing/docker-sandbox-runtime.js";import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";@@ -12,7 +12,7 @@ describe("docker CLI resolution", () => {vi.stubEnv("EVE_DOCKER_PATH", "/nonexistent/docker-binary");try {const appRoot = await createScratchDirectory("eve-docker-missing-");- const engine = createSandboxProviderHarness(createDockerSandboxProvider(), undefined);+ const engine = createSandboxProviderHarness(createDockerSandboxRuntime(), undefined);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 af23d70c7..f3d864351 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.test.ts@@ -1,12 +1,32 @@import { describe, expect, it, vi } from "vitest";-import { createDockerSandboxProvider } from "#execution/sandbox/bindings/docker.js";+import { createDockerSandboxRuntime } from "#internal/testing/docker-sandbox-runtime.js";import { createSandboxProviderHarness } from "#internal/testing/sandbox-provider-harness.js";import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";-describe("Docker sandbox deletion", () => {- it("stops and removes the session container", async () => {- const run: DockerCli["run"] = vi.fn(async (args: readonly string[]) => ({+function createContainerStoreCli() {+ let exists = false;+ const run: DockerCli["run"] = vi.fn(async (args: readonly string[]) => {+ if (args[0] === "rm") {+ const gone = !exists;+ exists = false;+ return {+ exitCode: gone ? 1 : 0,+ stderr: gone ? "Error response from daemon: No such container: eve-sbx" : "",+ stdout: "",+ stdoutBytes: Buffer.alloc(0),+ };+ }+ if (args[0] === "run") exists = true;+ if (args[0] === "container" && !exists) {+ return {+ exitCode: 1,+ stderr: "Error: No such container: eve-sbx",+ stdout: "",+ stdoutBytes: Buffer.alloc(0),+ };+ }+ return {exitCode: 0,stderr: "",stdout:@@ -16,30 +36,18 @@ describe("Docker sandbox deletion", () => {? "container-id-1\n": "",stdoutBytes: Buffer.alloc(0),- }));- const dockerCli: DockerCli = {- run,- stream() {- throw new Error("stream is not used by this test");- },};- const provider = createSandboxProviderHarness(- createDockerSandboxProvider(undefined, dockerCli),- {},- { preparedArtifact: () => ({ imageReference: "prepared-image" }) },- );- const handle = await provider.openSession({- appRoot: "/tmp/eve-app",- sandboxName: "session-key",- });- vi.mocked(run).mockClear();-- await handle.onSandboxDelete();-- expect(run).toHaveBeenNthCalledWith(1, ["stop", "-t", "0", "container-id-1"]);- expect(run).toHaveBeenNthCalledWith(2, ["rm", "-f", "container-id-1"]);});+ const dockerCli: DockerCli = {+ run,+ stream() {+ throw new Error("stream is not used by this test");+ },+ };+ return { dockerCli, run };+}+describe("Docker sandbox deletion", () => {it("keeps an old handle bound to the deleted container identity", async () => {let containerId = "container-id-1";const run: DockerCli["run"] = vi.fn(async (args: readonly string[]) => ({@@ -60,7 +68,7 @@ describe("Docker sandbox deletion", () => {},};const provider = createSandboxProviderHarness(- createDockerSandboxProvider(undefined, dockerCli),+ createDockerSandboxRuntime(undefined, dockerCli),{},{ preparedArtifact: () => ({ imageReference: "prepared-image" }) },);@@ -87,34 +95,35 @@ describe("Docker sandbox deletion", () => {expect.anything(),);});++ 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 abortSignal = new AbortController().signal;++ vi.mocked(run).mockClear();+ await handle.onSandboxDelete({ abortSignal });+ await handle.onSandboxDelete({ abortSignal });+ expect(vi.mocked(run).mock.calls.filter(([args]) => args[0] === "rm")).toEqual([+ [["rm", "-f", state.containerName], { signal: abortSignal }],+ [["rm", "-f", state.containerName], { signal: abortSignal }],+ ]);+ });});describe("Docker sandbox session identity", () => {it("names the container from the session key alone and removes it by key at session end", async () => {- let removed = false;- const run: DockerCli["run"] = vi.fn(async (args: readonly string[]) => {- const gone = args[0] === "rm" && removed;- if (args[0] === "rm") removed = true;- return {- exitCode: gone ? 1 : 0,- stderr: gone ? "Error response from daemon: No such container: eve-sbx" : "",- stdout:- args[0] === "container" && args[3] === "{{.State.Running}}"- ? "true\n"- : args[0] === "container" && args[3] === "{{.Id}}"- ? "container-id-1\n"- : "",- stdoutBytes: Buffer.alloc(0),- };- });- const dockerCli: DockerCli = {- run,- stream() {- throw new Error("stream is not used by this test");- },- };+ const { dockerCli, run } = createContainerStoreCli();const provider = createSandboxProviderHarness(- createDockerSandboxProvider(undefined, dockerCli),+ createDockerSandboxRuntime(undefined, dockerCli),{},{ preparedArtifact: () => ({ imageReference: "image-a" }) },);@@ -130,10 +139,8 @@ describe("Docker sandbox session identity", () => {vi.mocked(run).mockClear();await provider.endSession({ ...session, state: null });- await provider.endSession({ ...session, state: null });expect(vi.mocked(run).mock.calls.map(([args]) => args)).toEqual([["rm", "-f", state.containerName],- ["rm", "-f", state.containerName],]);});});@@ -142,7 +149,7 @@ 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(- createDockerSandboxProvider(undefined, {+ createDockerSandboxRuntime(undefined, {run,stream() {throw new Error("stream is not used by this test");diff --git a/packages/eve/src/execution/sandbox/bindings/docker.ts b/packages/eve/src/execution/sandbox/bindings/docker.tsindex 1d652135a..daf2a3ce2 100644--- a/packages/eve/src/execution/sandbox/bindings/docker.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker.ts@@ -1,30 +1,24 @@-import type { SandboxNetworkPolicy } from "#shared/sandbox-network-policy.js";-import type { SandboxSession } from "#shared/sandbox-session.js";-import { toErrorMessage } from "#shared/errors.js";-type NetworkPolicySandboxSession = SandboxSession & {- setNetworkPolicy(policy: SandboxNetworkPolicy): Promise<void>;-};import { randomUUID } from "node:crypto";-import {- runDockerBaseSetup,- startDockerContainer,- stopDockerContainerIfRunning,-} from "#execution/sandbox/bindings/docker-container.js";import {assertDockerDaemonAvailable,createDockerCli,type DockerCli,} from "#execution/sandbox/bindings/docker-cli.js";import {- assertDockerNetworkPolicy,- setDockerNetworkPolicy,-} from "#execution/sandbox/bindings/docker-network.js";+ createDockerConnection,+ type DockerSandboxExtensions,+} from "#execution/sandbox/bindings/docker-connection.js";+import {+ DOCKER_RESOURCES_MOUNT_PATH,+ runDockerBaseSetup,+ startDockerContainer,+} from "#execution/sandbox/bindings/docker-container.js";+import { assertDockerNetworkPolicy } from "#execution/sandbox/bindings/docker-network.js";import {createDockerSandboxOptionsHash,resolveDockerSandboxOptions,} from "#execution/sandbox/bindings/docker-options.js";-import { createDockerInternalSession } from "#execution/sandbox/bindings/docker-session.js";import {commitDockerTemplateImage,dockerImageExists,@@ -39,30 +33,25 @@ import {dockerfileImageReference,materializeSandboxDockerfile,} from "#execution/sandbox/dockerfile.js";-import {- hydrateSandboxProviderResources,- prepareImmutableResources,-} from "#execution/sandbox/bindings/immutable-resources.js";-import { createLoggingSandboxSession } from "#execution/sandbox/logging-session.js";-import { buildSandboxSession } from "#execution/sandbox/session.js";import { createSandboxProviderIdentity } from "#execution/sandbox/provider-identity.js";+import type {+ DockerSandboxEnvironmentOptions,+ DockerSandboxRuntimeOptions,+} from "#public/sandbox/docker-sandbox.js";import {- isSandboxPreparedArtifactRecord,- sandboxProviderResourceIdentity,- type SandboxPreparedArtifact,- type LegacySandboxProviderImplementation,- type SandboxProviderSessionContext,-} from "#shared/sandbox-provider.js";-import { SandboxTemplateNotProvisionedError } from "#shared/sandbox-template-error.js";+ SandboxSessionGoneError,+ SandboxTemplateNotProvisionedError,+ type SandboxConnection,+ type SandboxJson,+ type SandboxProviderImplementation,+ type SandboxSessionContext,+} from "#public/sandbox/provider.js";+import { toErrorMessage } from "#shared/errors.js";+import { isObject } from "#shared/guards.js";import {invalidPreparedSandboxArtifactError,invalidSandboxSessionStateError,} from "#shared/sandbox-recorded-data-error.js";-import { SandboxSessionGoneError } from "#shared/sandbox-session-gone-error.js";-import type {- DockerSandboxEnvironmentOptions,- DockerSandboxRuntimeOptions,-} from "#public/sandbox/docker-sandbox.js";export {DOCKER_TEMPLATE_IMAGE_REPOSITORY,@@ -82,31 +71,33 @@ type DockerSandboxSessionState = {readonly version: 2;};+/** Environment options the provider receives: eve runs `prepare` itself. */+export type DockerSandboxProviderOptions = Omit<DockerSandboxEnvironmentOptions, "prepare">;+/*** Creates the Docker sandbox provider.** Two-phase lifecycle mapped onto Docker primitives:*- * - `prewarm` runs the base image, applies base setup, runs the- * authored preparation, writes seed files, then `docker commit`s the- * container into a reusable template image.- * - `create` starts (or restarts) one long-lived container per session- * key from the template image. The container's filesystem carries- * session state across reconnects, so `shutdown` only stops the- * container and the next `create` restarts it with state intact.+ * - `prepare` runs the base image, applies base setup, lets eve seed the+ * workspace and skills and run the authored preparation, then+ * `docker commit`s the container into a reusable template image.+ * - `start` starts (or restarts) one long-lived container per session+ * from the template image. The container's filesystem carries session+ * state across reconnects, so stopping only stops the container and the+ * next `start` or `resume` restarts it with state intact.*/export function createDockerSandboxProvider(- createOptions?: DockerSandboxEnvironmentOptions,+ createOptions: DockerSandboxProviderOptions,dockerCli?: DockerCli,-): LegacySandboxProviderImplementation<+): SandboxProviderImplementation<DockerSandboxRuntimeOptions,DockerSandboxPreparedArtifact,DockerSandboxSessionState,- NetworkPolicySandboxSession+ DockerSandboxExtensions> {const cli = dockerCli ?? createDockerCli();- const authoredOptions = createOptions ?? {};- const options = resolveDockerSandboxOptions(authoredOptions);+ const options = resolveDockerSandboxOptions(createOptions);const optionsHash = createDockerSandboxOptionsHash(options);let daemonCheck: Promise<void> | undefined;@@ -136,12 +127,12 @@ export function createDockerSandboxProvider(}async function openDockerSession(- context: SandboxProviderSessionContext,+ context: SandboxSessionContext,openOptions: Readonly<DockerSandboxRuntimeOptions> | undefined,- artifactValue: SandboxPreparedArtifact,+ artifactValue: SandboxJson,containerName: string,createIfMissing: boolean,- ) {+ ): Promise<SandboxConnection<DockerSandboxExtensions>> {await ensureDaemon();let running = await inspectContainerRunning(containerName);if (running === undefined) {@@ -188,86 +179,56 @@ export function createDockerSandboxProvider(`restart sandbox session container "${containerName}"`,);}- const containerIdentity = await resolveDockerHandleIdentity(cli, containerName);- const session = buildSandboxSession(- createDockerInternalSession({ cli, containerIdentity }),- (policy) => setDockerNetworkPolicy(cli, containerIdentity, policy),- );- return {- sandbox: session,- async onSandboxDelete() {- await stopDockerContainerIfRunning(cli, containerIdentity);- expectDockerSuccess(- await cli.run(["rm", "-f", containerIdentity]),- `delete sandbox session container "${containerName}"`,- );- },- async onSandboxStop() {- await stopDockerContainerIfRunning(cli, containerIdentity);- },- async onRuntimeShutdown() {- await stopDockerContainerIfRunning(cli, containerIdentity);- },- };+ return createDockerConnection({+ cli,+ containerIdentity: await resolveDockerHandleIdentity(cli, containerName),+ });}return {- async onSessionEnd(context, state) {+ async onSessionEnd(context, state, { abortSignal }) {await ensureDaemon();const containerName = state?.containerName ?? dockerSessionName(context);- const removed = await cli.run(["rm", "-f", containerName]);+ const removed = await cli.run(["rm", "-f", containerName], { signal: abortSignal });if (removed.exitCode !== 0 && !/no such container/iu.test(removed.stderr)) {expectDockerSuccess(removed, `delete sandbox session container "${containerName}"`);}},async prepare(context) {- context.log?.("checking Docker daemon");+ context.log("checking Docker daemon");await ensureDaemon();const dockerfile = await materializeSandboxDockerfile({files: context.files,storagePath: context.storagePath,});- const templateKey = createSandboxProviderIdentity({- dockerfile: dockerfile?.contentHash,- optionsHash,- resources: sandboxProviderResourceIdentity(context.resources),- sourceRevision: context.sourceRevision,- version: 2,- }).slice(0, 24);+ const templateKey = context+ .templateKey({ dockerfile: dockerfile?.contentHash, optionsHash, version: 2 })+ .slice(0, 24);const templateReferenceInput = { optionsHash, templateKey };const imageReference = dockerTemplateImageReference(templateReferenceInput);- const resourceSource = context.resources.source;- const resourcesPath =- resourceSource.kind === "materialized"- ? await prepareImmutableResources({- storagePath: context.storagePath,- provider: DOCKER_PROVIDER_NAME,- resourcesKey: resourceSource.key,- sourcePath: resourceSource.path,- })- : undefined;const markerPath = resolveDockerTemplateMarkerPath(context.storagePath,templateReferenceInput,);- context.log?.(`checking cached template image "${imageReference}"`);+ context.log(`checking cached template image "${imageReference}"`);if (await dockerImageExists(cli, imageReference)) {- context.log?.("reusing cached template image");+ context.log("reusing cached template image");await touchDockerTemplateMarker(markerPath, imageReference);return { imageReference };}+ const resourcesPath = await context.resourcesDirectory();let baseImage = options.image;if (dockerfile === undefined) {- context.log?.(`checking base image "${options.image}"`);+ context.log(`checking base image "${options.image}"`);await ensureDockerBaseImage(cli, options);} else {baseImage = dockerfileImageReference({dockerfile,templateKey,});- context.log?.(`building sandbox Dockerfile "${dockerfile.path}"`);+ context.log(`building sandbox Dockerfile "${dockerfile.path}"`);await buildSandboxDockerfile({cli,dockerfile,@@ -276,7 +237,7 @@ export function createDockerSandboxProvider(}const buildContainerName = `${templateKey}-build-${randomUUID().slice(0, 8)}`;- context.log?.("starting template build container");+ context.log("starting template build container");await startDockerContainer({cli,containerName: buildContainerName,@@ -289,36 +250,20 @@ export function createDockerSandboxProvider(try {const buildContainerIdentity = await resolveDockerHandleIdentity(cli, buildContainerName);- context.log?.("preparing base runtime inside container");+ context.log("preparing base runtime inside container");await runDockerBaseSetup(cli, buildContainerIdentity);- const templateSession = buildSandboxSession(- createDockerInternalSession({- cli,- containerIdentity: buildContainerIdentity,- }),- (policy) => setDockerNetworkPolicy(cli, buildContainerIdentity, policy),+ await context.populate(+ createDockerConnection({ cli, containerIdentity: buildContainerIdentity }),+ resourcesPath === undefined ? undefined : { mountedAt: DOCKER_RESOURCES_MOUNT_PATH },);- await hydrateSandboxProviderResources({- log: context.log,- resources: context.resources,- session: templateSession,- });-- if (authoredOptions.prepare !== undefined) {- context.log?.("running sandbox preparation");- await authoredOptions.prepare(- createLoggingSandboxSession({ log: context.log, session: templateSession }),- );- }-// Quiesce before commit so the captured filesystem is stable.- context.log?.("stopping template build container");+ context.log("stopping template build container");expectDockerSuccess(await cli.run(["stop", "-t", "0", buildContainerIdentity]),`stop template build container "${buildContainerName}"`,);- context.log?.(`committing template image "${imageReference}"`);+ context.log(`committing template image "${imageReference}"`);const commit = await commitDockerTemplateImage({cli,containerIdentity: buildContainerIdentity,@@ -326,7 +271,7 @@ export function createDockerSandboxProvider(templateKey,});if (commit === "reused") {- context.log?.("reusing concurrently published template image");+ context.log("reusing concurrently published template image");}await touchDockerTemplateMarker(markerPath, imageReference);} finally {@@ -351,7 +296,13 @@ export function createDockerSandboxProvider(}const containerName = dockerSessionName(context);return {- handle: await openDockerSession(context, openOptions, artifactValue, containerName, true),+ connection: await openDockerSession(+ context,+ openOptions,+ artifactValue,+ containerName,+ true,+ ),state: { containerName, version: 2 },};},@@ -364,7 +315,7 @@ export function createDockerSandboxProvider(* and open options apply only when the container is created, so a session* keeps its container across rebuilds.*/-function dockerSessionName(context: SandboxProviderSessionContext): string {+function dockerSessionName(context: SandboxSessionContext): string {return `eve-sbx-${createSandboxProviderIdentity({namespace: context.storagePath,sessionId: context.session.id,@@ -372,21 +323,15 @@ function dockerSessionName(context: SandboxProviderSessionContext): string {}).slice(0, 32)}`;}-function requirePreparedDockerArtifact(- artifact: SandboxPreparedArtifact,-): DockerSandboxPreparedArtifact {- if (!isSandboxPreparedArtifactRecord(artifact) || typeof artifact.imageReference !== "string") {+function requirePreparedDockerArtifact(artifact: SandboxJson): DockerSandboxPreparedArtifact {+ if (!isObject(artifact) || typeof artifact.imageReference !== "string") {throw invalidPreparedSandboxArtifactError("Docker sandbox");}return { imageReference: artifact.imageReference };}-function requireDockerSessionState(state: SandboxPreparedArtifact): DockerSandboxSessionState {- if (- !isSandboxPreparedArtifactRecord(state) ||- state.version !== 2 ||- typeof state.containerName !== "string"- ) {+function requireDockerSessionState(state: SandboxJson): DockerSandboxSessionState {+ if (!isObject(state) || state.version !== 2 || typeof state.containerName !== "string") {throw invalidSandboxSessionStateError("Docker sandbox");}return { containerName: state.containerName, version: 2 };diff --git a/packages/eve/src/execution/sandbox/bindings/immutable-resources.test.ts b/packages/eve/src/execution/sandbox/bindings/immutable-resources.test.tsindex ae0d441e6..39e6871e0 100644--- a/packages/eve/src/execution/sandbox/bindings/immutable-resources.test.ts+++ b/packages/eve/src/execution/sandbox/bindings/immutable-resources.test.ts@@ -1,20 +1,17 @@import { describe, expect, it, vi } from "vitest";-import { hydrateSandboxProviderResources } from "#execution/sandbox/bindings/immutable-resources.js";+import { hydrateSandboxFromImmutableResources } from "#execution/sandbox/bindings/immutable-resources.js";-describe("hydrateSandboxProviderResources", () => {+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 hydrateSandboxProviderResources({- resources: { source: { key: "resources", kind: "materialized", path: "/compiled" } },- session: { run } as never,- });+ 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/"');+ 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.tsindex d8e752ab0..2e483bf2e 100644--- a/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts+++ b/packages/eve/src/execution/sandbox/bindings/immutable-resources.ts@@ -1,17 +1,8 @@import { join } from "node:path";-import {- copyDirectoryAtomically,- writeSandboxSeedFiles,-} from "#execution/sandbox/bindings/local-provider-utils.js";-import {- providerResourceTargetFiles,- type SandboxProviderResources,-} from "#shared/sandbox-provider.js";+import { copyDirectoryAtomically } from "#execution/sandbox/bindings/local-provider-utils.js";import type { SandboxSession } from "#shared/sandbox-session.js";-const SANDBOX_RESOURCES_ROOT = "/eve/resources";-function resolveImmutableResourcesPath(input: {readonly storagePath: string;readonly provider: string;@@ -31,36 +22,20 @@ export async function prepareImmutableResources(input: {return path;}-export async function hydrateSandboxProviderResources(input: {- readonly log?: (message: string) => void;- readonly resources: SandboxProviderResources;- readonly session: SandboxSession;-}): Promise<void> {- switch (input.resources.source.kind) {- case "none":- case "inline":- await writeSandboxSeedFiles(input.session, providerResourceTargetFiles(input.resources));- return;- case "materialized":- input.log?.("hydrating workspace and skills from read-only resources");- await hydrateSandboxFromImmutableResources(input.session);- return;- }-}-+/** `quotedRoot` is interpolated into the shell script, so callers pass it shell-quoted. */export async function hydrateSandboxFromImmutableResources(session: SandboxSession,- root = SANDBOX_RESOURCES_ROOT,+ quotedRoot: string,): Promise<void> {const result = await session.run({command: ["set -e",- `if [ -d ${root}/workspace ]; then cp -a ${root}/workspace/. /workspace/; fi`,- `if [ -d ${root}/skills ]; then`,+ `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 ${root}/skills/. "$HOME/.agents/skills/"`,+ ` cp -a ${quotedRoot}/skills/. "$HOME/.agents/skills/"`,"fi",].join("\n"),});diff --git a/packages/eve/src/internal/testing/docker-sandbox-runtime.ts b/packages/eve/src/internal/testing/docker-sandbox-runtime.tsnew file mode 100644index 000000000..04d4a9370--- /dev/null+++ b/packages/eve/src/internal/testing/docker-sandbox-runtime.ts@@ -0,0 +1,28 @@+import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.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<+ DockerSandboxRuntimeOptions,+ { readonly imageReference: string },+ { readonly containerName: string; readonly version: 2 },+ DockerSandboxSession+ >;+}diff --git a/packages/eve/src/internal/testing/fake-docker-cli.ts b/packages/eve/src/internal/testing/fake-docker-cli.tsnew file mode 100644index 000000000..879eb40bf--- /dev/null+++ b/packages/eve/src/internal/testing/fake-docker-cli.ts@@ -0,0 +1,89 @@+import type {+ DockerCli,+ DockerCommandResult,+ DockerProcess,+} from "#execution/sandbox/bindings/docker-cli.js";+import { bufferToStream } from "#execution/sandbox/stream-utils.js";++export type FakeResponse = Partial<DockerCommandResult> & {+ readonly streamStdout?: string;+};++export interface FakeDockerCall {+ readonly args: readonly string[];+ readonly stdin?: Buffer;+}++export function createFakeDockerCli(+ respond: (args: readonly string[]) => FakeResponse | undefined = () => undefined,+): { calls: FakeDockerCall[]; cli: DockerCli; killedStreams: (readonly string[])[] } {+ const calls: FakeDockerCall[] = [];+ const createdContainerNames = new Set<string>();+ const killedStreams: (readonly string[])[] = [];++ function resolve(args: readonly string[]): DockerCommandResult {+ let partial = respond(args) ?? {};+ if (args[0] === "container" && args[1] === "inspect" && args[3] === "{{.Id}}") {+ const containerName = args.at(-1) ?? "unknown";+ if (createdContainerNames.has(containerName) || (partial.exitCode ?? 0) === 0) {+ partial = { ...partial, exitCode: 0, stdout: fakeDockerContainerIdentity(containerName) };+ }+ }+ const stdout = partial.stdout ?? "";+ const result = {+ exitCode: partial.exitCode ?? 0,+ stderr: partial.stderr ?? "",+ stdout,+ stdoutBytes: partial.stdoutBytes ?? Buffer.from(stdout, "utf8"),+ };+ if (args[0] === "run" && result.exitCode === 0) {+ const nameIndex = args.indexOf("--name");+ const containerName = nameIndex === -1 ? undefined : args[nameIndex + 1];+ if (containerName !== undefined) createdContainerNames.add(containerName);+ }+ return result;+ }++ return {+ calls,+ killedStreams,+ cli: {+ async run(args, options) {+ calls.push({+ args: [...args],+ stdin: options?.stdin === undefined ? undefined : Buffer.from(options.stdin),+ });+ return resolve(args);+ },+ stream(args): DockerProcess {+ calls.push({ args: [...args] });+ const partial = respond(args) ?? {};+ return {+ stdout: bufferToStream(Buffer.from(partial.streamStdout ?? "", "utf8")),+ stderr: bufferToStream(Buffer.alloc(0)),+ async wait() {+ return { exitCode: partial.exitCode ?? 0 };+ },+ async kill() {+ killedStreams.push([...args]);+ },+ };+ },+ },+ };+}++export function findCall(+ calls: readonly FakeDockerCall[],+ predicate: (args: readonly string[]) => boolean,+): FakeDockerCall | undefined {+ return calls.find((call) => predicate(call.args));+}++export function isContainerInspect(args: readonly string[]): boolean {+ return args[0] === "container" && args[1] === "inspect";+}++export function fakeDockerContainerIdentity(containerName: string): string {+ return `sha256:${containerName}`;+}diff --git a/packages/eve/src/public/sandbox/docker-sandbox.ts b/packages/eve/src/public/sandbox/docker-sandbox.tsindex fe3a494a3..0a9287fb2 100644--- a/packages/eve/src/public/sandbox/docker-sandbox.ts+++ b/packages/eve/src/public/sandbox/docker-sandbox.ts@@ -10,6 +10,12 @@ export type DockerSandboxPullPolicy = "if-not-present" | "always" | "never";/** Coarse-grained egress policy for one live Docker sandbox. */export type DockerSandboxNetworkPolicy = Extract<SandboxNetworkPolicy, "allow-all" | "deny-all">;+/** Live sandbox capabilities exposed by a Docker environment. */+export interface DockerSandboxSession extends SandboxSession {+ /** Applies a coarse egress policy to the live container. */+ setNetworkPolicy(policy: DockerSandboxNetworkPolicy): Promise<void>;+}+/** Options shared by every sandbox created from one Docker environment. */export interface DockerSandboxEnvironmentOptions {/** Base container image. Defaults to eve's published sandbox image. */@@ -19,7 +25,7 @@ export interface DockerSandboxEnvironmentOptions {/** Base image pull behavior. @default "if-not-present" */readonly pullPolicy?: DockerSandboxPullPolicy;/** Idempotent setup captured in the prepared image. */- readonly prepare?: (sandbox: SandboxSession) => Promise<void> | void;+ readonly prepare?: (sandbox: DockerSandboxSession) => Promise<void> | void;}/** Options applied when eve creates one live Docker sandbox. */diff --git a/packages/eve/src/public/sandbox/docker.ts b/packages/eve/src/public/sandbox/docker.tsindex 893a39042..2d8e20fb3 100644--- a/packages/eve/src/public/sandbox/docker.ts+++ b/packages/eve/src/public/sandbox/docker.ts@@ -1,12 +1,3 @@-import type { SandboxSession } from "#shared/sandbox-session.js";-import type { DockerSandboxNetworkPolicy } from "#public/sandbox/docker-sandbox.js";--/** Live sandbox capabilities exposed by a Docker environment. */-export interface DockerSandboxSession extends SandboxSession {- /** Applies a coarse egress policy to the live container. */- setNetworkPolicy(policy: DockerSandboxNetworkPolicy): Promise<void>;-}-export {DockerSandbox,type DockerSandboxEnvironmentOptions,@@ -15,4 +6,5 @@ export {export type {DockerSandboxNetworkPolicy,DockerSandboxPullPolicy,+ DockerSandboxSession,} from "#public/sandbox/docker-sandbox.js";diff --git a/packages/eve/src/sandbox/providers/docker.ts b/packages/eve/src/sandbox/providers/docker.tsindex 40ad76697..122999898 100644--- a/packages/eve/src/sandbox/providers/docker.ts+++ b/packages/eve/src/sandbox/providers/docker.ts@@ -1,11 +1,16 @@-import type { DockerSandboxSession } from "#public/sandbox/docker.js";-import { createDockerSandboxProvider } from "#execution/sandbox/bindings/local.js";+import type { DockerCli } from "#execution/sandbox/bindings/docker-cli.js";+import type { DockerSandboxProviderOptions } from "#execution/sandbox/bindings/docker.js";+import {+ createDockerSandboxProvider,+ DOCKER_PROVIDER_NAME,+} from "#execution/sandbox/bindings/local.js";import type {DockerSandboxEnvironmentOptions,DockerSandboxRuntimeOptions,+ DockerSandboxSession,} from "#public/sandbox/docker-sandbox.js";+import { defineSandboxProvider, type SandboxProvider } from "#public/sandbox/provider.js";import type { SandboxEnvironment } from "#shared/sandbox-environment.js";-import { defineLegacySandboxProvider } from "#shared/sandbox-provider.js";export type {DockerSandboxEnvironmentOptions,@@ -14,18 +19,22 @@ export type {type DockerfileEnvironmentInput = Omit<DockerSandboxEnvironmentOptions, "image">;-const provider = defineLegacySandboxProvider<+/** Defines the Docker provider over `dockerCli`, the real `docker` CLI unless tests inject one. */+export function defineDockerSandboxProvider(+ dockerCli?: DockerCli,+): SandboxProvider<DockerSandboxEnvironmentOptions,DockerSandboxRuntimeOptions,- { readonly imageReference: string },- { readonly containerName: string; readonly version: 2 },DockerSandboxSession->({- name: "docker",- environment(options) {- return createDockerSandboxProvider(options);- },-});+> {+ return defineSandboxProvider({+ name: DOCKER_PROVIDER_NAME,+ environment: (options: DockerSandboxProviderOptions) =>+ createDockerSandboxProvider(options, dockerCli),+ });+}++const provider = defineDockerSandboxProvider();export const DockerSandbox = {...provider,