Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): share a parent sandbox with declared subagents (#2036)

Ruie8da57153c16
diff --git a/.changeset/fuzzy-pandas-share.md b/.changeset/fuzzy-pandas-share.md
new file mode 100644
index 000000000..92d550ba2
--- /dev/null
+++ b/.changeset/fuzzy-pandas-share.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Allow a child to return `parent.sandbox` from a `defineSandbox` callback, reusing the dispatching parent's live sandbox across agent sessions. Parent and child see the same files, processes, workspace, and sandbox home. A child that selects `parent.sandbox` cannot also declare managed workspace or skill resources; eve rejects that configuration before execution and requires either removing those resources or giving the child its own sandbox.
diff --git a/docs/sandbox.mdx b/docs/sandbox.mdx
index 4535b96e9..91a819633 100644
--- a/docs/sandbox.mdx
+++ b/docs/sandbox.mdx
@@ -116,6 +116,25 @@ export default defineSandbox({
`defineSandbox` and `defaultBackend` live on `eve/sandbox`. Omit `backend` and the runtime falls back to `defaultBackend()` (see [Backends](#backends)).
+### Sharing a parent's sandbox
+
+Sandbox definitions use two distinct forms. Pass an object to give an agent or subagent an independent sandbox. Passing a callback to `defineSandbox` opts a declared subagent into sharing: return `parent.sandbox` to select the dispatching agent's exact live sandbox. A raw function export remains a zero-argument definition factory.
+
+```ts title="agent/subagents/reviewer/sandbox.ts"
+import { defineSandbox } from "eve/sandbox";
+
+export default defineSandbox(({ parent }) => {
+ if (parent === null) throw new Error("reviewer must run as a child");
+ return parent.sandbox;
+});
+```
+
+The parent and child then see the same files, processes, `/workspace`, and sandbox home. Nested children that also select `parent.sandbox` keep using the same owning sandbox rather than creating another one. The owning sandbox's `bootstrap` and `onSession` hooks remain authoritative; the child cannot add its own sandbox hooks or backend configuration.
+
+An inheriting child must not declare managed files under its own `sandbox/workspace/` or `skills/` directories, including dynamic skills. Eve rejects that configuration before execution. Remove the child resources when the shared workspace is sufficient, or give the child its own sandbox when it needs independently seeded files or skills.
+
+The built-in `agent` self-delegation path continues to share the root agent's sandbox automatically.
+
## Backends
The backend decides where the sandbox runs. eve ships four pinned factories from nested `eve/sandbox/*` imports plus an availability-aware default from `eve/sandbox`:
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/agent.ts b/e2e/fixtures/agent-tools-sandbox/agent/agent.ts
index d3292ac9e..95fd9acdd 100644
--- a/e2e/fixtures/agent-tools-sandbox/agent/agent.ts
+++ b/e2e/fixtures/agent-tools-sandbox/agent/agent.ts
@@ -1,66 +1,6 @@
import { e2eAgentConfig } from "@eve-e2e/config";
import { defineAgent } from "eve";
-import type { MockModelRequest, MockModelResponse } from "eve/evals";
-
-const BASH_DIRECTIVE = /run the bash command `([^`]+)`/iu;
-const SKILL_DIRECTIVE = /load the `([^`]+)` skill/iu;
-
-/**
- * Scripted mock for the world suites: sandbox evals phrase every prompt as an
- * explicit directive, so the responder executes exactly the requested tool
- * and replies from its output. Turn state derives from the prompt: a tool
- * message after the latest user message means this turn's call already ran.
- */
-function respond(request: MockModelRequest): MockModelResponse | string {
- const message = request.lastUserMessage ?? "";
- const roles = request.messages.map((entry) => entry.role);
- const turnHasToolResult = roles.lastIndexOf("tool") > roles.lastIndexOf("user");
-
- const bash = BASH_DIRECTIVE.exec(message);
- if (bash?.[1] !== undefined) {
- if (!turnHasToolResult) {
- return { toolCalls: [{ input: { command: bash[1] }, name: "bash" }] };
- }
- if (/reply with the single word:\s*done/iu.test(message)) {
- return "done";
- }
- return bashStdout(request);
- }
-
- const skill = SKILL_DIRECTIVE.exec(message);
- if (skill?.[1] !== undefined) {
- if (!turnHasToolResult) {
- return { toolCalls: [{ input: { skill: skill[1] }, name: "load_skill" }] };
- }
- // Loaded skills instruct an exact reply whose text is the skill body's
- // final line (see the redeploy eval's deploy-note skill).
- return lastNonEmptyLine(formatOutput(request.toolResults.at(-1)?.output));
- }
-
- return `Mock reply: ${message}`;
-}
-
-function bashStdout(request: MockModelRequest): string {
- const output = [...request.toolResults]
- .reverse()
- .find((result) => result.name === "bash")?.output;
- if (typeof output === "object" && output !== null && "stdout" in output) {
- return String((output as { stdout: unknown }).stdout).trim();
- }
- return formatOutput(output);
-}
-
-function formatOutput(output: unknown): string {
- return typeof output === "string" ? output : JSON.stringify(output ?? "");
-}
-
-function lastNonEmptyLine(text: string): string {
- const lines = text
- .split("\n")
- .map((line) => line.trim())
- .filter((line) => line.length > 0);
- return lines.at(-1) ?? text;
-}
+import { respond } from "./lib/mock-responder.js";
export default defineAgent({
...e2eAgentConfig({ mock: respond }),
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts b/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts
new file mode 100644
index 000000000..31f64aef5
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts
@@ -0,0 +1,75 @@
+import type { MockModelRequest, MockModelResponse } from "eve/evals";
+
+const SUBAGENT_DIRECTIVE = /ask the `([^`]+)` subagent with message:\s*([\s\S]+)/iu;
+const BASH_DIRECTIVE = /run the bash command `([^`]+)`/iu;
+const SKILL_DIRECTIVE = /load the `([^`]+)` skill/iu;
+
+/**
+ * Scripted mock for the world suites: sandbox evals phrase every prompt as an
+ * explicit directive, so the responder executes exactly the requested tool
+ * and replies from its output. Turn state derives from the prompt: a tool
+ * message after the latest user message means this turn's call already ran.
+ */
+export function respond(request: MockModelRequest): MockModelResponse | string {
+ const message = request.lastUserMessage ?? "";
+ const roles = request.messages.map((entry) => entry.role);
+ const turnHasToolResult = roles.lastIndexOf("tool") > roles.lastIndexOf("user");
+
+ const subagent = SUBAGENT_DIRECTIVE.exec(message);
+ if (subagent?.[1] !== undefined && subagent[2] !== undefined) {
+ if (!turnHasToolResult) {
+ return { toolCalls: [{ input: { message: subagent[2] }, name: subagent[1] }] };
+ }
+ return toolOutput(request, subagent[1]);
+ }
+
+ const bash = BASH_DIRECTIVE.exec(message);
+ if (bash?.[1] !== undefined) {
+ if (!turnHasToolResult) {
+ return { toolCalls: [{ input: { command: bash[1] }, name: "bash" }] };
+ }
+ if (/reply with the single word:\s*done/iu.test(message)) {
+ return "done";
+ }
+ return bashStdout(request);
+ }
+
+ const skill = SKILL_DIRECTIVE.exec(message);
+ if (skill?.[1] !== undefined) {
+ if (!turnHasToolResult) {
+ return { toolCalls: [{ input: { skill: skill[1] }, name: "load_skill" }] };
+ }
+ // Loaded skills instruct an exact reply whose text is the skill body's
+ // final line (see the redeploy eval's deploy-note skill).
+ return lastNonEmptyLine(toolOutput(request, "load_skill"));
+ }
+
+ return `Mock reply: ${message}`;
+}
+
+function bashStdout(request: MockModelRequest): string {
+ const output = [...request.toolResults]
+ .reverse()
+ .find((result) => result.name === "bash")?.output;
+ if (typeof output === "object" && output !== null && "stdout" in output) {
+ return String((output as { stdout: unknown }).stdout).trim();
+ }
+ return formatOutput(output);
+}
+
+function toolOutput(request: MockModelRequest, name: string): string {
+ const output = [...request.toolResults].reverse().find((result) => result.name === name)?.output;
+ return formatOutput(output);
+}
+
+function formatOutput(output: unknown): string {
+ return typeof output === "string" ? output : JSON.stringify(output ?? "");
+}
+
+function lastNonEmptyLine(text: string): string {
+ const lines = text
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => line.length > 0);
+ return lines.at(-1) ?? text;
+}
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/agent.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/agent.ts
new file mode 100644
index 000000000..a49bb5fe6
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/agent.ts
@@ -0,0 +1,9 @@
+import { e2eSubagentConfig } from "@eve-e2e/config";
+import { defineAgent } from "eve";
+
+import { respond } from "../../lib/mock-responder.js";
+
+export default defineAgent({
+ description: "Runs sandbox commands in the root agent's shared workspace.",
+ ...e2eSubagentConfig({ mock: respond }),
+});
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/sandbox.ts
new file mode 100644
index 000000000..9deecea73
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/shared-sandbox/sandbox.ts
@@ -0,0 +1,6 @@
+import { defineSandbox } from "eve/sandbox";
+
+export default defineSandbox(({ parent }) => {
+ if (parent === null) throw new Error("shared-sandbox must run as a child");
+ return parent.sandbox;
+});
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/subagent-sharing.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/subagent-sharing.eval.ts
new file mode 100644
index 000000000..793532f83
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/subagent-sharing.eval.ts
@@ -0,0 +1,33 @@
+import { defineEval } from "eve/evals";
+import { includes } from "eve/evals/expect";
+
+const PARENT_TOKEN = "sandbox-parent-write-ok-N4K";
+const PARENT_PATH = "/workspace/parent-write.txt";
+const CHILD_TOKEN = "sandbox-child-write-ok-V8C";
+const CHILD_PATH = "/workspace/child-write.txt";
+
+export default defineEval({
+ description: "Sandbox: a declared child can share the parent's live workspace.",
+ async test(t) {
+ const parentWrite = await t.send(
+ `Run the bash command \`printf %s ${PARENT_TOKEN} > ${PARENT_PATH}\`. ` +
+ "Reply with the single word: done.",
+ );
+ parentWrite.expectOk();
+
+ const childTurn = await t.send(
+ `Ask the \`shared-sandbox\` subagent with message: ` +
+ `Run the bash command \`cat ${PARENT_PATH} && printf %s ${CHILD_TOKEN} > ${CHILD_PATH}\` ` +
+ "and reply with the command output verbatim.",
+ );
+ await t.require(childTurn.message, includes(PARENT_TOKEN));
+
+ const parentRead = await t.send(
+ `Run the bash command \`cat ${CHILD_PATH}\` and reply with the file contents verbatim.`,
+ );
+
+ t.succeeded();
+ t.calledSubagent("shared-sandbox", { output: new RegExp(PARENT_TOKEN) });
+ t.check(parentRead.message, includes(CHILD_TOKEN));
+ },
+});
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 7df110869..aaf7dea66 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -548,6 +548,7 @@ const compiledSandboxDefinitionSchema = z
*/
backendName: z.string().optional(),
description: z.string().optional(),
+ inheritsParent: z.boolean().optional(),
exportName: z.string().optional(),
logicalPath: z.string(),
revalidationKey: z.string().optional(),
diff --git a/packages/eve/src/compiler/normalize-helpers.ts b/packages/eve/src/compiler/normalize-helpers.ts
index 55fdb1387..315cc4931 100644
--- a/packages/eve/src/compiler/normalize-helpers.ts
+++ b/packages/eve/src/compiler/normalize-helpers.ts
@@ -12,6 +12,8 @@ import { toErrorMessage } from "#shared/errors.js";
import type { ModuleSourceRef } from "#shared/source-ref.js";
import type { CompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";
+const SANDBOX_PARENT_DEFINITION_MARKER = Symbol.for("eve.sandbox-parent-definition");
+
/**
* Shared compile-time context threaded through every per-primitive
* normalize step.
@@ -50,9 +52,24 @@ export async function loadModuleBackedDefinition(input: {
);
const exportValue = getAuthoredModuleExport(moduleNamespace, input.source);
+ // defineSandbox marks parent selectors so they remain distinguishable from
+ // zero-argument module factories without relying on JavaScript function arity.
+ if (
+ input.kind === "sandbox" &&
+ typeof exportValue === "function" &&
+ Reflect.get(exportValue, SANDBOX_PARENT_DEFINITION_MARKER) === true
+ ) {
+ return exportValue;
+ }
+
try {
return await materializeAuthoredModuleExport(exportValue);
} catch (error) {
+ if (input.kind === "sandbox" && typeof exportValue === "function") {
+ throw new Error(
+ `Failed to execute the sandbox export "${input.source.exportName ?? "default"}" from "${input.displayPath ?? input.source.logicalPath}" as a zero-argument definition factory. Parent-sharing callbacks must be passed to defineSandbox(...): ${toErrorMessage(error)}`,
+ );
+ }
throw new Error(
`Failed to execute the ${input.kind} export "${input.source.exportName ?? "default"}" from "${input.displayPath ?? input.source.logicalPath}": ${toErrorMessage(error)}`,
);
diff --git a/packages/eve/src/compiler/normalize-sandbox.scenario.test.ts b/packages/eve/src/compiler/normalize-sandbox.scenario.test.ts
new file mode 100644
index 000000000..9d4a10797
--- /dev/null
+++ b/packages/eve/src/compiler/normalize-sandbox.scenario.test.ts
@@ -0,0 +1,59 @@
+import { join } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import { compileAgentManifest } from "#compiler/normalize-manifest.js";
+import { discoverAgent } from "#discover/discover-agent.js";
+import { useScenarioApp } from "#internal/testing/scenario-app.js";
+
+describe("sandbox compilation", () => {
+ const scenarioApp = useScenarioApp();
+
+ it("preserves zero-argument sandbox definition factories", async () => {
+ const app = await scenarioApp({
+ files: {
+ "agent/sandbox.ts": "export default () => ({ description: 'factory sandbox' });\n",
+ },
+ name: "sandbox-definition-factory",
+ });
+
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+ const manifest = await compileAgentManifest(discovered.manifest);
+
+ expect(manifest.sandbox).toMatchObject({
+ description: "factory sandbox",
+ inheritsParent: undefined,
+ });
+ });
+
+ it("compiles managed child resources alongside the parent selector for runtime rejection", async () => {
+ const app = await scenarioApp({
+ files: {
+ "agent/subagents/foo/agent.ts":
+ "export default { description: 'foo', model: 'openai/gpt-5.4' };\n",
+ "agent/subagents/foo/description.md": "foo\n",
+ "agent/subagents/foo/sandbox/sandbox.ts": [
+ 'import { defineSandbox } from "eve/sandbox";',
+ "export default defineSandbox((...args) => args[0].parent.sandbox);",
+ "",
+ ].join("\n"),
+ "agent/subagents/foo/sandbox/workspace/bar.txt": "child seed\n",
+ },
+ installDependencies: true,
+ name: "inherited-sandbox-child-resources",
+ });
+
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+ const manifest = await compileAgentManifest(discovered.manifest);
+ expect(manifest.subagents[0]?.agent).toMatchObject({
+ sandbox: { inheritsParent: true },
+ workspaceResourceRoot: { rootEntries: ["bar.txt"] },
+ });
+ });
+});
diff --git a/packages/eve/src/compiler/normalize-sandbox.test.ts b/packages/eve/src/compiler/normalize-sandbox.test.ts
new file mode 100644
index 000000000..5c740a40c
--- /dev/null
+++ b/packages/eve/src/compiler/normalize-sandbox.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+
+import { resolveParentSandboxSelector } from "#compiler/normalize-sandbox.js";
+import { defineSandbox } from "#public/definitions/sandbox.js";
+
+describe("resolveParentSandboxSelector", () => {
+ it("recognizes a callback that returns parent.sandbox", async () => {
+ const selector = ({ parent }: { parent: { sandbox: unknown } }) => parent.sandbox;
+
+ await expect(resolveParentSandboxSelector(selector, "invalid sandbox")).resolves.toBe(true);
+ });
+
+ it("supports marked rest-parameter callbacks without relying on function arity", async () => {
+ const selector = defineSandbox((...args) => {
+ if (args[0].parent === null) throw new Error("parent required");
+ return args[0].parent.sandbox;
+ });
+
+ expect(selector.length).toBe(0);
+ await expect(resolveParentSandboxSelector(selector, "invalid sandbox")).resolves.toBe(true);
+ });
+
+ it("rejects callbacks that return anything else", async () => {
+ await expect(
+ resolveParentSandboxSelector((_context: unknown) => ({ nope: true }), "invalid sandbox"),
+ ).rejects.toThrow(
+ "The callback passed to defineSandbox(...) must return parent.sandbox. Export a sandbox definition object for an independent sandbox.",
+ );
+ });
+
+ it("reports authored callback errors", async () => {
+ await expect(
+ resolveParentSandboxSelector(() => {
+ throw new Error("authored failure");
+ }, "invalid sandbox"),
+ ).rejects.toThrow(
+ "The callback passed to defineSandbox(...) threw while selecting parent.sandbox: authored failure",
+ );
+ });
+
+ it("leaves object definitions unchanged", async () => {
+ await expect(resolveParentSandboxSelector({}, "invalid sandbox")).resolves.toBe(false);
+ });
+});
diff --git a/packages/eve/src/compiler/normalize-sandbox.ts b/packages/eve/src/compiler/normalize-sandbox.ts
index ed8e5f8b4..9311ab39f 100644
--- a/packages/eve/src/compiler/normalize-sandbox.ts
+++ b/packages/eve/src/compiler/normalize-sandbox.ts
@@ -21,15 +21,14 @@ export async function compileSandboxDefinition(
options: ModuleBackedDefinitionLoadOptions = {},
): Promise<CompiledSandboxDefinition> {
const message = `Expected the sandbox export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`;
- const normalized = normalizeSandboxDefinition(
- await loadModuleBackedDefinition({
- agentRoot,
- externalDependencies: options.externalDependencies,
- kind: "sandbox",
- source,
- }),
- message,
- );
+ const loaded = await loadModuleBackedDefinition({
+ agentRoot,
+ externalDependencies: options.externalDependencies,
+ kind: "sandbox",
+ source,
+ });
+ const inheritsParent = await resolveParentSandboxSelector(loaded, message);
+ const normalized = normalizeSandboxDefinition(inheritsParent ? {} : loaded, message);
const revalidationKey =
normalized.revalidationKey === undefined
? undefined
@@ -42,6 +41,7 @@ export async function compileSandboxDefinition(
return {
backendName: resolveCompiledBackendName(normalized.backend),
description: normalized.description,
+ inheritsParent: inheritsParent || undefined,
exportName: source.exportName,
logicalPath: source.logicalPath,
revalidationKey,
@@ -59,6 +59,33 @@ export async function compileSandboxDefinition(
* fails at runtime, where the error surfaces with full context) and
* simply leaves the name unrecorded.
*/
+const PARENT_SANDBOX_VALUE = Object.freeze({ __eveSandboxParentValue: Symbol("parent") });
+
+export async function resolveParentSandboxSelector(
+ value: unknown,
+ message: string,
+): Promise<boolean> {
+ if (typeof value !== "function") {
+ return false;
+ }
+
+ let selected: unknown;
+ try {
+ selected = await value({ parent: { sandbox: PARENT_SANDBOX_VALUE } });
+ } catch (error) {
+ throw new Error(
+ `${message} The callback passed to defineSandbox(...) threw while selecting parent.sandbox: ${toErrorMessage(error)}`,
+ );
+ }
+
+ if (selected !== PARENT_SANDBOX_VALUE) {
+ throw new Error(
+ `${message} The callback passed to defineSandbox(...) must return parent.sandbox. Export a sandbox definition object for an independent sandbox.`,
+ );
+ }
+ return true;
+}
+
function resolveCompiledBackendName(
backend: { readonly name: string } | undefined,
): string | undefined {
diff --git a/packages/eve/src/context/providers/sandbox.test.ts b/packages/eve/src/context/providers/sandbox.test.ts
index ca3e7acf7..e1a77bcd0 100644
--- a/packages/eve/src/context/providers/sandbox.test.ts
+++ b/packages/eve/src/context/providers/sandbox.test.ts
@@ -64,6 +64,28 @@ describe("sandboxProvider", () => {
});
});
+ it("uses explicit sharing metadata for self-delegation even without inheritsParent", async () => {
+ const ctx = new ContextContainer();
+ const registry: RuntimeSandboxRegistry = createStubSandboxRegistry();
+ const parentSandboxState = { initialized: true, session: null };
+
+ ctx.set(BundleKey, createBundle({ agentName: "weather-agent", registry }));
+ ctx.set(ChannelKey, {
+ kind: "subagent",
+ state: { parentSandboxState, sandboxSessionId: "root-sandbox-session" },
+ });
+ ctx.set(SessionIdKey, "self-child-session");
+
+ await sandboxProvider.create(ctx, createHarnessSession());
+
+ expect(ensureSandboxAccess).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sessionId: "root-sandbox-session",
+ state: parentSandboxState,
+ }),
+ );
+ });
+
it("tags sandbox backend resources with agent, channel, and session id", async () => {
const ctx = new ContextContainer();
const registry: RuntimeSandboxRegistry = createStubSandboxRegistry();
diff --git a/packages/eve/src/context/providers/sandbox.ts b/packages/eve/src/context/providers/sandbox.ts
index e1167250b..22ab89366 100644
--- a/packages/eve/src/context/providers/sandbox.ts
+++ b/packages/eve/src/context/providers/sandbox.ts
@@ -24,8 +24,11 @@ export const sandboxProvider: FrameworkContextProvider<SandboxAccess> = {
const sessionId = ctx.require(SessionIdKey);
const channel = ctx.get(ChannelKey);
const adapterState = channel?.state as Record<string, unknown> | undefined;
- const sandboxSessionId = (adapterState?.sandboxSessionId as string | undefined) ?? sessionId;
const parentSandboxState = adapterState?.parentSandboxState as SandboxState | undefined;
+ const inheritsParent = registry.sandbox?.definition.inheritsParent === true;
+ const sharedSandboxSessionId = adapterState?.sandboxSessionId as string | undefined;
+ const sharesSandbox = inheritsParent || sharedSandboxSessionId !== undefined;
+ const sandboxSessionId = sharesSandbox ? (sharedSandboxSessionId ?? sessionId) : sessionId;
return {
value: await ensureSandboxAccess({
@@ -34,7 +37,7 @@ export const sandboxProvider: FrameworkContextProvider<SandboxAccess> = {
registry,
runOnSession: async (callback) => await contextStorage.run(ctx, callback),
sessionId: sandboxSessionId,
- state: session.sandboxState ?? parentSandboxState ?? null,
+ state: session.sandboxState ?? (sharesSandbox ? parentSandboxState : undefined) ?? null,
tags: {
agent: resolveTagAgentName({ bundle, node }),
channel: resolveTagChannelKind(channel),
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
index 0d197f315..bc77f7a79 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
@@ -18,7 +18,9 @@ import {
CapabilitiesKey,
ChannelInstrumentationKey,
InitiatorAuthKey,
+ SandboxKey,
} from "#context/keys.js";
+import { withContextScope } from "#context/run-step.js";
import {
BundleKey,
ChannelKey,
@@ -152,6 +154,7 @@ export interface PreparedRuntimeActionDispatch {
readonly fanoutSize: number;
readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly sandboxSessionId: string;
readonly serializedContext: Record<string, unknown>;
readonly plan: readonly DispatchPlanEntry[];
readonly session: RuntimeSession;
@@ -183,7 +186,7 @@ export async function prepareRuntimeActionDispatch(input: {
const ctx = await deserializeContext(input.serializedContext);
const bundle = ctx.require(BundleKey);
const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);
- const session = hydrateDurableSession({
+ let session = hydrateDurableSession({
compactionOverrides: {
thresholdPercent: effectiveAgent.thresholdPercent,
},
@@ -192,9 +195,8 @@ export async function prepareRuntimeActionDispatch(input: {
});
const adapter = ctx.require(ChannelKey);
- // A corrupt handle store throws; surface that before anything dispatches.
- // A mid-loop throw after a sibling started would durably replay the whole
- // batch and re-dispatch that sibling.
+ // A corrupt handle store and rejected actions must resolve before sandbox
+ // initialization, which can provision backend resources and run onSession.
getAgentHandleStore(durableSession.state);
const plan = planDispatch({
actions: batch.actions,
@@ -204,6 +206,19 @@ export async function prepareRuntimeActionDispatch(input: {
taskControls: input.taskControls,
});
+ const sandboxSessionId = resolveActiveSandboxSessionId(adapter.state, session.sessionId);
+ if (planSharesSandbox({ bundle, plan })) {
+ try {
+ const scoped = await withContextScope(ctx, session, async (enrichedSession) => {
+ await ctx.require(SandboxKey).get();
+ return { result: undefined, session: enrichedSession };
+ });
+ session = scoped.session;
+ } finally {
+ ctx.clearVirtualContext();
+ }
+ }
+
return {
adapter,
adapterCtx: buildAdapterContext(adapter, ctx),
@@ -217,11 +232,37 @@ export async function prepareRuntimeActionDispatch(input: {
initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,
parentTraceContext: readSessionTraceContext(input.serializedContext, session.sessionId),
plan,
+ sandboxSessionId,
serializedContext: input.serializedContext,
session,
};
}
+function planSharesSandbox(input: {
+ readonly bundle: CompiledBundle;
+ readonly plan: readonly DispatchPlanEntry[];
+}): boolean {
+ const graph = (input.bundle as Partial<CompiledBundle>).graph;
+ return input.plan.some((entry) => {
+ if (entry.kind !== "start" || entry.target.kind !== "local") return false;
+ const action = entry.target.action;
+ const isSelfDelegation =
+ action.subagentName === "agent" &&
+ !input.bundle.subagentRegistry.subagentsByNodeId.has(action.nodeId);
+ return (
+ isSelfDelegation ||
+ graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox.definition.inheritsParent ===
+ true
+ );
+ });
+}
+
+function resolveActiveSandboxSessionId(adapterState: unknown, sessionId: string): string {
+ if (typeof adapterState !== "object" || adapterState === null) return sessionId;
+ const value = (adapterState as Record<string, unknown>).sandboxSessionId;
+ return typeof value === "string" && value.length > 0 ? value : sessionId;
+}
+
/**
* Emits the parent `subagent.called` control-plane event for one adopted
* child. Emission is observability, not control flow: a failure is logged
@@ -454,6 +495,7 @@ export async function startSubagent(input: {
readonly parentContinuationToken: string | undefined;
readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
readonly persistentSessions: boolean;
+ readonly sandboxSessionId: string;
readonly serializedContext: Record<string, unknown>;
readonly session: RuntimeSession;
readonly taskOwned: boolean;
@@ -483,6 +525,7 @@ export async function startSubagent(input: {
parentContinuationToken: input.parentContinuationToken,
parentTraceContext,
persistentSessions: input.persistentSessions,
+ sandboxSessionId: input.sandboxSessionId,
session: input.session,
source: input.target.source,
taskOwned: input.taskOwned,
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
index caedd2803..1cd1f12d9 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ChannelAdapter } from "#channel/adapter.js";
+import { ContextContainer, loadContext } from "#context/container.js";
import { RemoteAgentContinueRequestError } from "#execution/remote-agent-dispatch.js";
import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
@@ -26,8 +27,18 @@ import {
CapabilitiesKey,
ChannelInstrumentationKey,
InitiatorAuthKey,
+ SessionIdKey,
+ SessionKey,
} from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import type {
+ SandboxBackend,
+ SandboxBackendCreateInput,
+} from "#public/definitions/sandbox-backend.js";
+import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
+import type { ResolvedSandboxDefinition } from "#runtime/types.js";
+import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
const mocks = vi.hoisted(() => ({
continueRemoteAgentSession: vi.fn(),
@@ -233,6 +244,125 @@ describe("dispatchRuntimeActionsStep child starts", () => {
expect(writes).toHaveLength(1);
});
+ it("opens a shared parent sandbox with session context and durable backend tags", async () => {
+ const session = createStartSession({ kind: "local" });
+ const observedSessionIds: string[] = [];
+ const { backend, create } = createSandboxBackend();
+ const registry = createSandboxRegistry(backend, ({ ctx }) => {
+ observedSessionIds.push(ctx.session.id, loadContext().require(SessionKey).sessionId);
+ });
+ installSandboxContext({
+ child: { inheritsParent: true, name: "research", nodeId: "subagents/research" },
+ registry,
+ session,
+ });
+
+ await dispatchRuntimeActionsStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(observedSessionIds).toEqual(["parent-session", "parent-session"]);
+ expect(create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tags: {
+ agent: "parent-agent",
+ channel: "channel:test",
+ sessionId: "parent-session",
+ },
+ }),
+ );
+ expect(mocks.createSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ adapter: expect.objectContaining({
+ state: expect.objectContaining({
+ parentSandboxState: expect.objectContaining({ initialized: true }),
+ sandboxSessionId: "parent-session",
+ }),
+ }),
+ }),
+ );
+ });
+
+ it("opens a shared parent sandbox for a background-task child", async () => {
+ const session = createStartSession({ kind: "local" });
+ const { backend, create } = createSandboxBackend();
+ installSandboxContext({
+ child: { inheritsParent: true, name: "research", nodeId: "subagents/research" },
+ registry: createSandboxRegistry(backend),
+ session,
+ });
+ vi.spyOn(taskRunControl, "sendTaskCommandToOwner").mockResolvedValue({ runId: "task-run-1" });
+
+ await dispatchTaskStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(create).toHaveBeenCalledTimes(1);
+ expect(mocks.createSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ adapter: expect.objectContaining({
+ state: expect.objectContaining({ sandboxSessionId: "parent-session" }),
+ }),
+ mode: "conversation",
+ }),
+ );
+ });
+
+ it("does not open the parent sandbox for a declared subagent named agent", async () => {
+ const session = createNamedStartSession({
+ name: "agent",
+ nodeId: "subagents/agent",
+ });
+ const { backend, create } = createSandboxBackend();
+ installSandboxContext({
+ child: { inheritsParent: false, name: "agent", nodeId: "subagents/agent" },
+ registry: createSandboxRegistry(backend),
+ session,
+ });
+
+ await dispatchRuntimeActionsStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(create).not.toHaveBeenCalled();
+ expect(mocks.createSession).toHaveBeenCalledTimes(1);
+ });
+
+ it("rejects recursive self-delegation before opening the parent sandbox", async () => {
+ const session = createNamedStartSession({
+ name: "agent",
+ nodeId: "__root__",
+ session: { rootSessionId: "root-session", subagentDepth: 1 },
+ });
+ const { backend, create } = createSandboxBackend();
+ installSandboxContext({ registry: createSandboxRegistry(backend), session });
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ const result = await dispatchRuntimeActionsStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(result.results).toEqual([
+ expect.objectContaining({
+ output: expect.objectContaining({ code: "RECURSIVE_AGENT_ROOT_ONLY" }),
+ }),
+ ]);
+ expect(create).not.toHaveBeenCalled();
+ expect(mocks.createSession).not.toHaveBeenCalled();
+ });
+
it("records a tasks-mode child as an address and derives task identity separately", async () => {
const session = createStartSession({ kind: "local" });
installContext(
@@ -992,6 +1122,29 @@ function createStartSession(input: {
});
}
+function createNamedStartSession(input: {
+ readonly name: string;
+ readonly nodeId: string;
+ readonly session?: Partial<HarnessSession>;
+}): HarnessSession {
+ return setPendingRuntimeActionBatch({
+ actions: [
+ {
+ callId: "call-1",
+ description: `Delegate to ${input.name}`,
+ input: { message: "research this" },
+ kind: "subagent-call",
+ name: input.name,
+ nodeId: input.nodeId,
+ subagentName: input.name,
+ },
+ ],
+ event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },
+ responseMessages: [],
+ session: { ...createBaseSession(), ...input.session },
+ });
+}
+
function createPendingSession(input: {
readonly handle?: AgentHandle;
readonly agentId: string | null;
@@ -1054,6 +1207,93 @@ function installContext(
mocks.readDurableSession.mockResolvedValue(session);
}
+function createSandboxBackend() {
+ const sandbox = mockSandbox({ id: "shared-parent-sandbox" });
+ const create = vi.fn(async (input: SandboxBackendCreateInput) => ({
+ captureState: async () => ({
+ backendName: "test",
+ metadata: {},
+ sessionKey: input.sessionKey,
+ }),
+ session: sandbox.session,
+ shutdown: async () => {},
+ stop: async () => {},
+ useSessionFn: async () => sandbox.session,
+ }));
+ return {
+ backend: { create, name: "test", prewarm: vi.fn(async () => ({ reused: false })) },
+ create,
+ };
+}
+
+function createSandboxRegistry(
+ backend: SandboxBackend,
+ onSession?: ResolvedSandboxDefinition["onSession"],
+): RuntimeSandboxRegistry {
+ return {
+ sandbox: {
+ definition: {
+ backend,
+ logicalPath: "agent/sandbox.ts",
+ onSession,
+ sourceId: "agent/sandbox",
+ sourceKind: "module",
+ },
+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
+ },
+ };
+}
+
+function installSandboxContext(input: {
+ readonly child?: {
+ readonly inheritsParent: boolean;
+ readonly name: string;
+ readonly nodeId: string;
+ };
+ readonly registry: RuntimeSandboxRegistry;
+ readonly session: HarnessSession;
+}): void {
+ const root = {
+ agent: { config: { name: "parent-agent" }, connections: [] },
+ nodeId: "__root__",
+ sandboxRegistry: input.registry,
+ turnAgent: input.session.agent,
+ };
+ const nodesByNodeId = new Map<string, unknown>([["__root__", root]]);
+ const subagentsByNodeId = new Map<string, unknown>();
+ if (input.child !== undefined) {
+ nodesByNodeId.set(input.child.nodeId, {
+ sandboxRegistry: {
+ sandbox: {
+ definition: { inheritsParent: input.child.inheritsParent },
+ },
+ },
+ });
+ subagentsByNodeId.set(input.child.nodeId, {
+ definition: {
+ description: `Delegate to ${input.child.name}`,
+ kind: "subagent",
+ },
+ });
+ }
+
+ const ctx = new ContextContainer();
+ ctx.set(AuthKey, null);
+ ctx.set(InitiatorAuthKey, null);
+ ctx.set(SessionIdKey, input.session.sessionId);
+ ctx.set(ChannelKey, ADAPTER);
+ ctx.set(BundleKey, {
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ graph: { nodesByNodeId, root },
+ resolvedAgent: { config: {} },
+ subagentRegistry: { subagentsByNodeId },
+ turnAgent: input.session.agent,
+ } as never);
+
+ mocks.deserializeContext.mockResolvedValue(ctx);
+ mocks.readDurableSession.mockResolvedValue(input.session);
+}
+
function createWritable(writes: Uint8Array[] = []): WritableStream<Uint8Array> {
return new WritableStream({
write(chunk) {
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index b5d2bd6ba..0227b410d 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -92,6 +92,7 @@ export async function dispatchRuntimeActionsStep(
parentContinuationToken: input.parentContinuationToken,
parentTraceContext: prepared.parentTraceContext,
persistentSessions,
+ sandboxSessionId: prepared.sandboxSessionId,
serializedContext: prepared.serializedContext,
session,
taskOwned: false,
diff --git a/packages/eve/src/execution/sandbox/bindings/docker-cli.test.ts b/packages/eve/src/execution/sandbox/bindings/docker-cli.test.ts
new file mode 100644
index 000000000..5f76a16b3
--- /dev/null
+++ b/packages/eve/src/execution/sandbox/bindings/docker-cli.test.ts
@@ -0,0 +1,36 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { spawnSync } = vi.hoisted(() => ({ spawnSync: vi.fn() }));
+
+vi.mock("node:child_process", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("node:child_process")>()),
+ spawnSync,
+}));
+
+describe("isLinuxDockerDaemonAvailableSync", () => {
+ beforeEach(() => {
+ spawnSync.mockReset();
+ vi.resetModules();
+ });
+
+ it("accepts a reachable Linux-container daemon", async () => {
+ spawnSync.mockReturnValue({ status: 0, stdout: "linux\n" });
+
+ const { isLinuxDockerDaemonAvailableSync } = await import("./docker-cli.js");
+
+ expect(isLinuxDockerDaemonAvailableSync()).toBe(true);
+ });
+
+ it("rejects a reachable Windows-container daemon", async () => {
+ spawnSync.mockReturnValue({ status: 0, stdout: "windows\n" });
+
+ const { isLinuxDockerDaemonAvailableSync } = await import("./docker-cli.js");
+
+ expect(isLinuxDockerDaemonAvailableSync()).toBe(false);
+ expect(spawnSync).toHaveBeenCalledWith("docker", ["version", "--format", "{{.Server.Os}}"], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ timeout: 5_000,
+ });
+ });
+});
diff --git a/packages/eve/src/execution/sandbox/bindings/docker-cli.ts b/packages/eve/src/execution/sandbox/bindings/docker-cli.ts
index 52862f368..4120d24a2 100644
--- a/packages/eve/src/execution/sandbox/bindings/docker-cli.ts
+++ b/packages/eve/src/execution/sandbox/bindings/docker-cli.ts
@@ -104,27 +104,29 @@ function resolveDockerExecutable(): string {
return fromEnv !== undefined && fromEnv.length > 0 ? fromEnv : "docker";
}
-let cachedDockerAvailability: boolean | undefined;
+let cachedLinuxDockerAvailability: boolean | undefined;
/**
- * Synchronously probes whether a Docker daemon is reachable, for
- * `defaultSandbox()`'s availability chain. The result is cached for the
- * process lifetime: backend selection must be stable, and the probe
- * costs a subprocess round-trip.
+ * Synchronously probes whether a reachable Docker daemon runs Linux
+ * containers, for `defaultSandbox()`'s availability chain. eve's Docker
+ * sandbox image is Linux-only, so a Windows-container daemon is not a
+ * compatible default even though it answers the Docker CLI. The result is
+ * cached for the process lifetime: backend selection must be stable, and
+ * the probe costs a subprocess round-trip.
*/
-export function isDockerDaemonAvailableSync(): boolean {
- cachedDockerAvailability ??= probeDockerDaemonSync();
- return cachedDockerAvailability;
+export function isLinuxDockerDaemonAvailableSync(): boolean {
+ cachedLinuxDockerAvailability ??= probeLinuxDockerDaemonSync();
+ return cachedLinuxDockerAvailability;
}
-function probeDockerDaemonSync(): boolean {
+function probeLinuxDockerDaemonSync(): boolean {
try {
- const result = spawnSync(
- resolveDockerExecutable(),
- ["version", "--format", "{{.Server.Version}}"],
- { stdio: "ignore", timeout: 5_000 },
- );
- return result.status === 0;
+ const result = spawnSync(resolveDockerExecutable(), ["version", "--format", "{{.Server.Os}}"], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ timeout: 5_000,
+ });
+ return result.status === 0 && result.stdout.trim().toLowerCase() === "linux";
} catch {
return false;
}
diff --git a/packages/eve/src/execution/sandbox/bindings/local.ts b/packages/eve/src/execution/sandbox/bindings/local.ts
index b4c30f5f5..5aa561e45 100644
--- a/packages/eve/src/execution/sandbox/bindings/local.ts
+++ b/packages/eve/src/execution/sandbox/bindings/local.ts
@@ -21,7 +21,7 @@ export {
DOCKER_BACKEND_NAME,
pruneDockerSandboxTemplates,
} from "#execution/sandbox/bindings/docker.js";
-export { isDockerDaemonAvailableSync } from "#execution/sandbox/bindings/docker-cli.js";
+export { isLinuxDockerDaemonAvailableSync } from "#execution/sandbox/bindings/docker-cli.js";
export {
createJustBashSandboxBackend,
JUST_BASH_BACKEND_NAME,
diff --git a/packages/eve/src/execution/sandbox/ensure.test.ts b/packages/eve/src/execution/sandbox/ensure.test.ts
index 28a3c181e..78987a02f 100644
--- a/packages/eve/src/execution/sandbox/ensure.test.ts
+++ b/packages/eve/src/execution/sandbox/ensure.test.ts
@@ -346,6 +346,39 @@ describe("ensureSandboxAccess", () => {
);
});
+ it("derives an inherited sandbox from the parent owner identity", async () => {
+ const parentBackend = createBackend();
+ const childBackend = createBackend();
+ const registry = createTestRegistry({ inheritsParent: true }, childBackend);
+ const parentDefinition: ResolvedSandboxDefinition = {
+ backend: parentBackend,
+ logicalPath: "agent/sandbox.ts",
+ sourceHash: "parent-source-hash",
+ sourceId: "agent/sandbox",
+ sourceKind: "module",
+ };
+ const inheritedRegistry: RuntimeSandboxRegistry = {
+ sandbox: {
+ ...registry.sandbox,
+ inheritance: {
+ definition: parentDefinition,
+ nodeId: "__root__",
+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
+ },
+ },
+ };
+
+ const access = await ensure({ registry: inheritedRegistry });
+ await access.get();
+
+ expect(childBackend.create).not.toHaveBeenCalled();
+ expect(parentBackend.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sessionKey: expect.stringContaining("session_1-__root__"),
+ }),
+ );
+ });
+
it("passes runtime tags to the sandbox backend", async () => {
const backend = createBackend();
const registry = createTestRegistry({}, backend);
diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.ts
index db42c96a3..51e6a5e1c 100644
--- a/packages/eve/src/execution/sandbox/ensure.ts
+++ b/packages/eve/src/execution/sandbox/ensure.ts
@@ -68,17 +68,18 @@ export async function ensureSandboxAccess(input: EnsureSandboxAccessInput): Prom
if (registered === null) {
return null;
}
- const definition = registered.definition;
+ const inheritance = registered.inheritance;
+ const definition = inheritance?.definition ?? registered.definition;
const backend = definition.backend;
const templatePlan = createRuntimeSandboxTemplatePlan({
definition,
- workspaceResourceRoot: registered.workspaceResourceRoot,
+ workspaceResourceRoot: inheritance?.workspaceResourceRoot ?? registered.workspaceResourceRoot,
});
const keys = await createRuntimeSandboxKeys({
backendName: backend.name,
compiledArtifactsSource: input.compiledArtifactsSource,
- nodeId: input.nodeId,
+ nodeId: inheritance?.nodeId ?? input.nodeId,
sessionId: input.sessionId,
sourceId: definition.sourceId,
templatePlan,
@@ -178,7 +179,8 @@ export async function ensureSandboxAccess(input: EnsureSandboxAccessInput): Prom
},
async get(): Promise<SandboxSession | null> {
const handle = await getHandle();
- return handle?.session ?? null;
+ if (handle === null) return null;
+ return handle.session;
},
async stop(): Promise<void> {
const handle = await getHandle();
diff --git a/packages/eve/src/execution/sandbox/prewarm.test.ts b/packages/eve/src/execution/sandbox/prewarm.test.ts
index 182029f31..9f4338792 100644
--- a/packages/eve/src/execution/sandbox/prewarm.test.ts
+++ b/packages/eve/src/execution/sandbox/prewarm.test.ts
@@ -14,12 +14,20 @@ vi.mock("#execution/sandbox/template-prewarm-lock.js", () => ({
withSandboxTemplatePrewarmLock: async (_input: unknown, callback: () => Promise<unknown>) =>
await callback(),
}));
+const mocks = vi.hoisted(() => ({
+ materializeWorkspaceDirectory: vi.fn<
+ (path: string) => Promise<readonly { readonly content: Buffer; readonly path: string }[]>
+ >(async () => []),
+}));
+
vi.mock("#runtime/workspace/seed-files.js", () => ({
- materializeWorkspaceDirectory: vi.fn(async () => []),
+ materializeWorkspaceDirectory: mocks.materializeWorkspaceDirectory,
}));
describe("prewarmAppSandboxes", () => {
afterEach(() => {
+ mocks.materializeWorkspaceDirectory.mockReset();
+ mocks.materializeWorkspaceDirectory.mockResolvedValue([]);
vi.unstubAllEnvs();
});
diff --git a/packages/eve/src/execution/sandbox/prewarm.ts b/packages/eve/src/execution/sandbox/prewarm.ts
index 0a08204d4..37bbced8b 100644
--- a/packages/eve/src/execution/sandbox/prewarm.ts
+++ b/packages/eve/src/execution/sandbox/prewarm.ts
@@ -308,10 +308,7 @@ async function loadResourceRootSeedFiles(input: {
const materialized = await materializeWorkspaceDirectory(
`${input.compileDirectoryPath}/${input.workspaceResourceRoot.logicalPath}`,
);
- return materialized.map((file) => ({
- content: file.content,
- path: file.path,
- }));
+ return materialized.map((file) => ({ content: file.content, path: file.path }));
}
async function loadGraphFromArtifacts(input: {
@@ -335,7 +332,7 @@ async function loadGraphFromArtifacts(input: {
function collectNodeSandboxes(graph: ResolvedAgentGraphBundle): readonly NodeSandbox[] {
return [...graph.nodesByNodeId.entries()].flatMap(([nodeId, node]) => {
const registered = node.sandboxRegistry.sandbox;
- return registered === null ? [] : [{ ...registered, nodeId }];
+ return registered.definition.inheritsParent === true ? [] : [{ ...registered, nodeId }];
});
}
diff --git a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
index a5a9300c0..91a8e3828 100644
--- a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
@@ -173,7 +173,9 @@ describe("session-limit continuation decline integration", () => {
// result, reaches its own pre-model gate, and parks on its OWN
// continuation prompt.
const hitlTurn = await stream.nextTurn();
- expect(hitlTurn.at(-1)?.type).toBe("session.waiting");
+ expect(hitlTurn.at(-1)?.type, JSON.stringify(hitlTurn.at(-1), null, 2)).toBe(
+ "session.waiting",
+ );
expect(filterEventsByType(hitlTurn, "subagent.called")).toHaveLength(1);
expect(filterEventsByType(hitlTurn, "input.requested")).toHaveLength(1);
const requestId = requestIdFromPromptTurn(hitlTurn);
diff --git a/packages/eve/src/execution/subagent-start-local.ts b/packages/eve/src/execution/subagent-start-local.ts
index 7d184d43f..63cbdd15e 100644
--- a/packages/eve/src/execution/subagent-start-local.ts
+++ b/packages/eve/src/execution/subagent-start-local.ts
@@ -36,6 +36,7 @@ export async function startLocalSubagent(input: {
readonly parentContinuationToken: string | undefined;
readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
readonly persistentSessions: boolean;
+ readonly sandboxSessionId: string;
readonly session: RuntimeSession;
readonly source: SubagentInputSource;
readonly taskOwned: boolean;
@@ -54,9 +55,11 @@ export async function startLocalSubagent(input: {
channelMetadata: input.channelMetadata,
fanoutSize: input.fanoutSize,
initiatorAuth: input.initiatorAuth,
+ graph: input.bundle.graph,
parentContinuationToken: input.parentContinuationToken,
parentTraceContext: input.parentTraceContext,
persistentSessions: input.persistentSessions,
+ sandboxSessionId: input.sandboxSessionId,
session: input.session,
source,
});
diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/execution/subagent-tool.test.ts
index f6e95a6a2..b999f34a1 100644
--- a/packages/eve/src/execution/subagent-tool.test.ts
+++ b/packages/eve/src/execution/subagent-tool.test.ts
@@ -39,6 +39,14 @@ function buildRuntimeSubagentRunInput(
return buildSubagentRunInput({ ...input, source: { type: "runtime" } });
}
+function makeInheritingGraph(nodeId: string) {
+ return {
+ nodesByNodeId: new Map([
+ [nodeId, { sandboxRegistry: { sandbox: { definition: { inheritsParent: true } } } }],
+ ]),
+ };
+}
+
describe("buildSubagentRunInput", () => {
it("forwards parent capabilities to the child run input", () => {
const { runInput } = buildRuntimeSubagentRunInput({
@@ -336,18 +344,51 @@ describe("buildSubagentRunInput", () => {
});
});
- it("does not include sandbox sharing fields for normal subagents", () => {
+ it("carries parent sandbox state for declared subagents that opt into sharing", () => {
const sandboxState = { initialized: true, session: null };
const session = { ...makeSession(), sandboxState };
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
batchEvent: { sequence: 0, turnId: "turn-0" },
+ graph: makeInheritingGraph(makeAction().nodeId),
initiatorAuth: null,
session,
});
+ expect(runInput.adapter.state).toMatchObject({
+ parentSandboxState: sandboxState,
+ sandboxSessionId: "parent-session",
+ });
+ });
+
+ it("preserves the root sandbox identity through nested inheritance", () => {
+ const { runInput } = buildRuntimeSubagentRunInput({
+ action: makeAction(),
+ auth: null,
+ batchEvent: { sequence: 0, turnId: "turn-0" },
+ graph: makeInheritingGraph(makeAction().nodeId),
+ initiatorAuth: null,
+ sandboxSessionId: "root-sandbox-session",
+ session: { ...makeSession(), sessionId: "intermediate-child-session" },
+ });
+
+ expect(runInput.adapter.state).toMatchObject({
+ sandboxSessionId: "root-sandbox-session",
+ });
+ });
+
+ it("carries the parent session id before the inherited sandbox has been opened", () => {
+ const { runInput } = buildRuntimeSubagentRunInput({
+ action: makeAction(),
+ auth: null,
+ batchEvent: { sequence: 0, turnId: "turn-0" },
+ graph: makeInheritingGraph(makeAction().nodeId),
+ initiatorAuth: null,
+ session: makeSession(),
+ });
+
+ expect(runInput.adapter.state).toMatchObject({ sandboxSessionId: "parent-session" });
expect(runInput.adapter.state).not.toHaveProperty("parentSandboxState");
- expect(runInput.adapter.state).not.toHaveProperty("sandboxSessionId");
});
});
diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.ts
index 5c2645f7a..a4887a304 100644
--- a/packages/eve/src/execution/subagent-tool.ts
+++ b/packages/eve/src/execution/subagent-tool.ts
@@ -46,6 +46,23 @@ export interface SubagentRunInputBuild {
readonly runInput: RunInput;
}
+/**
+ * Runtime graph shape needed to answer sandbox-inheritance questions for
+ * one declared child node. Partial test bundles may omit the graph.
+ */
+export interface SubagentSandboxGraph {
+ readonly nodesByNodeId: ReadonlyMap<
+ string,
+ {
+ readonly sandboxRegistry: {
+ readonly sandbox: {
+ readonly definition: { readonly inheritsParent?: boolean };
+ } | null;
+ };
+ }
+ >;
+}
+
/**
* Builds the {@link RunInput} for one delegated subagent child run.
*/
@@ -68,6 +85,13 @@ export function buildSubagentRunInput(input: {
*/
readonly fanoutSize?: number;
readonly initiatorAuth: SessionAuthContext | null;
+ /**
+ * Runtime graph used to detect whether this declared child selected the
+ * dispatching parent's sandbox. Absence means no inheritance.
+ */
+ readonly graph?: SubagentSandboxGraph;
+ /** Durable session identity of the sandbox currently used by the parent. */
+ readonly sandboxSessionId?: string;
/** Hook token owned by the workflow currently waiting for this child. */
readonly parentContinuationToken?: string;
readonly parentTraceContext?: SessionTraceContext;
@@ -109,21 +133,28 @@ export function buildSubagentRunInput(input: {
-readonly [K in keyof RunSessionLimits]: RunSessionLimits[K];
} = resolveRemainingSessionTokenLimits(session, input.fanoutSize);
const requestedOutputSchema = normalizeRequestedOutputSchema(action.input.outputSchema);
+ const adapterState: Record<string, unknown> = {
+ callId: action.callId,
+ parentContinuationToken: input.parentContinuationToken ?? session.continuationToken,
+ parentSessionId: session.sessionId,
+ subagentName: action.subagentName,
+ };
+ const sharesSandbox =
+ input.graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox?.definition
+ .inheritsParent === true || action.subagentName === "agent";
+ if (sharesSandbox) {
+ if (session.sandboxState !== undefined) {
+ adapterState.parentSandboxState = session.sandboxState;
+ }
+ adapterState.sandboxSessionId = input.sandboxSessionId ?? session.sessionId;
+ }
const runInput: {
-readonly [K in keyof RunInput]: RunInput[K];
} = {
adapter: {
kind: SUBAGENT_ADAPTER_KIND,
- state: {
- callId: action.callId,
- parentContinuationToken: input.parentContinuationToken ?? session.continuationToken,
- parentSessionId: session.sessionId,
- subagentName: action.subagentName,
- ...(action.subagentName === "agent" && session.sandboxState
- ? { parentSandboxState: session.sandboxState, sandboxSessionId: session.sessionId }
- : {}),
- },
+ state: adapterState,
},
auth,
capabilities,
diff --git a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
index e39a40656..99e8e616b 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
@@ -161,6 +161,7 @@ export async function dispatchTaskStep(
// `experimental.subagentPersistentSessions` never produces a
// third mode here.
persistentSessions: true,
+ sandboxSessionId: prepared.sandboxSessionId,
serializedContext: prepared.serializedContext,
session,
taskOwned: true,
diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.ts
index bc676ff94..57ffd793e 100644
--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts
@@ -662,7 +662,9 @@ describe("turn cancellation integration", () => {
// The child asks a question; the proxy epilogue emits this turn's
// waiting boundary while the parent keeps waiting on the child.
const hitlTurn = await stream.nextTurn();
- expect(hitlTurn.at(-1)?.type).toBe("session.waiting");
+ expect(hitlTurn.at(-1)?.type, JSON.stringify(hitlTurn.at(-1), null, 2)).toBe(
+ "session.waiting",
+ );
const requested = filterEventsByType(hitlTurn, "input.requested");
expect(requested).toHaveLength(1);
const requestId = requested[0]?.data.requests[0]?.requestId;
diff --git a/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.test.ts b/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.test.ts
index a6a42ae84..7e659a15a 100644
--- a/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.test.ts
+++ b/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.test.ts
@@ -16,6 +16,7 @@ describe("createCompiledSandboxBackendPrunePlugin", () => {
const source = plugin.load?.(id);
+ expect(source).toContain("export const isLinuxDockerDaemonAvailableSync = () => false;");
expect(source).toContain("export const stopDevelopmentSandboxResources = pruned;");
});
});
diff --git a/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.ts b/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.ts
index 877853a35..5334dcaba 100644
--- a/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.ts
+++ b/packages/eve/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.ts
@@ -35,7 +35,7 @@ export function createCompiledSandboxBackendPrunePlugin(): BundlerPluginShape {
'export const DOCKER_BACKEND_NAME = "docker";',
'export const JUST_BASH_BACKEND_NAME = "just-bash";',
'export const MICROSANDBOX_BACKEND_NAME = "microsandbox";',
- "export const isDockerDaemonAvailableSync = () => false;",
+ "export const isLinuxDockerDaemonAvailableSync = () => false;",
"export const isMicrosandboxPlatformSupported = () => false;",
"export const pruneDockerSandboxTemplates = pruned;",
"export const pruneJustBashSandboxTemplates = pruned;",
diff --git a/packages/eve/src/public/definitions/sandbox.ts b/packages/eve/src/public/definitions/sandbox.ts
index 07aa3b890..17eb33fd0 100644
--- a/packages/eve/src/public/definitions/sandbox.ts
+++ b/packages/eve/src/public/definitions/sandbox.ts
@@ -27,6 +27,32 @@ export type {
SandboxSessionContext,
} from "#shared/sandbox-definition.js";
+/** Opaque reference to an ancestor's durable sandbox. */
+export interface SandboxAncestorReference {
+ readonly sandbox: SandboxParentValue;
+}
+
+/**
+ * Opaque value returned from a sandbox definition to select its parent's
+ * durable sandbox. It intentionally exposes no provider operations: authored
+ * code can only return it to eve.
+ */
+export interface SandboxParentValue {
+ readonly __eveSandboxParentValue: unique symbol;
+}
+
+/** Runtime ancestry passed to a parent-selecting sandbox definition. */
+export interface SandboxParentDefinitionContext {
+ readonly parent: SandboxAncestorReference | null;
+}
+
+/** A definition that selects the dispatching parent's exact sandbox. */
+export type SandboxParentDefinition = (
+ context: SandboxParentDefinitionContext,
+) => SandboxParentValue | Promise<SandboxParentValue>;
+
+const SANDBOX_PARENT_DEFINITION_MARKER = Symbol.for("eve.sandbox-parent-definition");
+
/**
* The shape passed to {@link defineSandbox}: a discriminated union over
* whether a `bootstrap` hook is present. `backend` is optional here (it is
@@ -44,13 +70,20 @@ export type SandboxDefinition<BO = Record<string, never>, SO = Record<string, ne
* when paired with a `workspace/` folder); subagents use
* `subagents/<name>/sandbox.ts`.
*
- * Returns the definition unchanged: this is an identity helper that only
- * attaches types. `backend` is optional and defaults to `defaultBackend()`
- * at runtime. The `BO`/`SO` generics type the options accepted by the
- * `use()` calls inside `bootstrap` and `onSession` respectively.
+ * Pass an object to define an independent sandbox. Passing a callback to
+ * `defineSandbox` opts into sharing: return `parent.sandbox` to select the
+ * dispatching parent's exact durable sandbox. It is intended for child-only
+ * definitions; throw when `parent` is `null`.
*/
+export function defineSandbox(definition: SandboxParentDefinition): SandboxParentDefinition;
export function defineSandbox<BO = Record<string, never>, SO = Record<string, never>>(
definition: SandboxDefinition<BO, SO>,
-): SandboxDefinition<BO, SO> {
+): SandboxDefinition<BO, SO>;
+export function defineSandbox<BO = Record<string, never>, SO = Record<string, never>>(
+ definition: SandboxDefinition<BO, SO> | SandboxParentDefinition,
+): SandboxDefinition<BO, SO> | SandboxParentDefinition {
+ if (typeof definition === "function") {
+ Object.defineProperty(definition, SANDBOX_PARENT_DEFINITION_MARKER, { value: true });
+ }
return definition;
}
diff --git a/packages/eve/src/public/sandbox/backends/default.ts b/packages/eve/src/public/sandbox/backends/default.ts
index adfb0c78a..54ef9faea 100644
--- a/packages/eve/src/public/sandbox/backends/default.ts
+++ b/packages/eve/src/public/sandbox/backends/default.ts
@@ -1,5 +1,5 @@
import {
- isDockerDaemonAvailableSync,
+ isLinuxDockerDaemonAvailableSync,
isMicrosandboxPlatformSupported,
} from "#execution/sandbox/bindings/local.js";
import { lazyBackend } from "#execution/sandbox/lazy-backend.js";
@@ -41,7 +41,7 @@ export interface DefaultSandboxProbes {
// this object literal evaluates. Accessing them at call time is safe.
const PRODUCTION_PROBES: DefaultSandboxProbes = {
isDeployedOnVercel: () => Boolean(process.env.VERCEL),
- isDockerAvailable: () => isDockerDaemonAvailableSync(),
+ isDockerAvailable: () => isLinuxDockerDaemonAvailableSync(),
isMicrosandboxSupported: () => isMicrosandboxPlatformSupported(),
};
@@ -51,7 +51,7 @@ const PRODUCTION_PROBES: DefaultSandboxProbes = {
*
* 1. **Vercel Sandbox** when deploying on Vercel (`process.env.VERCEL`
* is set) — local container/VM runtimes cannot run there.
- * 2. **Docker** when a Docker daemon is reachable.
+ * 2. **Docker** when a Linux-container Docker daemon is reachable.
* 3. **microsandbox** when the host supports it (macOS on Apple
* Silicon, or glibc Linux with KVM); `eve dev` auto-installs the
* package into the project.
diff --git a/packages/eve/src/public/sandbox/index.ts b/packages/eve/src/public/sandbox/index.ts
index febea59cb..800769694 100644
--- a/packages/eve/src/public/sandbox/index.ts
+++ b/packages/eve/src/public/sandbox/index.ts
@@ -4,10 +4,14 @@
*/
export {
defineSandbox,
+ type SandboxAncestorReference,
type SandboxBootstrapContext,
type SandboxBootstrapUseFn,
type SandboxCommandResult,
type SandboxDefinition,
+ type SandboxParentDefinition,
+ type SandboxParentDefinitionContext,
+ type SandboxParentValue,
type SandboxProcess,
type SandboxReadBinaryFileOptions,
type SandboxReadFileOptions,
diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.ts
index f703bb6b1..32d4ac813 100644
--- a/packages/eve/src/runtime/resolve-agent-graph.ts
+++ b/packages/eve/src/runtime/resolve-agent-graph.ts
@@ -29,6 +29,7 @@ import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
import { createRuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
import { createRuntimeToolRegistry } from "#runtime/tools/registry.js";
import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";
+import { createWorkspacePromptSection } from "#runtime/workspace/spec.js";
import type {
ResolvedChannelDefinition,
ResolvedDynamicSubagentDefinition,
@@ -100,6 +101,10 @@ export async function resolveRuntimeAgentGraph(
nodesByNodeId,
subagentNodesById,
});
+ attachInheritedSandboxWorkspaceResources({
+ manifest: input.manifest,
+ nodesByNodeId,
+ });
return {
nodesByNodeId,
@@ -460,6 +465,75 @@ function resolveRemoteAgentHeaders(value: unknown): HeadersValue | undefined {
return headers;
}
+function attachInheritedSandboxWorkspaceResources(input: {
+ readonly manifest: CompiledAgentManifest;
+ readonly nodesByNodeId: ReadonlyMap<string, ResolvedAgentGraphBundle["root"]>;
+}): void {
+ const parentNodeIdByChildNodeId = new Map(
+ input.manifest.subagentEdges.map((edge) => [edge.childNodeId, edge.parentNodeId]),
+ );
+
+ for (const [nodeId, node] of input.nodesByNodeId) {
+ if (node.sandboxRegistry.sandbox.definition.inheritsParent !== true) continue;
+ if (node.agent.dynamicSkillResolvers.length > 0) {
+ throw new ResolveRuntimeAgentGraphError(
+ `Sandbox "${node.sandboxRegistry.sandbox.definition.logicalPath}" selects parent.sandbox but agent node "${nodeId}" defines dynamic skills. Remove the child dynamic skills or give the child its own sandbox.`,
+ { nodeId },
+ );
+ }
+
+ const parentNodeId = parentNodeIdByChildNodeId.get(nodeId);
+ if (parentNodeId === undefined) {
+ throw new ResolveRuntimeAgentGraphError(
+ `Sandbox "${node.sandboxRegistry.sandbox.definition.logicalPath}" selects parent.sandbox but agent node "${nodeId}" has no parent.`,
+ { nodeId },
+ );
+ }
+ const owner = resolveSandboxOwnerNode({
+ nodeId: parentNodeId,
+ nodesByNodeId: input.nodesByNodeId,
+ parentNodeIdByChildNodeId,
+ });
+ (node.sandboxRegistry.sandbox as { inheritance?: unknown }).inheritance = {
+ definition: owner.sandboxRegistry.sandbox.definition,
+ nodeId: owner.nodeId,
+ workspaceResourceRoot: owner.sandboxRegistry.sandbox.workspaceResourceRoot,
+ };
+ const workspacePrompt = createWorkspacePromptSection(owner.agent.workspaceSpec);
+ if (workspacePrompt !== undefined) {
+ (node.turnAgent as { instructions: readonly string[] }).instructions = [
+ ...node.turnAgent.instructions,
+ workspacePrompt,
+ ];
+ }
+ }
+}
+
+function resolveSandboxOwnerNode(input: {
+ readonly nodeId: string;
+ readonly nodesByNodeId: ReadonlyMap<string, ResolvedAgentGraphBundle["root"]>;
+ readonly parentNodeIdByChildNodeId: ReadonlyMap<string, string>;
+}): ResolvedAgentGraphBundle["root"] {
+ const node = input.nodesByNodeId.get(toRuntimeNodeId(input.nodeId));
+ if (node === undefined) {
+ throw new ResolveRuntimeAgentGraphError(`Missing parent runtime node "${input.nodeId}".`, {
+ nodeId: input.nodeId,
+ });
+ }
+ if (node.sandboxRegistry.sandbox.definition.inheritsParent !== true) return node;
+
+ const parentNodeId = input.parentNodeIdByChildNodeId.get(input.nodeId);
+ if (parentNodeId === undefined) {
+ throw new ResolveRuntimeAgentGraphError(
+ `Inherited sandbox node "${input.nodeId}" has no parent.`,
+ {
+ nodeId: input.nodeId,
+ },
+ );
+ }
+ return resolveSandboxOwnerNode({ ...input, nodeId: parentNodeId });
+}
+
function createChildNodeIdsByParentNodeId(
manifest: CompiledAgentManifest,
): ReadonlyMap<string, readonly string[]> {
diff --git a/packages/eve/src/runtime/resolve-sandbox.ts b/packages/eve/src/runtime/resolve-sandbox.ts
index 74485b5f6..9ab72e1d1 100644
--- a/packages/eve/src/runtime/resolve-sandbox.ts
+++ b/packages/eve/src/runtime/resolve-sandbox.ts
@@ -23,21 +23,24 @@ export async function resolveSandboxDefinition(
nodeId: string | undefined,
): Promise<ResolvedSandboxDefinition> {
try {
- const resolvedExportValue = await loadResolvedModuleExport({
- definition,
- kindLabel: "sandbox",
- moduleMap,
- nodeId,
- });
- const resolvedRecord = expectObjectRecord(
- resolvedExportValue,
- `Expected the sandbox export "${definition.exportName ?? "default"}" from "${definition.logicalPath}" to return an object.`,
- );
+ const resolvedExportValue = definition.inheritsParent
+ ? undefined
+ : await loadResolvedModuleExport({
+ definition,
+ kindLabel: "sandbox",
+ moduleMap,
+ nodeId,
+ });
const sandboxDefinition: {
readonly backend?: unknown;
readonly bootstrap?: (input: unknown) => Promise<void> | void;
readonly onSession?: (input: unknown) => Promise<void> | void;
- } = resolvedRecord;
+ } = definition.inheritsParent
+ ? {}
+ : expectObjectRecord(
+ resolvedExportValue,
+ `Expected the sandbox export "${definition.exportName ?? "default"}" from "${definition.logicalPath}" to return an object.`,
+ );
const backend = resolveBackend(sandboxDefinition.backend, definition.logicalPath);
@@ -45,6 +48,7 @@ export async function resolveSandboxDefinition(
backend,
bootstrap: sandboxDefinition.bootstrap as ResolvedSandboxDefinition["bootstrap"],
description: definition.description,
+ inheritsParent: definition.inheritsParent,
exportName: definition.exportName,
logicalPath: definition.logicalPath,
onSession: sandboxDefinition.onSession as ResolvedSandboxDefinition["onSession"],
diff --git a/packages/eve/src/runtime/sandbox/registry.test.ts b/packages/eve/src/runtime/sandbox/registry.test.ts
new file mode 100644
index 000000000..01d932f56
--- /dev/null
+++ b/packages/eve/src/runtime/sandbox/registry.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from "vitest";
+
+import type { ResolvedSandboxDefinition } from "#runtime/types.js";
+import { createRuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
+
+const inheritedDefinition = {
+ backend: { name: "test" },
+ inheritsParent: true,
+ logicalPath: "agent/subagents/foo/sandbox.ts",
+ sourceId: "agent/subagents/foo/sandbox",
+ sourceKind: "module",
+} as ResolvedSandboxDefinition;
+
+describe("createRuntimeSandboxRegistry", () => {
+ it("allows an empty child to inherit its parent sandbox", () => {
+ expect(
+ createRuntimeSandboxRegistry({
+ authoredSandbox: inheritedDefinition,
+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
+ }),
+ ).toMatchObject({
+ sandbox: { definition: inheritedDefinition },
+ });
+ });
+
+ it("rejects child workspace resources when inheriting the parent sandbox", () => {
+ expect(() =>
+ createRuntimeSandboxRegistry({
+ authoredSandbox: inheritedDefinition,
+ workspaceResourceRoot: {
+ contentHash: "child-content",
+ logicalPath: "workspace-resources/foo",
+ rootEntries: ["bar.txt"],
+ },
+ }),
+ ).toThrow(
+ 'Sandbox "agent/subagents/foo/sandbox.ts" selects parent.sandbox but has managed workspace resources. Remove the child workspace or give the child its own sandbox.',
+ );
+ });
+});
diff --git a/packages/eve/src/runtime/sandbox/registry.ts b/packages/eve/src/runtime/sandbox/registry.ts
index fee842ff7..8ffb851af 100644
--- a/packages/eve/src/runtime/sandbox/registry.ts
+++ b/packages/eve/src/runtime/sandbox/registry.ts
@@ -27,6 +27,12 @@ export const DEFAULT_SANDBOX_SOURCE_ID = "eve:default-sandbox";
export interface RuntimeRegisteredSandbox {
readonly definition: ResolvedSandboxDefinition;
readonly workspaceResourceRoot: CompiledWorkspaceResourceRoot;
+ /** Parent-owned sandbox identity used by a child that selects parent.sandbox. */
+ readonly inheritance?: {
+ readonly definition: ResolvedSandboxDefinition;
+ readonly nodeId: string;
+ readonly workspaceResourceRoot: CompiledWorkspaceResourceRoot;
+ };
}
/**
@@ -53,6 +59,15 @@ export function createRuntimeSandboxRegistry(input: {
readonly workspaceResourceRoot: CompiledWorkspaceResourceRoot;
}): RuntimeSandboxRegistry {
const definition = input.authoredSandbox ?? createFrameworkSandboxDefinition();
+ if (
+ definition.inheritsParent === true &&
+ (input.workspaceResourceRoot.contentHash !== undefined ||
+ input.workspaceResourceRoot.rootEntries.length > 0)
+ ) {
+ throw new Error(
+ `Sandbox "${definition.logicalPath}" selects parent.sandbox but has managed workspace resources. Remove the child workspace or give the child its own sandbox.`,
+ );
+ }
return {
sandbox: {
definition,
diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.ts
index e05199e3b..3b7f87e80 100644
--- a/packages/eve/src/runtime/types.ts
+++ b/packages/eve/src/runtime/types.ts
@@ -145,6 +145,7 @@ export type ResolvedSandboxDefinition = ResolvedModuleSourceRef & {
*/
readonly backend: SandboxBackend;
readonly description?: string;
+ readonly inheritsParent?: boolean;
readonly onSession?: (input: SandboxSessionContext) => Promise<void> | void;
};
diff --git a/packages/eve/test/default-backend.test.ts b/packages/eve/test/default-backend.test.ts
index 7f43a930d..59280305a 100644
--- a/packages/eve/test/default-backend.test.ts
+++ b/packages/eve/test/default-backend.test.ts
@@ -31,7 +31,7 @@ describe("selectDefaultSandbox", () => {
expect(probed).toBe(false);
});
- it("picks docker when a daemon is available", () => {
+ it("picks docker when a compatible daemon is available", () => {
const backend = selectDefaultSandbox(
undefined,
probes({ isDockerAvailable: () => true, isMicrosandboxSupported: () => true }),