---
title: Code Mode
description: Let the model write one JavaScript program to compose tools, MCP connections, approvals, and subagents in a single turn.
url: "https://eve.dev/docs/tools/code-mode"
docs_index: /llms.txt
keywords:
  - code mode
  - programmatic tool calling
  - workflow tool
  - mcp code mode
---

> For an index of all documentation, see [/llms.txt](/llms.txt).

Code mode lets the model write one JavaScript program that finds tools, calls them in parallel, filters data in memory, and returns compact JSON. Enable it by exporting `workflow({ mode: "execute", tools: true })` from `agent/tools/workflow.ts`.

In a standard tool-calling loop, each tool result re-enters model context and adds another model call. Code mode moves loops, conditionals, and data filtering into JavaScript. When a program waits for approval, sign-in, or a subagent, eve saves its state and releases compute, so the wait survives restarts and redeploys.

**Release readiness** (99% less context · 2.5× fewer model calls)

Prompt: "Check 12 production services, review any with error rate above 1%, and request deploy approval for the API."

- **Standard tool loop**: 5 model calls, \~188 KB entering model context (36 tools upfront; Sequential waits across steps).
- **eve code mode**: 2 model calls, \~1.4 KB entering model context (186.6 KB kept in VM memory; workflow + catalog search; 1 batched pause).

```js
const services = await tools.ops__list_services({});
const checks = await Promise.all(
  services.map((s) => tools.ops__get_metrics({ id: s.id }))
);
const degraded = checks.filter((c) => c.errorRate > 0.01);
const [review, deploy] = await Promise.all([
  ctx.agent("release-reviewer", {
    message: JSON.stringify(degraded),
    outputSchema: { type: "object", properties: { safe: { type: "boolean" } } },
  }),
  tools.gated_deploy({ service: "api", degraded: degraded.length }),
]);
return { degraded: degraded.length, review, deploy };
```

**Large MCP catalog** (99.6% less context · 2× fewer model calls)

Prompt: "Search connected Linear and Stripe MCP servers, join 50 open bugs with customer MRR, and return the top 5."

- **Standard tool loop**: 4 model calls, \~232 KB entering model context (120 MCP schemas upfront; 50 raw tool results in context).
- **eve code mode**: 2 model calls, \~0.9 KB entering model context (231.1 KB kept in VM memory; 0 MCP upfront · search(); Mid-program OAuth sign-in if needed).

```js
const found = await search({ query: "linear__ issues" });
const listIssues = found.results[0].tool;
const issues = await tools[listIssues]({ label: "bug", limit: 50 });
const enriched = await Promise.all(
  issues.map(async (issue) => {
    const acct = await tools.stripe__get_customer({ id: issue.customerId });
    return { id: issue.id, title: issue.title, mrr: acct.mrr };
  })
);
return enriched.sort((a, b) => b.mrr - a.mrr).slice(0, 5);
```

**Batch subagent fan-out** (99.5% less context · 2× fewer model calls)

Prompt: "Classify 18 open support tickets using a fast subagent model and summarize only P0 escalations."

- **Standard tool loop**: 4 model calls, \~112 KB entering model context (Helpdesk + agent tools; 18 background task receipts).
- **eve code mode**: 2 model calls, \~0.6 KB entering model context (111.4 KB kept in VM memory; workflow + agent(); 1 wait for all 18 subagents).

```js
const tickets = await tools.helpdesk__list_open({ limit: 18 });
const classified = await Promise.all(
  tickets.map((t) =>
    ctx.agent("agent", {
      model: "haiku",
      message: `Classify ticket ${t.id}: ${t.subject}`,
      outputSchema: { type: "object", properties: { id: { type: "string" }, severity: { type: "string" } } },
    })
  )
);
return classified.filter((item) => item.severity === "P0");
```

## Enable code mode

Add one file under `agent/tools/` exporting `workflow({ mode: "execute", tools: true })` from `eve/tools/workflow`. The filename becomes the tool name the model sees.

```text
agent/
├── agent.ts
└── tools/
    └── workflow.ts   # exposes the `workflow` tool in code mode
```

```ts title="agent/tools/workflow.ts"
import { workflow } from "eve/tools/workflow";

export default workflow({
  mode: "execute", // required when tools is true
  tools: true, // exposes tools.<name>, search(), and ctx.agent()
  maxSubagents: 20, // integer 1–128; omit for 100
});
```

- `workflow()` is opt-in and is excluded from the default tool set. Agents without a `workflow()` tool pay no bundle or runtime cost for the JavaScript engine.
- Setting `tools: true` requires `mode: "execute"`. Omitting `mode` or passing `mode: "task"` fails TypeScript checks and throws a `TypeError` at runtime.
- Programs run inside a bundled QuickJS-WASM runtime with no external sandbox, container, or worker binding to provision.

## Inside a code-mode program

When the model calls `workflow({ js })`, eve runs `js` as the body of an `async` function. Supply statements and a `return` value directly without a surrounding function declaration.

| Global                                                | Behavior                                                                                                                       |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `tools.<name>(input)`                                 | Calls a direct tool, deferred tool, connection tool, workflow tool, or subagent by its flat catalog name.                      |
| `tools["name"](input)`                                | Calls a tool whose catalog name is not a JavaScript identifier, such as `"public-catalog__list_items"`.                        |
| `search({ query, limit? })`                           | Finds deferred tools, MCP tools, OpenAPI tools, and deferred skills. Returns `{ results, remaining, searched, unavailable? }`. |
| `ctx.agent(name, { message, outputSchema?, model? })` | Alias for `tools[name](input)`. Pass `outputSchema` for structured JSON and `model` when the target tool declares models.      |
| `console.log` / `info` / `warn` / `error` / `debug`   | Captures up to 64 KiB of log lines and attaches them as `logs` on the program result.                                          |

```js
// Find a deferred MCP tool on demand and read its catalog name
const { results } = await search({ query: "public-catalog__ list" });
const listItemsTool = results[0]?.tool ?? "public-catalog__list_items";

const items = await tools[listItemsTool]({});
const lowStock = items.filter((item) => item.stock < 5);

const [deploy, summary] = await Promise.all([
  tools.gated_deploy({ service: "api", lowStockCount: lowStock.length }),
  ctx.agent("release-reviewer", {
    message: JSON.stringify(lowStock),
    outputSchema: {
      type: "object",
      properties: {
        ready: { type: "boolean" },
        risks: { type: "array", items: { type: "string" } },
      },
      required: ["ready", "risks"],
    },
  }),
]);

return { lowStockCount: lowStock.length, deploy, summary };
```

### Search, connections, and typed outputs

Code mode keeps the `workflow` tool schema stable instead of regenerating one large declaration block on every turn:

- `search({ query, limit? })` returns `{ results, remaining, searched, unavailable? }`. Tool matches carry `{ tool, description, signature }`, and deferred skills carry `{ skill, description, path? }`. `limit` defaults to `10` (maximum `50`), and a prefix query such as `"linear__"` narrows results to one connection.
- [MCP](/docs/connections/mcp) and [OpenAPI](/docs/connections/openapi) tools use `<connectionName>__<toolName>`, derived from `agent/connections/<name>.ts`. Use `tools["public-catalog__list_items"]({})` when a name contains hyphens.
- OpenAPI tools return `{ status, statusText, body, location? }`. A connection that requires OAuth before listing tools exposes a sign-in entry callable via `await tools["<connectionName>"]({})`.
- Add `outputSchema` to custom tools so code mode can advertise their TypeScript return shape, and add `deferred: true` to keep rarely used tools out of the initial prompt:

```ts title="agent/tools/list_orders.ts"
import { defineTool } from "eve/tools";
import { z } from "zod";

export default defineTool({
  description: "List recent customer orders.",
  deferred: true, // stays out of the prompt until search() finds it
  inputSchema: z.object({ limit: z.number().int().min(1).max(100).default(25) }),
  outputSchema: z.object({
    orders: z.array(z.object({ id: z.string(), totalCents: z.number(), status: z.string() })),
  }),
  async execute({ limit }) {
    return { orders: await fetchRecentOrders(limit) };
  },
});
```

- Non-deferred tools with an `outputSchema` append `In workflow programs, tools.<name>(input) resolves to: <type>` to their tool description. Deferred tools return their full TypeScript signature from `search()`.
- Inside a program, eve bypasses `toModelOutput` projections so JavaScript receives raw structured JSON.
- eve validates completed outputs against declared `outputSchema` definitions for direct tools, MCP tools (except non-text content block lists), and `2xx` OpenAPI responses (excluding `204` and `205`). A mismatch throws a catchable `ToolError` prefixed with `InvalidToolOutput:`.

### Program return shape and bounds

Return values and call inputs serialize through `JSON.stringify`, and returning `undefined` yields `null`.

- On success, the model receives `{ result, logs?, calls, notCompleted? }`.
- On uncaught failure, the model receives `{ error, logs?, calls, notCompleted? }` as a tool error with the line number. When earlier calls already finished, the error appends `Calls that completed before this are not undone.`.
- `calls` counts outcomes across the run (`completed`, `failed`, `rejected`, `interrupted`, `abandoned`), and `notCompleted` lists up to 20 unfinished calls with `{ tool, outcome, input }`.
- `search()` counts toward the 1,024-call limit, but does not increment `calls` unless `eve__search` has an approval policy.
- Results over 10,000 estimated tokens (about 40,000 UTF-8 bytes) keep the first 30,000 and last 10,000 bytes, with a note that the middle was left out.

### Isolation and disallowed calls

Programs have no `fetch`, filesystem access, timers (`setTimeout`), module imports, or `process.env` credentials. App secrets and OAuth tokens stay in the app runtime.

- Await every call before returning. Leaving a call pending, such as the loser of `Promise.race` or `Promise.any`, fails the program.
- Programs cannot call reserved `eve__*` tools (use `search()` instead of `eve__search`) or another `workflow()` tool.
- Programs cannot call tools with `endsTurn: true` or a predicate, provider-executed tools such as `webSearch()`, or non-agent `serve` workflow tools.
- Programs cannot load skills (use `eve__skill` directly) or call subagents hidden with `tool: false` or `disableTool()`.
- Each `ctx.agent` call starts a fresh child session and rejects `taskId`.
- Calling `bash` inside a program runs in the foreground without promoting to a background task; commands still running after the foreground wait return `status: "running"`.

### Guide the model in instructions

Direct tools remain directly callable alongside `workflow`. Add short guidance in `agent/instructions.md` so the model uses code mode for multi-step work and keeps single lookups direct:

```md title="agent/instructions.md"
Use `workflow` when a request needs loops, parallel calls, filtering large payloads, or multiple connected services.
Call individual tools directly for simple one-step lookups.
Filter raw records inside JavaScript and return only the summary needed to answer.
```

## Pauses, approvals, and crash recovery

Code mode runs inside eve's durable session workflow rather than a one-shot script request. Step through how eve handles batched approvals, OAuth sign-ins, worker crashes, and user steering below.

**Batched Promise.all**

Two approval-gated tools and a subagent pause in one batch, release compute, and resume on the exact await line—even if one call is denied inside .catch().

```js
const items = await tools["public-catalog__list_items"]({});
const [deploy, rotation, note] = await Promise.all([
  tools.gated_deploy({ service: "api" })
    .catch((err) => ({ skipped: true, reason: err.message })),
  tools.rotate_webhook_secret({ env: "prod" }),
  ctx.agent("release-note", { message: `Check ${items.length} items` }),
]);
return { count: items.length, deploy, rotation, note };
```

- **Subagent finished; parked on batched approvals** (Parked · no compute held): Line 1 finished inline, and the un-gated release-note subagent ran first. Once it finished, eve opened both approval-gated tools in one batched prompt and saved the VM state.
- **Resumed from saved state and completed** (Completed): Both approved tools finished. eve restored the VM at line 7 with all three values—neither line 1 nor the subagent re-ran—and returned one JSON payload to the model.
- **Denial caught in JavaScript; program still finishes** (Completed · 1 rejected): Denying gated_deploy rejected its promise with a catchable ToolError. The script handled it in .catch(), kept the approved key rotation and subagent note, and recorded the rejection in calls and notCompleted.

**Mid-program OAuth**

When a connected MCP or OpenAPI tool requires user sign-in midway through a script, eve pauses the VM for OAuth and resumes without losing prior variables.

```js
const repo = await tools.get_repo_config({ name: "storefront" });
const issues = await tools.linear__list_issues({ team: repo.team });
const urgent = issues.filter((i) => i.priority === 1);
return { team: repo.team, urgent: urgent.map((i) => i.title) };
```

- **Paused for Linear OAuth sign-in** (Parked · sign-in required): Line 1 finished locally. On line 2, the Linear connection requested authorization. eve saved repo with the VM state and prompted the user to sign in.
- **Signed in, resumed at line 2, and returned** (Completed · 2 calls): After OAuth finished, eve ran linear__list_issues with the new token, restored the VM at line 3, filtered issues in JavaScript, and returned only the urgent titles.

**Crash & replay**

If the worker crashes mid-program, eve replays completed calls from recorded output, rejects in-flight calls so side effects aren't duplicated, and finishes without calling the model again.

```js
const invoice = await tools.billing__get_invoice({ id: "inv_94" });
let receipt;
try {
  receipt = await tools.billing__send_reminder({ id: invoice.id });
} catch (err) {
  receipt = { status: "needs_check", error: err.message };
}
const log = await tools.audit__record({ invoiceId: invoice.id, receipt });
return { invoiceId: invoice.id, receipt, auditId: log.id };
```

- **Running step · call-1/1 finished, call-1/2 in flight** (Running in QuickJS): Line 1 (call-1/1) already recorded its output. Line 4 (call-1/2) has started sending a reminder email when the worker process crashes.
- **Process crashed before checkpoint** (Interrupted · recovering): The model step already saved the program source before execution started, so recovery does not re-run the model. eve reads the recorded call events from the interrupted attempt.
- **Recovered without duplicating side effects** (Completed · replayed): On retry, call-1/1 replayed its recorded invoice without calling Billing again. call-1/2 threw a ToolError because its outcome was unknown; catch recorded it, and unstarted call-1/3 ran once.

**User steering**

When a user sends a new message while a program is running or parked on approval, eve withdraws the wait, stops the program cleanly, and hands control back to the model.

```js
const diff = await tools.get_release_diff({ service: "api" });
const deploy = await tools.gated_deploy({
  service: "api",
  commits: diff.commits.length,
});
return { deploy };
```

- **Parked waiting for deploy approval** (Parked · awaiting approval): Line 1 already fetched the release diff. Line 2 is parked waiting for approval on gated_deploy when the user decides to hold the release instead.
- **Stopped early for new user message** (Steered · handed to model): eve withdraws the pending approval, ends the program with completed and rejected counts, and delivers the new message directly to the model.

### Batched approvals and sign-ins

Every tool or connection called from JavaScript runs through its own [approval policy](/docs/human-in-the-loop) and OAuth flow:

- Independent gated calls inside `Promise.all` pause together in one batched approval prompt. When the same `Promise.all` batch also includes un-gated workflow tools or subagents (with no OAuth sign-in challenge), those sibling tasks run first and the batched approval prompt opens once they finish.
- Under an agent-wide `approval` policy on `defineAgent`, eve skips prompting on the outer `workflow` wrapper (unless the policy explicitly denies it) and enforces approval on each inner call instead.
- An agent-wide `approval` policy still applies to `eve__search` when the program calls `search()`. Allow `toolName === "eve__search"` in your policy if discovery should run without prompting.
- Denying an inner call rejects its promise with a catchable `ToolError` (`Tool execution was denied.`). The script can catch it and finish the approved work.
- If a connection requires OAuth midway through a script, eve saves VM state, prompts the user to sign in, and resumes at the exact `await` line afterward.

### Durable pauses and crash replay

Whenever a program waits on approvals, OAuth sign-ins, authored [workflow tools](/docs/tools/workflows), or [subagents](/docs/subagents), eve saves VM state (valid up to 365 days) and releases compute.

If the worker crashes before a checkpoint, recovery does not ask the model to rewrite the script:

1. Completed calls replay their recorded output without running again.
2. Calls that started without finishing throw a catchable `ToolError` (`The step running this call was interrupted. The call may or may not have taken effect.`) and record under `calls.abandoned` and `notCompleted`.
3. Unstarted calls run once under the same deterministic ID (`<programCallId>/<index>`).

### Steering and observability

- **Steering:** When a user sends a new message while a program runs or waits, eve cancels pending waits and ends the program with `Stopped early because a new message arrived.`. Completed counts remain in `calls`, and control returns to the model.
- **Traces:** Nested tool and subagent calls emit standard `call.requested` and `call.settled` events (plus `call.started` once execution begins; `search()` emits call events only when `eve__search` has an approval policy). Vercel [**Agent Runs**](/docs/observability/agent-runs) and local [`eve traces`](/docs/reference/cli#eve-traces) nest every inner span under the `workflow` span.
- **Channel status:** Built-in channels suppress typing-indicator churn for nested program calls while surfacing approvals, questions, and sign-in prompts normally.

## How eve compares to other harnesses

Standard loops spend a model call and prompt tokens on every step. Stateless code runners collapse one-shot API loops, but time out or lose state when a program pauses for human approval, OAuth sign-in, a subagent, or a worker crash.

eve runs code mode inside its durable session workflow on Vercel or self-hosted Postgres, releasing compute while paused and making crash recovery deterministic.

| Feature                        | Standard loop                                     | Stateless runner                             | eve code mode                                    |
| ------------------------------ | ------------------------------------------------- | -------------------------------------------- | ------------------------------------------------ |
| Multi-step loops & filtering   | 1 model call per step; raw payloads enter context | 1 program; intermediate data stays in VM     | 1 program; up to 1,024 calls                     |
| Large MCP & OpenAPI catalogs   | Upfront schemas or extra search steps             | Progressive search inside program            | On-demand search() with TS signatures            |
| Durable pauses                 | Often holds open requests or workers              | Stateless isolates time out across waits     | Saved VM state parks up to 365 days              |
| Parallel Promise.all approvals | Separate steps for tools, waits, and subagents    | Often limited to sequential calls on pause   | Batched approvals & sign-ins in Promise.all      |
| Mid-program crash recovery     | Re-runs the model or loses loop progress          | Whole script fails; risks duplicate writes   | Replays completed calls; rejects in-flight calls |
| Subagent fan-out               | Each child emits a receipt and wakes root         | Tools and HTTP connectors only               | ctx.agent() fan-out with outputSchema            |
| Raw JSON & outputSchema        | Model reads formatted toModelOutput output        | Untyped stdout or manual checks              | Raw JSON validated against outputSchema          |
| Isolation & portability        | Runs tools directly in app runtime                | Often tied to one cloud isolate or local CLI | Bundled QuickJS-WASM; Vercel or Postgres         |
| Nested traces & steering       | Flat tool spans per step                          | Opaque script blob; hard to interrupt        | Nested Agent Runs / eve traces + steering        |

## Options and limits

### Factory options

Pass options to `workflow()` from `eve/tools/workflow`:

| Option         | Type                  | Default  | Behavior                                                                                                      |
| -------------- | --------------------- | -------- | ------------------------------------------------------------------------------------------------------------- |
| `mode`         | `"task" \| "execute"` | `"task"` | Must be `"execute"` when `tools` is `true`. Runs in the foreground so the turn waits for the result directly. |
| `tools`        | `boolean`             | `false`  | Set `true` to expose `tools.<name>`, `search()`, and `ctx.agent()`. Omit or set `false` for agent-only mode.  |
| `maxSubagents` | integer `1`–`128`     | `100`    | Maximum child-agent calls per program before rejecting with `EXECUTE_AGENT_LIMIT_REACHED`.                    |

### Fixed runtime limits

QuickJS-WASM enforces fixed bounds automatically. Time spent parked on approvals, OAuth sign-ins, workflow tools, or subagents does not count toward CPU or wall-clock limits.

| Limit                                   | Value                   |
| --------------------------------------- | ----------------------- |
| Total calls per program                 | 1,024                   |
| Concurrent inline tool calls            | 32                      |
| JavaScript CPU time per start or resume | 30 seconds              |
| Wall-clock time per start or resume     | 5 minutes               |
| QuickJS heap memory                     | 64 MiB                  |
| QuickJS call stack                      | 2 MiB                   |
| Program source size (`js`)              | 256 KiB                 |
| Captured `console.*` output             | 64 KiB                  |
| Single call input or final return JSON  | 1 MiB                   |
| Single tool or child-agent output JSON  | 4 MiB                   |
| Saved VM state across waits             | 8 MiB                   |
| Model-facing result before truncation   | 10,000 estimated tokens |

## Troubleshooting

| What you see                                                        | What to do                                                                                                                                       |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `TypeError: workflow({ tools: true }) requires mode: "execute".`    | Add `mode: "execute"` to `workflow(...)` in `agent/tools/workflow.ts`, because code mode runs in the foreground of the turn.                     |
| `InvalidToolOutput` error inside the program                        | Align the tool or remote API response with its declared `outputSchema`, or catch the `ToolError` in JavaScript when partial failure is expected. |
| `The program returned while a call was still pending.`              | Await every call before returning, and replace `Promise.race` or `Promise.any` with `Promise.all` or `Promise.allSettled`.                       |
| `EXECUTE_CONTINUATION_LIMIT_REACHED`                                | Filter or trim large variables before awaiting approvals, sign-ins, or subagents, because saved state across waits is capped at 8 MiB.           |
| `EXECUTE_REPLAY_DIVERGED` after an interrupted step                 | Keep call order deterministic before awaits, because replay expects the same tool at each call index.                                            |
| `EXECUTE_CALL_LIMIT_REACHED` or `EXECUTE_AGENT_LIMIT_REACHED`       | Batch lookups in your tool APIs, split work across turns, or raise `maxSubagents` up to `128`.                                                   |
| `bash` returns `status: "running"` instead of running in background | Call `bash` directly outside `workflow` when a command may exceed the foreground timeout and promote to a background task.                       |

## When to use another tool

Code mode adds a script-generation step, so single-step lookups stay fastest as direct tool calls. Choose another surface when it fits the job better:

- **[Tools](/docs/tools):** Use `defineTool` for direct single-step calls that do not need loops, filtering, or multi-tool composition.
- **[Workflows as tools](/docs/tools/workflows):** Use `defineWorkflowTool` for version-controlled TypeScript orchestration with `"use workflow"`, webhooks, or timers authored ahead of time. Use `workflow()` without `tools: true` when you want background agent-only orchestration with `ctx.agents`, `ctx.ask()`, `ctx.sleep()`, `ctx.progress()`, `files` on `ctx.agent()`, or hidden subagents (`tool: false`); in `tools: true` mode, export `ask_question` or `sleep` and call them through `tools.*` instead.
- **[Tasks](/docs/tools/tasks):** Use background tasks when the root agent should receive a receipt immediately and keep chatting while long work finishes asynchronously.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)