Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): open the calling session's sandbox from workflow step helpers (#5059)

Andrew Barbadd0aac616ab8
diff --git a/.changeset/workflow-step-session-sandbox.md b/.changeset/workflow-step-session-sandbox.md
new file mode 100644
index 000000000..ed1f17373
--- /dev/null
+++ b/.changeset/workflow-step-session-sandbox.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+A `"use step"` helper in a workflow tool can now call `ctx.getSandbox()` to open the sandbox of the session that called the tool, on any sandbox provider, so a task can prepare files the session's later tool calls read. When the session had not recorded its sandbox when it called the tool, the step opens it with the owning session's sandbox definition; the step never owns the sandbox, and the session removes it when the session ends.
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index 3b791e8de..5ab1c76ba 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -111,7 +111,7 @@ import template from "../../prompts/template.txt?raw";
| `ctx.requireAuth(provider)` | Evict and re-authorize an inline provider, commonly after a downstream `401` |
| `ctx.approval` | Present only while a call runs after a person approved it: `responder` is who approved it and `responder.getToken(provider)` resolves their token. The call still runs as `ctx.session.auth.current`; see [Human-in-the-loop](/docs/human-in-the-loop) |
-Tool definitions accept `availableInSubagents: false` to restrict the tool to top-level root sessions, and `deferred: true` to keep the tool out of the model's tool list so the model finds it with `eve__search` and calls it with `eve__tool`; see [Tools](../tools#keep-a-tool-out-of-the-tool-list). `defineTool` definitions accept `endsTurn: true`, or a function that receives the `execute` output, to end the turn without a reply after a successful call; see [Tools](../tools#end-the-turn-after-a-tool-call). Authored workflow bodies also receive `ctx.agents`, a replay-stable map of callable-agent metadata, and `ctx.agent(name)`, which returns an `AgentSession` whose `send(message, options?)` resolves to a response with `result()`. A `"use step"` helper that receives the context directly should type it as `WorkflowStepToolContext`, which excludes `agents`, `agent`, and `ask`. The root-copy `agent` entry has an empty description when the root omits `description`. See [Workflows as tools](../tools/workflows#delegate-work-ctxagent) for the workflow-only context.
+Tool definitions accept `availableInSubagents: false` to restrict the tool to top-level root sessions, and `deferred: true` to keep the tool out of the model's tool list so the model finds it with `eve__search` and calls it with `eve__tool`; see [Tools](../tools#keep-a-tool-out-of-the-tool-list). `defineTool` definitions accept `endsTurn: true`, or a function that receives the `execute` output, to end the turn without a reply after a successful call; see [Tools](../tools#end-the-turn-after-a-tool-call). Authored workflow bodies also receive `ctx.agents`, a replay-stable map of callable-agent metadata, and `ctx.agent(name)`, which returns an `AgentSession` whose `send(message, options?)` resolves to a response with `result()`. A `"use step"` helper that receives the context directly should type it as `WorkflowStepToolContext`, which excludes `agents`, `agent`, and `ask`; its `getSandbox()` opens the sandbox of the session that called the tool (see [Use the session sandbox in a step](../tools/workflows#use-the-session-sandbox-in-a-step)). The root-copy `agent` entry has an empty description when the root omits `description`. See [Workflows as tools](../tools/workflows#delegate-work-ctxagent) for the workflow-only context.
## Imports at a glance
diff --git a/docs/sandbox/index.mdx b/docs/sandbox/index.mdx
index b4fcfd23c..4043159cf 100644
--- a/docs/sandbox/index.mdx
+++ b/docs/sandbox/index.mdx
@@ -54,7 +54,7 @@ export default defineSandbox(() => environment.open());
`environment.open()` starts the persistent sandbox owned by the current eve session. The `defineSandbox()` selector runs until initialization succeeds, then eve checkpoints the selected provider and its state. Later workflow steps and process restarts call the provider's `resume()` directly without rerunning the selector or `environment.open()`.
-Pass options for the live sandbox to `open()`, then configure the returned sandbox before returning it. `open()` applies its options only when it creates the sandbox. Initialization can run more than once against the same sandbox, for example when a subagent that shares the sandbox opens it before the parent does, or on the next access after an initialization that failed. Make it safe to repeat:
+Pass options for the live sandbox to `open()`, then configure the returned sandbox before returning it. `open()` applies its options only when it creates the sandbox. Initialization can run more than once against the same sandbox, for example when a subagent that shares the sandbox opens it before the parent does, when a [workflow step](/docs/tools/workflows#use-the-session-sandbox-in-a-step) opens it before the session records it, or on the next access after an initialization that failed. Make it safe to repeat:
```ts
import { defineSandbox } from "eve/sandbox";
diff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdx
index f2451c207..4550949e3 100644
--- a/docs/tools/workflows.mdx
+++ b/docs/tools/workflows.mdx
@@ -90,9 +90,9 @@ or days later, the run resumes, deploys, and returns. The model sees one tool re
`agent`, `agents`, `ask`, and `reply`; each call it receives carries its own `callId` and
`abortSignal`.
A `"use step"` helper that receives `ctx` directly gets a restricted `WorkflowStepToolContext` with
- `session`, `callId`, `toolName`, `abortSignal`, `getToken`, and `requireAuth`. Read `ctx.agents`, call
+ `session`, `callId`, `toolName`, `abortSignal`, `getSandbox`, `getToken`, and `requireAuth`. Read `ctx.agents`, call
`ctx.agent()`, and call `ctx.ask()` in the workflow body; pass only the serializable values the step needs.
- `getSandbox` remains unavailable.
+ Call `getSandbox`, `getToken`, and `requireAuth` in a step: the workflow body throws when it calls them.
- The tool's input must be a JSON object. Workflow bodies are for static tools under `agent/tools/`,
not tools returned from `defineDynamic` resolvers.
@@ -438,6 +438,62 @@ itself contains no credentials.
Cancelling an authorization wait withdraws its callback. Cancellation uses the existing turn
cancellation path rather than a separate authorization completion event.
+## Use the session sandbox in a step
+
+Pass `ctx` directly to a step helper and call `ctx.getSandbox()` there. The step opens the
+[sandbox](/docs/sandbox) of the session that called the tool, the same sandbox that session's
+turns use. When the session shares its parent's sandbox, as a copy started by the built-in `agent`
+tool does, the step opens that shared sandbox. The step sees files the session wrote, and the
+session's later tool calls see files the step writes:
+
+```ts title="agent/tools/analyze.ts"
+import { defineWorkflowTool, type WorkflowStepToolContext } from "eve/tools";
+import { z } from "zod";
+
+export default defineWorkflowTool({
+ description: "Prepare the input file for an analysis run.",
+ inputSchema: z.object({ value: z.string() }),
+ async task(input, ctx) {
+ "use workflow";
+ await prepareInput(ctx, input);
+ return { path: "/workspace/input.json" };
+ },
+});
+
+async function prepareInput(ctx: WorkflowStepToolContext, input: { value: string }) {
+ "use step";
+ const sandbox = await ctx.getSandbox();
+ await sandbox.writeTextFile({ path: "/workspace/input.json", content: JSON.stringify(input) });
+}
+```
+
+- The workflow body cannot open the sandbox, because it replays. `ctx.getSandbox()` in the body
+ throws and tells you to pass `ctx` to a step helper.
+- The step opens the sandbox directly, with any sandbox provider. If the session recorded its
+ sandbox before it called the tool, the step resumes it. Otherwise, or if that sandbox is gone by
+ the time the step runs, the step opens it the way the session's first turn would: it runs your
+ `defineSandbox()` definition, and the provider finds or creates the sandbox by the session's id. The session's later turns open the same sandbox. Your
+ definition can run once for each caller that opens the sandbox before the session records it,
+ so make its initialization safe to repeat.
+- The step does not own the sandbox. When the step ends, even by throwing, eve lets go of the
+ step's handle and leaves the sandbox running for the session. eve never stops or deletes the
+ sandbox for a step, and `sandbox.stop()` and `sandbox.delete()` in a step fail without a retry,
+ because the session's turns may be using the sandbox.
+- The session removes the sandbox when the session ends, even when only a step opened it. A step
+ that is still running when the session ends can open the sandbox again after that cleanup, and
+ nothing removes the new one.
+- When the eve server shuts down, it stops the sandboxes its sessions opened, but not one that
+ only a step opened. With Docker or microsandbox, that container or VM keeps running until the
+ session ends or you stop it.
+- A step can use the sandbox while the session's turns use it too, as subagents that share a
+ sandbox do. Give each one its own files to write.
+- Steps run at least once and retry after a failure, so make sandbox writes safe to repeat. Write
+ whole files instead of appending to them, or check for earlier output first.
+- When the session shares its parent's sandbox, the step opens it by the parent's session id with
+ the parent's sandbox definition, and the parent removes it when the parent ends.
+- A step runs wherever the workflow runs. A sandbox that lives on one machine, such as just-bash
+ on the local disk, is reachable from a step only on that machine, as in local development.
+
## Ask a human: `ctx.ask`
```ts
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/agent.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/agent.ts
new file mode 100644
index 000000000..aeaf4a551
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/agent.ts
@@ -0,0 +1,18 @@
+import { defineAgent } from "eve";
+import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";
+
+const STEPS = ["prepare_note", "read_note"] as const;
+
+export default defineAgent({
+ description: "Prepares a note in its sandbox from a workflow step and reads it back.",
+ // Always scripted: the eval checks the sandbox the step shares, not model planning.
+ model: mockModel(respond),
+});
+
+function respond(request: MockModelRequest): MockModelResponse | string {
+ for (const name of STEPS) {
+ const result = request.toolResults.find((entry) => entry.name === name);
+ if (result === undefined) return { toolCalls: [{ input: {}, name }] };
+ }
+ return String(request.toolResults.find((entry) => entry.name === "read_note")?.output);
+}
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/sandbox.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/sandbox.ts
new file mode 100644
index 000000000..da46aacc7
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/sandbox.ts
@@ -0,0 +1,11 @@
+import { defineSandbox } from "eve/sandbox";
+import { JustBashSandbox } from "eve/sandbox/just-bash";
+import { VercelSandbox } from "eve/sandbox/vercel";
+
+// Vercel Sandbox when deployed, and just-bash elsewhere so the eval needs no
+// container runtime.
+export const environment = process.env.VERCEL
+ ? VercelSandbox.environment()
+ : JustBashSandbox.environment();
+
+export default defineSandbox(() => environment.open());
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/prepare_note.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/prepare_note.ts
new file mode 100644
index 000000000..07a732598
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/prepare_note.ts
@@ -0,0 +1,26 @@
+import { defineWorkflowTool, type WorkflowStepToolContext } from "eve/tools";
+import { z } from "zod";
+
+import { environment } from "../sandbox.js";
+
+export default defineWorkflowTool({
+ description: "Prepares the note in a workflow step.",
+ inputSchema: z.object({}),
+ async execute(_input, ctx) {
+ "use workflow";
+ return await prepareNote(ctx);
+ },
+});
+
+async function prepareNote(ctx: WorkflowStepToolContext) {
+ "use step";
+ // The session has not opened its sandbox yet, so the step creates it under the session's id.
+ // The step imports its own copy of the environment the session's sandbox uses.
+ const sandbox = await ctx.getSandbox(environment);
+ // Writing the whole file keeps a retried step's write the same.
+ await sandbox.writeTextFile({
+ content: "step-sandbox-note-ok-H3R:prepared-in-step",
+ path: "/workspace/step-note.txt",
+ });
+ return "prepared";
+}
diff --git a/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/read_note.ts b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/read_note.ts
new file mode 100644
index 000000000..9e33db347
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/agent/subagents/step-sandbox/tools/read_note.ts
@@ -0,0 +1,11 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+export default defineTool({
+ description: "Reads the prepared note from the session's sandbox.",
+ inputSchema: z.object({}),
+ async execute(_input, ctx) {
+ const sandbox = await ctx.getSandbox();
+ return await sandbox.readTextFile({ path: "/workspace/step-note.txt" });
+ },
+});
diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/workflow-step-sandbox.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/workflow-step-sandbox.eval.ts
new file mode 100644
index 000000000..4c0a03e30
--- /dev/null
+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/workflow-step-sandbox.eval.ts
@@ -0,0 +1,21 @@
+import { defineEval } from "eve/evals";
+import { includes } from "eve/evals/expect";
+
+// A workflow step opens the child's sandbox before the child does, and a later
+// tool call of the child reads the step's note from the same sandbox.
+const NOTE = "step-sandbox-note-ok-H3R:prepared-in-step";
+
+export default defineEval({
+ description: "Sandbox: a workflow step shares the calling session's sandbox.",
+ async test(t) {
+ const turn = await t.send(
+ "Ask the `step-sandbox` subagent with message: " +
+ "Alice is preparing an analysis workspace. Prepare the note and read it back.",
+ );
+ turn.expectOk();
+
+ t.succeeded();
+ t.calledSubagent("step-sandbox", { count: 1, status: "completed" });
+ t.check(turn.message, includes(NOTE));
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v97.ts b/packages/eve/extension-contracts/compatibility/tool/v97.ts
new file mode 100644
index 000000000..f5306fdff
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v97.ts
@@ -0,0 +1,25 @@
+// Epoch 97 of the tool capability: step helpers typed with its context still accept the workflow context.
+import { defineWorkflowTool, type WorkflowStepToolContext } from "#public/tools/index.js";
+
+async function readIssue(ctx: WorkflowStepToolContext, issue: string) {
+ "use step";
+ const { token } = await ctx.getToken({
+ principalType: "app",
+ getToken: async () => ({ token: "service-credential" }),
+ });
+ return { issue, authorized: token.length > 0, session: ctx.session.id };
+}
+
+export default defineWorkflowTool({
+ description: "Read an issue from the issue service.",
+ inputSchema: {
+ type: "object",
+ properties: { issue: { type: "string" } },
+ required: ["issue"],
+ additionalProperties: false,
+ },
+ async execute(input: { issue: string }, ctx) {
+ "use workflow";
+ return await readIssue(ctx, input.issue);
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/tool/v98.json b/packages/eve/extension-contracts/reports/tool/v98.json
new file mode 100644
index 000000000..ab773eeb8
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v98.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 98,
+ "sha256": "5ee6d41fbb5ba8c82569e3902e52882457d07b8cbc2d6a282fead36cd229e9f9",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolDefinition",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "decide",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "serializeModelInputSchema",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index d041d30f5..d8d0ff93c 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,10 +22,10 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 97,
+ current: 98,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78, 80, 81, 82, 84,
- 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 97,
+ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 97, 98,
],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
diff --git a/packages/eve/src/execution/agent-sessions/context.ts b/packages/eve/src/execution/agent-sessions/context.ts
index cbaa5d99d..532493dfc 100644
--- a/packages/eve/src/execution/agent-sessions/context.ts
+++ b/packages/eve/src/execution/agent-sessions/context.ts
@@ -74,6 +74,7 @@ type CallerDispatch = Pick<
| "inheritedConversation"
| "localDevRequest"
| "sandboxSessionId"
+ | "sandboxState"
| "serializedContext"
| "session"
| "traceRoot"
@@ -105,7 +106,7 @@ export function captureAgentSessionContext(
sessionId: session.sessionId,
turn: { id: batch.event.turnId, sequence: batch.event.sequence },
},
- sandbox: { sessionId: caller.sandboxSessionId, state: session.sandboxState },
+ sandbox: { sessionId: caller.sandboxSessionId, state: caller.sandboxState },
traceRoot: caller.traceRoot,
trace: resolveToolCallAgentTrace({
callId,
diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.ts
index 3787afe66..121622b70 100644
--- a/packages/eve/src/execution/coordination-dispatch-shared.ts
+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts
@@ -2,6 +2,7 @@
import { buildAdapterContext } from "#channel/adapter-context.js";
import { type ChannelAdapter, type ChannelAdapterContext } from "#channel/adapter.js";
+import type { SandboxState } from "#sandbox/state.js";
import {
AuthKey,
CapabilitiesKey,
@@ -78,6 +79,8 @@ export interface PreparedCoordinationDispatch<PlanEntry = RuntimeWorkflowTaskReq
/** Lineage of the session running this dispatch, when it is itself a delegated child. */
readonly parentSession: SessionParent | undefined;
readonly sandboxSessionId: string;
+ /** The state of that sandbox: this session's own, or else its owner's when it shares it. */
+ readonly sandboxState?: SandboxState;
readonly serializedContext: Record<string, unknown>;
readonly plan: readonly PlanEntry[];
readonly session: HarnessSessionBase;
@@ -158,6 +161,7 @@ export async function prepareActionDispatch<PlanEntry>(input: {
});
const sandboxSessionId = resolveActiveSandboxSessionId(adapter.state, session.sessionId);
+ const sandboxState = session.sandboxState ?? resolveOwnerSandboxState(adapter.state);
return {
adapter,
@@ -174,6 +178,7 @@ export async function prepareActionDispatch<PlanEntry>(input: {
parentSession: ctx.get(ParentSessionKey),
plan,
sandboxSessionId,
+ sandboxState,
serializedContext: input.serializedContext,
session,
traceRoot: childTraceRoot(ctx, session.sessionId),
@@ -191,6 +196,12 @@ function childTraceRoot(ctx: ContextReader, sessionId: string): SessionTraceRoot
return { kind: "inherited", sessionId: resolveTraceRootSessionId(ctx, sessionId) };
}
+/** A child that shares its owner's sandbox uses the owner's state until it records its own. */
+function resolveOwnerSandboxState(adapterState: unknown): SandboxState | undefined {
+ if (typeof adapterState !== "object" || adapterState === null) return undefined;
+ return (adapterState as Record<string, unknown>).parentSandboxState as SandboxState | undefined;
+}
+
function resolveActiveSandboxSessionId(adapterState: unknown, sessionId: string): string {
if (typeof adapterState !== "object" || adapterState === null) return sessionId;
const value = (adapterState as Record<string, unknown>).sandboxSessionId;
diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.ts
index f5318419f..ea36b2d2e 100644
--- a/packages/eve/src/execution/sandbox/ensure.ts
+++ b/packages/eve/src/execution/sandbox/ensure.ts
@@ -47,6 +47,13 @@ interface EnsureSandboxAccessInput {
readonly registry: RuntimeSandboxRegistry;
readonly sessionId: string;
readonly state: SandboxState | null;
+ /**
+ * `true` for a caller that borrows a session's sandbox outside its turns,
+ * such as a workflow step. Its handle stays out of the shutdown registry,
+ * which tracks one handle per session, so it never replaces or drops the
+ * session's own.
+ */
+ readonly borrowed?: boolean;
}
/** The access `ensureSandboxAccess` builds, with what the opener may do beyond the sandbox API. */
@@ -92,6 +99,12 @@ export async function ensureSandboxAccess(
let opened: OpenedSandbox | undefined;
let opening: Promise<SandboxProviderHandle> | undefined;
let requiring: Promise<SandboxProviderHandle> | undefined;
+ const track: typeof trackActiveSandboxHandle = (entry) => {
+ if (input.borrowed !== true) trackActiveSandboxHandle(entry);
+ };
+ const untrack: typeof untrackActiveSandboxHandle = (entry) => {
+ if (input.borrowed !== true) untrackActiveSandboxHandle(entry);
+ };
const appRoot =
getRuntimeCompiledArtifactsSandboxAppRoot(input.compiledArtifactsSource) ?? process.cwd();
const captured = (): SandboxState => ({ session: persisted });
@@ -226,7 +239,7 @@ export async function ensureSandboxAccess(
});
const handle = await opening;
installHandle(provider.providerName, handle);
- trackActiveSandboxHandle({
+ track({
handle,
providerName: provider.providerName,
sessionId: input.sessionId,
@@ -314,7 +327,7 @@ export async function ensureSandboxAccess(
persisted = null;
throw error;
}
- trackActiveSandboxHandle({
+ track({
handle: opened.handle,
providerName: opened.providerName,
sessionId: input.sessionId,
@@ -334,7 +347,7 @@ export async function ensureSandboxAccess(
function forgetHandle() {
const current = opened;
if (current !== undefined) {
- untrackActiveSandboxHandle({
+ untrack({
handle: current.handle,
providerName: current.providerName,
sessionId: input.sessionId,
diff --git a/packages/eve/src/execution/tools/workflow/body.test.ts b/packages/eve/src/execution/tools/workflow/body.test.ts
index dd2a5e5ad..6304239fd 100644
--- a/packages/eve/src/execution/tools/workflow/body.test.ts
+++ b/packages/eve/src/execution/tools/workflow/body.test.ts
@@ -62,6 +62,17 @@ it("binds workflow-only methods to the run context", async () => {
});
});
+it("points a workflow body that opens the sandbox to a step helper", async () => {
+ mocks.execute.mockImplementation(async (_input, ctx: WorkflowToolContext) => ctx.getSandbox());
+ await expect(startCallBody(input).outcome).resolves.toMatchObject({
+ error: {
+ message:
+ 'ctx.getSandbox() is not available inside a workflow tool; pass ctx directly to a "use step" helper to open the session\'s sandbox. Tool "deploy" runs as a durable workflow body, which only replays deterministic code.',
+ },
+ status: "failed",
+ });
+});
+
// #3836: a selected option's answer carries `text: undefined`, and a tool that
// returns it as-is, or returns nothing, must still complete with JSON.
it.each([
diff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.ts
index 5c6463e78..8c3f52ab8 100644
--- a/packages/eve/src/execution/tools/workflow/body.ts
+++ b/packages/eve/src/execution/tools/workflow/body.ts
@@ -283,7 +283,11 @@ export function createSharedContext(
return {
agent,
ask: askPerson,
- getSandbox: () => unavailable("getSandbox()", "the session sandbox belongs to the turn"),
+ getSandbox: () =>
+ unavailable(
+ "getSandbox()",
+ 'pass ctx directly to a "use step" helper to open the session\'s sandbox',
+ ),
getToken: () =>
unavailable("getToken()", 'pass ctx directly to a "use step" helper to resolve credentials'),
requireAuth: () =>
diff --git a/packages/eve/src/execution/tools/workflow/step-context.ts b/packages/eve/src/execution/tools/workflow/step-context.ts
index 0a008f3ff..e878d47d6 100644
--- a/packages/eve/src/execution/tools/workflow/step-context.ts
+++ b/packages/eve/src/execution/tools/workflow/step-context.ts
@@ -1,5 +1,7 @@
import type { SessionContext } from "#context/session-context.js";
+import type { AgentSessionBundle } from "#execution/agent-sessions/context.js";
import type { AuthorizationResult, AuthorizationSignal } from "#harness/authorization.js";
+import type { SandboxState } from "#sandbox/state.js";
export type WorkflowStepAuthorizationResult = AuthorizationResult & {
readonly attemptId: string;
@@ -14,6 +16,16 @@ export interface WorkflowStepContext {
readonly baseUrl: string;
readonly token: string;
readonly authorizationResults: readonly WorkflowStepAuthorizationResult[];
+ readonly sandbox: WorkflowStepSandbox;
+}
+
+/** Where `ctx.getSandbox()` finds the calling session's sandbox: its agent and sandbox key. */
+export interface WorkflowStepSandbox {
+ readonly bundle: AgentSessionBundle;
+ /** The session that owns the sandbox the caller uses: its own, or the owner's it shares. */
+ readonly sessionId: string;
+ /** The caller's recorded sandbox state when the call was made, which the step resumes. */
+ readonly state?: SandboxState;
}
export type WorkflowStepResult = { readonly authorized: readonly string[] } & (
diff --git a/packages/eve/src/execution/tools/workflow/step-execution.test.ts b/packages/eve/src/execution/tools/workflow/step-execution.test.ts
index 17a8adef5..156611712 100644
--- a/packages/eve/src/execution/tools/workflow/step-execution.test.ts
+++ b/packages/eve/src/execution/tools/workflow/step-execution.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from "vitest";
import { withWorkflowStepAuthorization } from "#execution/tools/workflow/step-execution.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import { AuthKey } from "#context/keys.js";
@@ -13,6 +13,20 @@ import type {
import type { ToolContext } from "#tools/definition.js";
import type { WorkflowToolContext } from "#tools/workflow-definition.js";
import type { AuthorizationDefinition } from "#shared/connection-types.js";
+import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";
+import { defineSandbox } from "#public/definitions/sandbox.js";
+import { shutdownActiveSandboxHandles } from "#execution/sandbox/active-handles.js";
+import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
+import { withDevelopmentWorkflowGeneration } from "#internal/workflow/development-generation-context.js";
+import {
+ createBundledRuntimeCompiledArtifactsSource,
+ createDiskRuntimeCompiledArtifactsSource,
+} from "#runtime/compiled-artifacts-source.js";
+import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
+import {
+ defineSandboxProvider,
+ type SandboxProviderSessionContext,
+} from "#shared/sandbox-provider.js";
const durable = vi.hoisted(() => ({
attempt: 1,
@@ -30,6 +44,22 @@ vi.mock("#compiled/@workflow/core/index.js", () => ({
}),
}),
}));
+const bundle = vi.hoisted(() => ({
+ loadedFrom: [] as unknown[],
+ registry: undefined as RuntimeSandboxRegistry | undefined,
+}));
+vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({
+ getCompiledRuntimeAgentBundle: async (input: { compiledArtifactsSource: unknown }) => {
+ bundle.loadedFrom.push(input.compiledArtifactsSource);
+ return {
+ compiledArtifactsSource: input.compiledArtifactsSource,
+ graph: { root: { nodeId: "__root__", sandboxRegistry: bundle.registry } },
+ };
+ },
+}));
+vi.mock("#runtime/sandbox/prepared-artifacts.js", () => ({
+ loadSandboxPreparedArtifact: async () => null,
+}));
vi.mock("#internal/workflow/runtime.js", () => ({
getRun: () => ({
getReadable: ({ namespace }: { namespace: string }) => ({
@@ -39,7 +69,67 @@ vi.mock("#internal/workflow/runtime.js", () => ({
}),
}));
-function context(user = "user-1"): WorkflowStepContext {
+/**
+ * A provider whose `start` upserts a sandbox by session id and whose
+ * `onSessionEnd` deletes by it, as the provider contract requires. Each open
+ * hands out its own handle over the shared sandbox; `shutDown` records which
+ * ones the runtime's shutdown stopped.
+ */
+function upsertSandboxes() {
+ const live = new Map<string, ReturnType<typeof mockSandbox>>();
+ const starts: string[] = [];
+ const handles: object[] = [];
+ const shutDown: object[] = [];
+ const stopped: Mock<() => Promise<void>> = vi.fn(async () => {});
+ const deleted: Mock<() => Promise<void>> = vi.fn(async () => {});
+ const handleFor = (key: string) => {
+ let sandbox = live.get(key);
+ if (sandbox === undefined) {
+ sandbox = mockSandbox();
+ live.set(key, sandbox);
+ }
+ const handle = {
+ sandbox: sandbox.session,
+ onRuntimeShutdown: async () => void shutDown.push(handle),
+ onSandboxDelete: deleted,
+ onSandboxStop: stopped,
+ };
+ handles.push(handle);
+ return handle;
+ };
+ const provider = defineSandboxProvider({
+ name: "upsert",
+ environment: () => ({
+ onSessionEnd: async (context: SandboxProviderSessionContext) =>
+ void live.delete(context.session.id),
+ prepare: async () => null,
+ resume: async (_context: unknown, _artifact: unknown, state: { readonly key: string }) =>
+ handleFor(state.key),
+ start: async (context: SandboxProviderSessionContext) => {
+ starts.push(context.session.id);
+ return { handle: handleFor(context.session.id), state: { key: context.session.id } };
+ },
+ }),
+ });
+ const environment = provider.environment();
+ const registry: RuntimeSandboxRegistry = {
+ sandbox: {
+ definition: {
+ environment,
+ kind: "independent",
+ logicalPath: "sandbox.ts",
+ revisionHash: "hash",
+ selector: defineSandbox(() => environment.open()),
+ sourceId: "sandbox",
+ sourceKind: "module",
+ },
+ workspaceResourceRoot: { logicalPath: "", rootEntries: [] },
+ },
+ };
+ return { deleted, handles, provider, registry, shutDown, starts, stopped };
+}
+
+function context(user = "user-1", sessionId = "session-1"): WorkflowStepContext {
const auth = {
attributes: {},
authenticator: "test",
@@ -59,6 +149,7 @@ function context(user = "user-1"): WorkflowStepContext {
},
callId: "call-1",
toolName: "devbox",
+ sandbox: { bundle: { source: createBundledRuntimeCompiledArtifactsSource() }, sessionId },
};
}
@@ -74,10 +165,12 @@ async function runStep<TContext = ToolContext>(
}
describe("workflow step authorization", () => {
- beforeEach(() => {
+ beforeEach(async () => {
durable.attempt = 1;
durable.stepId = "step-1";
durable.entries.clear();
+ bundle.loadedFrom = [];
+ await shutdownActiveSandboxHandles();
});
afterEach(() => vi.unstubAllEnvs());
it.each([
@@ -107,6 +200,104 @@ describe("workflow step authorization", () => {
},
);
+ it("resolves a development delivery's generation and starts the sandbox by key", async () => {
+ const { registry, starts } = upsertSandboxes();
+ bundle.registry = registry;
+ const owner = { ...context("user-1", "owner-session") };
+ // `eve dev` deliveries carry the generation a development source resolves to.
+ const generation = {
+ generationId: "generation-1",
+ source: createDiskRuntimeCompiledArtifactsSource("/virtual/app"),
+ };
+ const plan = { path: "/workspace/plan.txt" };
+ await expect(
+ withDevelopmentWorkflowGeneration(generation, () =>
+ runStep(
+ async (ctx) => {
+ await (await ctx.getSandbox()).writeTextFile({ ...plan, content: "draft" });
+ return "written";
+ },
+ {
+ ...owner,
+ sandbox: { bundle: { source: { kind: "development" } }, sessionId: "owner-session" },
+ },
+ ),
+ ),
+ ).resolves.toMatchObject({ kind: "result", output: "written" });
+ expect(bundle.loadedFrom).toEqual([generation.source]);
+ expect(starts).toEqual(["owner-session"]);
+ });
+
+ it("leaves the session's handle tracked for runtime shutdown after a step uses the sandbox", async () => {
+ const { handles, registry, shutDown } = upsertSandboxes();
+ bundle.registry = registry;
+ // The session's turn opened its sandbox in this process.
+ const session = await ensureSandboxAccess({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ nodeId: "__root__",
+ registry,
+ sessionId: "session-1",
+ state: null,
+ });
+ await session.get();
+ const sessionHandle = handles[0];
+ await expect(runStep(async (ctx) => void (await ctx.getSandbox()))).resolves.toMatchObject({
+ kind: "result",
+ });
+ await shutdownActiveSandboxHandles();
+ // The step's handle neither replaced nor dropped the session's.
+ expect(handles).toHaveLength(2);
+ expect(shutDown).toEqual([sessionHandle]);
+ });
+
+ it("fails ctx.getSandbox() without retrying once its step has returned", async () => {
+ const { registry, starts } = upsertSandboxes();
+ bundle.registry = registry;
+ const result = await runStep(async (ctx) => () => ctx.getSandbox());
+ const later = result.kind === "result" ? (result.output as () => Promise<unknown>) : undefined;
+ await expect(later?.()).rejects.toMatchObject({
+ fatal: true,
+ message: expect.stringContaining(
+ 'was called after the "use step" function of tool "devbox" returned',
+ ),
+ });
+ expect(starts).toEqual([]);
+ });
+
+ it("accepts its own copy of the session's environment and leaves stopping and deleting to the session", async () => {
+ const { deleted, provider, registry, stopped } = upsertSandboxes();
+ bundle.registry = registry;
+ // The step imports its own copy of the module that declares the environment.
+ await expect(
+ runStep(async (ctx) => {
+ await ctx.getSandbox(provider.environment());
+ return "opened";
+ }),
+ ).resolves.toMatchObject({ output: "opened" });
+ const other = defineSandboxProvider({
+ name: "other",
+ environment: () => ({
+ onSessionEnd: async () => {},
+ prepare: async () => null,
+ resume: vi.fn(),
+ start: vi.fn(),
+ }),
+ }).environment();
+ const misuse: [string, (ctx: ToolContext) => Promise<unknown>][] = [
+ ["received a sandbox environment", (ctx) => ctx.getSandbox(other)],
+ ["sandbox.stop() is unavailable", async (ctx) => await (await ctx.getSandbox()).stop()],
+ ["sandbox.delete() is unavailable", async (ctx) => await (await ctx.getSandbox()).delete()],
+ ];
+ for (const [message, access] of misuse) {
+ await expect(runStep(access)).rejects.toMatchObject({
+ fatal: true,
+ message: expect.stringContaining(message),
+ });
+ }
+ expect(stopped).not.toHaveBeenCalled();
+ expect(deleted).not.toHaveBeenCalled();
+ });
+
it("does not exchange a consumed code again when the rest of the step retries", async () => {
let exchanged = false;
const complete = vi.fn(async () => {
diff --git a/packages/eve/src/execution/tools/workflow/step-execution.ts b/packages/eve/src/execution/tools/workflow/step-execution.ts
index 7d0759e22..540792f6c 100644
--- a/packages/eve/src/execution/tools/workflow/step-execution.ts
+++ b/packages/eve/src/execution/tools/workflow/step-execution.ts
@@ -1,6 +1,13 @@
import { getStepMetadata } from "#compiled/@workflow/core/index.js";
import { ContextContainer, contextStorage } from "#context/container.js";
-import { AuthKey, InitiatorAuthKey, SessionIdKey, SessionKey } from "#context/keys.js";
+import { AuthKey, InitiatorAuthKey, SandboxKey, SessionIdKey, SessionKey } from "#context/keys.js";
+import type { SessionContext } from "#context/session-context.js";
+import { ensureSandboxAccess, type EnsuredSandboxAccess } from "#execution/sandbox/ensure.js";
+import { createLogger, logError } from "#internal/logging.js";
+import { resolveDurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";
+import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
+import type { SandboxEnvironmentIdentity } from "#shared/sandbox-environment.js";
+import type { SandboxAccess } from "#sandbox/state.js";
import { isConnectionAuthorizationFailedError } from "#connections/errors.js";
import {
isAuthorizationSignal,
@@ -13,10 +20,13 @@ import { buildBaseToolContext } from "#context/build-base-tool-context.js";
import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
import { completeWorkflowStepAuthorization } from "#execution/tools/workflow/authorization-completion.js";
import {
+ type WorkflowStepContext,
type WorkflowStepInvocation,
type WorkflowStepResult,
} from "#execution/tools/workflow/step-context.js";
+const log = createLogger("workflow-step");
+
/** Keeps token capabilities and bearer values inside the executing step. */
export function withWorkflowStepAuthorization(execute: (...args: never[]) => unknown) {
const wrapped = async function (
@@ -34,18 +44,35 @@ export function withWorkflowStepAuthorization(execute: (...args: never[]) => unk
context.setVirtualContext(AuthorizationHookKey, input.token);
context.setVirtualContext(PendingAuthorizationResultKey, input.authorizationResults);
+ const sandbox = openStepSandbox(input);
return contextStorage.run(context, async (): Promise<WorkflowStepResult> => {
const auth = createAuthorizationContext({
scope: input.toolName,
completeAuthorization: completeWorkflowStepAuthorization,
});
+ const base = buildBaseToolContext({
+ toolName: input.toolName,
+ options: { abortSignal: input.abortSignal, toolCallId: input.callId },
+ });
const ctx = {
- ...buildBaseToolContext({
- toolName: input.toolName,
- options: { abortSignal: input.abortSignal, toolCallId: input.callId },
- }),
+ ...base,
agent: () => unavailableInStep("ctx.agent()", "Call ctx.agent() in the workflow body."),
ask: () => unavailableInStep("ctx.ask()", "Call ctx.ask() in the workflow body."),
+ getSandbox: (async (environment?: SandboxEnvironmentIdentity) => {
+ const access = await sandbox.open();
+ // The step imports its own copy of the module that declares the
+ // environment, so it can't match by identity. An agent has one
+ // sandbox definition, and the argument only narrows the type, so
+ // the provider is enough.
+ if (environment !== undefined && access.environment?.provider !== environment.provider) {
+ throw fatal(
+ 'ctx.getSandbox() in a "use step" function received a sandbox environment the session\'s sandbox does not use. ' +
+ "Pass the environment the agent's sandbox definition opens, or call ctx.getSandbox() without one.",
+ );
+ }
+ context.setVirtualContext(SandboxKey, access);
+ return await base.getSandbox();
+ }) as SessionContext["getSandbox"],
getToken: auth.getToken,
requireAuth: auth.requireAuth,
};
@@ -71,6 +98,8 @@ export function withWorkflowStepAuthorization(execute: (...args: never[]) => unk
Object.assign(error, { fatal: true });
}
throw error;
+ } finally {
+ await sandbox.release();
}
const remaining = context.get(PendingAuthorizationResultKey) ?? [];
const authorized = input.authorizationResults
@@ -86,9 +115,91 @@ export function withWorkflowStepAuthorization(execute: (...args: never[]) => unk
return wrapped;
}
+/**
+ * The calling session's sandbox, opened on the step's first `ctx.getSandbox()`
+ * under the key of the session that owns it, and let go of when the step
+ * ends. Recorded state, when the call captured it, resumes the sandbox;
+ * without it, or when that sandbox is gone, the provider's `start` upserts
+ * it by that key with the owner's sandbox definition, so the session finds
+ * the same sandbox and its session-end cleanup removes it. The step never owns the sandbox: the
+ * session's turns may be using it, so the step can neither stop nor delete it.
+ * A step that never asks for it loads nothing.
+ */
+function openStepSandbox(input: WorkflowStepContext) {
+ const { bundle, sessionId, state } = input.sandbox;
+ // The step's own context replaces the delivery's, which carries the
+ // development generation a development source resolves to.
+ const delivery = contextStorage.getStore();
+ const resolveSource = () => resolveDurableCompiledArtifactsSource(bundle.source);
+ let opening: Promise<EnsuredSandboxAccess> | undefined;
+ let released = false;
+ const open = async (): Promise<EnsuredSandboxAccess> => {
+ const compiled = await getCompiledRuntimeAgentBundle({
+ compiledArtifactsSource:
+ delivery === undefined ? resolveSource() : contextStorage.run(delivery, resolveSource),
+ nodeId: bundle.nodeId,
+ });
+ const node = compiled.graph.root;
+ return await ensureSandboxAccess({
+ compiledArtifactsSource: compiled.compiledArtifactsSource,
+ nodeId: node.nodeId,
+ ownsSandbox: false,
+ registry: node.sandboxRegistry,
+ sessionId,
+ state: state ?? null,
+ borrowed: true,
+ });
+ };
+ const openOnce = (): Promise<EnsuredSandboxAccess> => {
+ opening ??= open().catch((error: unknown) => {
+ opening = undefined;
+ throw error;
+ });
+ return opening;
+ };
+ return {
+ async open(): Promise<SandboxAccess> {
+ if (released) {
+ throw fatal(
+ `ctx.getSandbox() was called after the "use step" function of tool "${input.toolName}" returned. ` +
+ "Call it inside the step, which lets go of the sandbox when it ends.",
+ );
+ }
+ const access = await openOnce();
+ return {
+ ...access,
+ delete: () =>
+ unavailableInStep(
+ "sandbox.delete()",
+ "The step borrows the session's sandbox, and only the session can delete it.",
+ ),
+ stop: () =>
+ unavailableInStep(
+ "sandbox.stop()",
+ "The session's turns may be using the sandbox; eve lets go of the step's handle when the step ends.",
+ ),
+ };
+ },
+ async release(): Promise<void> {
+ released = true;
+ const access = await opening?.catch(() => undefined);
+ try {
+ await access?.detach();
+ } catch (error) {
+ logError(log, "failed to release a workflow step's sandbox", error, {
+ sessionId,
+ toolName: input.toolName,
+ });
+ }
+ },
+ };
+}
+
function unavailableInStep(capability: string, guidance: string): never {
- throw Object.assign(
- new Error(`${capability} is unavailable inside a "use step" function. ${guidance}`),
- { fatal: true },
- );
+ throw fatal(`${capability} is unavailable inside a "use step" function. ${guidance}`);
+}
+
+/** A misuse a retry would repeat, which the Workflow SDK fails without retrying. */
+function fatal(message: string): Error {
+ return Object.assign(new Error(message), { fatal: true });
}
diff --git a/packages/eve/src/execution/tools/workflow/step.ts b/packages/eve/src/execution/tools/workflow/step.ts
index 669f7775c..f5ecb91dd 100644
--- a/packages/eve/src/execution/tools/workflow/step.ts
+++ b/packages/eve/src/execution/tools/workflow/step.ts
@@ -74,6 +74,7 @@ async function executeAuthorizedStep(
ctx,
execute,
receiver,
+ run,
});
} catch (error) {
if (!ctx.abortSignal.aborted) {
@@ -116,8 +117,9 @@ async function invokeAuthorizedStep(input: {
readonly ctx: ToolContext;
readonly execute: (invocation: WorkflowStepInvocation) => Promise<unknown>;
readonly receiver: unknown;
+ readonly run: WorkflowToolRunContext;
}): Promise<WorkflowStepResult> {
- const { args, authorizationResults, callbackToken, ctx, execute, receiver } = input;
+ const { args, authorizationResults, callbackToken, ctx, execute, receiver, run } = input;
const context: WorkflowStepContext = {
callId: ctx.callId,
toolName: ctx.toolName,
@@ -126,6 +128,11 @@ async function invokeAuthorizedStep(input: {
baseUrl: getWorkflowMetadata().url,
token: callbackToken,
authorizationResults,
+ sandbox: {
+ bundle: run.agentContext.bundle,
+ sessionId: run.agentContext.sandbox.sessionId,
+ state: run.agentContext.sandbox.state,
+ },
};
const invocation: WorkflowStepInvocation = {
args: args.map((arg) => (arg === ctx ? null : arg)),
diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
index 8210757a2..80ab202f7 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
@@ -22,6 +22,9 @@ import {
failingDeployWorkflow,
reportingDeployWorkflow,
returnAskAnswerWorkflow,
+ sandboxParallelPrepareWorkflow,
+ sandboxStepRuns,
+ sandboxPrepareWorkflow,
stepReferenceWorkflow,
workflowContextMisuseWorkflow,
} from "#internal/testing/workflow-tool-fixtures.js";
@@ -140,6 +143,187 @@ describe("workflow tools", () => {
expect(consoleOutput.unexpected(workflowSdkNotice.fatalStep)).toEqual([]);
});
+ it("opens the session's sandbox from steps before the session does, and the session's end removes it", async () => {
+ const readBySession: (string | null)[] = [];
+ let reply = "";
+ sandboxStepRuns().clear();
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-step-sandbox-first",
+ execute: sandboxParallelPrepareWorkflow,
+ modules: [
+ {
+ logicalPath: "hooks/sandbox.ts",
+ loadNamespace: async () => ({
+ default: defineHook({
+ events: {
+ // The session's turn uses its sandbox after the steps wrote to it.
+ async "action.result"(_event, ctx) {
+ const sandbox = await ctx.getSandbox();
+ readBySession.push(await sandbox.readTextFile({ path: "/workspace/plan.txt" }));
+ },
+ },
+ }),
+ }),
+ },
+ ],
+ toolName: "deploy_service",
+ });
+
+ await runtime.run(async () => {
+ const run = await startSessionOwner(workflowEntry, [
+ {
+ kind: "initial",
+ ownerDeploymentId: "dpl_inline",
+ input: { message: 'Run deploy_service with service "api"' },
+ serializedContext: buildWorkflowToolSerializedContext({
+ continuationToken: "schedule:workflow-step-sandbox-first",
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+ try {
+ const turn = await stream.nextTurn();
+ reply = String(filterEventsByType(turn, "message.completed").at(-1)?.data.message);
+ await resumeSessionInbox(sessionCommandHookToken(run.runId), { kind: "reset" });
+ const terminal = await stream.nextTurn();
+ expect(filterEventsByType(terminal, "session.completed")).toHaveLength(1);
+ } finally {
+ stream.dispose();
+ if ((await run.status) === "running") await run.cancel();
+ }
+ });
+
+ // Two concurrent steps opened the sandbox first, each running once, and a third read both
+ // files. The session's turn saw the same sandbox, and its end removed it by key.
+ expect(reply).toContain('"config":"config:api"');
+ expect(reply).toContain('"plan":"plan:api"');
+ expect(Object.fromEntries(sandboxStepRuns())).toEqual({ config: 1, plan: 1 });
+ expect(readBySession).toEqual(["plan:api"]);
+ const keys = new Set(runtime.sandboxEvents.map((event) => event.split(":")[1]));
+ expect(keys.size).toBe(1);
+ expect(runtime.sandboxCleanups).toEqual([...keys]);
+ });
+
+ it("resumes from a step the sandbox the session opened before the call", async () => {
+ const readBySession: (string | null)[] = [];
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-step-sandbox",
+ execute: sandboxPrepareWorkflow,
+ modules: [
+ {
+ logicalPath: "hooks/sandbox.ts",
+ loadNamespace: async () => ({
+ default: defineHook({
+ events: {
+ async "message.received"(_event, ctx) {
+ const sandbox = await ctx.getSandbox();
+ await sandbox.writeTextFile({
+ content: "from-session",
+ path: "/workspace/seed.txt",
+ });
+ },
+ async "action.result"(_event, ctx) {
+ const sandbox = await ctx.getSandbox();
+ readBySession.push(
+ await sandbox.readTextFile({ path: "/workspace/prepared.txt" }),
+ );
+ },
+ },
+ }),
+ }),
+ },
+ ],
+ toolName: "deploy_service",
+ });
+
+ const output = await runtime.run(async () => {
+ const run = await startSessionOwner(workflowEntry, [
+ {
+ kind: "initial",
+ ownerDeploymentId: "dpl_inline",
+ input: { message: 'Run deploy_service with service "api"' },
+ serializedContext: buildWorkflowToolSerializedContext({
+ continuationToken: "schedule:workflow-step-sandbox",
+ }),
+ },
+ ]);
+ return String(await readFirstTurnReply(run));
+ });
+
+ // The step resumed the state the session recorded instead of running the definition again.
+ expect(output).toContain('"seed":"from-session"');
+ expect(readBySession).toEqual(["prepared:api"]);
+ const events = runtime.sandboxEvents.map((event) => event.split(":")[0]);
+ expect(events.filter((event) => event === "definition")).toHaveLength(1);
+ expect(events.filter((event) => event === "start")).toHaveLength(1);
+ expect(events).toContain("resume");
+ });
+
+ it("opens the parent's sandbox from a step of a child that shares it", async () => {
+ const readBySession: [string, string | null][] = [];
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-step-sandbox-child",
+ execute: sandboxPrepareWorkflow,
+ modules: [
+ {
+ logicalPath: "hooks/sandbox.ts",
+ loadNamespace: async () => ({
+ default: defineHook({
+ events: {
+ async "message.received"(_event, ctx) {
+ const sandbox = await ctx.getSandbox();
+ readBySession.push([
+ ctx.session.id,
+ await sandbox.readTextFile({ path: "/workspace/prepared.txt" }),
+ ]);
+ },
+ },
+ }),
+ }),
+ },
+ ],
+ toolName: "deploy_service",
+ });
+
+ let parentId = "";
+ await runtime.run(async () => {
+ // The built-in `agent` copy shares the root's sandbox and calls the workflow tool.
+ const run = await startSessionOwner(workflowEntry, [
+ {
+ kind: "initial",
+ ownerDeploymentId: "dpl_inline",
+ input: { message: 'Delegate to a subagent: Run deploy_service with service "api"' },
+ serializedContext: buildWorkflowToolSerializedContext({
+ continuationToken: "schedule:workflow-step-sandbox-child",
+ }),
+ },
+ ]);
+ parentId = run.runId;
+ const stream = captureTurnEvents(run);
+ try {
+ // The child's task settles within the parent's first turn; the parent reads on the next.
+ await stream.nextTurn();
+ await resumeSessionInbox(
+ { sessionId: run.runId },
+ { kind: "send", payload: { message: "Alice checks the prepared file." } },
+ );
+ await stream.nextTurn();
+ await resumeSessionInbox(sessionCommandHookToken(run.runId), { kind: "reset" });
+ await stream.nextTurn();
+ } finally {
+ stream.dispose();
+ if ((await run.status) === "running") await run.cancel();
+ }
+ });
+
+ // The child's step opened the sandbox under the parent's key, so the parent reads its file and
+ // the parent's end removes it.
+ const keys = new Set(runtime.sandboxEvents.map((event) => event.split(":")[1]));
+ expect([...keys]).toEqual([parentId]);
+ expect(readBySession).toContainEqual([parentId, "prepared:api"]);
+ expect(runtime.sandboxCleanups).toEqual([parentId]);
+ });
+
it("settles the call with an error when the workflow body throws", async () => {
const runtime = await createWorkflowToolRuntime({
agentName: "workflow-tool-fail",
diff --git a/packages/eve/src/internal/testing/app-harness.ts b/packages/eve/src/internal/testing/app-harness.ts
index 95ca68c7f..587127411 100644
--- a/packages/eve/src/internal/testing/app-harness.ts
+++ b/packages/eve/src/internal/testing/app-harness.ts
@@ -20,7 +20,10 @@ import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";
import { createNodeHarnessTools } from "#execution/node-step.js";
import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";
import { defineSandbox } from "#public/definitions/sandbox.js";
-import { defineSandboxProvider } from "#shared/sandbox-provider.js";
+import {
+ defineSandboxProvider,
+ type SandboxProviderSessionContext,
+} from "#shared/sandbox-provider.js";
import {
buildActiveSessionContext,
type ActiveSessionInit,
@@ -117,6 +120,11 @@ export interface TestRuntime {
): Promise<unknown>;
/** Session ids whose sandbox cleanup ran when the session ended, in order. */
readonly sandboxCleanups: readonly string[];
+ /**
+ * What happened to the sessions' sandboxes, in order, as `<event>:<session id>`:
+ * `definition` when `sandbox.ts` runs, then `start`, `resume`, or `delete`.
+ */
+ readonly sandboxEvents: readonly string[];
/**
* Clears the compiled-artifact snapshot, bundle cache, and sessions' sandboxes.
* Tests that re-use a runtime across multiple assertions can call this to
@@ -148,6 +156,7 @@ const TEST_SANDBOX_PROVIDER_NAME = "eve-test-memory";
function createTestSandboxProvider() {
const sessionSandboxes = new Map<string, MockSandbox>();
const endedSessionIds: string[] = [];
+ const events: string[] = [];
function createHandle(sessionId: string) {
let sandbox = sessionSandboxes.get(sessionId);
@@ -159,6 +168,7 @@ function createTestSandboxProvider() {
return {
sandbox: opened.session,
async onSandboxDelete(options?: import("#shared/sandbox-provider.js").SandboxDeleteOptions) {
+ events.push(`delete:${sessionId}`);
sessionSandboxes.delete(sessionId);
await opened.access.delete?.(options);
},
@@ -179,10 +189,12 @@ function createTestSandboxProvider() {
async prepare() {
return null;
},
- async resume(context) {
+ async resume(context: SandboxProviderSessionContext) {
+ events.push(`resume:${context.session.id}`);
return createHandle(context.session.id);
},
- async start(context) {
+ async start(context: SandboxProviderSessionContext) {
+ events.push(`start:${context.session.id}`);
return { handle: createHandle(context.session.id), state: null };
},
}),
@@ -191,8 +203,10 @@ function createTestSandboxProvider() {
clear: () => {
sessionSandboxes.clear();
endedSessionIds.length = 0;
+ events.length = 0;
},
endedSessionIds,
+ events,
provider,
};
}
@@ -208,7 +222,13 @@ export async function createTestRuntime(descriptor: TestAppDescriptor = {}): Pro
{
loadNamespace: async () => {
const environment = sandboxes.provider.environment();
- return { environment, default: defineSandbox(() => environment.open()) };
+ return {
+ environment,
+ default: defineSandbox(({ session }) => {
+ sandboxes.events.push(`definition:${session.id}`);
+ return environment.open();
+ }),
+ };
},
logicalPath: "sandbox.ts",
},
@@ -302,6 +322,7 @@ export async function createTestRuntime(descriptor: TestAppDescriptor = {}): Pro
run,
runAsSession,
sandboxCleanups: sandboxes.endedSessionIds,
+ sandboxEvents: sandboxes.events,
session,
tools,
};
diff --git a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
index 7d7952eb8..892f84b35 100644
--- a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
+++ b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
@@ -12,7 +12,7 @@ import {
sleep as workflowSleep,
} from "#compiled/@workflow/core/index.js";
-import type { WorkflowToolContext } from "#tools/workflow-definition.js";
+import type { WorkflowStepToolContext, WorkflowToolContext } from "#tools/workflow-definition.js";
import {
ConnectionAuthorizationFailedError,
ConnectionAuthorizationRequiredError,
@@ -40,6 +40,56 @@ export async function authorizedDeployWorkflow(input: DeployInput, ctx: Workflow
return { plan, authenticatedAs };
}
+export async function sandboxPrepareWorkflow(input: DeployInput, ctx: WorkflowToolContext) {
+ "use workflow";
+ return await prepareSandboxStep(input.service, ctx);
+}
+
+async function prepareSandboxStep(service: string, ctx: WorkflowStepToolContext) {
+ "use step";
+ const sandbox = await ctx.getSandbox();
+ const seed = await sandbox.readTextFile({ path: "/workspace/seed.txt" });
+ await sandbox.writeTextFile({ content: `prepared:${service}`, path: "/workspace/prepared.txt" });
+ return { seed };
+}
+
+export async function sandboxParallelPrepareWorkflow(input: DeployInput, ctx: WorkflowToolContext) {
+ "use workflow";
+ await Promise.all([
+ writeSandboxFileStep(ctx, "plan", input.service),
+ writeSandboxFileStep(ctx, "config", input.service),
+ ]);
+ return await readSandboxFilesStep(ctx);
+}
+
+const STEP_RUNS = Symbol.for("eve.test.sandbox-step-runs");
+
+/**
+ * How many times each sandbox-writing step ran, by file name, so a test can
+ * rule out reruns. Steps run from their own bundled copy of this module, so
+ * the count lives on `globalThis`.
+ */
+export function sandboxStepRuns(): Map<string, number> {
+ const shared = globalThis as typeof globalThis & { [STEP_RUNS]?: Map<string, number> };
+ return (shared[STEP_RUNS] ??= new Map());
+}
+async function writeSandboxFileStep(ctx: WorkflowStepToolContext, name: string, service: string) {
+ "use step";
+ const runs = sandboxStepRuns();
+ runs.set(name, (runs.get(name) ?? 0) + 1);
+ const sandbox = await ctx.getSandbox();
+ await sandbox.writeTextFile({ content: `${name}:${service}`, path: `/workspace/${name}.txt` });
+}
+
+async function readSandboxFilesStep(ctx: WorkflowStepToolContext) {
+ "use step";
+ const sandbox = await ctx.getSandbox();
+ return {
+ config: await sandbox.readTextFile({ path: "/workspace/config.txt" }),
+ plan: await sandbox.readTextFile({ path: "/workspace/plan.txt" }),
+ };
+}
+
export async function workflowContextMisuseWorkflow(_input: DeployInput, ctx: WorkflowToolContext) {
"use workflow";
return await readAgentsStep(ctx);
diff --git a/packages/eve/src/tools/workflow-definition.test.ts b/packages/eve/src/tools/workflow-definition.test.ts
index af81a75bd..417d5b9f9 100644
--- a/packages/eve/src/tools/workflow-definition.test.ts
+++ b/packages/eve/src/tools/workflow-definition.test.ts
@@ -38,10 +38,9 @@ describe("defineWorkflowTool", () => {
});
// @ts-expect-error The message is sent with send(), not passed to ctx.agent().
void ctx.agent("researcher", { message: "Review the deployment." });
- // Token capabilities are available when this context is passed into a step.
- void ctx.getToken;
- // @ts-expect-error Workflow bodies do not have a session sandbox.
- void ctx.getSandbox;
+ // Token and sandbox capabilities are available when this context is passed into a step.
+ const useStepContext = async (stepCtx: WorkflowStepToolContext) => stepCtx;
+ void useStepContext(ctx);
return { deployed: input.service };
},
approvalKey(input) {
@@ -104,6 +103,7 @@ describe("defineWorkflowTool", () => {
it("exposes only step-safe capabilities on WorkflowStepToolContext", () => {
const useStepContext = (ctx: WorkflowStepToolContext) => {
+ void ctx.getSandbox;
void ctx.getToken;
void ctx.requireAuth;
void ctx.abortSignal;
diff --git a/packages/eve/src/tools/workflow-definition.ts b/packages/eve/src/tools/workflow-definition.ts
index 176f4ec64..4e9a3f50f 100644
--- a/packages/eve/src/tools/workflow-definition.ts
+++ b/packages/eve/src/tools/workflow-definition.ts
@@ -45,10 +45,21 @@ export interface AgentSessionOptions {
readonly model?: AgentSessionModelSelection;
}
-/** Context capabilities available inside an authored `"use step"` helper. */
+/**
+ * Context capabilities available inside an authored `"use step"` helper.
+ *
+ * `getSandbox()` opens the sandbox of the session that made the call, the
+ * same sandbox its turns use. If the session had not recorded its sandbox
+ * when it called the tool, the step opens it with the sandbox definition of
+ * the session that owns it (the parent's, for a session that shares its
+ * parent's sandbox), so make that definition safe to run again. The step does not own the sandbox: eve lets go of the
+ * step's handle when the step ends and never stops or deletes the sandbox for
+ * it, and `stop()` and `delete()` throw. The session deletes it when the
+ * session ends. Steps can retry, so make sandbox writes safe to repeat.
+ */
export type WorkflowStepToolContext = Pick<
ToolContext,
- "abortSignal" | "callId" | "session" | "toolName" | "getToken" | "requireAuth"
+ "abortSignal" | "callId" | "session" | "toolName" | "getSandbox" | "getToken" | "requireAuth"
>;
/** Options for one message to a `ctx.agent` session. */
@@ -96,10 +107,14 @@ export interface AgentSession {
): Promise<AgentResponse<TOutput>>;
}
-/** Members the context of every workflow tool entry point shares. */
+/**
+ * Members the context of every workflow tool entry point shares.
+ * `getSandbox`, `getToken`, and `requireAuth` work only after `ctx` is passed
+ * to a `"use step"` helper; the workflow body throws when it calls them.
+ */
export type WorkflowSharedContext = Pick<
ToolContext,
- "session" | "toolName" | "getToken" | "requireAuth"
+ "session" | "toolName" | "getSandbox" | "getToken" | "requireAuth"
> & {
/**
* Returns a new session with the agent of this invocation name. Nothing