Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): code mode - remove agent-wide tool wrapping (#295)

Andrew Barba5c32eb0f9363
diff --git a/.changeset/clean-waves-workflow.md b/.changeset/clean-waves-workflow.md
new file mode 100644
index 000000000..8b256e3b7
--- /dev/null
+++ b/.changeset/clean-waves-workflow.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Remove `defineAgent({ experimental: { codeMode } })` and the `EVE_EXPERIMENTAL_CODE_MODE` fallback. Tools are always exposed directly to the model; model-authored JavaScript orchestration remains available through the experimental `Workflow` tool for subagents and remote agents.
diff --git a/.changeset/swift-agents-delegate.md b/.changeset/swift-agents-delegate.md
new file mode 100644
index 000000000..48023097b
--- /dev/null
+++ b/.changeset/swift-agents-delegate.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Strengthen the built-in `agent` tool guidance so models know when and how to split large tasks across a fixed batch of parallel recursive calls.
diff --git a/docs/agent-config.md b/docs/agent-config.md
index 486c26ae7..4460a65c1 100644
--- a/docs/agent-config.md
+++ b/docs/agent-config.md
@@ -106,15 +106,13 @@ external in hosted output, list it in `build.externalDependencies`.
`defineAgent` takes a few more fields, all optional. For the exported types, see the [TypeScript API](./reference/typescript-api).
-| Field | Type | Default | Description |
-| -------------- | ------------------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `reasoning` | `AgentReasoningDefinition` | provider default | Provider-agnostic reasoning effort forwarded to the agent's turn model calls. |
-| `modelOptions` | `AgentModelOptionsDefinition` | none | Provider option overrides forwarded to the model call. |
-| `experimental` | `{ codeMode?: boolean; workflow?: { world?: string } }` | flags unset | Opt-in flags that can change or disappear in any release. Treat them as unstable. `codeMode` routes executable tools through a sandboxed code-execution wrapper, where the model writes JavaScript that calls the tools inside the [sandbox](./sandbox). `workflow.world` selects the Workflow world package backing session state, queues, hooks, and streams on the root agent. |
-| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for task-mode runs (a subagent, schedule, or remote job). Interactive conversation turns ignore it unless the client supplies a per-message schema. |
-| `build` | `{ externalDependencies?: string[] }` | none | Hosted-build packaging controls. `externalDependencies` keeps listed packages external while eve compiles authored modules such as tools and channels, and traces those packages into the hosted output. |
-
-`codeMode` is experimental and may change or be removed.
+| Field | Type | Default | Description |
+| -------------- | --------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `reasoning` | `AgentReasoningDefinition` | provider default | Provider-agnostic reasoning effort forwarded to the agent's turn model calls. |
+| `modelOptions` | `AgentModelOptionsDefinition` | none | Provider option overrides forwarded to the model call. |
+| `experimental` | `{ workflow?: { world?: string } }` | unset | Opt-in settings that can change or disappear in any release. Treat them as unstable. `workflow.world` selects the Workflow world package backing session state, queues, hooks, and streams on the root agent. |
+| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for task-mode runs (a subagent, schedule, or remote job). Interactive conversation turns ignore it unless the client supplies a per-message schema. |
+| `build` | `{ externalDependencies?: string[] }` | none | Hosted-build packaging controls. `externalDependencies` keeps listed packages external while eve compiles authored modules such as tools and channels, and traces those packages into the hosted output. |
`externalDependencies` is a packaging control only. It keeps selected packages as runtime dependencies in the hosted output; it does not authorize, configure, or review any third-party service those packages may call.
diff --git a/docs/guides/dynamic-workflows.md b/docs/guides/dynamic-workflows.md
index 511b6b477..e3881c3e6 100644
--- a/docs/guides/dynamic-workflows.md
+++ b/docs/guides/dynamic-workflows.md
@@ -3,7 +3,7 @@ title: "Dynamic Workflows"
description: "The experimental Workflow tool: let the model orchestrate its own subagents from model-authored JavaScript as one durable step."
---
-The experimental `Workflow` tool lets the model write JavaScript that coordinates the agent's own subagents as a single durable step. The program can run them in sequence, feed one result into the next, fan out over a list, and combine the results. You enable the capability and the model decides and runs the orchestration. It is the agents-only slice of [code mode](../agent-config#other-defineagent-fields) (the broader `codeMode` flag that routes all of an agent's tools through model-authored JavaScript).
+The experimental `Workflow` tool lets the model write JavaScript that coordinates the agent's own subagents as a single durable step. The program can run them in sequence, feed one result into the next, fan out over a list, and combine the results. You enable the capability and the model decides and runs the orchestration.
A single turn can already call several subagents, and parallel tool calls dispatch concurrently. What a workflow adds is _programmatic_ coordination. The program decides how many subagents to run based on an earlier result, which output feeds which call, and how to combine everything. That is logic the model cannot express as a few one-off calls.
@@ -63,12 +63,6 @@ That is an allowlist, not a denylist. The sandbox cannot read files, open a sock
- **Approval-safe.** A subagent that needs human approval (HITL, human-in-the-loop) mid-run surfaces its request to the user, and the workflow picks back up once that is answered, same as direct delegation.
- **Observable.** Every orchestrated subagent emits the usual `subagent.called` / `subagent.completed` events on the parent stream and gets its own child session and stream. The telemetry matches direct delegation, so existing dashboards and cost attribution keep working.
-## Relationship to code mode
-
-[Code mode](../agent-config#other-defineagent-fields) is the broader version, where the model drives _all_ of an agent's tools (files, shell, web, and agents) from JavaScript. A workflow covers only the subagents. The two do not interfere. Enabling the `Workflow` tool leaves code mode untouched, and an agent can run both at once.
-
-`codeMode` is experimental and may change or be removed.
-
## What to read next
- Declare the subagents a workflow orchestrates → [Subagents](../subagents)
diff --git a/docs/subagents.mdx b/docs/subagents.mdx
index 20b6ea0e9..b505fc131 100644
--- a/docs/subagents.mdx
+++ b/docs/subagents.mdx
@@ -16,7 +16,7 @@ Every agent gets an `agent` tool by default. The model calls it to delegate a su
}
```
-The copy shares the parent's sandbox and tools, and a child's file writes are immediately visible to the parent. That is what makes parallel calls natural: fan out a few copies to fix different files at once. The copy inherits auth and connections, but starts with fresh conversation history and fresh state. If a declared subagent calls `agent`, the child is a copy of _that_ subagent, not the root.
+The copy shares the parent's sandbox and tools, and a child's file writes are immediately visible to the parent. That is what makes parallel calls natural: emit multiple `agent` calls in one response to fan out a small, fixed set of independent subtasks. eve runs that batch concurrently and returns every result before the parent continues. Give children non-overlapping write scopes when they work in the shared sandbox. The copy inherits auth and connections, but starts with fresh conversation history and fresh state. If a declared subagent calls `agent`, the child is a copy of _that_ subagent, not the root.
The parent transfers data to the child through the `message` input it gives the subagent. Do not include sensitive data in a subagent request unless that child and its inherited tools, connections, sandbox, and telemetry path are appropriate for that data.
diff --git a/e2e/fixtures/agent-subagents/agent/tools/workflow.ts b/e2e/fixtures/agent-subagents/agent/tools/workflow.ts
new file mode 100644
index 000000000..783084219
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/agent/tools/workflow.ts
@@ -0,0 +1 @@
+export { ExperimentalWorkflow as default } from "eve/tools";
diff --git a/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts
new file mode 100644
index 000000000..4842ab877
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts
@@ -0,0 +1,42 @@
+import { defineEval } from "eve/evals";
+
+const SUBAGENT_TOKEN = "SUBAGENT_TOKEN=echo-marker-9F2X";
+const DOUBLE_SUBAGENT_TOKEN = new RegExp(`${SUBAGENT_TOKEN}.*${SUBAGENT_TOKEN}`, "s");
+
+function isFanOutProgram(input: unknown): boolean {
+ if (typeof input !== "object" || input === null) return false;
+ const js = (input as { js?: unknown }).js;
+ return (
+ typeof js === "string" &&
+ js.includes("Promise.all") &&
+ js.includes("echo-marker") &&
+ js.includes("workflow alpha") &&
+ js.includes("workflow beta")
+ );
+}
+
+/** Dynamic Workflow smoke: sandboxed JavaScript fans out durable children. */
+export default defineEval({
+ description:
+ "Dynamic Workflow smoke: model-authored JavaScript fans out two local subagent calls and combines their results.",
+ async test(t) {
+ const turn = await t.send(
+ "Use the Workflow tool exactly once to fan out two independent echo-marker subagent calls. In its JavaScript, create the messages 'workflow alpha' and 'workflow beta', map them through echo-marker inside Promise.all, and return the resulting two-element array. Do not call echo-marker outside Workflow. Then reply with the returned array verbatim as JSON.",
+ );
+ turn.expectOk();
+
+ t.didNotFail();
+ t.completed();
+ t.calledTool("Workflow", { input: isFanOutProgram, times: 1 });
+ t.event(
+ (events) =>
+ events.filter(
+ (event) => event.type === "subagent.called" && event.data.name === "echo-marker",
+ ).length === 2,
+ "Workflow dispatched exactly two echo-marker children",
+ );
+ t.calledSubagent("echo-marker", { output: /SUBAGENT_TOKEN=echo-marker-9F2X/ });
+ t.messageIncludes(DOUBLE_SUBAGENT_TOKEN);
+ t.noFailedActions();
+ },
+});
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 7baf3f717..125303a17 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -340,7 +340,6 @@ const compiledAgentConfigSchema: z.ZodType<CompiledAgentDefinition> = z
description: z.string().optional(),
experimental: z
.object({
- codeMode: z.boolean().optional(),
workflow: compiledAgentWorkflowDefinitionSchema.optional(),
})
.strict()
@@ -683,7 +682,6 @@ export function createCompiledAgentNodeManifest(input: {
input.config.experimental === undefined
? undefined
: {
- codeMode: input.config.experimental.codeMode,
workflow:
input.config.experimental.workflow === undefined
? undefined
diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.ts
index 3efa9cb87..a86b1c36d 100644
--- a/packages/eve/src/compiler/normalize-agent-config.ts
+++ b/packages/eve/src/compiler/normalize-agent-config.ts
@@ -140,10 +140,6 @@ function normalizeExperimentalDefinition(
const compiledExperimental: Mutable<NonNullable<CompiledAgentDefinition["experimental"]>> = {};
- if (experimental.codeMode !== undefined) {
- compiledExperimental.codeMode = experimental.codeMode;
- }
-
if (experimental.workflow !== undefined) {
compiledExperimental.workflow = {
world: experimental.workflow.world,
diff --git a/packages/eve/src/execution/dispatch-code-mode-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
similarity index 58%
rename from packages/eve/src/execution/dispatch-code-mode-runtime-actions-step.ts
rename to packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
index caf7b8075..cbd382e7a 100644
--- a/packages/eve/src/execution/dispatch-code-mode-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
@@ -1,29 +1,19 @@
-/**
- * Dispatches runtime actions originating from code mode.
- *
- * Reads the pending code mode runtime action from session state,
- * builds a runtime action request from the interrupt payload, stores
- * it as a temporary PendingRuntimeActionBatch, and delegates to the
- * standard dispatch step. The batch is only needed for dispatch —
- * the harness never sees it because results flow through
- * continuePendingCodeModeRuntimeAction, not resolvePendingRuntimeActions.
- */
-
-import { buildRuntimeActionFromInterrupt } from "#harness/code-mode-runtime-action-state.js";
-import { getPendingCodeModeInterrupt } from "#harness/code-mode-interrupt-state.js";
-import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
-import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
+import { deserializeContext } from "#context/serialize.js";
+import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
import {
createDurableSessionState,
type DurableSessionState,
readDurableSession,
} from "#execution/durable-session-store.js";
import { hydrateDurableSession } from "#execution/session.js";
-import { deserializeContext } from "#context/serialize.js";
+import { getPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";
+import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
+import { buildRuntimeActionFromWorkflowInterrupt } from "#harness/workflow-runtime-action-state.js";
import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
-import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
+import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
-export async function dispatchCodeModeRuntimeActionsStep(input: {
+/** Dispatches the child-agent action currently blocking a dynamic workflow. */
+export async function dispatchWorkflowRuntimeActionsStep(input: {
readonly callbackBaseUrl?: string;
readonly parentWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
@@ -35,14 +25,10 @@ export async function dispatchCodeModeRuntimeActionsStep(input: {
"use step";
const durableSession = await readDurableSession(input.sessionState);
- const codeModeAction = getPendingCodeModeInterrupt(durableSession.state);
-
- if (codeModeAction === undefined) {
- return { results: [], sessionState: input.sessionState };
- }
-
- const action = buildRuntimeActionFromInterrupt(codeModeAction.interrupt);
+ const pending = getPendingWorkflowInterrupt(durableSession.state);
+ if (pending === undefined) return { results: [], sessionState: input.sessionState };
+ const action = buildRuntimeActionFromWorkflowInterrupt(pending.interrupt);
const ctx = await deserializeContext(input.serializedContext);
const bundle = ctx.require(BundleKey);
const session = hydrateDurableSession({
@@ -55,17 +41,15 @@ export async function dispatchCodeModeRuntimeActionsStep(input: {
const sessionWithBatch = setPendingRuntimeActionBatch({
actions: [action],
- event: { sequence: 0, stepIndex: 0, turnId: "code-mode-dispatch" },
+ event: { sequence: 0, stepIndex: 0, turnId: "workflow-dispatch" },
responseMessages: [],
session,
});
- const batchState = createDurableSessionState({ session: sessionWithBatch });
-
return dispatchRuntimeActionsStep({
callbackBaseUrl: input.callbackBaseUrl,
parentWritable: input.parentWritable,
serializedContext: input.serializedContext,
- sessionState: batchState,
+ sessionState: createDurableSessionState({ session: sessionWithBatch }),
});
}
diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.ts
index 9671dabf2..e1cc21add 100644
--- a/packages/eve/src/execution/next-driver-action.ts
+++ b/packages/eve/src/execution/next-driver-action.ts
@@ -35,7 +35,7 @@ export type NextDriverAction =
readonly serializedContext: Record<string, unknown>;
}
| {
- readonly kind: "dispatch-code-mode-runtime-actions";
+ readonly kind: "dispatch-workflow-runtime-actions";
readonly pendingActionKeys: readonly string[];
readonly sessionState: DurableSessionState;
readonly serializedContext: Record<string, unknown>;
diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.ts
index 3cd9f2612..ececac66a 100644
--- a/packages/eve/src/execution/node-step.test.ts
+++ b/packages/eve/src/execution/node-step.test.ts
@@ -12,7 +12,7 @@ import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";
import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";
import type { RuntimeToolRegistry } from "#runtime/tools/registry.js";
import { createRuntimeToolRegistry } from "#runtime/tools/registry.js";
-import { createExecutionNodeStep } from "#execution/node-step.js";
+import { createExecutionNodeStep, createNodeHarnessTools } from "#execution/node-step.js";
import { createSession } from "#execution/session.js";
import { createStubSandboxRegistry } from "#internal/testing/stub-sandbox-registry.js";
@@ -23,22 +23,6 @@ vi.mock("ai", () => ({
tool: vi.fn((definition: unknown) => definition),
}));
-vi.mock("#compiled/experimental-ai-sdk-code-mode/index.js", () => ({
- continueCodeModeApproval: vi.fn(),
- continueCodeModeInterrupt: vi.fn(),
- createCodeModeTool: vi.fn(() => ({
- description: "Code mode.",
- execute: async () => "tool-output",
- inputSchema: {},
- })),
- getCodeModeApprovalResponse: vi.fn(),
- getCodeModeInterrupt: vi.fn(() => undefined),
- isCodeModeApprovalInterrupt: vi.fn(() => false),
- replaceCodeModeInterruptResult: vi.fn(),
- toCodeModeApprovalMessages: vi.fn(() => []),
- unwrapCodeModeResult: vi.fn((value: unknown) => ({ output: value, status: "completed" })),
-}));
-
vi.mock("../runtime/agent/resolve-model.js", () => ({
resolveRuntimeModelReference: vi.fn().mockResolvedValue({}),
}));
@@ -73,7 +57,15 @@ function setupMockAgentForToolExecution(toolName: string, args: unknown): void {
const tools = (
settings as {
- readonly tools: Record<string, { execute: (input: unknown) => Promise<unknown> }>;
+ readonly tools: Record<
+ string,
+ {
+ execute: (
+ input: unknown,
+ options: { readonly toolCallId: string },
+ ) => Promise<unknown>;
+ }
+ >;
}
).tools;
const tool = tools[toolName];
@@ -82,7 +74,7 @@ function setupMockAgentForToolExecution(toolName: string, args: unknown): void {
throw new Error(`Missing test tool "${toolName}".`);
}
- const output = await tool.execute(args);
+ const output = await tool.execute(args, { toolCallId: `call-${toolName}` });
const result = {
finishReason: "stop",
@@ -226,13 +218,22 @@ function createNoopRuntime(): Runtime {
};
}
+describe("createNodeHarnessTools", () => {
+ it("guides the model to split large tasks across parallel recursive agent calls", () => {
+ const agentTool = createNodeHarnessTools({ node: createTestNode() }).get("agent");
+
+ expect(agentTool?.description).toContain("split a large task into independent pieces");
+ expect(agentTool?.description).toContain("multiple `agent` calls in one response");
+ expect(agentTool?.description).toContain("run a small fixed set in parallel");
+ expect(agentTool?.description).toContain("include essential context");
+ expect(agentTool?.description).toContain("non-overlapping scopes");
+ expect(agentTool?.description).not.toContain("eve");
+ });
+});
+
describe("createExecutionNodeStep", () => {
it("builds a usable harness step for the root node", async () => {
- vi.stubEnv("EVE_EXPERIMENTAL_CODE_MODE", "1");
-
- setupMockAgentForToolExecution("code_mode", {
- js: 'return await tools["regular-tool"]({ question: "Run the tool." });',
- });
+ setupMockAgentForToolExecution("regular-tool", { question: "Run the tool." });
const toolRegistry = await createRuntimeToolRegistry({
tools: [
@@ -266,15 +267,31 @@ describe("createExecutionNodeStep", () => {
node: rootNode,
});
- const result = await step(
- createSession({
- continuationToken: "test-root",
- sessionId: "sess-root",
- turnAgent: rootNode.turnAgent,
- }),
- {
- message: "Run the tool.",
- },
+ const ctx = new ContextContainer();
+ ctx.set(AuthKey, null);
+ ctx.set(InitiatorAuthKey, null);
+ ctx.set(BundleKey, {
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ } as never);
+ ctx.set(ChannelKey, { kind: "http" });
+ ctx.set(SessionIdKey, "sess-root");
+ ctx.set(SessionKey, {
+ auth: { current: null, initiator: null },
+ sessionId: "sess-root",
+ turn: { id: "root-turn", sequence: 0 },
+ });
+
+ const result = await contextStorage.run(ctx, () =>
+ step(
+ createSession({
+ continuationToken: "test-root",
+ sessionId: "sess-root",
+ turnAgent: rootNode.turnAgent,
+ }),
+ {
+ message: "Run the tool.",
+ },
+ ),
);
expect(result.next).toEqual({ done: true, output: "tool-output" });
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index 060eda031..79f17af9b 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -8,7 +8,6 @@ import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { createLogger } from "#internal/logging.js";
import type { RuntimeIdentity } from "#protocol/message.js";
import type { RunMode } from "#shared/run-mode.js";
-import { resolveCodeModeEnabled } from "#shared/code-mode.js";
import {
resolveRuntimeModelReference,
type RuntimeModelResolutionScope,
@@ -25,6 +24,13 @@ import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
const log = createLogger("execution.node-step");
+const BUILT_IN_AGENT_TOOL_DESCRIPTION = [
+ "Delegate a focused subtask to a fresh copy of yourself.",
+ "Use it to isolate complex work or split a large task into independent pieces.",
+ "Issue multiple `agent` calls in one response to run a small fixed set in parallel.",
+ "Each child has fresh history and state but shares your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes.",
+].join(" ");
+
/**
* Factory that creates a {@link Runtime} for the given compiled
* artifacts source and optional node id. Matches the signature of
@@ -67,7 +73,6 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): St
const tools = createNodeHarnessTools({ node: input.node });
return createToolLoopHarness({
capabilities: input.capabilities,
- codeMode: resolveCodeModeEnabled(input.node.agent.config?.experimental?.codeMode),
workflow: input.node.agent.workflowEnabled === true,
handleEvent: input.handleEvent,
mode: input.mode,
@@ -142,7 +147,7 @@ export function createNodeHarnessTools(input: {
if (!tools.has("agent")) {
tools.set("agent", {
- description: "Launch a new agent to handle a complex, multi-step subtask.",
+ description: BUILT_IN_AGENT_TOOL_DESCRIPTION,
inputSchema: jsonSchema(SUBAGENT_TOOL_INPUT_SCHEMA),
name: "agent",
runtimeAction: {
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index e51e5c2d9..52ec16ae1 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -57,12 +57,12 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {
return;
}
- if (result.action === "dispatch-code-mode-runtime-actions") {
+ if (result.action === "dispatch-workflow-runtime-actions") {
await notifyDriverStep({
completionToken: input.completionToken,
payload: {
action: {
- kind: "dispatch-code-mode-runtime-actions",
+ kind: "dispatch-workflow-runtime-actions",
pendingActionKeys: result.pendingRuntimeActionKeys,
serializedContext: result.serializedContext,
sessionState: result.sessionState,
diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.ts
index 908ba810c..be15e0fbc 100644
--- a/packages/eve/src/execution/workflow-entry.ts
+++ b/packages/eve/src/execution/workflow-entry.ts
@@ -33,7 +33,7 @@ import {
} from "#execution/workflow-errors.js";
import { resolveVercelProductionCallbackBaseUrl } from "#execution/workflow-callback-url.js";
import { createSessionStep } from "#execution/create-session-step.js";
-import { dispatchCodeModeRuntimeActionsStep } from "#execution/dispatch-code-mode-runtime-actions-step.js";
+import { dispatchWorkflowRuntimeActionsStep } from "#execution/dispatch-workflow-runtime-actions-step.js";
import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
import {
dispatchTurnStep,
@@ -289,11 +289,11 @@ async function runDriverLoop(input: {
driverWritable: input.driverWritable,
});
- case "dispatch-code-mode-runtime-actions":
+ case "dispatch-workflow-runtime-actions":
case "dispatch-runtime-actions": {
const dispatchStep =
- action.kind === "dispatch-code-mode-runtime-actions"
- ? dispatchCodeModeRuntimeActionsStep
+ action.kind === "dispatch-workflow-runtime-actions"
+ ? dispatchWorkflowRuntimeActionsStep
: dispatchRuntimeActionsStep;
const dispatchResult = await dispatchStep({
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index 8810aa882..a6b96d71c 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -19,10 +19,10 @@ import { hasPendingInputBatch } from "#harness/input-requests.js";
import { coalesceTurnInputs } from "#harness/messages.js";
import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
import {
- getRuntimeActionKeyFromInterrupt,
- isCodeModeRuntimeActionInterrupt,
-} from "#harness/code-mode-runtime-action-state.js";
-import { getPendingCodeModeInterrupt } from "#harness/code-mode-interrupt-state.js";
+ getRuntimeActionKeyFromWorkflowInterrupt,
+ isWorkflowRuntimeActionInterrupt,
+} from "#harness/workflow-runtime-action-state.js";
+import { getPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";
import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";
import type { JsonObject } from "#shared/json.js";
@@ -90,7 +90,7 @@ export type DurableStepResult =
readonly sessionState: DurableSessionState;
}
| {
- readonly action: "dispatch-code-mode-runtime-actions";
+ readonly action: "dispatch-workflow-runtime-actions";
readonly pendingRuntimeActionKeys: readonly string[];
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
@@ -356,14 +356,16 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
if (stepResult.next === null) {
writer.releaseLock();
- const codeModeInterrupt = getPendingCodeModeInterrupt(stepResult.session.state);
+ const workflowInterrupt = getPendingWorkflowInterrupt(stepResult.session.state);
if (
- codeModeInterrupt !== undefined &&
- isCodeModeRuntimeActionInterrupt(codeModeInterrupt.interrupt)
+ workflowInterrupt !== undefined &&
+ isWorkflowRuntimeActionInterrupt(workflowInterrupt.interrupt)
) {
return {
- action: "dispatch-code-mode-runtime-actions",
- pendingRuntimeActionKeys: [getRuntimeActionKeyFromInterrupt(codeModeInterrupt.interrupt)],
+ action: "dispatch-workflow-runtime-actions",
+ pendingRuntimeActionKeys: [
+ getRuntimeActionKeyFromWorkflowInterrupt(workflowInterrupt.interrupt),
+ ],
serializedContext: nextSerializedContext,
sessionState: nextState,
};
diff --git a/packages/eve/src/harness/action-result-helpers.ts b/packages/eve/src/harness/action-result-helpers.ts
index b1aa78f0b..38d727d0d 100644
--- a/packages/eve/src/harness/action-result-helpers.ts
+++ b/packages/eve/src/harness/action-result-helpers.ts
@@ -39,8 +39,8 @@ function toJsonValue(value: unknown): JsonValue {
*
* This is the single coercion point for `action.result` projection. Both
* native tool execution (via {@link createRuntimeToolResultFromStepResult} /
- * {@link createRuntimeToolResultFromMessagePart}) and code-mode nested tool
- * calls funnel through here, so the raw-output-vs-`toModelOutput` decision —
+ * {@link createRuntimeToolResultFromMessagePart}) and Workflow child calls
+ * funnel through here, so the raw-output-vs-`toModelOutput` decision —
* always raw — is decided once. The output is validated as JSON here so bad
* values never reach protocol events or persisted history.
*/
diff --git a/packages/eve/src/harness/code-mode-interrupt-state.ts b/packages/eve/src/harness/code-mode-interrupt-state.ts
deleted file mode 100644
index 2d1a85517..000000000
--- a/packages/eve/src/harness/code-mode-interrupt-state.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import type { ModelMessage } from "ai";
-
-import type { HarnessSession, SessionStateMap } from "#harness/types.js";
-import type { CodeModeInterrupt } from "#shared/code-mode.js";
-
-const PENDING_KEY = "eve.harness.pendingCodeModeInterrupt";
-
-/**
- * One code-mode invocation parked on a host interrupt (nested-tool approval,
- * connection auth, or any future durable interrupt kind), plus the assistant
- * response messages that produced the outer `code_mode` tool result.
- *
- * Every interrupt kind rides this single pending slot; the kind-specific
- * behavior lives in {@link parkOnCodeModeInterrupt} /
- * {@link continuePendingCodeModeInterrupt}, keyed by `interrupt.payload.kind`.
- */
-export interface PendingCodeModeInterrupt {
- readonly interrupt: CodeModeInterrupt;
- readonly responseMessages: readonly ModelMessage[];
-}
-
-/** Returns the pending code-mode interrupt stored on the session, if any. */
-export function getPendingCodeModeInterrupt(
- state: SessionStateMap | undefined,
-): PendingCodeModeInterrupt | undefined {
- const value = state?.[PENDING_KEY];
- if (!isRecord(value)) return undefined;
- if (!isCodeModeInterruptShape(value.interrupt) || !Array.isArray(value.responseMessages)) {
- return undefined;
- }
- return {
- interrupt: value.interrupt,
- responseMessages: value.responseMessages as ModelMessage[],
- };
-}
-
-/** Stores one pending code-mode interrupt on the session. */
-export function setPendingCodeModeInterrupt(input: {
- readonly interrupt: CodeModeInterrupt;
- readonly responseMessages: readonly ModelMessage[];
- readonly session: HarnessSession;
-}): HarnessSession {
- return {
- ...input.session,
- state: {
- ...input.session.state,
- [PENDING_KEY]: {
- interrupt: input.interrupt,
- responseMessages: input.responseMessages,
- } satisfies PendingCodeModeInterrupt,
- },
- };
-}
-
-/** Clears any pending code-mode interrupt from the session. */
-export function clearPendingCodeModeInterrupt(session: HarnessSession): HarnessSession {
- if (session.state?.[PENDING_KEY] === undefined) {
- return session;
- }
-
- const state = { ...session.state };
- delete state[PENDING_KEY];
-
- return {
- ...session,
- state: Object.keys(state).length > 0 ? state : undefined,
- };
-}
-
-// Loose structural guard for our own persisted interrupt. The package's full
-// `isCodeModeInterrupt` additionally verifies the signed continuation and
-// ledger; that check belongs on resume (`continueCodeModeInterrupt`), not on
-// reading state we wrote ourselves.
-function isCodeModeInterruptShape(value: unknown): value is CodeModeInterrupt {
- return (
- isRecord(value) &&
- value.type === "code-mode-interrupt" &&
- typeof value.interruptId === "string" &&
- typeof value.outerToolCallId === "string" &&
- isRecord(value.payload) &&
- typeof value.payload.kind === "string" &&
- isRecord(value.continuation) &&
- typeof value.continuation.outerToolCallId === "string"
- );
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
diff --git a/packages/eve/src/harness/code-mode-lifecycle.test.ts b/packages/eve/src/harness/code-mode-lifecycle.test.ts
deleted file mode 100644
index d999aa5a1..000000000
--- a/packages/eve/src/harness/code-mode-lifecycle.test.ts
+++ /dev/null
@@ -1,464 +0,0 @@
-import { jsonSchema } from "ai";
-import { describe, expect, it } from "vitest";
-
-import { ContextContainer, contextStorage } from "#context/container.js";
-import { createCodeModeLifecycle } from "#harness/code-mode-lifecycle.js";
-import type { HarnessEmissionState } from "#harness/emission.js";
-import type { HarnessToolMap } from "#harness/types.js";
-import { defineState } from "#public/definitions/state.js";
-import type { HandleMessageStreamEvent } from "#protocol/message.js";
-
-const emissionState: HarnessEmissionState = {
- sequence: 2,
- sessionStarted: true,
- stepIndex: 3,
- turnId: "turn_abc",
-};
-
-function createTools(): HarnessToolMap {
- return new Map([
- [
- "lookup",
- {
- description: "Lookup data.",
- execute: async () => ({ ok: true }),
- inputSchema: jsonSchema({ type: "object" }),
- name: "lookup",
- },
- ],
- ]);
-}
-
-describe("createCodeModeLifecycle", () => {
- it("emits nested tool calls and results as eve action events", async () => {
- const events: HandleMessageStreamEvent[] = [];
- const lifecycle = createCodeModeLifecycle({
- emit: async (event) => {
- events.push(event);
- },
- emissionState,
- tools: createTools(),
- });
-
- await lifecycle.onNestedToolCall?.({
- bridgeIndex: 1,
- input: { id: "123" },
- inputBytes: 12,
- invocationId: "code-mode-1",
- outerToolCallId: "outer-call",
- replayed: false,
- startedAtMs: 10,
- toolCallId: "outer-call:tool-1",
- toolName: "lookup",
- });
- await lifecycle.onNestedToolResult?.({
- bridgeIndex: 1,
- completedAtMs: 20,
- durationMs: 10,
- input: { id: "123" },
- inputBytes: 12,
- invocationId: "code-mode-1",
- outerToolCallId: "outer-call",
- output: { value: "ok" },
- outputBytes: 14,
- replayed: false,
- startedAtMs: 10,
- status: "fulfilled",
- toolCallId: "outer-call:tool-1",
- toolName: "lookup",
- });
-
- expect(events).toEqual([
- {
- data: {
- actions: [
- {
- callId: "outer-call:tool-1",
- input: { id: "123" },
- kind: "tool-call",
- toolName: "lookup",
- },
- ],
- sequence: 2,
- stepIndex: 3,
- turnId: "turn_abc",
- },
- type: "actions.requested",
- },
- {
- data: {
- result: {
- callId: "outer-call:tool-1",
- kind: "tool-result",
- output: { value: "ok" },
- toolName: "lookup",
- },
- sequence: 2,
- status: "completed",
- stepIndex: 3,
- turnId: "turn_abc",
- },
- type: "action.result",
- },
- ]);
- });
-
- it("projects a rejected nested result through the shared action-result helper", async () => {
- const events: HandleMessageStreamEvent[] = [];
- const lifecycle = createCodeModeLifecycle({
- emit: async (event) => {
- events.push(event);
- },
- emissionState,
- tools: createTools(),
- });
-
- await lifecycle.onNestedToolResult?.({
- bridgeIndex: 1,
- completedAtMs: 20,
- durationMs: 10,
- error: new Error("lookup boom"),
- input: { id: "123" },
- inputBytes: 12,
- invocationId: "code-mode-1",
- outerToolCallId: "outer-call",
- replayed: false,
- startedAtMs: 10,
- status: "rejected",
- toolCallId: "outer-call:tool-1",
- toolName: "lookup",
- });
-
- expect(events).toEqual([
- {
- data: {
- error: {
- code: "ACTION_RESULT_FAILED",
- message: "lookup boom",
- },
- result: {
- callId: "outer-call:tool-1",
- isError: true,
- kind: "tool-result",
- output: "lookup boom",
- toolName: "lookup",
- },
- sequence: 2,
- status: "failed",
- stepIndex: 3,
- turnId: "turn_abc",
- },
- type: "action.result",
- },
- ]);
- });
-
- it("emits raw nested output structurally without re-validating it", async () => {
- const events: HandleMessageStreamEvent[] = [];
- const lifecycle = createCodeModeLifecycle({
- emit: async (event) => {
- events.push(event);
- },
- emissionState,
- tools: createTools(),
- });
-
- const rawOutput = { nested: { items: [1, 2, 3] }, summary: "ok" };
- await lifecycle.onNestedToolResult?.({
- bridgeIndex: 1,
- completedAtMs: 20,
- durationMs: 10,
- input: {},
- inputBytes: 2,
- invocationId: "code-mode-1",
- outerToolCallId: "outer-call",
- output: rawOutput,
- outputBytes: 30,
- replayed: false,
- startedAtMs: 10,
- status: "fulfilled",
- toolCallId: "outer-call:tool-1",
- toolName: "lookup",
- });
-
- const [event] = events;
- if (event?.type !== "action.result") {
- throw new Error("expected an action.result event");
- }
- expect(event.data.result).toEqual({
- callId: "outer-call:tool-1",
- kind: "tool-result",
- output: rawOutput,
- toolName: "lookup",
- });
- });
-
- it("skips replayed nested calls during continuation replay", async () => {
- const events: HandleMessageStreamEvent[] = [];
- const lifecycle = createCodeModeLifecycle({
- emit: async (event) => {
- events.push(event);
- },
- emissionState,
- skipReplayed: true,
- tools: createTools(),
- });
-
- await lifecycle.onNestedToolCall?.({
- bridgeIndex: 1,
- input: { id: "old" },
- inputBytes: 12,
- invocationId: "code-mode-1",
- outerToolCallId: "outer-call",
- replayed: true,
- startedAtMs: 10,
- toolCallId: "outer-call:tool-1",
- toolName: "lookup",
- });
- await lifecycle.onNestedToolCall?.({
- bridgeIndex: 2,
- input: { id: "new" },
- inputBytes: 12,
- invocationId: "code-mode-1",
- outerToolCallId: "outer-call",
- replayed: false,
- startedAtMs: 20,
- toolCallId: "outer-call:tool-2",
- toolName: "lookup",
- });
-
- expect(events).toHaveLength(1);
- expect(events[0]).toMatchObject({
- data: {
- actions: [
- {
- callId: "outer-call:tool-2",
- input: { id: "new" },
- kind: "tool-call",
- toolName: "lookup",
- },
- ],
- },
- type: "actions.requested",
- });
- });
-
- it("dispatches lifecycle events under the invoking context, not the build-time one", async () => {
- // experimental-ai-sdk-code-mode >= 1.0.11 re-enters the originating
- // invocation's context at the worker bridge before invoking these hooks, so
- // the lifecycle is context-transparent: `defineState` writes land in the
- // session active when the hook runs, not the one active when it was built.
- const lifecycleDispatches = defineState<string[]>(
- "test.code-mode.lifecycle.dispatch-context",
- () => [],
- );
- const buildSession = new ContextContainer();
- const callSession = new ContextContainer();
-
- const lifecycle = await contextStorage.run(buildSession, async () =>
- createCodeModeLifecycle({
- emit: async (event) => {
- lifecycleDispatches.update((events) => [...events, event.type]);
- },
- emissionState,
- tools: createTools(),
- }),
- );
-
- await contextStorage.run(callSession, async () => {
- await lifecycle.onNestedToolCall?.({
- bridgeIndex: 1,
- input: { id: "123" },
- inputBytes: 12,
- invocationId: "code-mode-1",
- outerToolCallId: "outer-call",
- replayed: false,
- startedAtMs: 10,
- toolCallId: "outer-call:tool-1",
- toolName: "lookup",
- });
- await lifecycle.onNestedToolResult?.({
- bridgeIndex: 1,
- completedAtMs: 20,
- durationMs: 10,
- input: { id: "123" },
- inputBytes: 12,
- invocationId: "code-mode-1",
- outerToolCallId: "outer-call",
- output: { value: "ok" },
- outputBytes: 14,
- replayed: false,
- startedAtMs: 10,
- status: "fulfilled",
- toolCallId: "outer-call:tool-1",
- toolName: "lookup",
- });
- });
-
- expect(contextStorage.run(callSession, () => lifecycleDispatches.get())).toEqual([
- "actions.requested",
- "action.result",
- ]);
- expect(contextStorage.run(buildSession, () => lifecycleDispatches.get())).toEqual([]);
- });
-
- it("state written by an action.result handler is visible to a subsequent tool in the invocation context", async () => {
- // Mirrors a production SQL flow: execute_sql → action.result hook writes
- // latestSql → finalize_answer reads latestSql. The package re-enters the
- // originating invocation's context (invocationSession) at the worker bridge
- // before dispatching execute and lifecycle hooks, so all three run under it
- // regardless of which session built the tools/lifecycle. State written by
- // the hook must therefore be visible to the next tool, and isolated from an
- // unrelated session (otherSession).
- const latestSql = defineState<string | null>("test.code-mode.latest-sql", () => null);
-
- const otherSession = new ContextContainer();
- const invocationSession = new ContextContainer();
-
- const tools: HarnessToolMap = new Map([
- [
- "execute_sql",
- {
- description: "Run SQL.",
- execute: async () => ({ appliedSql: "SELECT 1" }),
- inputSchema: jsonSchema({ type: "object" }),
- name: "execute_sql",
- },
- ],
- [
- "finalize_answer",
- {
- description: "Finalize.",
- execute: async () => {
- const sql = latestSql.get();
- return { capturedSql: sql };
- },
- inputSchema: jsonSchema({ type: "object" }),
- name: "finalize_answer",
- },
- ],
- ]);
-
- // Tools and lifecycle can be built under any session; the wrapper and
- // lifecycle are context-transparent.
- const { hostTools, lifecycle } = await contextStorage.run(otherSession, async () => {
- const { buildToolSet } = await import("#harness/tools.js");
- const { applySandboxToolSet } = await import("#harness/code-mode.js");
- const { CODE_MODE_SURFACE } = await import("#harness/sandbox-surface.js");
- const flatTools = buildToolSet({ tools });
- const { hostTools } = await applySandboxToolSet({
- harnessTools: tools,
- tools: flatTools,
- surfaces: [CODE_MODE_SURFACE],
- });
-
- const lifecycle = createCodeModeLifecycle({
- emit: async (event) => {
- // Simulate the action.result hook writing state, like a production agent's
- // turn-metrics hook captures appliedSql.
- if (event.type === "action.result") {
- const result = (event.data as { result: { toolName: string; output: unknown } }).result;
- if (result.toolName === "execute_sql") {
- const output = result.output as { appliedSql?: string };
- if (typeof output?.appliedSql === "string") {
- latestSql.update(() => output.appliedSql!);
- }
- }
- }
- },
- emissionState,
- tools,
- });
-
- return { hostTools, lifecycle };
- });
-
- // The bridge handler runs every callback under the re-entered invocation
- // context — the guarantee the package provides on eve's behalf.
- const result = await contextStorage.run(invocationSession, async () => {
- // 1. execute_sql runs under the invocation context.
- const executeSql = hostTools.execute_sql as {
- execute: (input: unknown, options: unknown) => Promise<unknown>;
- };
- await executeSql.execute({}, { messages: [], toolCallId: "call_1" });
-
- // 2. Lifecycle fires action.result; the hook writes latestSql.
- await lifecycle.onNestedToolResult?.({
- bridgeIndex: 1,
- completedAtMs: 20,
- durationMs: 10,
- input: {},
- inputBytes: 2,
- invocationId: "inv-1",
- outerToolCallId: "outer-1",
- output: { appliedSql: "SELECT 1" },
- outputBytes: 30,
- replayed: false,
- startedAtMs: 10,
- status: "fulfilled",
- toolCallId: "call_1",
- toolName: "execute_sql",
- });
-
- // 3. finalize_answer reads latestSql back from the same context.
- const finalizeAnswer = hostTools.finalize_answer as {
- execute: (input: unknown, options: unknown) => Promise<unknown>;
- };
- return finalizeAnswer.execute({}, { messages: [], toolCallId: "call_2" });
- });
-
- expect(result).toEqual({ capturedSql: "SELECT 1" });
- expect(contextStorage.run(invocationSession, () => latestSql.get())).toBe("SELECT 1");
- expect(contextStorage.run(otherSession, () => latestSql.get())).toBeNull();
- });
-
- it("state written by a hook is visible to a post-step channel handler in the invocation context", async () => {
- // Mirrors a production turn.completed handler reading pendingFinalAnswer after the
- // code-mode step finishes. The package re-enters the invocation context
- // (invocationSession) before the bridge dispatches the hook, so the write
- // lands there and a later channel handler reading in the step scope sees it.
- const pendingAnswer = defineState<string | null>("test.code-mode.pending-answer", () => null);
-
- const otherSession = new ContextContainer();
- const invocationSession = new ContextContainer();
-
- const lifecycle = await contextStorage.run(otherSession, async () =>
- createCodeModeLifecycle({
- emit: async (event) => {
- if (event.type === "action.result") {
- pendingAnswer.update(() => "42 active users");
- }
- },
- emissionState,
- tools: createTools(),
- }),
- );
-
- // Bridge handler fires under the re-entered invocation context.
- await contextStorage.run(invocationSession, async () => {
- await lifecycle.onNestedToolResult?.({
- bridgeIndex: 1,
- completedAtMs: 20,
- durationMs: 10,
- input: {},
- inputBytes: 2,
- invocationId: "inv-1",
- outerToolCallId: "outer-1",
- output: { answer: "42" },
- outputBytes: 14,
- replayed: false,
- startedAtMs: 10,
- status: "fulfilled",
- toolCallId: "call_1",
- toolName: "finalize_answer",
- });
- });
-
- // Channel handler reads in the invocation scope (the step scope).
- const readInInvocation = contextStorage.run(invocationSession, () => pendingAnswer.get());
- const readInOther = contextStorage.run(otherSession, () => pendingAnswer.get());
-
- expect(readInInvocation).toBe("42 active users");
- expect(readInOther).toBeNull();
- });
-});
diff --git a/packages/eve/src/harness/code-mode.test.ts b/packages/eve/src/harness/code-mode.test.ts
deleted file mode 100644
index e7df568a4..000000000
--- a/packages/eve/src/harness/code-mode.test.ts
+++ /dev/null
@@ -1,469 +0,0 @@
-import { jsonSchema, tool } from "ai";
-import { describe, expect, it } from "vitest";
-
-import { applySandboxToolSet, buildSandboxHostTools } from "#harness/code-mode.js";
-import { CODE_MODE_SURFACE, WORKFLOW_SURFACE } from "#harness/sandbox-surface.js";
-import { ContextContainer, contextStorage } from "#context/container.js";
-import { ContextKey } from "#context/key.js";
-import { LiveStepToolsKey } from "#context/keys.js";
-import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import { buildToolSet } from "#harness/tools.js";
-import type { HarnessToolMap } from "#harness/types.js";
-import { isCodeModeEnvEnabled, resolveCodeModeEnabled } from "#shared/code-mode.js";
-
-describe("resolveCodeModeEnabled", () => {
- it("reads the EVE_EXPERIMENTAL_CODE_MODE backstop", () => {
- expect(isCodeModeEnvEnabled({ EVE_EXPERIMENTAL_CODE_MODE: "1" })).toBe(true);
- expect(isCodeModeEnvEnabled({ EVE_EXPERIMENTAL_CODE_MODE: "true" })).toBe(false);
- expect(isCodeModeEnvEnabled({ EVE_EXPERIMENTAL_CODE_MODE: "0" })).toBe(false);
- expect(isCodeModeEnvEnabled({})).toBe(false);
- });
-
- it("prefers the authored flag over the env backstop", () => {
- expect(resolveCodeModeEnabled(true, { EVE_EXPERIMENTAL_CODE_MODE: "0" })).toBe(true);
- expect(resolveCodeModeEnabled(false, { EVE_EXPERIMENTAL_CODE_MODE: "1" })).toBe(false);
- expect(resolveCodeModeEnabled(undefined, { EVE_EXPERIMENTAL_CODE_MODE: "1" })).toBe(true);
- expect(resolveCodeModeEnabled(undefined, {})).toBe(false);
- });
-});
-
-describe("applySandboxToolSet", () => {
- it("moves every executable tool behind code_mode", async () => {
- const harnessTools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
- [
- "bash",
- {
- description: "Run a shell command.",
- execute: async () => "ok",
- inputSchema: jsonSchema({ type: "object" }),
- name: "bash",
- },
- ],
- [
- "connection_search",
- {
- description: "Search connections.",
- execute: async () => [],
- inputSchema: jsonSchema({ type: "object" }),
- name: "connection_search",
- },
- ],
- [
- "read_file",
- {
- description: "Read a workspace file.",
- execute: async () => "contents",
- inputSchema: jsonSchema({ type: "object" }),
- name: "read_file",
- },
- ],
- [
- "write_file",
- {
- description: "Write a workspace file.",
- execute: async () => ({ ok: true }),
- inputSchema: jsonSchema({ type: "object" }),
- name: "write_file",
- },
- ],
- [
- "echo",
- {
- description: "Echo.",
- execute: async () => "echo",
- inputSchema: jsonSchema({ type: "object" }),
- name: "echo",
- },
- ],
- ]);
-
- const flatTools = buildToolSet({ capabilities: { requestInput: true }, tools: harnessTools });
- const { hostTools, modelTools } = await applySandboxToolSet({
- harnessTools,
- tools: flatTools,
- surfaces: [CODE_MODE_SURFACE],
- });
-
- expect(modelTools.bash).toBeUndefined();
- expect(modelTools.connection_search).toBeUndefined();
- expect(modelTools.read_file).toBeUndefined();
- expect(modelTools.write_file).toBeUndefined();
- expect(modelTools.echo).toBeUndefined();
- expect(modelTools.code_mode).toBeDefined();
- expect(hostTools.bash).toBeDefined();
- expect(hostTools.connection_search).toBeDefined();
- expect(hostTools.read_file).toBeDefined();
- expect(hostTools.write_file).toBeDefined();
- expect(hostTools.echo).toBeDefined();
- });
-
- it("never sandboxes load_skill — it stays a direct model tool", async () => {
- const harnessTools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
- [
- "load_skill",
- {
- description: "Load a skill into the session.",
- execute: async () => "ok",
- inputSchema: jsonSchema({ type: "object" }),
- name: "load_skill",
- },
- ],
- [
- "bash",
- {
- description: "Run a shell command.",
- execute: async () => "ok",
- inputSchema: jsonSchema({ type: "object" }),
- name: "bash",
- },
- ],
- ]);
-
- const flatTools = buildToolSet({ tools: harnessTools });
- const { hostTools, modelTools } = await applySandboxToolSet({
- harnessTools,
- tools: flatTools,
- surfaces: [CODE_MODE_SURFACE],
- });
-
- // load_skill is directly callable and never enters the sandbox.
- expect(modelTools.load_skill).toBeDefined();
- expect(hostTools.load_skill).toBeUndefined();
- // ordinary executable tools are still sandboxed.
- expect(hostTools.bash).toBeDefined();
- expect(modelTools.bash).toBeUndefined();
- expect(modelTools.code_mode).toBeDefined();
- });
-
- it("returns raw nested host tool output inside code mode", async () => {
- const rawOutput = { secret: "hidden", summary: "visible" };
- const harnessTools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
- [
- "report",
- {
- description: "Build report.",
- execute: async () => rawOutput,
- inputSchema: jsonSchema({ type: "object" }),
- name: "report",
- toModelOutput: () => ({ type: "text", value: "visible" }),
- },
- ],
- ]);
-
- const flatTools = buildToolSet({ tools: harnessTools });
- const { hostTools } = await applySandboxToolSet({
- harnessTools,
- tools: flatTools,
- surfaces: [CODE_MODE_SURFACE],
- });
- const reportTool = hostTools.report as {
- execute?: (input: unknown, options: unknown) => Promise<unknown>;
- };
-
- await expect(reportTool.execute?.({}, { messages: [], toolCallId: "call_1" })).resolves.toBe(
- rawOutput,
- );
- });
-
- it("keeps provider-managed tools direct when they have no executor", async () => {
- const harnessTools: HarnessToolMap = new Map();
- const { hostTools, modelTools } = await applySandboxToolSet({
- harnessTools,
- tools: {
- web_search: tool({
- description: "Provider search.",
- inputSchema: jsonSchema({ type: "object" }),
- }),
- },
- surfaces: [CODE_MODE_SURFACE],
- });
-
- expect(modelTools.web_search).toBeDefined();
- expect(modelTools.code_mode).toBeUndefined();
- expect(hostTools.web_search).toBeUndefined();
- });
-
- it("wraps host tools context-transparently (the package owns the worker context seam)", async () => {
- // Code mode bridges host-tool calls back from a pooled worker_thread whose
- // `message` callback Node binds to the invocation that first created the
- // worker. experimental-ai-sdk-code-mode >= 1.0.11 re-enters the originating
- // invocation's AsyncLocalStorage context before dispatching host callbacks,
- // so eve no longer re-pins context in the wrapper. The wrapper must stay
- // transparent: it observes whatever context the caller provides, never a
- // context captured at build time. The cross-invocation worker guarantee is
- // covered by the package's own regression test.
- const SessionMarkerKey = new ContextKey<string>("test.code-mode.session-marker");
-
- const buildSession = new ContextContainer();
- buildSession.set(SessionMarkerKey, "build-session");
- const callSession = new ContextContainer();
- callSession.set(SessionMarkerKey, "call-session");
-
- let observedSession: string | undefined;
- const harnessTools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
- [
- "read_state",
- {
- description: "Read the active session marker.",
- execute: async () => {
- observedSession = contextStorage.getStore()?.get(SessionMarkerKey);
- return observedSession;
- },
- inputSchema: jsonSchema({ type: "object" }),
- name: "read_state",
- },
- ],
- ]);
-
- // Host tools are built inside the build session's scope.
- const flatTools = buildToolSet({ tools: harnessTools });
- const { hostTools } = await contextStorage.run(buildSession, async () =>
- applySandboxToolSet({ harnessTools, tools: flatTools, surfaces: [CODE_MODE_SURFACE] }),
- );
- const readStateTool = hostTools.read_state as {
- execute: (input: unknown, options: unknown) => Promise<unknown>;
- };
-
- // Invoked while a different context is ambient: the wrapper passes it
- // through untouched instead of restoring the build-time context.
- const result = await contextStorage.run(callSession, async () =>
- readStateTool.execute({}, { messages: [], toolCallId: "call_1" }),
- );
-
- expect(observedSession).toBe("call-session");
- expect(result).toBe("call-session");
- });
-
- it("wraps host tool approval checks context-transparently", async () => {
- // needsApproval, like execute, must observe the caller's context. The
- // package re-enters the originating invocation's context at the worker
- // bridge (experimental-ai-sdk-code-mode >= 1.0.11), so the wrapper does not
- // re-pin it to the build-time context.
- const SessionMarkerKey = new ContextKey<string>("test.code-mode.approval-session-marker");
-
- const buildSession = new ContextContainer();
- buildSession.set(SessionMarkerKey, "build-session");
- const callSession = new ContextContainer();
- callSession.set(SessionMarkerKey, "call-session");
-
- let observedSession: string | undefined;
- const harnessTools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
- [
- "guarded",
- {
- description: "Requires approval.",
- execute: async () => "ok",
- inputSchema: jsonSchema({ type: "object" }),
- name: "guarded",
- needsApproval: () => {
- observedSession = contextStorage.getStore()?.get(SessionMarkerKey);
- return true;
- },
- },
- ],
- ]);
-
- const flatTools = buildToolSet({ tools: harnessTools });
- const { hostTools } = await contextStorage.run(buildSession, async () =>
- applySandboxToolSet({ harnessTools, tools: flatTools, surfaces: [CODE_MODE_SURFACE] }),
- );
- const guardedTool = hostTools.guarded as {
- needsApproval: (input: unknown, options: unknown) => Promise<boolean> | boolean;
- };
-
- const result = await contextStorage.run(callSession, async () =>
- guardedTool.needsApproval({}, { messages: [], toolCallId: "call_1" }),
- );
-
- expect(observedSession).toBe("call-session");
- expect(result).toBe(true);
- });
-
- it("preserves dynamic tool approval gates in sandbox host tools", async () => {
- const needsApproval = () => true;
- const ctx = new ContextContainer();
- ctx.setVirtualContext(LiveStepToolsKey, [
- {
- description: "Requires approval.",
- execute: async () => "ok",
- inputSchema: jsonSchema({ type: "object" }),
- name: "tfl__getLineStatus",
- needsApproval,
- },
- ]);
-
- const hostTools = await contextStorage.run(ctx, () =>
- buildSandboxHostTools({ tools: new Map() }),
- );
- const guardedTool = hostTools.tfl__getLineStatus as {
- needsApproval?: (input: unknown) => Promise<boolean> | boolean;
- };
-
- await expect(guardedTool.needsApproval?.({ line: "victoria" })).resolves.toBe(true);
- });
-
- it("dual-routes runtime action tools to both modelTools and hostTools", async () => {
- const harnessTools: HarnessToolMap = new Map<string, HarnessToolDefinition>([
- [
- "researcher",
- {
- description: "Delegate to the researcher subagent.",
- inputSchema: jsonSchema({ type: "object" }),
- name: "researcher",
- runtimeAction: {
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- },
- },
- ],
- [
- "remote_reviewer",
- {
- description: "Delegate to the remote reviewer.",
- inputSchema: jsonSchema({ type: "object" }),
- name: "remote_reviewer",
- runtimeAction: {
- kind: "remote-agent-call",
- nodeId: "subagents/remote-reviewer.ts",
- remoteAgentName: "remote_reviewer",
- subagentName: "remote_reviewer",
- },
- },
- ],
- [
- "bash",
- {
- description: "Run a shell command.",
- execute: async () => "ok",
- inputSchema: jsonSchema({ type: "object" }),
- name: "bash",
- },
- ],
- ]);
-
- const flatTools = buildToolSet({ tools: harnessTools });
- const { hostTools, modelTools } = await applySandboxToolSet({
- harnessTools,
- tools: flatTools,
- surfaces: [CODE_MODE_SURFACE],
- });
-
- expect(modelTools.researcher).toBeDefined();
- expect(modelTools.remote_reviewer).toBeDefined();
- expect(modelTools.bash).toBeUndefined();
- expect(modelTools.code_mode).toBeDefined();
- expect(hostTools.researcher).toBeDefined();
- expect(hostTools.researcher!.execute).toBeDefined();
- expect(hostTools.remote_reviewer).toBeDefined();
- expect(hostTools.remote_reviewer!.execute).toBeDefined();
- expect(hostTools.bash).toBeDefined();
- });
-});
-
-describe("applySandboxToolSet — Workflow partition", () => {
- function orchestrationTools(): HarnessToolMap {
- return new Map<string, HarnessToolDefinition>([
- [
- "researcher",
- {
- description: "Delegate to the researcher subagent.",
- inputSchema: jsonSchema({ type: "object" }),
- name: "researcher",
- runtimeAction: {
- kind: "subagent-call",
- nodeId: "subagents/researcher",
- subagentName: "researcher",
- },
- },
- ],
- [
- "remote_reviewer",
- {
- description: "Delegate to the remote reviewer.",
- inputSchema: jsonSchema({ type: "object" }),
- name: "remote_reviewer",
- runtimeAction: {
- kind: "remote-agent-call",
- nodeId: "subagents/remote-reviewer.ts",
- remoteAgentName: "remote_reviewer",
- subagentName: "remote_reviewer",
- },
- },
- ],
- [
- "bash",
- {
- description: "Run a shell command.",
- execute: async () => "ok",
- inputSchema: jsonSchema({ type: "object" }),
- name: "bash",
- },
- ],
- ]);
- }
-
- it("sandboxes only subagent/remote tools and leaves other tools direct", async () => {
- const harnessTools = orchestrationTools();
- const flatTools = buildToolSet({ tools: harnessTools });
- const { hostTools, modelTools } = await applySandboxToolSet({
- harnessTools,
- tools: flatTools,
- surfaces: [WORKFLOW_SURFACE],
- });
-
- // The Workflow sandbox is emitted; code_mode is not (code mode is off).
- expect(modelTools.Workflow).toBeDefined();
- expect(modelTools.code_mode).toBeUndefined();
- // Agents stay directly callable AND enter the Workflow sandbox.
- expect(modelTools.researcher).toBeDefined();
- expect(modelTools.remote_reviewer).toBeDefined();
- expect(hostTools.researcher).toBeDefined();
- expect(hostTools.remote_reviewer).toBeDefined();
- // bash is never sandboxed by Workflow: it stays a direct model tool.
- expect(modelTools.bash).toBeDefined();
- expect(hostTools.bash).toBeUndefined();
- });
-
- it("describes the Workflow tool as an agents-only orchestrator", async () => {
- const harnessTools = orchestrationTools();
- const flatTools = buildToolSet({ tools: harnessTools });
- const { modelTools } = await applySandboxToolSet({
- harnessTools,
- tools: flatTools,
- surfaces: [WORKFLOW_SURFACE],
- });
-
- const description = (modelTools.Workflow as { description?: string }).description ?? "";
- expect(description).toContain("Orchestrate this agent's subagents");
- expect(description).toContain("Promise.all");
- });
-
- it("keeps agents in both sandboxes and other host tools only in code_mode when both are enabled", async () => {
- const harnessTools = orchestrationTools();
- const flatTools = buildToolSet({ tools: harnessTools });
- const { hostTools, modelTools } = await applySandboxToolSet({
- harnessTools,
- tools: flatTools,
- surfaces: [WORKFLOW_SURFACE, CODE_MODE_SURFACE],
- });
-
- expect(modelTools.Workflow).toBeDefined();
- expect(modelTools.code_mode).toBeDefined();
- // bash is sandboxed by code mode (not directly callable).
- expect(modelTools.bash).toBeUndefined();
- expect(hostTools.researcher).toBeDefined();
- expect(hostTools.remote_reviewer).toBeDefined();
- expect(hostTools.bash).toBeDefined();
-
- const workflowDescription = (modelTools.Workflow as { description?: string }).description ?? "";
- const codeModeDescription =
- (modelTools.code_mode as { description?: string }).description ?? "";
- // Agents are callable from BOTH sandboxes; code mode is the full surface
- // (agents + host tools), Workflow is agents-only.
- expect(workflowDescription).toContain("researcher");
- expect(codeModeDescription).toContain("researcher");
- expect(codeModeDescription).toContain("bash");
- expect(workflowDescription).not.toContain("bash");
- });
-});
diff --git a/packages/eve/src/harness/code-mode.ts b/packages/eve/src/harness/code-mode.ts
deleted file mode 100644
index 644a309da..000000000
--- a/packages/eve/src/harness/code-mode.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-import { type ToolSet } from "ai";
-
-import type { SessionCapabilities } from "#channel/types.js";
-import { contextStorage } from "#context/container.js";
-import { buildDynamicTools } from "#context/build-dynamic-tools.js";
-import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import type { HarnessToolMap } from "#harness/types.js";
-import { isAuthorizationSignal } from "#harness/authorization.js";
-import { CODE_MODE_RUNTIME_ACTION_INTERRUPT_KIND } from "#harness/code-mode-runtime-action-state.js";
-import {
- CODE_MODE_CONNECTION_AUTH_INTERRUPT_KIND,
- markCodeModeToolExecutionOptions,
- toCodeModeConnectionAuthArgs,
-} from "#runtime/framework-tools/code-mode-connection-auth.js";
-import { loadCodeModeModule, type CodeModeOptions } from "#shared/code-mode.js";
-import { ALL_SANDBOX_SURFACES, type SandboxSurface } from "#harness/sandbox-surface.js";
-import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
-import { buildToolSet, buildToolSetFromDefinitions } from "#harness/tools.js";
-
-/**
- * Framework tools that must never enter a sandbox — they stay directly callable
- * by the model even when code mode or Workflow is on. `load_skill` is a
- * control-plane action (it injects skill instructions into the session), not
- * data work to script, so code never calls it.
- */
-const NEVER_SANDBOXED_TOOL_NAMES: ReadonlySet<string> = new Set([LOAD_SKILL_TOOL_NAME]);
-
-interface SandboxPartitionInput {
- readonly lifecycle?: CodeModeOptions["lifecycle"];
- readonly tools: ToolSet;
- readonly harnessTools: HarnessToolMap;
- /** Sandbox surfaces to emit, in claim-priority order (first claim wins). */
- readonly surfaces: readonly SandboxSurface[];
-}
-
-interface SandboxPartition {
- readonly hostTools: ToolSet;
- readonly modelTools: ToolSet;
-}
-
-export function createEveCodeModeOptions(
- input: {
- readonly lifecycle?: CodeModeOptions["lifecycle"];
- } = {},
-): CodeModeOptions {
- const options: {
- approval: {
- mode: "interrupt";
- };
- lifecycle?: CodeModeOptions["lifecycle"];
- } = {
- approval: {
- mode: "interrupt",
- },
- };
-
- if (input.lifecycle !== undefined) {
- options.lifecycle = input.lifecycle;
- }
-
- return options;
-}
-
-export async function applySandboxToolSet(input: SandboxPartitionInput): Promise<SandboxPartition> {
- const modelTools: Record<string, ToolSet[string]> = {};
- const buckets = new Map<SandboxSurface, Record<string, ToolSet[string]>>(
- input.surfaces.map((surface) => [surface, {}]),
- );
-
- for (const [name, tool] of Object.entries(input.tools)) {
- // Never-sandboxed tools (e.g. load_skill) stay directly callable and enter
- // no sandbox.
- if (NEVER_SANDBOXED_TOOL_NAMES.has(name)) {
- modelTools[name] = tool;
- continue;
- }
-
- const harnessTool = input.harnessTools.get(name);
- const isRuntimeAction = harnessTool?.runtimeAction !== undefined;
-
- // Agents stay directly callable by the model in addition to entering any
- // sandbox, so a single delegation never has to go through code.
- if (isRuntimeAction) {
- modelTools[name] = tool;
- }
-
- // A tool enters every sandbox that claims it. Agents are claimed by both
- // surfaces, so when code mode and Workflow are both enabled they are
- // callable from either sandbox; ordinary host tools are claimed only by
- // code mode.
- const claimingSurfaces = input.surfaces.filter((surface) => surface.claims(harnessTool, tool));
- if (claimingSurfaces.length === 0) {
- // Unclaimed and not an agent: a plain direct tool — provider-managed
- // tools, or any host tool when no code-mode surface is active.
- if (!isRuntimeAction) {
- modelTools[name] = tool;
- }
- continue;
- }
-
- const wrapped =
- isRuntimeAction && harnessTool !== undefined
- ? createRuntimeActionHostTool(harnessTool)
- : wrapHostToolForCodeMode(tool);
- for (const surface of claimingSurfaces) {
- buckets.get(surface)![name] = wrapped;
- }
- }
-
- const hostTools: Record<string, ToolSet[string]> = {};
- for (const surface of input.surfaces) {
- const bucket = buckets.get(surface)!;
- if (Object.keys(bucket).length === 0) {
- continue;
- }
- Object.assign(hostTools, bucket);
- modelTools[surface.toolName] = await createSandboxTool(surface, bucket, input.lifecycle);
- }
-
- return {
- hostTools: hostTools as ToolSet,
- modelTools: modelTools as ToolSet,
- };
-}
-
-/**
- * Builds one model-facing sandbox tool for a surface from its claimed host
- * tools. `createCodeModeTool` auto-generates a description listing the callable
- * tool signatures; the surface's optional {@link SandboxSurface.describe}
- * transform frames it (e.g. the agents-only Workflow framing).
- */
-async function createSandboxTool(
- surface: SandboxSurface,
- hostTools: Record<string, ToolSet[string]>,
- lifecycle: CodeModeOptions["lifecycle"],
-): Promise<ToolSet[string]> {
- const { createCodeModeTool } = await loadCodeModeModule();
- const base = createCodeModeTool(
- hostTools,
- createEveCodeModeOptions({ lifecycle }),
- ) as ToolSet[string];
- if (surface.describe === undefined) {
- return base;
- }
- const generated = typeof base.description === "string" ? base.description : "";
- return {
- ...base,
- description: surface.describe({ generated, toolNames: Object.keys(hostTools) }),
- } as ToolSet[string];
-}
-
-export async function buildSandboxHostTools(input: {
- readonly approvedTools?: ReadonlySet<string>;
- readonly capabilities?: SessionCapabilities;
- readonly tools: HarnessToolMap;
-}): Promise<ToolSet> {
- const flatTools = buildToolSet({
- approvedTools: input.approvedTools,
- capabilities: input.capabilities,
- tools: input.tools,
- });
-
- const ctx = contextStorage.getStore();
- if (ctx !== undefined) {
- const dynamicTools = buildDynamicTools(ctx);
- const dynamicToolSet = buildToolSetFromDefinitions({
- approvedTools: input.approvedTools,
- capabilities: input.capabilities,
- tools: dynamicTools,
- });
- for (const [name, toolDefinition] of Object.entries(dynamicToolSet)) {
- flatTools[name] ??= toolDefinition;
- }
- }
-
- // Replay reconstructs the sandbox tool surface for whichever interrupt is
- // pending. Build across every known surface — a script only references its
- // own tools, so the superset is safe and lets any sandbox kind replay.
- return (
- await applySandboxToolSet({
- harnessTools: input.tools,
- tools: flatTools,
- surfaces: ALL_SANDBOX_SURFACES,
- })
- ).hostTools;
-}
-
-function createRuntimeActionHostTool(harnessTool: HarnessToolDefinition): ToolSet[string] {
- return {
- description: harnessTool.description,
- inputSchema: harnessTool.inputSchema,
- execute: async (input: never, options: never) => {
- const interrupt = (options as Record<string, unknown>)?.codeModeInterrupt as
- | { resolution?: unknown }
- | undefined;
- if (interrupt?.resolution !== undefined) {
- return interrupt.resolution;
- }
- const { requestCodeModeInterrupt } = await loadCodeModeModule();
- return requestCodeModeInterrupt({
- kind: CODE_MODE_RUNTIME_ACTION_INTERRUPT_KIND,
- runtimeAction: harnessTool.runtimeAction,
- toolInput: input,
- toolName: harnessTool.name,
- });
- },
- } as ToolSet[string];
-}
-
-function wrapHostToolForCodeMode(tool: ToolSet[string]): ToolSet[string] {
- const execute = tool.execute;
-
- if (execute === undefined) {
- return tool;
- }
-
- // No context plumbing here on purpose. Code mode bridges host-tool calls back
- // from a pooled `worker_thread`'s `message` callback; the package re-enters
- // the originating invocation's `AsyncLocalStorage` context before dispatching
- // `execute`/`needsApproval`/lifecycle hooks (experimental-ai-sdk-code-mode
- // >= 1.0.11) on every entry path, initial and continuation. So `ctx.session`,
- // auth, `getSandbox()`, and `defineState` already resolve against the running
- // session. This wrapper stays context-transparent and only translates the
- // host-tool authorization signal into a code-mode connection-auth interrupt.
- const invoke = async (input: never, options: never): Promise<unknown> => {
- const output = await resolveExecuteOutput(
- execute(input, markCodeModeToolExecutionOptions(options) as never),
- );
- if (isAuthorizationSignal(output)) {
- const { requestCodeModeInterrupt } = await loadCodeModeModule();
- const connectionName = output.challenges[0]?.name;
- if (connectionName) {
- requestCodeModeInterrupt({
- args: toCodeModeConnectionAuthArgs(input),
- challenges: output.challenges,
- connectionName,
- kind: CODE_MODE_CONNECTION_AUTH_INTERRUPT_KIND,
- toolName: "",
- });
- }
- }
- return output;
- };
-
- return {
- ...tool,
- execute: (input: never, options: never) => invoke(input, options),
- } as ToolSet[string];
-}
-
-async function resolveExecuteOutput(output: unknown): Promise<unknown> {
- if (isAsyncIterable(output)) {
- let finalOutput: unknown;
- for await (const part of output) {
- finalOutput = part;
- }
- return finalOutput;
- }
- return await output;
-}
-
-function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {
- return (
- typeof value === "object" &&
- value !== null &&
- Symbol.asyncIterator in value &&
- typeof (value as { readonly [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] ===
- "function"
- );
-}
diff --git a/packages/eve/src/harness/input-extraction.test.ts b/packages/eve/src/harness/input-extraction.test.ts
index ce9f4202c..a7721f366 100644
--- a/packages/eve/src/harness/input-extraction.test.ts
+++ b/packages/eve/src/harness/input-extraction.test.ts
@@ -127,7 +127,7 @@ describe("extractToolApprovalInputRequests", () => {
]);
});
- it("extracts a code-mode approval request from a sibling tool call", () => {
+ it("extracts an approval request from a sibling tool call", () => {
const result = extractToolApprovalInputRequests({
content: [
{
diff --git a/packages/eve/src/harness/sandbox-surface.test.ts b/packages/eve/src/harness/sandbox-surface.test.ts
deleted file mode 100644
index eb915af9b..000000000
--- a/packages/eve/src/harness/sandbox-surface.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- CODE_MODE_SURFACE,
- WORKFLOW_SURFACE,
- isSandboxEnabled,
- selectSandboxSurfaces,
-} from "#harness/sandbox-surface.js";
-
-describe("selectSandboxSurfaces", () => {
- it("returns no surfaces when neither sandbox is enabled", () => {
- expect(selectSandboxSurfaces({})).toEqual([]);
- expect(isSandboxEnabled({})).toBe(false);
- });
-
- it("emits only the matching surface for each single flag", () => {
- expect(selectSandboxSurfaces({ codeMode: true })).toEqual([CODE_MODE_SURFACE]);
- expect(selectSandboxSurfaces({ workflow: true })).toEqual([WORKFLOW_SURFACE]);
- });
-
- it("emits both surfaces when both are enabled", () => {
- expect(selectSandboxSurfaces({ codeMode: true, workflow: true })).toEqual([
- WORKFLOW_SURFACE,
- CODE_MODE_SURFACE,
- ]);
- expect(isSandboxEnabled({ codeMode: true, workflow: true })).toBe(true);
- });
-});
-
-describe("sandbox surface claims", () => {
- const subagentTool = { runtimeAction: { kind: "subagent-call" } } as never;
-
- it("Workflow claims only runtime-action (agent) tools", () => {
- expect(WORKFLOW_SURFACE.claims(subagentTool, {} as never)).toBe(true);
- expect(WORKFLOW_SURFACE.claims(undefined, { execute: async () => "x" } as never)).toBe(false);
- });
-
- it("code mode claims agents and any executable host tool, but not provider tools", () => {
- expect(CODE_MODE_SURFACE.claims(subagentTool, {} as never)).toBe(true);
- expect(CODE_MODE_SURFACE.claims(undefined, { execute: async () => "x" } as never)).toBe(true);
- expect(CODE_MODE_SURFACE.claims(undefined, {} as never)).toBe(false);
- });
-});
diff --git a/packages/eve/src/harness/sandbox-surface.ts b/packages/eve/src/harness/sandbox-surface.ts
deleted file mode 100644
index b76902ae7..000000000
--- a/packages/eve/src/harness/sandbox-surface.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import type { ToolSet } from "ai";
-
-import type { HarnessToolDefinition } from "#harness/execute-tool.js";
-import { workflowToolDescription } from "#harness/workflow-tool-description.js";
-import { CODE_MODE_TOOL_NAME, WORKFLOW_TOOL_NAME } from "#shared/code-mode.js";
-
-/**
- * A model-facing code-execution sandbox over a *subset* of the agent's tools.
- *
- * `code_mode` and `Workflow` are two instances of this one concept: each is a
- * QuickJS sandbox the model drives by writing JavaScript, differing only in
- * which tools it exposes and how it presents itself. Modeling them as surfaces
- * (rather than parallel boolean branches) keeps the partition uniform and makes
- * a third sandbox a one-line addition.
- */
-export interface SandboxSurface {
- /** Reserved model-facing tool name (e.g. `"code_mode"`, `"Workflow"`). */
- readonly toolName: string;
- /**
- * Whether this surface wraps the given tool into its sandbox. A tool enters
- * *every* active surface that claims it, so an agent tool — claimed by both
- * surfaces — is callable from either sandbox when both are enabled.
- */
- readonly claims: (
- harnessTool: HarnessToolDefinition | undefined,
- tool: ToolSet[string],
- ) => boolean;
- /**
- * Optional transform applied to the description auto-generated by
- * `createCodeModeTool`. Receives the generated text (which lists the callable
- * tool signatures) and the names of the tools in this sandbox, so the framing
- * can adapt to what is actually callable. Omit to use the generated
- * description as-is.
- */
- readonly describe?: (input: {
- readonly generated: string;
- readonly toolNames: readonly string[];
- }) => string;
-}
-
-/**
- * The `Workflow` sandbox: agents only. Its sole callable operations are the
- * agent's subagents and remote agents, for orchestrating them from
- * model-authored JavaScript.
- */
-export const WORKFLOW_SURFACE: SandboxSurface = {
- toolName: WORKFLOW_TOOL_NAME,
- claims: (harnessTool) => harnessTool?.runtimeAction !== undefined,
- describe: ({ generated, toolNames }) => {
- const framing = workflowToolDescription(toolNames);
- return generated.length > 0 ? `${framing}\n\n${generated}` : framing;
- },
-};
-
-/**
- * The `code_mode` sandbox: every sandboxable tool — subagent/remote-agent
- * (`runtimeAction`) tools and ordinary executable host tools (bash, fs, web,
- * skills). Provider-managed tools with no executor are never sandboxed. This is
- * unchanged by whether `Workflow` is also enabled.
- */
-export const CODE_MODE_SURFACE: SandboxSurface = {
- toolName: CODE_MODE_TOOL_NAME,
- claims: (harnessTool, tool) =>
- harnessTool?.runtimeAction !== undefined || tool.execute !== undefined,
-};
-
-/**
- * Active sandbox surfaces for a harness config. A tool enters every surface
- * that claims it, so the two compose without interfering: `code_mode` is the
- * full sandbox (agents + host tools) regardless of `Workflow`, and `Workflow`
- * is an additional agents-only sandbox. When both are enabled, agents are
- * callable from either; other host tools remain only in `code_mode`. Order is
- * the emission order and does not affect routing.
- */
-export function selectSandboxSurfaces(config: {
- readonly codeMode?: boolean;
- readonly workflow?: boolean;
-}): SandboxSurface[] {
- const surfaces: SandboxSurface[] = [];
- if (config.workflow === true) {
- surfaces.push(WORKFLOW_SURFACE);
- }
- if (config.codeMode === true) {
- surfaces.push(CODE_MODE_SURFACE);
- }
- return surfaces;
-}
-
-/** Whether any sandbox surface is active — i.e. the model gets a sandbox tool. */
-export function isSandboxEnabled(config: {
- readonly codeMode?: boolean;
- readonly workflow?: boolean;
-}): boolean {
- return config.codeMode === true || config.workflow === true;
-}
-
-/**
- * Every known surface. Used on replay to rebuild the full sandbox tool set
- * without knowing which surface a pending interrupt came from — a script only
- * references its own tools, so the superset is safe.
- */
-export const ALL_SANDBOX_SURFACES: readonly SandboxSurface[] = [
- WORKFLOW_SURFACE,
- CODE_MODE_SURFACE,
-];
diff --git a/packages/eve/src/harness/tool-interrupts.test.ts b/packages/eve/src/harness/tool-interrupts.test.ts
index 01731e18a..72cb4ecac 100644
--- a/packages/eve/src/harness/tool-interrupts.test.ts
+++ b/packages/eve/src/harness/tool-interrupts.test.ts
@@ -15,7 +15,6 @@ import {
import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
import { readToolInterrupt, stashToolInterrupt } from "#harness/tool-interrupts.js";
import { wrapToolExecute } from "#harness/tools.js";
-import { markCodeModeToolExecutionOptions } from "#runtime/framework-tools/code-mode-connection-auth.js";
function signalWithVerifier(): AuthorizationSignal {
return requestAuthorization([
@@ -103,19 +102,6 @@ describe("wrapToolExecute", () => {
expect(readToolInterrupt(ctx, "call_1")).toBe(signal);
});
- it("passes the full signal through untouched for code-mode host execution", async () => {
- const signal = signalWithVerifier();
- const wrapped = wrapToolExecute({ ...baseDef, execute: async () => signal })!;
- const ctx = new ContextContainer();
- const options = markCodeModeToolExecutionOptions({ toolCallId: "call_2" }) as {
- toolCallId: string;
- };
- const output = await contextStorage.run(ctx, () => wrapped({}, options));
-
- expect(output).toBe(signal); // not redacted — code-mode reads the raw signal
- expect(readToolInterrupt(ctx, "call_2")).toBeUndefined(); // not stashed
- });
-
it("passes non-interrupt outputs through unchanged", async () => {
const wrapped = wrapToolExecute({ ...baseDef, execute: async () => ({ ok: true }) })!;
const ctx = new ContextContainer();
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index fd4fc416f..c924cc377 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -29,7 +29,6 @@ import { setPendingInputBatch } from "#harness/input-requests.js";
import { stashToolInterrupt } from "#harness/tool-interrupts.js";
import { createToolLoopHarness } from "#harness/tool-loop.js";
import type { HarnessEmitFn, HarnessSession, ToolLoopHarnessConfig } from "#harness/types.js";
-import { isCodeModeEnvEnabled } from "#shared/code-mode.js";
import {
CONDITIONAL_DELIVERY_INSTRUCTION,
EMPTY_DELIVERY_SENTINEL,
@@ -107,7 +106,6 @@ function createTestConfig(
overrides?: Partial<ToolLoopHarnessConfig>,
): ToolLoopHarnessConfig {
return {
- codeMode: isCodeModeEnvEnabled(),
handleEvent: emit,
mode,
resolveModel: vi.fn().mockResolvedValue({} as LanguageModel),
@@ -565,7 +563,7 @@ describe("createToolLoopHarness", () => {
);
});
- it("keeps executable tools direct when code mode is disabled", async () => {
+ it("keeps executable tools directly available to the model", async () => {
setupMockAgent({
finishReason: "stop",
response: { messages: [{ content: "Hello!", role: "assistant" }] },
@@ -574,7 +572,7 @@ describe("createToolLoopHarness", () => {
toolResults: [],
});
- const config = createTestConfig("conversation", undefined, { codeMode: false });
+ const config = createTestConfig("conversation");
const runStep = createToolLoopHarness(config);
const session = createTestSession();
@@ -583,7 +581,7 @@ describe("createToolLoopHarness", () => {
const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0];
expect(agentCall).toBeDefined();
expect(agentCall!.tools).toHaveProperty("add");
- expect(agentCall!.tools).not.toHaveProperty("code_mode");
+ expect(agentCall!.tools).not.toHaveProperty("Workflow");
});
it("forwards the agent reasoning effort to the model call", async () => {
@@ -631,7 +629,7 @@ describe("createToolLoopHarness", () => {
},
]);
- const config = createTestConfig("conversation", undefined, { codeMode: false });
+ const config = createTestConfig("conversation");
const runStep = createToolLoopHarness(config);
await contextStorage.run(ctx, () => runStep(createTestSession(), { message: "Hi" }));
@@ -670,7 +668,6 @@ describe("createToolLoopHarness", () => {
},
});
const config: ToolLoopHarnessConfig = {
- codeMode: true,
mode: "conversation",
resolveModel: vi.fn().mockResolvedValue({} as LanguageModel),
tools: new Map([
@@ -698,16 +695,12 @@ describe("createToolLoopHarness", () => {
const runStep = createToolLoopHarness(config);
await runStep(session, { message: "search" });
- // The ToolLoopAgent should expose the user's web_search override through code mode,
+ // The ToolLoopAgent should expose the user's web_search override directly,
// not replace it with a provider-managed tool.
const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0];
expect(agentCall).toBeDefined();
- expect(agentCall!.tools).not.toHaveProperty("web_search");
- expect(agentCall!.tools).toHaveProperty("code_mode");
- const codeModeTool = (agentCall!.tools as Record<string, unknown>).code_mode as {
- description?: string;
- };
- expect(codeModeTool?.description).toContain("Custom search.");
+ expect(agentCall!.tools).toHaveProperty("web_search");
+ expect(agentCall!.tools).not.toHaveProperty("Workflow");
});
it("returns done when task mode finishes with stop", async () => {
@@ -2576,8 +2569,6 @@ describe("createToolLoopHarness", () => {
});
it("retries with the offending tool dropped and a one-shot system note", async () => {
- vi.stubEnv("CODE_MODE", "1");
-
const resolveRuntimeContext = vi.fn((input: InstrumentationStepStartedEventInput) => ({
runtimeContext: {
"test.attempt": Array.isArray(input.modelInput.instructions) ? "retry" : "original",
@@ -2610,7 +2601,6 @@ describe("createToolLoopHarness", () => {
},
});
const config: ToolLoopHarnessConfig = {
- codeMode: true,
mode: "conversation",
resolveModel: vi.fn().mockResolvedValue("anthropic/claude-opus-4.7"),
tools: new Map([
@@ -2659,7 +2649,7 @@ describe("createToolLoopHarness", () => {
const retryCall = vi.mocked(ToolLoopAgent).mock.calls[1]?.[0];
const retryTools = retryCall!.tools as Record<string, unknown>;
expect(retryTools.web_search).toBeUndefined();
- expect(retryTools.code_mode).toBeDefined();
+ expect(retryTools.add).toBeDefined();
expect(vi.mocked(ToolLoopAgent).mock.calls[0]?.[0].runtimeContext).toMatchObject({
"test.attempt": "original",
});
@@ -5719,7 +5709,6 @@ describe("createToolLoopHarness", () => {
],
]);
const config = createTestConfig("conversation", undefined, {
- codeMode: false,
resolveModel: vi.fn().mockResolvedValue("anthropic/claude-sonnet-4-5"),
tools,
});
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index a3a073733..bc350c98b 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -16,7 +16,6 @@ import {
type TypedToolCall,
type TypedToolResult,
} from "ai";
-import type { SessionCapabilities } from "#channel/types.js";
import { isScheduleAppAuth } from "#channel/schedule-auth.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import {
@@ -42,25 +41,19 @@ import {
} from "#protocol/message.js";
import type { InstrumentationDefinition } from "#public/instrumentation/index.js";
import { ASK_QUESTION_TOOL_NAME } from "#runtime/framework-tools/ask-question.js";
-import { isCodeModeRuntimeActionInterrupt } from "#harness/code-mode-runtime-action-state.js";
-import { isCodeModeConnectionAuthInterrupt } from "#runtime/framework-tools/code-mode-connection-auth.js";
+import { isWorkflowRuntimeActionInterrupt } from "#harness/workflow-runtime-action-state.js";
import type { InputRequest } from "#runtime/input/types.js";
import {
hydrateSandboxAttachments,
stageAttachmentsToSandbox,
} from "#harness/attachment-staging.js";
+import { applyWorkflowTool, buildWorkflowHostTools } from "#harness/workflow-sandbox.js";
+import { createWorkflowLifecycle } from "#harness/workflow-lifecycle.js";
import {
- applySandboxToolSet,
- buildSandboxHostTools,
- createEveCodeModeOptions,
-} from "#harness/code-mode.js";
-import { createCodeModeLifecycle } from "#harness/code-mode-lifecycle.js";
-import { isSandboxEnabled, selectSandboxSurfaces } from "#harness/sandbox-surface.js";
-import {
- clearPendingCodeModeInterrupt,
- getPendingCodeModeInterrupt,
- setPendingCodeModeInterrupt,
-} from "#harness/code-mode-interrupt-state.js";
+ clearPendingWorkflowInterrupt,
+ getPendingWorkflowInterrupt,
+ setPendingWorkflowInterrupt,
+} from "#harness/workflow-interrupt-state.js";
import {
compactMessages,
getInputTokenCount,
@@ -100,7 +93,6 @@ import {
import { getInstrumentationConfig } from "#harness/instrumentation-config.js";
import { resolveAssistantStepText } from "#harness/messages.js";
import {
- type AuthorizationChallenge,
type AuthorizationSignal,
isAuthorizationSignal,
setPendingAuthorization,
@@ -145,10 +137,11 @@ import {
} from "#harness/step-hooks.js";
import { buildToolSetFromDefinitions, buildToolSetWithProviderTools } from "#harness/tools.js";
import {
- CODE_MODE_TOOL_NAME,
- loadCodeModeModule,
- type CodeModeInterrupt,
-} from "#shared/code-mode.js";
+ continueWorkflowSandboxInterrupt,
+ getWorkflowSandboxInterrupt,
+ type WorkflowSandboxInterrupt,
+ unwrapWorkflowSandboxResult,
+} from "#shared/workflow-sandbox.js";
import {
buildFinalOutputTool,
FINAL_OUTPUT_TOOL_NAME,
@@ -615,7 +608,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
? [...modelMessages, { role: "user" as const, content: opts.trailingUserNote }]
: modelMessages;
- const sandboxSurfaces = selectSandboxSurfaces(config);
const flatTools = await buildToolSetWithProviderTools({
approvedTools,
capabilities: config.capabilities,
@@ -643,20 +635,19 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
}
const modelTools =
- sandboxSurfaces.length > 0
+ config.workflow === true
? (
- await applySandboxToolSet({
+ await applyWorkflowTool({
harnessTools: config.tools,
lifecycle:
emit !== undefined
- ? createCodeModeLifecycle({
+ ? createWorkflowLifecycle({
emit,
emissionState,
tools: config.tools,
})
: undefined,
tools: flatTools,
- surfaces: sandboxSurfaces,
})
).modelTools
: flatTools;
@@ -715,11 +706,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
throw new EmptyModelResponseError();
}
await emitStepActions(emit, emissionState, stepResult, {
- excludedActionToolNames: new Set([
- ASK_QUESTION_TOOL_NAME,
- CODE_MODE_TOOL_NAME,
- FINAL_OUTPUT_TOOL_NAME,
- ]),
+ excludedActionToolNames: new Set([ASK_QUESTION_TOOL_NAME, FINAL_OUTPUT_TOOL_NAME]),
handledInlineToolResultCallIds,
tools: config.tools,
});
@@ -789,21 +776,18 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
await emitStepStarted(emit, emissionState, messages);
}
- // Code-mode continuations (OAuth, approval, runtime-action, …) replay
- // the sandbox through one generic interrupt path. They run after
- // step.started so dynamic tools are populated.
- const pendingCodeModeInterrupt = await continuePendingCodeModeInterrupt({
- capabilities: config.capabilities,
+ // Workflow continuations replay the sandbox after step.started so nested
+ // action lifecycle events keep the active turn's emission coordinates.
+ const pendingWorkflowInterrupt = await continuePendingWorkflowInterrupt({
childResults: stepInput.input?.runtimeActionResults,
config,
emit,
emissionState,
- messages,
runStep,
session,
});
- if (pendingCodeModeInterrupt !== null) {
- return pendingCodeModeInterrupt;
+ if (pendingWorkflowInterrupt !== null) {
+ return pendingWorkflowInterrupt;
}
let result: HarnessStepResult;
@@ -1400,16 +1384,16 @@ async function handleStepResult(input: {
compaction: createNextCompactionConfig(session.compaction, promptMessages, result),
};
- if (isSandboxEnabled(config)) {
- const { getCodeModeInterrupt } = await loadCodeModeModule();
- const codeModeInterrupt = getCodeModeInterrupt(result);
- if (codeModeInterrupt !== undefined) {
- return parkOnCodeModeInterrupt({
+ if (config.workflow === true) {
+ const workflowInterrupt = await getWorkflowSandboxInterrupt(result);
+ if (workflowInterrupt !== undefined) {
+ if (!isWorkflowRuntimeActionInterrupt(workflowInterrupt)) {
+ throw new Error(`Unsupported Workflow interrupt kind "${workflowInterrupt.payload.kind}".`);
+ }
+ return parkOnWorkflowInterrupt({
baseSession,
- config,
- emit,
emissionState,
- interrupt: codeModeInterrupt,
+ interrupt: workflowInterrupt,
promptMessages,
responseMessages,
});
@@ -1747,144 +1731,94 @@ async function finishConversationTurn(input: {
return { next: null, session };
}
-/**
- * Continues a code-mode invocation parked on any host interrupt (nested-tool
- * approval, connection auth, …). One generic path: pick the kind-specific
- * resolution, replay the sandbox through the package, splice the final output
- * back into the outer `code_mode` tool result, and re-park if the replay hit a
- * further interrupt.
- */
-async function continuePendingCodeModeInterrupt(input: {
- readonly capabilities?: SessionCapabilities;
+/** Replays a parked dynamic workflow with completed child-agent results. */
+async function continuePendingWorkflowInterrupt(input: {
readonly childResults?: readonly { readonly output?: unknown }[];
readonly config: ToolLoopHarnessConfig;
readonly emit?: ToolLoopHarnessConfig["handleEvent"];
readonly emissionState: ReturnType<typeof getHarnessEmissionState>;
- readonly messages: readonly ModelMessage[];
readonly runStep: StepFn;
readonly session: HarnessSession;
}): Promise<StepResult | null> {
- const pending = getPendingCodeModeInterrupt(input.session.state);
- if (pending === undefined) {
- return null;
- }
-
- const {
- continueCodeModeApproval,
- continueCodeModeInterrupt,
- getCodeModeApprovalResponse,
- isCodeModeApprovalInterrupt,
- replaceCodeModeInterruptResult,
- unwrapCodeModeResult,
- } = await loadCodeModeModule();
+ const pending = getPendingWorkflowInterrupt(input.session.state);
+ if (pending === undefined) return null;
const interrupt = pending.interrupt;
-
- // Approval can only continue once the user's tool-approval-response arrives;
- // until then stay parked. Connection-auth resumes as authorized whenever the
- // turn replays — the authorization webhook drove the resume.
- const approvalResponse = isCodeModeApprovalInterrupt(interrupt)
- ? getCodeModeApprovalResponse([...input.messages], interrupt)
- : undefined;
- if (isCodeModeApprovalInterrupt(interrupt) && approvalResponse === undefined) {
- return { next: null, session: input.session };
+ if (!isWorkflowRuntimeActionInterrupt(interrupt)) {
+ throw new Error(`Unsupported Workflow interrupt kind "${interrupt.payload.kind}".`);
}
- const options = createEveCodeModeOptions({
- lifecycle:
- input.emit !== undefined
- ? createCodeModeLifecycle({
- emit: input.emit,
- emissionState: input.emissionState,
- skipReplayed: true,
- tools: input.config.tools,
- })
- : undefined,
- });
+ const lifecycle =
+ input.emit === undefined
+ ? undefined
+ : createWorkflowLifecycle({
+ emit: input.emit,
+ emissionState: input.emissionState,
+ skipReplayed: true,
+ tools: input.config.tools,
+ });
let continuationOutput: unknown;
try {
- const hostTools = await buildSandboxHostTools({
- approvedTools: getApprovedTools(input.session),
- capabilities: input.capabilities,
+ const hostTools = buildWorkflowHostTools({
tools: input.config.tools,
});
- if (isCodeModeApprovalInterrupt(interrupt) && approvalResponse !== undefined) {
- continuationOutput = await continueCodeModeApproval({
- approvalResponse,
- interrupt,
- options,
- tools: hostTools,
- });
- } else if (isCodeModeConnectionAuthInterrupt(interrupt)) {
- continuationOutput = await continueCodeModeInterrupt({
- interrupt,
- resolution: { status: "authorized" as const },
+ const childResults = input.childResults ?? [];
+ let currentInterrupt = interrupt;
+ let resultIndex = 0;
+ // Promise.all can park several child calls together. Resolve one ledger
+ // entry per replay until every supplied child result has been consumed.
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ continuationOutput = await continueWorkflowSandboxInterrupt({
+ interrupt: currentInterrupt,
+ lifecycle,
+ resolution: childResults[resultIndex]?.output,
tools: hostTools,
- options,
});
- } else if (isCodeModeRuntimeActionInterrupt(interrupt)) {
- const childResults = input.childResults ?? [];
- let currentInterrupt = interrupt;
- let resultIndex = 0;
- // Each cycle resolves one interrupted entry. For Promise.all with
- // N agent calls, the bridge batches all N, all children dispatch
- // concurrently, and we loop to resolve one per replay.
- // eslint-disable-next-line no-constant-condition
- while (true) {
- continuationOutput = await continueCodeModeInterrupt({
- interrupt: currentInterrupt,
- resolution: childResults[resultIndex]?.output,
- tools: hostTools,
- options,
- });
- const loopUnwrapped = unwrapCodeModeResult(continuationOutput);
- if (loopUnwrapped.status !== "interrupted") break;
- if (!isCodeModeRuntimeActionInterrupt(loopUnwrapped.interrupt)) break;
- if (resultIndex + 1 >= childResults.length) break;
- resultIndex++;
- currentInterrupt = loopUnwrapped.interrupt as CodeModeInterrupt;
- }
- } else {
- throw new Error(`Unsupported code-mode interrupt kind "${interrupt.payload.kind}".`);
+ const loopUnwrapped = await unwrapWorkflowSandboxResult(continuationOutput);
+ if (loopUnwrapped.status !== "interrupted") break;
+ if (!isWorkflowRuntimeActionInterrupt(loopUnwrapped.interrupt)) break;
+ if (resultIndex + 1 >= childResults.length) break;
+ resultIndex++;
+ currentInterrupt = loopUnwrapped.interrupt;
}
} catch (error) {
- logError(log, "code-mode interrupt continuation failed", error);
+ logError(log, "Workflow interrupt continuation failed", error);
continuationOutput = {
- error: "code_mode_continuation_failed",
+ error: "workflow_continuation_failed",
message: toErrorMessage(error),
retryable: false,
};
}
- const unwrapped = unwrapCodeModeResult(continuationOutput);
+ const unwrapped = await unwrapWorkflowSandboxResult(continuationOutput);
const finalOutput = unwrapped.status === "interrupted" ? unwrapped.interrupt : unwrapped.output;
const baseMessages = [...input.session.history, ...pending.responseMessages];
- const replacedMessages = isCodeModeRuntimeActionInterrupt(interrupt)
- ? replaceCodeModeToolResult(
- baseMessages,
- (interrupt as { outerToolCallId?: string }).outerToolCallId,
- finalOutput,
- )
- : replaceCodeModeInterruptResult(baseMessages, interrupt as never, finalOutput);
-
- let session = clearPendingCodeModeInterrupt({
+ const replacedMessages = replaceWorkflowToolResult(
+ baseMessages,
+ (interrupt as { outerToolCallId?: string }).outerToolCallId,
+ finalOutput,
+ );
+
+ let session = clearPendingWorkflowInterrupt({
...input.session,
history: replacedMessages,
});
if (unwrapped.status === "interrupted") {
+ if (!isWorkflowRuntimeActionInterrupt(unwrapped.interrupt)) {
+ throw new Error(`Unsupported Workflow interrupt kind "${unwrapped.interrupt.payload.kind}".`);
+ }
const promptMessageCount = input.session.history.length;
const promptMessages = replacedMessages.slice(0, promptMessageCount);
const responseMessages = replacedMessages.slice(promptMessageCount);
session = { ...session, history: promptMessages };
- return parkOnCodeModeInterrupt({
+ return parkOnWorkflowInterrupt({
baseSession: session,
- config: input.config,
- emit: input.emit,
emissionState: input.emissionState,
- interrupt: unwrapped.interrupt as CodeModeInterrupt,
+ interrupt: unwrapped.interrupt,
promptMessages,
responseMessages,
});
@@ -1893,14 +1827,7 @@ async function continuePendingCodeModeInterrupt(input: {
return { next: input.runStep, session };
}
-/**
- * Parks the turn on a code-mode host interrupt. Stores the interrupt on the
- * single pending slot, then runs the kind-specific side effect: connection-auth
- * surfaces the authorization challenges and parks on pending authorization;
- * approval surfaces the nested tool's approval request through eve's existing
- * input-request UX.
- */
-function replaceCodeModeToolResult(
+function replaceWorkflowToolResult(
messages: readonly ModelMessage[],
outerToolCallId: string | undefined,
output: unknown,
@@ -1922,108 +1849,20 @@ function replaceCodeModeToolResult(
}) as ModelMessage[];
}
-async function parkOnCodeModeInterrupt(input: {
+function parkOnWorkflowInterrupt(input: {
readonly baseSession: HarnessSession;
- readonly config: ToolLoopHarnessConfig;
- readonly emit?: ToolLoopHarnessConfig["handleEvent"];
readonly emissionState: ReturnType<typeof getHarnessEmissionState>;
- readonly interrupt: CodeModeInterrupt;
+ readonly interrupt: WorkflowSandboxInterrupt;
readonly promptMessages: readonly ModelMessage[];
readonly responseMessages: readonly ModelMessage[];
-}): Promise<StepResult> {
- const { isCodeModeApprovalInterrupt, toCodeModeApprovalMessages } = await loadCodeModeModule();
- const interrupt = input.interrupt;
+}): StepResult {
const baseSession: HarnessSession = {
...input.baseSession,
history: [...input.promptMessages],
};
- // Connection-auth: the host tool's execute already called startAuthorization
- // and registered the webhook hook; wrapHostToolForCodeMode threaded the
- // challenges through the interrupt payload. Surface them and park on pending
- // authorization — don't call startAuthorization again.
- if (isCodeModeConnectionAuthInterrupt(interrupt)) {
- const challenges: AuthorizationChallenge[] = [...(interrupt.payload.challenges ?? [])];
-
- if (input.emit) {
- for (const ch of challenges) {
- await input.emit(
- createAuthorizationRequiredEvent({
- authorization: ch.challenge,
- name: ch.name,
- description: ch.challenge.instructions ?? `Authorization required for ${ch.name}`,
- webhookUrl: ch.hookUrl,
- sequence: input.emissionState.sequence,
- stepIndex: input.emissionState.stepIndex,
- turnId: input.emissionState.turnId,
- }),
- );
- }
- }
-
- const parkedSession = setPendingCodeModeInterrupt({
- interrupt,
- responseMessages: input.responseMessages,
- session: {
- ...baseSession,
- state: setPendingAuthorization(baseSession.state, { challenges }),
- },
- });
-
- return { next: null, session: parkedSession };
- }
-
- // Approval: surface the nested tool's approval request as an eve input
- // request so the existing approval UX drives the resume.
- if (isCodeModeApprovalInterrupt(interrupt)) {
- const approvalMessages = toCodeModeApprovalMessages(interrupt);
- const approvalRequests = extractToolApprovalInputRequests({
- content: extractAssistantContent(approvalMessages),
- });
-
- let parkedSession = setPendingInputBatch({
- event: {
- sequence: input.emissionState.sequence,
- stepIndex: input.emissionState.stepIndex,
- turnId: input.emissionState.turnId,
- },
- requests: approvalRequests,
- responseMessages: approvalMessages,
- session: setPendingCodeModeInterrupt({
- interrupt,
- responseMessages: input.responseMessages,
- session: baseSession,
- }),
- });
-
- if (input.emit) {
- await input.emit(
- createInputRequestedEvent({
- requests: approvalRequests,
- sequence: input.emissionState.sequence,
- stepIndex: input.emissionState.stepIndex,
- turnId: input.emissionState.turnId,
- }),
- );
-
- if (input.config.mode === "conversation") {
- const nextEmissionState = await emitTurnEpilogue(
- input.emit,
- input.emissionState,
- input.config.mode,
- );
- parkedSession = setHarnessEmissionState(parkedSession, nextEmissionState);
- }
- }
-
- return { next: null, session: parkedSession };
- }
-
- // Runtime-action and any other future kinds: park with no side effects.
- // The turn step detects the pending state and routes to the appropriate
- // driver action.
- const parkedSession = setPendingCodeModeInterrupt({
- interrupt,
+ const parkedSession = setPendingWorkflowInterrupt({
+ interrupt: input.interrupt,
responseMessages: input.responseMessages,
session: baseSession,
});
@@ -2031,18 +1870,6 @@ async function parkOnCodeModeInterrupt(input: {
return { next: null, session: setHarnessEmissionState(parkedSession, input.emissionState) };
}
-function extractAssistantContent(
- messages: readonly ModelMessage[],
-): NonNullable<HarnessStepResult["content"]> {
- const content: NonNullable<HarnessStepResult["content"]> = [];
- for (const message of messages) {
- if (message.role === "assistant" && Array.isArray(message.content)) {
- content.push(...(message.content as NonNullable<HarnessStepResult["content"]>));
- }
- }
- return content;
-}
-
function createNextCompactionConfig(
current: CompactionConfig,
promptMessages: readonly ModelMessage[],
diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.ts
index e4fca9603..49bfd49fd 100644
--- a/packages/eve/src/harness/tools.ts
+++ b/packages/eve/src/harness/tools.ts
@@ -18,7 +18,6 @@ import {
} from "#harness/authorization.js";
import { stashToolInterrupt } from "#harness/tool-interrupts.js";
import { withToolOutputSerializationError } from "#harness/tool-output-serialization.js";
-import { isCodeModeToolExecutionOptions } from "#runtime/framework-tools/code-mode-connection-auth.js";
type ToolModelOutputValue =
| { readonly type: "json"; readonly value: JSONValue }
@@ -151,11 +150,7 @@ export function buildToolSetFromDefinitions(input: {
* stashed out-of-band ({@link stashToolInterrupt}) for the park detector while
* the AI SDK records an opaque {@link AuthorizationPendingModelOutput} that
* omits OAuth URLs, user codes, and hook URLs from model-facing history.
- *
- * Code-mode host executions consume the raw signal directly (see
- * `harness/code-mode.ts`) and their output is not a model-facing tool result,
- * so they pass through untouched. Returns `undefined` for client-side tools
- * (no `execute`).
+ * Returns `undefined` for client-side tools (no `execute`).
*/
export function wrapToolExecute(
definition: HarnessToolDefinition,
@@ -165,7 +160,6 @@ export function wrapToolExecute(
return async (input, options) => {
const output = await execute(input);
if (isAuthorizationSignal(output)) {
- if (isCodeModeToolExecutionOptions(options)) return output;
stashToolInterrupt(loadContext(), options.toolCallId, output);
return modelFacingAuthorizationOutput(output);
}
diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.ts
index be1b5e6f8..f447588dd 100644
--- a/packages/eve/src/harness/types.ts
+++ b/packages/eve/src/harness/types.ts
@@ -189,19 +189,11 @@ export interface ToolLoopHarnessConfig {
*/
readonly capabilities?: SessionCapabilities;
/**
- * Routes executable tools through the sandboxed code-execution wrapper
- * instead of exposing them directly to the model. Resolved by the
- * runtime from the agent's `experimental.codeMode` flag (with the
- * `EVE_EXPERIMENTAL_CODE_MODE` env backstop). Defaults to `false`.
- */
- readonly codeMode?: boolean;
- /**
- * Exposes the `Workflow` orchestration tool — a code-mode-style sandbox
+ * Exposes the `Workflow` orchestration tool — an isolated JavaScript sandbox
* whose only callable operations are this agent's subagents and remote
* agents. Resolved by the runtime from the agent's `workflowEnabled` flag
* (set when `agent/tools/workflow.ts` re-exports the `Workflow` marker).
- * Independent of {@link ToolLoopHarnessConfig.codeMode} — both may be on at
- * once. Defaults to `false`.
+ * Defaults to `false`.
*/
readonly workflow?: boolean;
readonly handleEvent?: HandleEventFn;
diff --git a/packages/eve/src/harness/workflow-interrupt-state.ts b/packages/eve/src/harness/workflow-interrupt-state.ts
new file mode 100644
index 000000000..302a17d6d
--- /dev/null
+++ b/packages/eve/src/harness/workflow-interrupt-state.ts
@@ -0,0 +1,71 @@
+import type { ModelMessage } from "ai";
+
+import type { HarnessSession, SessionStateMap } from "#harness/types.js";
+import { WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND } from "#harness/workflow-runtime-action-state.js";
+import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";
+
+const PENDING_KEY = "eve.harness.pendingWorkflowInterrupt";
+
+export interface PendingWorkflowInterrupt {
+ readonly interrupt: WorkflowSandboxInterrupt;
+ readonly responseMessages: readonly ModelMessage[];
+}
+
+export function getPendingWorkflowInterrupt(
+ state: SessionStateMap | undefined,
+): PendingWorkflowInterrupt | undefined {
+ const value = state?.[PENDING_KEY];
+ if (!isRecord(value)) return undefined;
+ if (!isWorkflowInterruptShape(value.interrupt) || !Array.isArray(value.responseMessages)) {
+ return undefined;
+ }
+ return {
+ interrupt: value.interrupt,
+ responseMessages: value.responseMessages as ModelMessage[],
+ };
+}
+
+export function setPendingWorkflowInterrupt(input: {
+ readonly interrupt: WorkflowSandboxInterrupt;
+ readonly responseMessages: readonly ModelMessage[];
+ readonly session: HarnessSession;
+}): HarnessSession {
+ return {
+ ...input.session,
+ state: {
+ ...input.session.state,
+ [PENDING_KEY]: {
+ interrupt: input.interrupt,
+ responseMessages: input.responseMessages,
+ } satisfies PendingWorkflowInterrupt,
+ },
+ };
+}
+
+export function clearPendingWorkflowInterrupt(session: HarnessSession): HarnessSession {
+ if (session.state?.[PENDING_KEY] === undefined) return session;
+
+ const state = { ...session.state };
+ delete state[PENDING_KEY];
+ return {
+ ...session,
+ state: Object.keys(state).length > 0 ? state : undefined,
+ };
+}
+
+function isWorkflowInterruptShape(value: unknown): value is WorkflowSandboxInterrupt {
+ return (
+ isRecord(value) &&
+ value.type === "code-mode-interrupt" &&
+ typeof value.interruptId === "string" &&
+ typeof value.outerToolCallId === "string" &&
+ isRecord(value.payload) &&
+ value.payload.kind === WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND &&
+ isRecord(value.continuation) &&
+ typeof value.continuation.outerToolCallId === "string"
+ );
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/packages/eve/src/harness/workflow-lifecycle.test.ts b/packages/eve/src/harness/workflow-lifecycle.test.ts
new file mode 100644
index 000000000..ee079ca06
--- /dev/null
+++ b/packages/eve/src/harness/workflow-lifecycle.test.ts
@@ -0,0 +1,164 @@
+import { jsonSchema } from "ai";
+import { describe, expect, it } from "vitest";
+
+import { ContextContainer, contextStorage } from "#context/container.js";
+import type { HarnessEmissionState } from "#harness/emission.js";
+import { createWorkflowLifecycle } from "#harness/workflow-lifecycle.js";
+import type { HarnessToolMap } from "#harness/types.js";
+import { defineState } from "#public/definitions/state.js";
+import type { HandleMessageStreamEvent } from "#protocol/message.js";
+
+const emissionState: HarnessEmissionState = {
+ sequence: 2,
+ sessionStarted: true,
+ stepIndex: 3,
+ turnId: "turn_abc",
+};
+
+function createTools(): HarnessToolMap {
+ return new Map([
+ [
+ "researcher",
+ {
+ description: "Delegate to the researcher.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "researcher",
+ runtimeAction: {
+ kind: "subagent-call",
+ nodeId: "subagents/researcher",
+ subagentName: "researcher",
+ },
+ },
+ ],
+ ]);
+}
+
+function nestedCall(replayed = false) {
+ return {
+ bridgeIndex: 1,
+ input: { message: "Investigate" },
+ inputBytes: 24,
+ invocationId: "workflow-1",
+ outerToolCallId: "outer-call",
+ replayed,
+ startedAtMs: 10,
+ toolCallId: "outer-call:tool-1",
+ toolName: "researcher",
+ };
+}
+
+describe("createWorkflowLifecycle", () => {
+ it("emits nested subagent calls and results as action events", async () => {
+ const events: HandleMessageStreamEvent[] = [];
+ const lifecycle = createWorkflowLifecycle({
+ emit: async (event) => {
+ events.push(event);
+ },
+ emissionState,
+ tools: createTools(),
+ });
+
+ await lifecycle.onNestedToolCall?.(nestedCall());
+ await lifecycle.onNestedToolResult?.({
+ ...nestedCall(),
+ completedAtMs: 20,
+ durationMs: 10,
+ output: { value: "ok" },
+ outputBytes: 14,
+ status: "fulfilled",
+ });
+
+ expect(events[0]).toMatchObject({
+ data: {
+ actions: [
+ {
+ callId: "outer-call:tool-1",
+ kind: "subagent-call",
+ subagentName: "researcher",
+ },
+ ],
+ sequence: 2,
+ stepIndex: 3,
+ turnId: "turn_abc",
+ },
+ type: "actions.requested",
+ });
+ expect(events[1]).toMatchObject({
+ data: {
+ result: {
+ callId: "outer-call:tool-1",
+ output: { value: "ok" },
+ toolName: "researcher",
+ },
+ },
+ type: "action.result",
+ });
+ });
+
+ it("projects rejected child results through the shared result contract", async () => {
+ const events: HandleMessageStreamEvent[] = [];
+ const lifecycle = createWorkflowLifecycle({
+ emit: async (event) => {
+ events.push(event);
+ },
+ emissionState,
+ tools: createTools(),
+ });
+
+ await lifecycle.onNestedToolResult?.({
+ ...nestedCall(),
+ completedAtMs: 20,
+ durationMs: 10,
+ error: new Error("child failed"),
+ status: "rejected",
+ });
+
+ expect(events[0]).toMatchObject({
+ data: {
+ result: { isError: true, output: "child failed" },
+ status: "failed",
+ },
+ type: "action.result",
+ });
+ });
+
+ it("skips replayed calls during continuation", async () => {
+ const events: HandleMessageStreamEvent[] = [];
+ const lifecycle = createWorkflowLifecycle({
+ emit: async (event) => {
+ events.push(event);
+ },
+ emissionState,
+ skipReplayed: true,
+ tools: createTools(),
+ });
+
+ await lifecycle.onNestedToolCall?.(nestedCall(true));
+ expect(events).toEqual([]);
+ });
+
+ it("dispatches lifecycle events in the invoking context", async () => {
+ const lifecycleDispatches = defineState<string[]>(
+ "test.workflow.lifecycle.dispatch-context",
+ () => [],
+ );
+ const buildSession = new ContextContainer();
+ const callSession = new ContextContainer();
+ const lifecycle = await contextStorage.run(buildSession, async () =>
+ createWorkflowLifecycle({
+ emit: async (event) => {
+ lifecycleDispatches.update((events) => [...events, event.type]);
+ },
+ emissionState,
+ tools: createTools(),
+ }),
+ );
+
+ await contextStorage.run(callSession, () => lifecycle.onNestedToolCall?.(nestedCall()));
+
+ expect(contextStorage.run(callSession, () => lifecycleDispatches.get())).toEqual([
+ "actions.requested",
+ ]);
+ expect(contextStorage.run(buildSession, () => lifecycleDispatches.get())).toEqual([]);
+ });
+});
diff --git a/packages/eve/src/harness/code-mode-lifecycle.ts b/packages/eve/src/harness/workflow-lifecycle.ts
similarity index 58%
rename from packages/eve/src/harness/code-mode-lifecycle.ts
rename to packages/eve/src/harness/workflow-lifecycle.ts
index 6696dd796..bd543a82e 100644
--- a/packages/eve/src/harness/code-mode-lifecycle.ts
+++ b/packages/eve/src/harness/workflow-lifecycle.ts
@@ -1,49 +1,38 @@
import type { ToolSet, TypedToolCall } from "ai";
import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
+import type { HarnessEmissionState } from "#harness/emission.js";
+import { createRuntimeActionRequestFromToolCall } from "#harness/runtime-actions.js";
+import type { HarnessToolMap } from "#harness/types.js";
import { createLogger } from "#internal/logging.js";
import {
createActionResultEvent,
createActionsRequestedEvent,
type HandleMessageStreamEvent,
} from "#protocol/message.js";
-import type { HarnessEmissionState } from "#harness/emission.js";
-import { createRuntimeActionRequestFromToolCall } from "#harness/runtime-actions.js";
-import type { HarnessToolMap } from "#harness/types.js";
import { toErrorMessage } from "#shared/errors.js";
-import type { CodeModeOptions } from "#shared/code-mode.js";
+import type { WorkflowSandboxLifecycle } from "#shared/workflow-sandbox.js";
-const log = createLogger("harness.code-mode-lifecycle");
+const log = createLogger("harness.workflow-lifecycle");
-type EmitCodeModeLifecycleEvent = (event: HandleMessageStreamEvent) => Promise<void>;
+type EmitWorkflowLifecycleEvent = (event: HandleMessageStreamEvent) => Promise<void>;
-/**
- * Builds code-mode lifecycle hooks that project nested host tool calls onto
- * eve's existing action event stream.
- */
-export function createCodeModeLifecycle(input: {
- readonly emit: EmitCodeModeLifecycleEvent;
+/** Projects sandboxed subagent calls onto eve's existing action event stream. */
+export function createWorkflowLifecycle(input: {
+ readonly emit: EmitWorkflowLifecycleEvent;
readonly emissionState: HarnessEmissionState;
readonly skipReplayed?: boolean;
readonly tools: HarnessToolMap;
-}): NonNullable<CodeModeOptions["lifecycle"]> {
- // No context plumbing here on purpose. The package dispatches these lifecycle
- // hooks from the same pooled-worker bridge as host-tool `execute`, and re-enters
- // the originating invocation's `AsyncLocalStorage` context before doing so
- // (experimental-ai-sdk-code-mode >= 1.0.11). So `emit` and any hook it triggers
- // already write to the running session's `defineState`; this projection stays
- // context-transparent.
+}): WorkflowSandboxLifecycle {
return {
onHookError(error, event) {
- log.warn("code-mode lifecycle hook failed", {
+ log.warn("workflow lifecycle hook failed", {
error,
hook: event.hook,
});
},
async onNestedToolCall(event) {
- if (input.skipReplayed === true && event.replayed) {
- return;
- }
+ if (input.skipReplayed === true && event.replayed) return;
const toolCall = {
input: event.input,
@@ -54,12 +43,7 @@ export function createCodeModeLifecycle(input: {
await input.emit(
createActionsRequestedEvent({
- actions: [
- createRuntimeActionRequestFromToolCall({
- toolCall,
- tools: input.tools,
- }),
- ],
+ actions: [createRuntimeActionRequestFromToolCall({ toolCall, tools: input.tools })],
sequence: input.emissionState.sequence,
stepIndex: input.emissionState.stepIndex,
turnId: input.emissionState.turnId,
@@ -67,13 +51,8 @@ export function createCodeModeLifecycle(input: {
);
},
async onNestedToolResult(event) {
- if (input.skipReplayed === true && event.replayed) {
- return;
- }
-
- if (event.status === "interrupted") {
- return;
- }
+ if (input.skipReplayed === true && event.replayed) return;
+ if (event.status === "interrupted") return;
const result = createRuntimeToolResultFromValue({
callId: event.toolCallId,
diff --git a/packages/eve/src/harness/code-mode-runtime-action-state.ts b/packages/eve/src/harness/workflow-runtime-action-state.ts
similarity index 72%
rename from packages/eve/src/harness/code-mode-runtime-action-state.ts
rename to packages/eve/src/harness/workflow-runtime-action-state.ts
index 432e137c1..cbeb8fa7a 100644
--- a/packages/eve/src/harness/code-mode-runtime-action-state.ts
+++ b/packages/eve/src/harness/workflow-runtime-action-state.ts
@@ -2,20 +2,20 @@ import type { HarnessRuntimeActionDefinition } from "#harness/execute-tool.js";
import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";
import type { RuntimeActionRequest } from "#runtime/actions/types.js";
import type { JsonObject } from "#shared/json.js";
-import type { CodeModeInterrupt } from "#shared/code-mode.js";
+import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";
-export const CODE_MODE_RUNTIME_ACTION_INTERRUPT_KIND = "eve.runtime-action";
+export const WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND = "eve.workflow-runtime-action";
-export function isCodeModeRuntimeActionInterrupt(interrupt: unknown): boolean {
+export function isWorkflowRuntimeActionInterrupt(interrupt: unknown): boolean {
return (
isRecord(interrupt) &&
isRecord(interrupt.payload) &&
- interrupt.payload.kind === CODE_MODE_RUNTIME_ACTION_INTERRUPT_KIND
+ interrupt.payload.kind === WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND
);
}
-export function buildRuntimeActionFromInterrupt(
- interrupt: CodeModeInterrupt,
+export function buildRuntimeActionFromWorkflowInterrupt(
+ interrupt: WorkflowSandboxInterrupt,
): RuntimeActionRequest {
const raw = interrupt.payload as Record<string, unknown>;
const runtimeAction = raw.runtimeAction as HarnessRuntimeActionDefinition;
@@ -47,8 +47,10 @@ export function buildRuntimeActionFromInterrupt(
};
}
-export function getRuntimeActionKeyFromInterrupt(interrupt: CodeModeInterrupt): string {
- return getRuntimeActionRequestKey(buildRuntimeActionFromInterrupt(interrupt));
+export function getRuntimeActionKeyFromWorkflowInterrupt(
+ interrupt: WorkflowSandboxInterrupt,
+): string {
+ return getRuntimeActionRequestKey(buildRuntimeActionFromWorkflowInterrupt(interrupt));
}
function sanitizeCallId(id: string): string {
diff --git a/packages/eve/src/harness/workflow-sandbox.test.ts b/packages/eve/src/harness/workflow-sandbox.test.ts
new file mode 100644
index 000000000..c005e8c94
--- /dev/null
+++ b/packages/eve/src/harness/workflow-sandbox.test.ts
@@ -0,0 +1,134 @@
+import { asSchema, jsonSchema } from "ai";
+import { describe, expect, it } from "vitest";
+
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import { applyWorkflowTool, buildWorkflowHostTools } from "#harness/workflow-sandbox.js";
+import { buildToolSet } from "#harness/tools.js";
+import type { HarnessToolMap } from "#harness/types.js";
+
+function orchestrationTools(): HarnessToolMap {
+ return new Map<string, HarnessToolDefinition>([
+ [
+ "researcher",
+ {
+ description: "Delegate to the researcher subagent.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "researcher",
+ runtimeAction: {
+ kind: "subagent-call",
+ nodeId: "subagents/researcher",
+ subagentName: "researcher",
+ },
+ },
+ ],
+ [
+ "remote_reviewer",
+ {
+ description: "Delegate to the remote reviewer.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "remote_reviewer",
+ runtimeAction: {
+ kind: "remote-agent-call",
+ nodeId: "subagents/remote-reviewer.ts",
+ remoteAgentName: "remote_reviewer",
+ subagentName: "remote_reviewer",
+ },
+ },
+ ],
+ [
+ "bash",
+ {
+ description: "Run a shell command.",
+ execute: async () => "ok",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "bash",
+ },
+ ],
+ ]);
+}
+
+describe("applyWorkflowTool", () => {
+ it("adds only agent runtime actions to the sandbox", async () => {
+ const harnessTools = orchestrationTools();
+ const flatTools = buildToolSet({ tools: harnessTools });
+ const { hostTools, modelTools } = await applyWorkflowTool({ harnessTools, tools: flatTools });
+
+ expect(modelTools.Workflow).toBeDefined();
+ expect(modelTools.researcher).toBeDefined();
+ expect(modelTools.remote_reviewer).toBeDefined();
+ expect(modelTools.bash).toBeDefined();
+ expect(hostTools.researcher?.execute).toBeDefined();
+ expect(hostTools.remote_reviewer?.execute).toBeDefined();
+ expect(hostTools.bash).toBeUndefined();
+ });
+
+ it("describes Workflow as an agents-only orchestrator", async () => {
+ const harnessTools = orchestrationTools();
+ const { modelTools } = await applyWorkflowTool({
+ harnessTools,
+ tools: buildToolSet({ tools: harnessTools }),
+ });
+
+ const description = (modelTools.Workflow as { description?: string }).description ?? "";
+ expect(description).toContain("Use `Workflow` for:");
+ expect(description).toContain("Do not use `Workflow` when:");
+ expect(description).toContain("Promise.all");
+ expect(description).toContain("researcher");
+ expect(description).toContain("Available agent API:");
+ expect(description).not.toContain("bash");
+ expect(description).not.toContain("code-mode");
+
+ const inputSchema = asSchema(modelTools.Workflow?.inputSchema).jsonSchema;
+ expect(inputSchema).toMatchObject({
+ properties: {
+ js: { description: expect.stringContaining("JavaScript orchestration program") },
+ },
+ });
+ });
+
+ it("does not add Workflow when no agent runtime actions exist", async () => {
+ const harnessTools: HarnessToolMap = new Map([
+ [
+ "bash",
+ {
+ description: "Run a shell command.",
+ execute: async () => "ok",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "bash",
+ },
+ ],
+ ]);
+ const flatTools = buildToolSet({ tools: harnessTools });
+ const { hostTools, modelTools } = await applyWorkflowTool({ harnessTools, tools: flatTools });
+
+ expect(modelTools.Workflow).toBeUndefined();
+ expect(modelTools.bash).toBeDefined();
+ expect(hostTools).toEqual({});
+ });
+
+ it("rebuilds only workflow agent host tools for continuation", () => {
+ const hostTools = buildWorkflowHostTools({ tools: orchestrationTools() });
+
+ expect(hostTools.researcher).toBeDefined();
+ expect(hostTools.remote_reviewer).toBeDefined();
+ expect(hostTools.bash).toBeUndefined();
+ });
+
+ it("does not construct ordinary tools while rebuilding the continuation surface", () => {
+ const tools: HarnessToolMap = new Map([
+ [
+ "bash",
+ {
+ description: "Run a shell command.",
+ execute: async () => "ok",
+ get inputSchema(): never {
+ throw new Error("ordinary tool schema should not be read");
+ },
+ name: "bash",
+ },
+ ],
+ ]);
+
+ expect(buildWorkflowHostTools({ tools })).toEqual({});
+ });
+});
diff --git a/packages/eve/src/harness/workflow-sandbox.ts b/packages/eve/src/harness/workflow-sandbox.ts
new file mode 100644
index 000000000..c71043591
--- /dev/null
+++ b/packages/eve/src/harness/workflow-sandbox.ts
@@ -0,0 +1,107 @@
+import { jsonSchema, type ToolSet } from "ai";
+
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import type { HarnessToolMap } from "#harness/types.js";
+import { WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND } from "#harness/workflow-runtime-action-state.js";
+import { workflowToolDescription } from "#harness/workflow-tool-description.js";
+import {
+ createWorkflowSandboxTool,
+ readWorkflowSandboxResolution,
+ requestWorkflowSandboxInterrupt,
+ type WorkflowSandboxLifecycle,
+ WORKFLOW_TOOL_NAME,
+} from "#shared/workflow-sandbox.js";
+
+interface WorkflowToolSet {
+ readonly hostTools: ToolSet;
+ readonly modelTools: ToolSet;
+}
+
+/**
+ * Adds the dynamic `Workflow` tool while leaving every ordinary model tool
+ * untouched. Only subagent and remote-agent runtime actions enter the sandbox.
+ */
+export async function applyWorkflowTool(input: {
+ readonly harnessTools: HarnessToolMap;
+ readonly lifecycle?: WorkflowSandboxLifecycle;
+ readonly tools: ToolSet;
+}): Promise<WorkflowToolSet> {
+ const hostTools = createWorkflowHostTools(input.harnessTools, Object.keys(input.tools));
+
+ if (Object.keys(hostTools).length === 0) {
+ return { hostTools, modelTools: input.tools };
+ }
+
+ const workflowTool = await createWorkflowSandboxTool({
+ hostTools,
+ lifecycle: input.lifecycle,
+ });
+ const generated = typeof workflowTool.description === "string" ? workflowTool.description : "";
+ const framing = workflowToolDescription(Object.keys(hostTools));
+ const apiReference = workflowApiReference(generated);
+ const modelTools: Record<string, ToolSet[string]> = { ...input.tools };
+ modelTools[WORKFLOW_TOOL_NAME] = {
+ ...workflowTool,
+ description: apiReference.length > 0 ? `${framing}\n\n${apiReference}` : framing,
+ inputSchema: jsonSchema({
+ type: "object",
+ properties: {
+ js: {
+ type: "string",
+ description:
+ "Complete JavaScript orchestration program. Call only the agents listed in the Workflow description and return one JSON-serializable result.",
+ },
+ },
+ required: ["js"],
+ additionalProperties: false,
+ }),
+ } as ToolSet[string];
+
+ return {
+ hostTools,
+ modelTools: modelTools as ToolSet,
+ };
+}
+
+function workflowApiReference(generatedDescription: string): string {
+ const marker = "Tools:\n";
+ const start = generatedDescription.indexOf(marker);
+ if (start < 0) return generatedDescription;
+ return `Available agent API:\n${generatedDescription.slice(start + marker.length)}`;
+}
+
+/** Rebuilds the subagent-only host surface used to resume a parked workflow. */
+export function buildWorkflowHostTools(input: { readonly tools: HarnessToolMap }): ToolSet {
+ return createWorkflowHostTools(input.tools, input.tools.keys());
+}
+
+function createWorkflowHostTools(tools: HarnessToolMap, names: Iterable<string>): ToolSet {
+ const hostTools: Record<string, ToolSet[string]> = {};
+
+ for (const name of names) {
+ const tool = tools.get(name);
+ if (tool?.runtimeAction !== undefined) {
+ hostTools[name] = createWorkflowRuntimeActionHostTool(tool);
+ }
+ }
+
+ return hostTools as ToolSet;
+}
+
+function createWorkflowRuntimeActionHostTool(harnessTool: HarnessToolDefinition): ToolSet[string] {
+ return {
+ description: harnessTool.description,
+ inputSchema: harnessTool.inputSchema,
+ execute: async (toolInput: unknown, options: unknown) => {
+ const resolution = readWorkflowSandboxResolution(options);
+ if (resolution !== undefined) return resolution;
+
+ return requestWorkflowSandboxInterrupt({
+ kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND,
+ runtimeAction: harnessTool.runtimeAction,
+ toolInput,
+ toolName: harnessTool.name,
+ });
+ },
+ } as ToolSet[string];
+}
diff --git a/packages/eve/src/harness/workflow-tool-description.test.ts b/packages/eve/src/harness/workflow-tool-description.test.ts
index 6306270c6..0b40168bf 100644
--- a/packages/eve/src/harness/workflow-tool-description.test.ts
+++ b/packages/eve/src/harness/workflow-tool-description.test.ts
@@ -3,14 +3,26 @@ import { describe, expect, it } from "vitest";
import { workflowToolDescription } from "#harness/workflow-tool-description.js";
describe("workflowToolDescription", () => {
- it("names every callable agent and shows a subagent example when a subagent exists", () => {
- const description = workflowToolDescription(["agent", "researcher", "stock_price"]);
+ it("explains when orchestration is and is not appropriate", () => {
+ const description = workflowToolDescription(["agent", "researcher"]);
+
+ expect(description).toContain("Use `Workflow` for:");
+ expect(description).toContain("Do not use `Workflow` when:");
+ expect(description).toContain("map-reduce");
+ expect(description).toContain("dependent pipelines");
+ expect(description).toContain("one delegation");
+ expect(description).toContain("small fixed set");
+ expect(description).toContain("ordinary tools");
+ });
+
+ it("names every callable agent and safely formats a hyphenated subagent example", () => {
+ const description = workflowToolDescription(["agent", "echo-marker", "stock_price"]);
expect(description).toContain("`agent`");
- expect(description).toContain("`researcher`");
+ expect(description).toContain("`echo-marker`");
expect(description).toContain("`stock_price`");
- // The example calls a declared subagent, not the built-in `agent`.
- expect(description).toContain("researcher({");
+ expect(description).toContain('tools["echo-marker"]({');
+ expect(description).not.toContain("tools.echo-marker");
});
it("omits the subagent example and demonstrates agent() when only the built-in agent is callable", () => {
diff --git a/packages/eve/src/harness/workflow-tool-description.ts b/packages/eve/src/harness/workflow-tool-description.ts
index b46ae8a83..d29953aac 100644
--- a/packages/eve/src/harness/workflow-tool-description.ts
+++ b/packages/eve/src/harness/workflow-tool-description.ts
@@ -9,8 +9,8 @@
* - a single simple subagent example is appended *only when* the agent has a
* declared subagent or remote agent (i.e. an agent other than `agent`).
*
- * The exact input signatures auto-generated by `createCodeModeTool` are appended
- * after this framing.
+ * The sandbox package's generated input signatures are appended after this
+ * framing.
*
* @param toolNames - Names of the agent functions callable inside the sandbox.
*/
@@ -20,14 +20,26 @@ export function workflowToolDescription(toolNames: readonly string[]): string {
const subagents = agents.filter((name) => name !== "agent");
const subagentExample =
subagents.length > 0
- ? `\n\nDeclared subagents are called the same way — e.g. \`const note = await tools.${subagents[0]}({ message: "..." });\`.`
+ ? `\n\nDeclared subagents use the same API — e.g. \`const note = await ${agentAccess(subagents[0]!)}({ message: "..." });\`.`
: "";
- return `Orchestrate this agent's subagents by writing a JavaScript program the runtime executes deterministically — fan out independent subtasks, run staged pipelines, and combine results in code, in a single step.
+ return `Use \`Workflow\` when a task needs JavaScript to coordinate multiple child-agent calls as one durable step. It is an orchestration tool, not a general-purpose tool runner.
-The only callable operations are these agents — no filesystem, network, shell, or other tools: ${list}. Call each as \`await tools.<name>(input)\`; it resolves to the child's result, or a typed object when you pass an \`outputSchema\`. Sequence with \`await\`, run agents concurrently with \`Promise.all([...])\`, and use \`map\`/\`filter\`/\`flatMap\` to build calls and combine results. The program's return value becomes the tool result.
+Use \`Workflow\` for:
+- fan-out or map-reduce over a list, especially when the number of calls comes from runtime data;
+- dependent pipelines where one agent's result becomes another agent's input;
+- conditional branches or follow-up calls chosen from earlier results;
+- deterministic filtering, sorting, or aggregation of several agent results before returning one value.
-Reach for this when work decomposes into independent or staged subtasks — map-reduce over a list, a plan-then-verify pipeline, or fan-out-and-gather. For a single delegation, call the agent directly.
+Do not use \`Workflow\` when:
+- one delegation, or a small fixed set of unrelated delegations, can be called directly;
+- no child-agent call is needed;
+- the task needs files, network, shell, connections, skills, or ordinary tools — none are available inside Workflow;
+- JavaScript would only wrap work the parent agent can express more clearly with direct calls.
+
+Workflow earns its overhead when code materially controls call count, concurrency, ordering, data flow, or aggregation. Put the complete orchestration in one JavaScript program and return the final JSON-serializable value.
+
+The only callable operations are these agents — no filesystem, network, shell, or other tools: ${list}. Call them only through the \`tools\` object, using the exact member syntax in the API reference below. Each call is async and resolves to the child's result, or a typed object when you pass an \`outputSchema\`. Sequence with \`await\`, run agents concurrently with \`Promise.all([...])\`, and use \`map\`/\`filter\`/\`flatMap\` to build calls and combine results. The program's return value becomes the tool result.
Example — fan out across areas with \`agent\`, then pipe the results into a synthesis step:
\`\`\`js
@@ -47,3 +59,9 @@ const verdict = await tools.agent({
return verdict;
\`\`\`${subagentExample}`;
}
+
+function agentAccess(name: string): string {
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(name)
+ ? `tools.${name}`
+ : `tools[${JSON.stringify(name)}]`;
+}
diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.ts
index 951a9dc7b..c4e9990cf 100644
--- a/packages/eve/src/internal/authored-definition/core.ts
+++ b/packages/eve/src/internal/authored-definition/core.ts
@@ -7,7 +7,6 @@ import type { ScheduleDefinition, ScheduleRunHandler } from "#public/definitions
import type { SkillDefinition, SkillFileContent } from "#public/definitions/skill.js";
import type { InstructionsDefinition } from "#public/definitions/instructions.js";
import {
- expectBoolean,
expectFunction,
expectObjectRecord,
expectOnlyKnownKeys,
@@ -177,13 +176,9 @@ function normalizeAgentExperimentalDefinition(
message: string,
): NonNullable<NormalizedAgentDefinition["experimental"]> {
const record = expectObjectRecord(value, message);
- expectOnlyKnownKeys(record, ["codeMode", "workflow"], message);
+ expectOnlyKnownKeys(record, ["workflow"], message);
const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["experimental"]>> = {};
- if (record.codeMode !== undefined) {
- normalizedDefinition.codeMode = expectBoolean(record.codeMode, message);
- }
-
if (record.workflow !== undefined) {
normalizedDefinition.workflow = normalizeAgentWorkflowDefinition(record.workflow, message);
}
diff --git a/packages/eve/src/internal/nitro/host/code-mode-runtime-dependency-plugin.ts b/packages/eve/src/internal/nitro/host/code-mode-runtime-dependency-plugin.ts
deleted file mode 100644
index b4161e258..000000000
--- a/packages/eve/src/internal/nitro/host/code-mode-runtime-dependency-plugin.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import * as codeMode from "#compiled/experimental-ai-sdk-code-mode/index.js";
-import { installCodeModeModule } from "#shared/code-mode.js";
-
-installCodeModeModule(codeMode);
-
-export default function installCodeModeRuntimeDependencyPlugin(): void {}
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
index 22d3da254..da5bd8ee7 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
@@ -149,7 +149,6 @@ describe("createApplicationNitro", () => {
});
afterEach(() => {
- delete process.env.EVE_EXPERIMENTAL_CODE_MODE;
delete process.env.VERCEL;
});
@@ -552,48 +551,30 @@ describe("createApplicationNitro", () => {
);
});
- it("includes the code-mode runtime plugin only when code mode is enabled", async () => {
+ it("includes the Workflow sandbox runtime plugin only when Workflow is enabled", async () => {
const directNitroStub = createNitroStub();
- const codeModeNitroStub = createNitroStub();
+ const workflowNitroStub = createNitroStub();
createNitroMock.mockResolvedValueOnce(directNitroStub.nitro);
- createNitroMock.mockResolvedValueOnce(codeModeNitroStub.nitro);
+ createNitroMock.mockResolvedValueOnce(workflowNitroStub.nitro);
const { createApplicationNitro } =
await import("#internal/nitro/host/create-application-nitro.js");
- await createApplicationNitro(createPreparedHost(), false);
- vi.stubEnv("EVE_EXPERIMENTAL_CODE_MODE", "1");
- await createApplicationNitro(createPreparedHost(), false);
+ const directHost = createPreparedHost();
+ const workflowHost = createPreparedHost();
+ workflowHost.compileResult.manifest.workflowEnabled = true;
+
+ await createApplicationNitro(directHost, false);
+ await createApplicationNitro(workflowHost, false);
const directPlugins = createNitroMock.mock.calls[0]?.[0].plugins as string[];
- const codeModePlugins = createNitroMock.mock.calls[1]?.[0].plugins as string[];
+ const workflowPlugins = createNitroMock.mock.calls[1]?.[0].plugins as string[];
expect(directPlugins).not.toEqual(
- expect.arrayContaining([expect.stringContaining("code-mode-runtime-dependency-plugin.ts")]),
+ expect.arrayContaining([expect.stringContaining("workflow-sandbox-runtime-plugin.ts")]),
);
- expect(codeModePlugins).toEqual(
- expect.arrayContaining([expect.stringContaining("code-mode-runtime-dependency-plugin.ts")]),
- );
- });
-
- it("includes the code-mode runtime plugin when an agent opts in via experimental.codeMode", async () => {
- const nitroStub = createNitroStub();
- createNitroMock.mockResolvedValueOnce(nitroStub.nitro);
-
- const { createApplicationNitro } =
- await import("#internal/nitro/host/create-application-nitro.js");
-
- const preparedHost = createPreparedHost();
- preparedHost.compileResult.manifest.config = {
- ...preparedHost.compileResult.manifest.config,
- experimental: { codeMode: true },
- } as typeof preparedHost.compileResult.manifest.config;
-
- await createApplicationNitro(preparedHost, false);
-
- const plugins = createNitroMock.mock.calls[0]?.[0].plugins as string[];
- expect(plugins).toEqual(
- expect.arrayContaining([expect.stringContaining("code-mode-runtime-dependency-plugin.ts")]),
+ expect(workflowPlugins).toEqual(
+ expect.arrayContaining([expect.stringContaining("workflow-sandbox-runtime-plugin.ts")]),
);
});
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
index dc4c14ee2..67f8d57e7 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
@@ -35,7 +35,6 @@ import type { NitroBuildSurface, PreparedApplicationHost } from "#internal/nitro
import { createEveVercelOptions } from "#internal/nitro/host/vercel-build-output-config.js";
import { applyWorkflowTransform } from "#internal/workflow-bundle/workflow-builders.js";
import { transformDynamicToolExecute } from "#internal/workflow-bundle/dynamic-tool-transform.js";
-import { resolveCodeModeEnabled } from "#shared/code-mode.js";
import type { CompiledAgentManifest } from "#compiler/manifest.js";
/**
@@ -99,22 +98,10 @@ function includesWorkflowStepRegistrations(surface: NitroBuildSurface): boolean
return includesWorkflowSurface(surface);
}
-/**
- * Reports whether any agent in the compiled graph runs in code mode, so the
- * host build only bundles the sandbox worker assets when they are needed.
- *
- * Each node resolves its own `experimental.codeMode` flag with the
- * `EVE_EXPERIMENTAL_CODE_MODE` env backstop, matching the runtime decision.
- */
-function manifestEnablesCodeMode(manifest: CompiledAgentManifest): boolean {
+/** Whether any agent needs the dynamic Workflow sandbox runtime. */
+function manifestEnablesWorkflow(manifest: CompiledAgentManifest): boolean {
const nodes = [manifest, ...manifest.subagents.map((subagent) => subagent.agent)];
- // The Workflow tool reuses the code-mode runtime (QuickJS sandbox), so its
- // dependency must be bundled whenever any node enables code mode OR the
- // Workflow tool.
- return nodes.some(
- (node) =>
- resolveCodeModeEnabled(node.config.experimental?.codeMode) || node.workflowEnabled === true,
- );
+ return nodes.some((node) => node.workflowEnabled === true);
}
function manifestHasWebSocketChannel(manifest: CompiledAgentManifest): boolean {
@@ -688,11 +675,9 @@ export async function createApplicationNitro(
includesApplicationSurface(surface) &&
(dev || manifestHasWebSocketChannel(preparedHost.compileResult.manifest));
const nitroPlugins: string[] = [];
- if (manifestEnablesCodeMode(preparedHost.compileResult.manifest)) {
+ if (manifestEnablesWorkflow(preparedHost.compileResult.manifest)) {
nitroPlugins.push(
- resolvePackageSourceFilePath(
- "src/internal/nitro/host/code-mode-runtime-dependency-plugin.ts",
- ),
+ resolvePackageSourceFilePath("src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts"),
);
}
if (preparedHost.compiledArtifacts.instrumentationPluginPath !== undefined) {
diff --git a/packages/eve/src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts b/packages/eve/src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts
new file mode 100644
index 000000000..a7714cbc1
--- /dev/null
+++ b/packages/eve/src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts
@@ -0,0 +1,18 @@
+import {
+ continueCodeModeInterrupt,
+ createCodeModeTool,
+ getCodeModeInterrupt,
+ requestCodeModeInterrupt,
+ unwrapCodeModeResult,
+} from "#compiled/experimental-ai-sdk-code-mode/index.js";
+import { installWorkflowSandboxModule } from "#shared/workflow-sandbox.js";
+
+installWorkflowSandboxModule({
+ continueCodeModeInterrupt,
+ createCodeModeTool,
+ getCodeModeInterrupt,
+ requestCodeModeInterrupt,
+ unwrapCodeModeResult,
+});
+
+export default function installWorkflowSandboxRuntimePlugin(): void {}
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts
index c8406dc61..3d4fb9cc9 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.ts
@@ -10,7 +10,7 @@ import { createConnectionSearchResolver } from "#runtime/framework-tools/connect
import type { AgentInfoManifestData } from "#internal/nitro/routes/agent-info/load-agent-info-data.js";
import type { ResolvedChannelDefinition, ResolvedToolDefinition } from "#runtime/types.js";
import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
-import { CODE_MODE_TOOL_NAME, WORKFLOW_TOOL_NAME } from "#shared/code-mode.js";
+import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";
import type {
AgentInfoFrameworkChannelEntry,
AgentInfoFrameworkToolEntry,
@@ -239,7 +239,7 @@ export function buildAgentInfoResponseFromManifest(
status,
};
}),
- reserved: [CODE_MODE_TOOL_NAME, WORKFLOW_TOOL_NAME, LOAD_SKILL_TOOL_NAME],
+ reserved: [WORKFLOW_TOOL_NAME, LOAD_SKILL_TOOL_NAME],
},
version: 1,
workflow: {
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
index 9a54d8584..a071d953c 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
@@ -20,7 +20,7 @@ import type {
ResolvedToolDefinition,
} from "#runtime/types.js";
import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";
-import { CODE_MODE_TOOL_NAME, WORKFLOW_TOOL_NAME } from "#shared/code-mode.js";
+import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";
import type { ModelRouting } from "#shared/agent-definition.js";
import type { ModelEndpointStatus } from "#shared/model-endpoint-status.js";
@@ -402,7 +402,7 @@ function buildToolInfo(agent: ResolvedAgent): AgentInfoTools {
),
],
framework,
- reserved: [CODE_MODE_TOOL_NAME, WORKFLOW_TOOL_NAME, LOAD_SKILL_TOOL_NAME],
+ reserved: [WORKFLOW_TOOL_NAME, LOAD_SKILL_TOOL_NAME],
};
}
diff --git a/packages/eve/src/public/definitions/tool.ts b/packages/eve/src/public/definitions/tool.ts
index 4806cf715..e68d1eb8a 100644
--- a/packages/eve/src/public/definitions/tool.ts
+++ b/packages/eve/src/public/definitions/tool.ts
@@ -337,7 +337,7 @@ export interface EnableWorkflowToolSentinel {
}
/**
- * Opt-in marker for the framework `Workflow` tool, a code-mode sandbox whose
+ * Opt-in marker for the framework `Workflow` tool, an isolated JavaScript sandbox whose
* only callable operations are this agent's subagents and remote agents, for
* orchestrating them from model-authored JavaScript. Re-export it as the
* default export of `agent/tools/workflow.ts`:
diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
index 63a947e1e..6249eb625 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
@@ -223,42 +223,6 @@ describe("createMockAuthoredRuntimeModel", () => {
]);
});
- it("emits code-mode source for weather tools when code mode is the visible tool", async () => {
- const result = await generateWithPrompt(
- [
- {
- content: "What is the weather for Lisbon?",
- role: "user",
- },
- ],
- [
- {
- description: [
- "Run sandboxed JavaScript with these host tools.",
- "declare const tools: {",
- " /** Get the current weather for a city. */",
- " get_weather: (input: { city: string }) => Promise<unknown>;",
- "};",
- ].join("\n"),
- name: "code_mode",
- type: "function",
- },
- ],
- );
-
- expect(result.finishReason).toEqual({ raw: undefined, unified: "tool-calls" });
- expect(result.content).toEqual([
- {
- input: JSON.stringify({
- js: 'return await tools.get_weather({ city: "Lisbon" });',
- }),
- toolCallId: "call_code_mode",
- toolName: "code_mode",
- type: "tool-call",
- },
- ]);
- });
-
it("builds ask_question input from prompt text and option labels", async () => {
const result = await generateWithPrompt(
[
diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.ts b/packages/eve/src/runtime/agent/mock-model-adapter.ts
index 30ae34b1d..2ddadd7a8 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.ts
@@ -14,7 +14,6 @@ import {
resolveMockFixtureToken,
resolveWeatherCity,
} from "#runtime/agent/mock-model-fixtures.js";
-import { CODE_MODE_TOOL_NAME } from "#shared/code-mode.js";
import {
type BootstrapGenerateResult,
type BootstrapPrompt,
@@ -221,29 +220,6 @@ function createAuthoredToolCallResult(
const city = resolveWeatherCity(lastUserMessage);
const toolInput = createMockAuthoredToolInput(tool, lastUserMessage, city);
- if (tool.name === CODE_MODE_TOOL_NAME) {
- const nestedToolName = findRelevantCodeModeHostTool(tool.description, lastUserMessage);
-
- if (nestedToolName === null) {
- return null;
- }
-
- const js = `return await tools${formatCodeModeToolAccess(nestedToolName)}({ city: ${JSON.stringify(
- city,
- )} });`;
-
- return createToolCallGenerateResult({
- input: {
- js,
- },
- inputTokens: estimateTokenCount(getPromptText(options.prompt)),
- modelId,
- outputTokens: estimateTokenCount(js),
- toolCallId: createToolCallId(tool.name),
- toolName: tool.name,
- });
- }
-
return createToolCallGenerateResult({
input: toolInput,
inputTokens: estimateTokenCount(getPromptText(options.prompt)),
@@ -554,50 +530,6 @@ function findRelevantTool(
);
}
-function findRelevantCodeModeHostTool(
- description: string | undefined,
- message: string,
-): string | null {
- if (description === undefined) {
- return null;
- }
-
- return findRelevantTool(parseCodeModeHostTools(description), message)?.name ?? null;
-}
-
-function parseCodeModeHostTools(description: string): AvailableBootstrapTool[] {
- const tools: AvailableBootstrapTool[] = [];
- let pendingDescription: string | undefined;
-
- for (const line of description.split("\n")) {
- const comment = /^\s*\/\*\*\s*(.*?)\s*\*\/\s*$/u.exec(line);
-
- if (comment?.[1] !== undefined) {
- pendingDescription = comment[1];
- continue;
- }
-
- const declaration = /^\s*(?:([$A-Z_a-z][$\w]*)|(["'])(.*?)\2)\s*:\s*\(input:/u.exec(line);
- const name = declaration?.[1] ?? declaration?.[3];
-
- if (name === undefined) {
- continue;
- }
-
- tools.push({
- description: pendingDescription,
- name,
- });
- pendingDescription = undefined;
- }
-
- return tools;
-}
-
-function formatCodeModeToolAccess(toolName: string): string {
- return /^[$A-Z_a-z][$\w]*$/u.test(toolName) ? `.${toolName}` : `[${JSON.stringify(toolName)}]`;
-}
-
function normalizeText(value: string): string {
return value
.toLowerCase()
diff --git a/packages/eve/src/runtime/framework-tools/code-mode-connection-auth.ts b/packages/eve/src/runtime/framework-tools/code-mode-connection-auth.ts
deleted file mode 100644
index b1b4d4f62..000000000
--- a/packages/eve/src/runtime/framework-tools/code-mode-connection-auth.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import type {
- CodeModeInterrupt,
- CodeModeInterruptExecutionContext,
- CodeModeInterruptPayload,
-} from "#shared/code-mode.js";
-
-import type { AuthorizationChallenge } from "#harness/authorization.js";
-import type { JsonValue } from "#public/types/json.js";
-import { isObject } from "#shared/guards.js";
-
-export const CODE_MODE_CONNECTION_AUTH_INTERRUPT_KIND = "eve.connection-auth";
-
-export interface CodeModeConnectionAuthPayload extends CodeModeInterruptPayload {
- readonly kind: typeof CODE_MODE_CONNECTION_AUTH_INTERRUPT_KIND;
- readonly args: JsonValue;
- readonly challenges?: readonly AuthorizationChallenge[];
- readonly connectionName: string;
- readonly toolName: string;
-}
-
-export type CodeModeConnectionAuthResolution =
- | {
- readonly status: "authorized";
- }
- | {
- readonly reason: string;
- readonly retryable: boolean;
- readonly status: "failed";
- };
-
-export type CodeModeConnectionAuthContext = CodeModeInterruptExecutionContext<
- CodeModeConnectionAuthPayload,
- CodeModeConnectionAuthResolution
->;
-
-const CODE_MODE_TOOL_EXECUTION_FLAG = "__eveCodeMode";
-
-export function markCodeModeToolExecutionOptions(options: unknown): unknown {
- if (!isObject(options)) {
- return { [CODE_MODE_TOOL_EXECUTION_FLAG]: true };
- }
-
- return {
- ...options,
- [CODE_MODE_TOOL_EXECUTION_FLAG]: true,
- };
-}
-
-export function isCodeModeToolExecutionOptions(options: unknown): boolean {
- return isObject(options) && options[CODE_MODE_TOOL_EXECUTION_FLAG] === true;
-}
-
-export function readCodeModeConnectionAuthContext(
- options: unknown,
-): CodeModeConnectionAuthContext | undefined {
- if (!isObject(options)) return undefined;
- const codeModeInterrupt = options.codeModeInterrupt;
- if (!isObject(codeModeInterrupt)) return undefined;
- if (!isCodeModeConnectionAuthPayload(codeModeInterrupt.payload)) return undefined;
- if (!isCodeModeConnectionAuthResolution(codeModeInterrupt.resolution)) return undefined;
- if (typeof codeModeInterrupt.interruptId !== "string") return undefined;
- return {
- interruptId: codeModeInterrupt.interruptId,
- payload: codeModeInterrupt.payload,
- resolution: codeModeInterrupt.resolution,
- };
-}
-
-export function isCodeModeConnectionAuthPayload(
- value: unknown,
-): value is CodeModeConnectionAuthPayload {
- return (
- isObject(value) &&
- value.kind === CODE_MODE_CONNECTION_AUTH_INTERRUPT_KIND &&
- typeof value.connectionName === "string" &&
- typeof value.toolName === "string" &&
- "args" in value
- );
-}
-
-export function isCodeModeConnectionAuthInterrupt(
- value: unknown,
-): value is CodeModeInterrupt<CodeModeConnectionAuthPayload> {
- if (!isObject(value) || value.type !== "code-mode-interrupt") {
- return false;
- }
-
- return isCodeModeConnectionAuthPayload(value.payload);
-}
-
-export function toConnectionAuthResolutionFailure(input: {
- readonly reason: string;
- readonly retryable: boolean;
-}): CodeModeConnectionAuthResolution {
- return {
- reason: input.reason,
- retryable: input.retryable,
- status: "failed",
- };
-}
-
-export function toCodeModeConnectionAuthArgs(value: unknown): JsonValue {
- if (value === undefined) return null;
- try {
- return JSON.parse(JSON.stringify(value)) as JsonValue;
- } catch {
- return null;
- }
-}
-
-function isCodeModeConnectionAuthResolution(
- value: unknown,
-): value is CodeModeConnectionAuthResolution {
- if (!isObject(value) || typeof value.status !== "string") return false;
- if (value.status === "authorized") return true;
- return (
- value.status === "failed" &&
- typeof value.reason === "string" &&
- typeof value.retryable === "boolean"
- );
-}
diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
index ebbba343f..75cc41f83 100644
--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
+++ b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
@@ -56,9 +56,8 @@ const CONNECTION_SEARCH_OUTPUT_SCHEMA: JsonObject = {
/**
* Durable context key for connection search results. Written by
- * `executeConnectionSearch` so the resolver can find discovered tools
- * even in code-mode (where tool results are wrapped inside the
- * `code_mode` tool and not directly visible in messages).
+ * `executeConnectionSearch` so the resolver can find discovered tools without
+ * relying on model-facing tool result history.
*/
const ConnectionSearchResultsKey = new ContextKey<readonly ConnectionSearchResultItem[]>(
"eve.connectionSearchResults",
diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.ts
index a4c932394..a1f8c0b3b 100644
--- a/packages/eve/src/runtime/resolve-agent-graph.ts
+++ b/packages/eve/src/runtime/resolve-agent-graph.ts
@@ -26,7 +26,7 @@ import { createRuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
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 { CODE_MODE_TOOL_NAME, WORKFLOW_TOOL_NAME } from "#shared/code-mode.js";
+import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";
import type {
ResolvedChannelDefinition,
ResolvedRuntimeDelegationNode,
@@ -171,7 +171,6 @@ async function resolveRuntimeAgentNode(
},
{
reservedToolNames: [
- CODE_MODE_TOOL_NAME,
WORKFLOW_TOOL_NAME,
...(frameworkToolNames.has(LOAD_SKILL_TOOL_NAME) ||
authoredToolNames.has(LOAD_SKILL_TOOL_NAME)
diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.ts
index 35794f166..78477776d 100644
--- a/packages/eve/src/runtime/resolve-agent.ts
+++ b/packages/eve/src/runtime/resolve-agent.ts
@@ -210,7 +210,12 @@ function createResolvedAgentConfig(manifest: CompiledAgentNodeManifest): Resolve
}
if (manifest.config.experimental !== undefined) {
- config.experimental = { codeMode: manifest.config.experimental.codeMode };
+ config.experimental = {
+ workflow:
+ manifest.config.experimental.workflow === undefined
+ ? undefined
+ : { world: manifest.config.experimental.workflow.world },
+ };
}
if (manifest.config.outputSchema !== undefined) {
diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.ts
index c171750d0..b90d5b2b5 100644
--- a/packages/eve/src/runtime/types.ts
+++ b/packages/eve/src/runtime/types.ts
@@ -373,7 +373,7 @@ export interface ResolvedAgent {
/**
* Whether the author opted into the framework `Workflow` orchestration tool
* by re-exporting the `Workflow` marker as the default export of a file in
- * `agent/tools/`. When true, the harness exposes a code-mode-style sandbox
+ * `agent/tools/`. When true, the harness exposes an isolated JavaScript sandbox
* whose only callable operations are this agent's subagents and remote
* agents.
*/
diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.ts
index 335030445..d2a7e4fdb 100644
--- a/packages/eve/src/shared/agent-definition.ts
+++ b/packages/eve/src/shared/agent-definition.ts
@@ -100,20 +100,8 @@ export interface PublicAgentCompactionDefinition {
* Experimental, opt-in agent capabilities authored in `agent.ts`.
*
* These options are unstable and may change or be removed in any release.
- * Each agent (the root agent and every subagent) carries its own flags, so
- * code mode can be enabled for the whole graph, only a subagent, or only
- * the parent.
*/
export interface AgentExperimentalDefinition {
- /**
- * Routes executable tools through a sandboxed code-execution wrapper
- * instead of exposing them directly to the model. The model writes
- * JavaScript that calls the tools inside the sandbox.
- *
- * When unset, eve falls back to the `EVE_EXPERIMENTAL_CODE_MODE`
- * environment variable (`"1"` enables it) for backwards compatibility.
- */
- readonly codeMode?: boolean;
/**
* Durable Workflow runtime configuration. Root agents may use this to select
* the Workflow world backing sessions and runs.
diff --git a/packages/eve/src/shared/code-mode.ts b/packages/eve/src/shared/code-mode.ts
deleted file mode 100644
index d078d8cd9..000000000
--- a/packages/eve/src/shared/code-mode.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import type * as CodeModeModule from "#compiled/experimental-ai-sdk-code-mode/index.js";
-
-/** Internal AI SDK tool name used for eve's code-mode wrapper. */
-export const CODE_MODE_TOOL_NAME = "code_mode";
-
-/**
- * Model-facing tool name for eve's `Workflow` orchestration wrapper — a
- * code-mode sandbox restricted to subagent and remote-agent calls. Reserved so
- * authored tools cannot collide with it.
- */
-export const WORKFLOW_TOOL_NAME = "Workflow";
-
-const CODE_MODE_MODULE_KEY = Symbol.for("eve.codeMode.module");
-const CODE_MODE_MODULE_SPECIFIER = ["#compiled", "experimental-ai-sdk-code-mode", "index.js"].join(
- "/",
-);
-
-type CodeModeModuleNamespace = typeof CodeModeModule;
-
-type CodeModeGlobal = typeof globalThis & {
- [CODE_MODE_MODULE_KEY]?: CodeModeModuleNamespace;
-};
-
-let codeModeModulePromise: Promise<CodeModeModuleNamespace> | undefined;
-
-export type {
- CodeModeApprovalInterrupt,
- CodeModeInterrupt,
- CodeModeInterruptExecutionContext,
- CodeModeInterruptPayload,
- CodeModeOptions,
-} from "#compiled/experimental-ai-sdk-code-mode/index.js";
-
-/**
- * Reads the `EVE_EXPERIMENTAL_CODE_MODE` backstop. Per-agent
- * `experimental.codeMode` takes precedence; this env var is the
- * fallback applied to agents that do not set the flag.
- */
-export function isCodeModeEnvEnabled(
- env: { readonly [name: string]: string | undefined } = process.env,
-): boolean {
- return env.EVE_EXPERIMENTAL_CODE_MODE === "1";
-}
-
-/**
- * Resolves the effective code-mode setting for one agent. The authored
- * `experimental.codeMode` flag wins; when omitted, eve falls back to the
- * {@link isCodeModeEnvEnabled} environment backstop.
- */
-export function resolveCodeModeEnabled(
- experimentalCodeMode: boolean | undefined,
- env: { readonly [name: string]: string | undefined } = process.env,
-): boolean {
- return experimentalCodeMode ?? isCodeModeEnvEnabled(env);
-}
-
-export function installCodeModeModule(module: CodeModeModuleNamespace): void {
- (globalThis as CodeModeGlobal)[CODE_MODE_MODULE_KEY] = module;
-}
-
-export async function loadCodeModeModule(): Promise<CodeModeModuleNamespace> {
- const installed = (globalThis as CodeModeGlobal)[CODE_MODE_MODULE_KEY];
- if (installed !== undefined) {
- return installed;
- }
-
- codeModeModulePromise ??= importCodeModeModule(CODE_MODE_MODULE_SPECIFIER);
- return await codeModeModulePromise;
-}
-
-async function importCodeModeModule(specifier: string): Promise<CodeModeModuleNamespace> {
- return (await import(specifier)) as CodeModeModuleNamespace;
-}
diff --git a/packages/eve/src/shared/tool-definition.ts b/packages/eve/src/shared/tool-definition.ts
index d6fa8a810..d89e63d34 100644
--- a/packages/eve/src/shared/tool-definition.ts
+++ b/packages/eve/src/shared/tool-definition.ts
@@ -49,8 +49,7 @@ export interface PublicToolDefinition<
inputSchema: PublicToolInputSchema<TInput>;
/**
* Optional schema describing the value returned by the tool executor.
- * Code mode uses this to expose typed host-tool return values to the
- * generated program, and the AI SDK can use it for tool result typing.
+ * The AI SDK can use this for tool result typing.
*/
outputSchema?: PublicToolOutputSchema<TOutput>;
}
diff --git a/packages/eve/src/shared/workflow-sandbox.ts b/packages/eve/src/shared/workflow-sandbox.ts
new file mode 100644
index 000000000..29cea8e79
--- /dev/null
+++ b/packages/eve/src/shared/workflow-sandbox.ts
@@ -0,0 +1,114 @@
+import type { ToolSet } from "ai";
+import type * as CodeModeModule from "#compiled/experimental-ai-sdk-code-mode/index.js";
+
+/** Model-facing tool name for eve's dynamic subagent orchestration tool. */
+export const WORKFLOW_TOOL_NAME = "Workflow";
+
+const WORKFLOW_SANDBOX_MODULE_KEY = Symbol.for("eve.workflowSandbox.module");
+const WORKFLOW_SANDBOX_MODULE_SPECIFIER = [
+ "#compiled",
+ "experimental-ai-sdk-code-mode",
+ "index.js",
+].join("/");
+
+type WorkflowSandboxModule = Pick<
+ typeof CodeModeModule,
+ | "continueCodeModeInterrupt"
+ | "createCodeModeTool"
+ | "getCodeModeInterrupt"
+ | "requestCodeModeInterrupt"
+ | "unwrapCodeModeResult"
+>;
+
+type WorkflowSandboxGlobal = typeof globalThis & {
+ [WORKFLOW_SANDBOX_MODULE_KEY]?: WorkflowSandboxModule;
+};
+
+export type WorkflowSandboxInterrupt = CodeModeModule.CodeModeInterrupt;
+export type WorkflowSandboxLifecycle = NonNullable<CodeModeModule.CodeModeOptions["lifecycle"]>;
+
+let workflowSandboxModulePromise: Promise<WorkflowSandboxModule> | undefined;
+
+export function installWorkflowSandboxModule(module: WorkflowSandboxModule): void {
+ (globalThis as WorkflowSandboxGlobal)[WORKFLOW_SANDBOX_MODULE_KEY] = module;
+}
+
+export async function createWorkflowSandboxTool(input: {
+ readonly hostTools: ToolSet;
+ readonly lifecycle?: WorkflowSandboxLifecycle;
+}): Promise<ToolSet[string]> {
+ const { createCodeModeTool } = await loadWorkflowSandboxModule();
+ return createCodeModeTool(
+ input.hostTools,
+ createWorkflowSandboxOptions(input.lifecycle),
+ ) as ToolSet[string];
+}
+
+export async function requestWorkflowSandboxInterrupt(input: {
+ readonly kind: string;
+ readonly runtimeAction: unknown;
+ readonly toolInput: unknown;
+ readonly toolName: string;
+}): Promise<unknown> {
+ const { requestCodeModeInterrupt } = await loadWorkflowSandboxModule();
+ return requestCodeModeInterrupt(input);
+}
+
+export async function getWorkflowSandboxInterrupt(
+ result: unknown,
+): Promise<WorkflowSandboxInterrupt | undefined> {
+ const { getCodeModeInterrupt } = await loadWorkflowSandboxModule();
+ return getCodeModeInterrupt(result as never);
+}
+
+export async function continueWorkflowSandboxInterrupt(input: {
+ readonly interrupt: WorkflowSandboxInterrupt;
+ readonly lifecycle?: WorkflowSandboxLifecycle;
+ readonly resolution: unknown;
+ readonly tools: ToolSet;
+}): Promise<unknown> {
+ const { continueCodeModeInterrupt } = await loadWorkflowSandboxModule();
+ return continueCodeModeInterrupt({
+ interrupt: input.interrupt,
+ options: createWorkflowSandboxOptions(input.lifecycle),
+ resolution: input.resolution,
+ tools: input.tools,
+ } as never);
+}
+
+export async function unwrapWorkflowSandboxResult(
+ value: unknown,
+): Promise<
+ | { readonly output: unknown; readonly status: "completed" }
+ | { readonly interrupt: WorkflowSandboxInterrupt; readonly status: "interrupted" }
+> {
+ const { unwrapCodeModeResult } = await loadWorkflowSandboxModule();
+ return unwrapCodeModeResult(value) as
+ | { readonly output: unknown; readonly status: "completed" }
+ | { readonly interrupt: WorkflowSandboxInterrupt; readonly status: "interrupted" };
+}
+
+export function readWorkflowSandboxResolution(options: unknown): unknown {
+ if (typeof options !== "object" || options === null) return undefined;
+ const interrupt = (options as Record<string, unknown>).codeModeInterrupt;
+ if (typeof interrupt !== "object" || interrupt === null) return undefined;
+ return (interrupt as Record<string, unknown>).resolution;
+}
+
+function createWorkflowSandboxOptions(
+ lifecycle: WorkflowSandboxLifecycle | undefined,
+): CodeModeModule.CodeModeOptions {
+ return lifecycle === undefined ? {} : { lifecycle };
+}
+
+async function loadWorkflowSandboxModule(): Promise<WorkflowSandboxModule> {
+ const installed = (globalThis as WorkflowSandboxGlobal)[WORKFLOW_SANDBOX_MODULE_KEY];
+ if (installed !== undefined) return installed;
+
+ workflowSandboxModulePromise ??= importWorkflowSandboxModule(WORKFLOW_SANDBOX_MODULE_SPECIFIER);
+ return await workflowSandboxModulePromise;
+}
+
+async function importWorkflowSandboxModule(specifier: string): Promise<WorkflowSandboxModule> {
+ return (await import(specifier)) as WorkflowSandboxModule;
+}
diff --git a/packages/eve/src/source-change/apply-model-name.test.ts b/packages/eve/src/source-change/apply-model-name.test.ts
index d57fc3519..262afb0b0 100644
--- a/packages/eve/src/source-change/apply-model-name.test.ts
+++ b/packages/eve/src/source-change/apply-model-name.test.ts
@@ -38,7 +38,7 @@ describe("applyModelNameToSource", () => {
const source = `export default defineAgent({
// primary model
model: "a/b",
- experimental: { codeMode: true },
+ experimental: { workflow: { world: "@acme/workflow-world" } },
});
`;
const result = await applyModelNameToSource(source, "c/d");
@@ -46,7 +46,9 @@ describe("applyModelNameToSource", () => {
expect(result.kind).toBe("applied");
if (result.kind !== "applied") return;
expect(result.nextSource).toContain("// primary model");
- expect(result.nextSource).toContain("experimental: { codeMode: true }");
+ expect(result.nextSource).toContain(
+ 'experimental: { workflow: { world: "@acme/workflow-world" } }',
+ );
expect(result.nextSource).toContain(`model: "c/d"`);
});
@@ -95,7 +97,7 @@ describe("applyModelNameToSource", () => {
it("bails when model is absent", async () => {
const result = await applyModelNameToSource(
- `export default defineAgent({ experimental: { codeMode: true } });\n`,
+ `export default defineAgent({ experimental: { workflow: {} } });\n`,
"c/d",
);
diff --git a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
index 0df3dd7b6..6c08e0855 100644
--- a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
+++ b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts
@@ -290,11 +290,11 @@ describe("app runtime dependency tracing", () => {
await import(pathToFileURL(bundledDependencyModule.modulePath).href);
}, 30_000);
- it("bundles code-mode inline worker assets only when an agent enables code mode", async () => {
- async function createCodeModeAssetsApp(label: string, codeMode: boolean): Promise<string> {
- const appRoot = await createScratchDirectory(`eve-app-code-mode-assets-${label}-build-`);
+ it("bundles Workflow sandbox worker assets only when an agent enables Workflow", async () => {
+ async function createWorkflowAssetsApp(label: string, workflow: boolean): Promise<string> {
+ const appRoot = await createScratchDirectory(`eve-app-workflow-assets-${label}-build-`);
- await mkdir(join(appRoot, "agent"), {
+ await mkdir(join(appRoot, "agent", "subagents", "researcher"), {
recursive: true,
});
@@ -302,7 +302,7 @@ describe("app runtime dependency tracing", () => {
join(appRoot, "package.json"),
`${JSON.stringify(
{
- name: `code-mode-assets-${label}-test`,
+ name: `workflow-assets-${label}-test`,
private: true,
type: "module",
},
@@ -310,20 +310,32 @@ describe("app runtime dependency tracing", () => {
2,
)}\n`,
);
- const agentLines = ["export default {", ' model: "openai/gpt-5.4-mini",'];
- if (codeMode) {
- agentLines.push(" experimental: { codeMode: true },");
+ await writeFile(
+ join(appRoot, "agent", "agent.ts"),
+ 'export default { model: "openai/gpt-5.4-mini" };\n',
+ );
+ await writeFile(join(appRoot, "agent", "instructions.md"), "Trace Workflow assets.\n");
+ await writeFile(
+ join(appRoot, "agent", "subagents", "researcher", "agent.ts"),
+ 'export default { description: "Research.", model: "openai/gpt-5.4-mini" };\n',
+ );
+ await writeFile(
+ join(appRoot, "agent", "subagents", "researcher", "instructions.md"),
+ "Research the request.\n",
+ );
+ if (workflow) {
+ await mkdir(join(appRoot, "agent", "tools"), { recursive: true });
+ await writeFile(
+ join(appRoot, "agent", "tools", "workflow.ts"),
+ 'export default { kind: "eve:enable-workflow-tool" };\n',
+ );
}
- agentLines.push("};", "");
- await writeFile(join(appRoot, "agent", "agent.ts"), agentLines.join("\n"));
- await writeFile(join(appRoot, "agent", "instructions.md"), "Trace code-mode assets.\n");
return appRoot;
}
- vi.stubEnv("EVE_EXPERIMENTAL_CODE_MODE", undefined);
const disabledOutputDir = await buildApplication(
- await createCodeModeAssetsApp("disabled", false),
+ await createWorkflowAssetsApp("disabled", false),
);
const disabledTracedPackageJson = await readTracedServerPackageJson(disabledOutputDir);
const disabledServerSource = await readJavaScriptModulesRecursively(
@@ -332,14 +344,14 @@ describe("app runtime dependency tracing", () => {
expect(disabledServerSource).not.toContain("[Unprintable QuickJS value]");
- const enabledOutputDir = await buildApplication(await createCodeModeAssetsApp("enabled", true));
+ const enabledOutputDir = await buildApplication(await createWorkflowAssetsApp("enabled", true));
const tracedServerPackageJson = await readTracedServerPackageJson(enabledOutputDir);
const enabledServerSource = await readJavaScriptModulesRecursively(
join(enabledOutputDir, "server"),
);
expect(enabledServerSource).toContain("[Unprintable QuickJS value]");
- // The code-mode runtime ships bundled inline, never traced — and
+ // The Workflow sandbox runtime ships bundled inline, never traced — and
// these apps do not declare the optional just-bash engine, so its
// quickjs dependency must not sneak into the trace either.
expect(disabledTracedPackageJson.dependencies).not.toHaveProperty("quickjs-emscripten");
diff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.ts
index df6d80445..7d3bfad1d 100644
--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts
+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts
@@ -959,7 +959,7 @@ describe("compileAgent", () => {
);
});
- it("compiles the authored experimental.codeMode flag into the manifest config", async () => {
+ it("rejects the removed experimental.codeMode field", async () => {
const { agentRoot, appRoot } = await createAppRoot(
"eve-compile-experimental-code-mode-",
APP_ROOT_OPTIONS,
@@ -977,11 +977,7 @@ describe("compileAgent", () => {
].join("\n"),
);
- const result = await compileAgent({
- startPath: appRoot,
- });
-
- expect(result.manifest.config.experimental).toEqual({ codeMode: true });
+ await expect(compileAgent({ startPath: appRoot })).rejects.toThrow("codeMode");
});
it("uses the authored local subagent id as the canonical compiled runtime id", async () => {
diff --git a/packages/eve/test/tui-client/tui-connection-auth-user.ts b/packages/eve/test/tui-client/tui-connection-auth-user.ts
index b9a09122e..86cf6ef91 100644
--- a/packages/eve/test/tui-client/tui-connection-auth-user.ts
+++ b/packages/eve/test/tui-client/tui-connection-auth-user.ts
@@ -50,10 +50,7 @@ import { theme } from "./lib/theme.ts";
* either in the MCP tool's `action.result`, or echoed verbatim in
* the assistant's `message.completed`. The marker is random per
* run and only ever produced by the bearer-gated MCP stub, so its
- * presence proves the OAuth token reached MCP. (In code mode the
- * nested tool result arrives on the resumed turn and the model
- * addresses the tool through generated JavaScript, so detection
- * must not hinge on exact toolName equality.)
+ * presence proves the OAuth token reached MCP.
* 4. A normal channel follow-up on the same anchored thread resumes
* the original session after auth completes. This guards the
* durable hook state used by Slack-like follow-ups.
@@ -198,10 +195,8 @@ runEnvironment("tui-connection-auth-user", async ({ cleanup, target: resolveTarg
if (event.type === "action.result") {
const ar = event as ActionResultStreamEvent;
const result = ar.data.result;
- // Match on the marker, not exact toolName equality: in code mode
- // the nested result arrives on the resumed turn and the model may
- // reach the tool through a normalized identifier. The marker is
- // random per run and only the bearer-gated MCP stub can emit it.
+ // Match on the marker as well as the stable tool-name suffix. The marker
+ // is random per run and only the bearer-gated MCP stub can emit it.
if (
result.kind === "tool-result" &&
result.toolName.includes("echo_marker") &&
@@ -215,10 +210,9 @@ runEnvironment("tui-connection-auth-user", async ({ cleanup, target: resolveTarg
}
}
- // Fallback proof for code mode: the prompt instructs the model to
- // echo the tool's returned text verbatim, so the final assistant
- // message carries the marker even when the nested tool result event
- // is suppressed or attributed differently.
+ // Fallback proof: the prompt instructs the model to echo the tool's
+ // returned text verbatim, so the final assistant message carries the
+ // marker even if the result event is unavailable.
if (
event.type === "message.completed" &&
typeof event.data.message === "string" &&
diff --git a/turbo.json b/turbo.json
index d361c5d5f..2e968b65c 100644
--- a/turbo.json
+++ b/turbo.json
@@ -46,7 +46,6 @@
},
"test": {
"cache": false,
- "env": ["EVE_EXPERIMENTAL_CODE_MODE"],
"inputs": [
"$TURBO_DEFAULT$",
"!.eve/**",
@@ -77,7 +76,6 @@
},
"test:integration": {
"cache": false,
- "env": ["EVE_EXPERIMENTAL_CODE_MODE"],
"inputs": [
"$TURBO_DEFAULT$",
"!.eve/**",
@@ -93,7 +91,6 @@
},
"test:scenario": {
"cache": false,
- "env": ["EVE_EXPERIMENTAL_CODE_MODE"],
"inputs": [
"$TURBO_DEFAULT$",
"!.eve/**",
@@ -109,7 +106,6 @@
},
"test:unit": {
"cache": false,
- "env": ["EVE_EXPERIMENTAL_CODE_MODE"],
"inputs": [
"$TURBO_DEFAULT$",
"!.eve/**",