|
| 1 | +# CodeAct Execution Mode — Design |
| 2 | + |
| 3 | +Status: implemented behind `executionMode: "codeact"` (default stays `"tools"`). |
| 4 | +Code: `packages/agents/src/codeact/`. |
| 5 | + |
| 6 | +## What this is |
| 7 | + |
| 8 | +An alternative action space for the agent step loop. In the default mode the |
| 9 | +model acts by emitting one JSON tool call per action, the host executes it, and |
| 10 | +the result comes back as a tool message — one round trip per tool. In CodeAct |
| 11 | +mode the model acts by writing a JavaScript program; the program runs in the |
| 12 | +QuickJS sandbox where the same toolbelt is exposed as async functions |
| 13 | +(`tools.web_search(...)`), and one round trip can chain, loop over, branch on, |
| 14 | +and post-process any number of tool calls. The program's output — return value, |
| 15 | +console logs, thrown error — comes back as the observation for the next turn. |
| 16 | + |
| 17 | +The research this follows: |
| 18 | + |
| 19 | +- **CodeAct** (Wang et al., ICML 2024, arXiv:2402.01030) — executable code as |
| 20 | + the action space beats JSON/text tool calling: up to +20% success, ~30% fewer |
| 21 | + turns. The core loop here (code action → execution observation → repair) is |
| 22 | + that paper's. |
| 23 | +- **CaveAgent** (arXiv:2601.01569) — a *persistent* runtime across turns |
| 24 | + (stateful objects survive between actions) adds +5–13.5% success and ~28% |
| 25 | + fewer tokens on data-heavy tasks. Our `state` object is this: it lives on the |
| 26 | + host and syncs back after every action, so turn N+1 can read what turn N |
| 27 | + computed without re-serializing it through the transcript. |
| 28 | +- **MCP design-choice study** (arXiv:2602.15945) and Anthropic's |
| 29 | + *Code execution with MCP* (Nov 2025) — decoupling tool *results* from model |
| 30 | + *context* is where the token savings come from (their headline example: |
| 31 | + 98.7% reduction). A CodeAct program can fetch a large payload, reduce it in |
| 32 | + the sandbox, and surface only the reduction; in tool mode the whole payload |
| 33 | + transits the transcript. |
| 34 | +- **To Run or Not to Run** (arXiv:2606.26978) — execution isn't free; there are |
| 35 | + regimes where restricting it saves cost with little accuracy loss. That is |
| 36 | + why this is a *mode*, not a replacement: the default stays `"tools"`, and the |
| 37 | + eval suite exists to measure where codeact actually wins before any default |
| 38 | + flips. |
| 39 | + |
| 40 | +## What already exists (and is reused unchanged) |
| 41 | + |
| 42 | +| Piece | Where | Role here | |
| 43 | +|---|---|---| |
| 44 | +| QuickJS WASM sandbox | `packages/agents/src/js-sandbox.ts` (`runInSandbox`) | Executes every action. All its limits (30 s timeout, 64 MB heap, fetch caps, output truncation, SSRF guard, workspace containment) apply per action. | |
| 45 | +| Tool base class + registry | `src/tools/base-tool.ts`, `tool-registry.ts` | The toolbelt is the same `Tool[]` the tool-mode step gets — codeact adds no capability that tool mode doesn't have. | |
| 46 | +| Provider loop | `BaseProvider.generateLoop` | Drives the turn loop; codeact presents exactly one provider tool. | |
| 47 | +| Result-schema validation | `src/utils/json-schema-validate.ts` | `finish(result)` validates host-side with the same checker `finish_step` uses. | |
| 48 | +| Never-reject bridge convention | `js-sandbox.ts` / `script-runner.ts` | Host bridges resolve `{ok, ...}` envelopes; a guest prelude re-throws. Required by the QuickJS handle-leak workaround. | |
| 49 | +| Agent memory | `context.memory` | Step/task results land under the same keys; memory tools are in the toolbelt as functions like everything else. | |
| 50 | + |
| 51 | +CodeAct is *not* script mode. `ScriptRunner` orchestrates **sub-agents** |
| 52 | +(`agent()` spawns a `StepExecutor`); codeact is what a single step *does |
| 53 | +instead of* JSON tool calls. The two compose: a script-mode run whose |
| 54 | +sub-steps execute in codeact mode is just both flags set. |
| 55 | + |
| 56 | +## The action protocol |
| 57 | + |
| 58 | +The model sees **one** provider tool: |
| 59 | + |
| 60 | +``` |
| 61 | +execute_code({ code: string }) |
| 62 | +``` |
| 63 | + |
| 64 | +Code actions arrive through a tool call rather than fenced text because every |
| 65 | +provider adapter already delivers tool calls reliably; scraping code blocks |
| 66 | +out of prose is exactly the fragility tool calling was invented to avoid. The |
| 67 | +CodeAct paper's gains come from the *action space* being code, not from the |
| 68 | +transport being free text. |
| 69 | + |
| 70 | +Inside the sandbox, on top of the standard surface (`console`, `fetch`, |
| 71 | +`workspace`, `crypto`, `data`, `format`, …), the action gets: |
| 72 | + |
| 73 | +- **`tools.<name>(args)`** — one async function per tool in the step's |
| 74 | + toolbelt. Calls bridge to `Tool.executeTool` on the host. A tool that |
| 75 | + returns an `{error}` payload throws in the guest, so `try/catch` is the |
| 76 | + error-handling idiom. Per-action tool-call cap (`maxToolCallsPerAction`, |
| 77 | + default 50) so a runaway loop can't drain budgets silently. |
| 78 | +- **`state`** — a plain object that persists across actions within the step |
| 79 | + (host-side, synced back after every run via the sandbox's global sync-back). |
| 80 | + Fetch once, reuse every turn; never re-fetch to re-look at something. |
| 81 | +- **`finish(result)`** — completes the step. For schema'd steps the host |
| 82 | + validates against the declared schema; an invalid result throws in the guest |
| 83 | + with the violation list, so the same action can repair and retry, or the |
| 84 | + failure becomes the observation for the next action. Valid `finish` ends the |
| 85 | + provider loop (AbortController, same mechanism as `finish_step`). |
| 86 | +- **The action's return value** — becomes part of the observation. Returning a |
| 87 | + small summary of big intermediate data is the context-decoupling move; the |
| 88 | + prompt says so explicitly. |
| 89 | + |
| 90 | +The observation sent back as the tool result is a JSON envelope: |
| 91 | + |
| 92 | +``` |
| 93 | +{ ok, result?, error?, stack?, logs?, finished?, toolCalls } |
| 94 | +``` |
| 95 | + |
| 96 | +truncated by the same `truncateToolResult` cap as any tool result (20 000 |
| 97 | +chars). `toolCalls` is the count consumed, so the model can see budget burn. |
| 98 | + |
| 99 | +### Completion semantics (identical contract to StepExecutor) |
| 100 | + |
| 101 | +- Schema'd step: only a schema-valid `finish(result)` completes. Iterations |
| 102 | + exhausted → explicit failed step, never a silent guess. |
| 103 | +- Unschema'd step: `finish(...)` works, and a plain assistant message with no |
| 104 | + tool call also finalizes (its text is the result) — the same prose-mode rule |
| 105 | + the tool-mode executor has. |
| 106 | +- Failure reporting, memory writes (`step:<id>`, `task:<id>` with |
| 107 | + `useFinishTask`), and the `ProcessingMessage` stream (`task_update`, |
| 108 | + `step_result`, `tool_call_update`, `chunk`) are byte-compatible with |
| 109 | + `StepExecutor`, so every consumer — CLI tree, web ExecutionTree, script |
| 110 | + runner, supervisor — works unchanged. |
| 111 | + |
| 112 | +Each host-bridged tool invocation is surfaced as a `tool_call_update` (id |
| 113 | +`codeact_<n>`), so observability keeps per-tool granularity even though the |
| 114 | +provider transcript only carries `execute_code`. |
| 115 | + |
| 116 | +## Prompting |
| 117 | + |
| 118 | +`buildCodeActSystemPrompt` renders: |
| 119 | + |
| 120 | +1. The action contract (write code, observe, repair; `state` discipline; keep |
| 121 | + observations small — return summaries, stash payloads in `state` or |
| 122 | + memory). |
| 123 | +2. The tool catalog as **typed signatures**, generated from each tool's JSON |
| 124 | + schema (`await tools.browse({url: string, timeout?: number})` + first |
| 125 | + sentence of the description). Signatures cost a fraction of full JSON |
| 126 | + schemas in the prompt — the progressive-disclosure half of the Anthropic |
| 127 | + MCP result. |
| 128 | +3. A condensed sandbox API reference (what exists beyond `tools.*`, what is |
| 129 | + blocked, the key limits) derived from the same manifest the Code-node |
| 130 | + prompt uses, so it cannot advertise an API the sandbox doesn't marshal. |
| 131 | +4. The output-schema section for schema'd steps. |
| 132 | + |
| 133 | +Caller-supplied system prompts remain preambles, exactly as in |
| 134 | +`StepExecutor.buildSystemPrompt` — they cannot override the execution |
| 135 | +contract. |
| 136 | + |
| 137 | +## Security posture |
| 138 | + |
| 139 | +The action executes with the same privileges tool mode already grants: |
| 140 | + |
| 141 | +- Every `tools.*` function is a tool the model could have called directly; the |
| 142 | + bridge adds **no** capability. Per-step `tools` allow-lists stay a privilege |
| 143 | + boundary — a codeact step only sees its allowed subset. |
| 144 | +- The sandbox's own limits bound the new part (arbitrary computation): CPU via |
| 145 | + interrupt handler, heap, fetch count/size/SSRF guard, workspace containment, |
| 146 | + no `eval`/`Function`, no module loader. |
| 147 | +- The genuinely new risk (per the MCP design-choice study) is *composition*: |
| 148 | + one action can chain tool calls without per-call visibility in the provider |
| 149 | + transcript. Mitigations: per-action tool-call cap, per-invocation |
| 150 | + `tool_call_update` events (nothing becomes invisible to the host), and the |
| 151 | + 30 s default action timeout. |
| 152 | +- `finish` validation is host-side; the guest cannot forge a completed step. |
| 153 | + |
| 154 | +## Integration surface |
| 155 | + |
| 156 | +- `AgentOptions.executionMode?: "tools" | "codeact"` — threaded through |
| 157 | + `Agent` → `ParallelTaskExecutor` → `TaskExecutor`, which picks the executor |
| 158 | + class per step (`createStepExecutor`). Script mode forwards it to its |
| 159 | + sub-agents; process-mode fan-out steps use it too. |
| 160 | +- **The setting**: `NODETOOL_AGENT_EXECUTION_MODE` (`tools` | `codeact`), |
| 161 | + registered in the settings registry so it appears in the Settings UI and |
| 162 | + `nodetool settings`. Resolution precedence, everywhere a mode is resolved |
| 163 | + (`resolveExecutionMode`): explicit option > the setting > `"tools"`. The |
| 164 | + server mirrors the stored value into the environment at startup |
| 165 | + (`applyAgentExecutionModeSetting`); a real environment variable wins over |
| 166 | + the stored value, and a Settings change takes effect on the next server |
| 167 | + start. |
| 168 | +- CLI: `nodetool agent run <yaml> --codeact`; the agent YAML also takes |
| 169 | + `execution_mode: codeact`. Flag > YAML > setting. |
| 170 | + |
| 171 | +## Evaluation |
| 172 | + |
| 173 | +`eval codeact` (registered next to `subtask`): objectives with instrumented |
| 174 | +tools where the interesting metric is *rounds* and *tool routing*, scored |
| 175 | +structurally (required tools invoked, forbidden ones not, action count within |
| 176 | +bounds, final result correct). Run the same cases through both modes to get |
| 177 | +the paper's comparison on our own toolbelt: |
| 178 | + |
| 179 | +```bash |
| 180 | +npm run dev:nodetool -- eval codeact -p anthropic -m claude-sonnet-5 |
| 181 | +``` |
| 182 | + |
| 183 | +Harness tests (`tests/codeact-executor.test.ts`) drive the executor with a |
| 184 | +`ScriptedProvider` — tool chaining in one action, `state` persistence across |
| 185 | +actions, schema repair after an invalid `finish`, error observations, prose |
| 186 | +finalization — no network, no model. |
| 187 | + |
| 188 | +## Non-goals (now) |
| 189 | + |
| 190 | +- Flipping the default. `"tools"` remains until the eval says otherwise per |
| 191 | + the cost-effectiveness caveat above. |
| 192 | +- Python actions. The sandbox is JS; the CodeAct result is about code as the |
| 193 | + action space, not about Python specifically. |
| 194 | +- Replacing planners. GraphPlanner/ScriptPlanner/CodePlanner already use |
| 195 | + code-shaped *artifacts*; this changes the step execution loop only. |
| 196 | +- The chat/websocket toolbelt. Chat turns keep tool mode; wiring codeact into |
| 197 | + the websocket runner is a follow-up once step-level evals justify it. |
0 commit comments