Skip to content

script tool: combine tool calls in one JavaScript step, off by default - #2815

Open
joshbarrington wants to merge 1 commit into
Agent-Field:devfrom
joshbarrington:script-tool
Open

joshbarrington wants to merge 1 commit into
Agent-Field:devfrom
joshbarrington:script-tool

Conversation

@joshbarrington

@joshbarrington joshbarrington commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What this adds

A script tool. The model writes a short JavaScript program that calls its other tools as await tools.<name>(args); only what the program prints or returns goes back to the model. One step can make many calls, run them at the same time, and keep only what matters from large results.

Off by default, behind two switches (plumbing, beside CODEAF_TASK_BELT), so each can be measured on its own:

switch who carries script
CODEAF_TASK_SCRIPT=on bash-belt task workers: plan runs and tasks the chat starts
CODEAF_CHAT_SCRIPT=on the conversation itself

Key metrics

bench/scriptbench, Sonnet 5.5, a binary built from this change, three seeds per arm, same-wave pairs. Cost is each cell's whole bill from its usage ledger.

question arm mean cost mean input tokens score tool calls in chat
manual-last (29 pages) baseline $0.626 449k 1.00 ×3 29–33
CODEAF_CHAT_SCRIPT=on $0.140 (4.5× less) 171k 1.00 ×3 3–4 scripts, 43–50 calls inside
manual-find (40 pages) baseline $0.968 533k 1.00 ×3 40
CODEAF_CHAT_SCRIPT=on $0.111 (8.7× less) 204k 0.93, 1.00, 0.93 6–7 scripts, 88–145 calls inside
  • The cost ranges do not overlap between arms; wall time is the same (~110 s).
  • Input tokens fall to ~38%: pages fetched inside a script never enter the conversation, so every later request is cheaper.
  • The two 0.93s are one page whose heading says "deleting"; the question's wording invited that match and has been tightened (re-scored under the new rule: 1.00, 0.93, 1.00 vs the baseline's 0.93 ×3).

Where it does not help:

  • When bash can do the whole job in one command. On three questions about click's source, Sonnet answered each with 1–4 bash calls running Python's ast; neither arm wrote a script and the costs matched. These are kept in the benchmark as controls.
  • On code changes. In bench/oneroad pilots, four cells wrote one script between them, and it failed. DeepSeek v4 flash read the tool as Node.js; Sonnet chained commands inside bash instead.

So the tool pays where a model must call a non-shell tool (manual, web_fetch, read_document, memory, services) many times and keep part of each result. Only manual is measured; the others should behave alike but are untested.

How it works

  • Runtime: internal/jsrun has a shared machine (goja VM, call/token/wall ceilings, uncatchable stops) under both the saved-program host (unchanged) and the new script host. It is not Node.js: no require, fs, process, network or clock. The description says so in its second sentence and ends with a worked example.
  • Same gate: every nested call goes through Agent.executeTool (approval policy, fence, record, telemetry). A refused call rejects that call's promise with the policy's own text. executeTool puts the turn's episode and hub on the context, so every road that reaches it (turn loop or saved program) is gated, and a script that finds no episode refuses to run.
  • bash inside a script resolves to {output, exit_code, truncated, full_output_path} whatever its exit; a timeout or stop rejects. A script sees up to 1 MiB of one command; what it returns is cut to the window as usual. Other tools resolve to their text, never guessed into JSON.
  • Limits: up to 4 calls in flight; 200 calls, 10 minutes, 16 MiB of output, none catchable. A call refused for its own arguments does not count.
  • Allowlist: a script can call only bash, read, ls, grep, find, read_document, manual, recall, web_search and web_fetch. Any other tool is refused by name ("… cannot be called from a script; a script can call …"), so a tool added to the belt later stays out of reach until it is allowed on purpose.
  • Who carries it: quick workers never do.
  • One step: a script counts once against the step cap and in every step count (the worker's "step N/M" frame, the room, the child-run cap). Its calls and their plan writes are recorded on its trajectory line and drawn indented under it, on the plan page and in the live view. The plan store's live row gains a migrated tool column. The migration runs whether or not a switch is on; an older binary still reads the database.
  • Prompt and manual: the worker page names the tool only when the belt carries it; the chat adds no page line (the description carries it). how-tasks-run.md has sections for both switches.

Review follow-ups

Answers to the review of 23 November, all in this push:

  1. Saved programs bypassed approval (tool_script.go:126). Fixed as suggested: runScript fails closed when there is no episode, and executeTool adds the episode and hub to the context when the caller has not (this covers subharnessEnv.Tool). TestASavedProgramsScriptMeetsTheSameGate runs a saved program's script under a policy that denies bash and checks the command never ran; TestAScriptOutsideATurnRefusesToRun checks the refusal.
  2. Quick tasks deadlocked (task_run.go:8014). Quick workers no longer carry script, so the quick lock is never taken twice. TestAQuickWorkerDoesNotCarryScript.
  3. Denylist (tool_script.go:42). Replaced by the allowlist above. TestChatScriptReachesOnlyTheToolsItIsAllowed runs through a real turn with an episode, so each refused tool is refused by the allowlist, not by a nil episode.

The smaller points:

  • Heap and regexp time: not bounded. The manual and the change entry now say so.
  • "Off by default" is not byte-identical: correct. The manual sections stay so the manual tool can explain the switches, and the plandb live.tool migration runs unconditionally (noted above).
  • Approval tests: added the saved-program road, a nested chat call that needs approval (allowed and refused, TestAChatScriptsCallThatNeedsApprovalWaitsForTheAnswer), and a tui3 test that the prompt is asked on the nested call's row under its script (TestAnApprovalInsideAScriptIsAskedOnTheNestedRow).

Found while fixing those (two code-review rounds):

  • Every surface draws a script as one call. Each nested event carries its script's id (Event.FromScript), including a script whose call had no id. The tui3 feed, the app backend's turn pump and task pilot, the remote server's weighing, factory logs, headless output and the plan room all keep a script's calls under it, instead of counting them as the model's own steps.
  • Model-only extras stay with the model. A read inside a script returns the file, never the held-read pointer, and is not recorded as held. A script's results carry no job footer or fix-recall line. Secrets are still redacted.
  • Counts: a script counts only the calls that ran, and says how many it did not wait for. A failing check inside a script counts as a check the node ran.
  • Cleanup: the chat's wide bash is built only when a script runs bash, and session.ScriptToolName replaces the "script" literal elsewhere.

Benchmarks

  • New bench/scriptbench: five read-heavy questions (three on click 8.1.7 as controls, two needing a manual lookup per page). check.py computes every answer from the source with ast or from the binary's own manual corpus (manualtruth/), never from a model. run.sh refuses a binary whose manual differs from the checkout, and keeps codeaf off the cells' PATH.
  • bench/oneroad:
    • Arms: codeaf-script-* and codeaf-chatscript-*.
    • Counters: script use from chat-task transcripts as well as trajectories; worker spend from v3/usage.jsonl. The plan store's spend rows missed most of it.
    • macOS: a portable settle fingerprint and load average, and a short profile path for the socket.
    • Hygiene: each harness starts under env -i with a short allowlist, so no shell secrets reach a --yolo worker. The cell's engine is stopped when the cell ends, and a cell stopped at an approval prompt is recorded as BLOCKED, not OK.

Testing

New tests in internal/jsrun, internal/session, internal/run (real bash worker), internal/plandb and internal/tui3. Each review fix has a test that fails without it. make test-quick, make changelog-check and make test-packed-manual manual-gates pass.

make pr-ready on macOS ends red only on tests that fail identically on a clean origin/dev worktree:

  • SIGPIPE family (yes x | head -1 exits 141 on this machine): TestBashBeltTruncation*, TestACommandLookFailsOnAFailingPipeStage, TestWatchTickFailsOnAFailingPipeStage, and bare's TestAnEarlyReaderIsNotAFailureButEveryOtherStageIs.
  • TestTheFixedPrefixStaysUnderItsBudget: the base is 13 bytes over; this PR measures the same 52,510 bytes.
  • TestLandLeavesOutUntrackedBuildCachesOnly: marked already failing on the base by the harness.
  • Six internal/session tests failed under full-suite load and pass alone on this branch; one tui3 test was marked flaky and passed on retry.

Not covered and known limits

  • An approval prompt raised from inside a chat script is now tested in internal/session and internal/tui3, but has still not been exercised live; every benchmark cell ran --yolo.
  • A script's memory and a native regexp match are not bounded; the 10-minute wall cannot stop either partway.
  • When a script ends without awaiting a call, that call is cancelled and its answer dropped. The closing line says how many calls it did not wait for, but a refusal from one of them is not reported.
  • searchTools/describeTool for scripts are not included.

@AbirAbbas AbirAbbas left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the write-up and the benchmark. The cost numbers are compelling, and the shape is right: one chokepoint, off by default, an off-limits list, and a test with each review fix. I read the diff and ran a few probes against the PR checkout. Two things block it for me and one more needs settling; details are inline.

  1. Nested calls can skip the approval gate when the script is reached through the saved-program road (tool_script.go:126).
  2. A script in a quick task deadlocks on the task's own lock (task_run.go:8014).
  3. The off-limits list is a denylist and doesn't cover what its description promises (tool_script.go:42).

Smaller things:

  • Nothing bounds the VM's heap or regexp time. goja has no memory limit, and its interrupt can't stop a native regexp or the export of a huge value. A script that allocates in a loop can take the whole process down without ever calling a tool, so neither the approval gate nor the 10 minute wall helps. I haven't run a destructive probe, but I'd at least say so in the manual.
  • "Off by default" isn't quite byte-identical. how-tasks-run.md gains sections about both switches that the manual tool returns whatever the switches say, and the plandb live.tool migration runs unconditionally (compatible with an older binary as far as I can tell, but not nothing).
  • Approval tests: TestScriptNestedCallMeetsTheSameGate is a real deny-and-no-side-effect test. There's no test for the saved-program road or for a nested call that needs a prompt (the "not covered" item in the description), and the chat off-limits test calls scriptCall with a nil episode and exits at the name check, so it never reaches consent.

if err := decodeToolArguments(args, &in); err != nil || strings.TrimSpace(in.Source) == "" {
return "script needs source: the JavaScript to run", true, nil
}
ep, hub, parent := episodeFrom(ctx), eventHubFrom(ctx), callIDFrom(ctx)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the approval hole. The episode and hub come from the context, and ep.preAction treats a nil episode as allow-everything (hooks.go:415, the whole pre-action chain including the approval gate is skipped). runTools plants both on the context (loop.go:3612), but the saved-program road doesn't: subharnessEnv.Tool passes e.ep/e.hub to executeTool as parameters and leaves the context bare (subharness_env.go:356). A saved program's whitelist accepts any non-empty tool name (exec/manifest.go:408), so with CODEAF_CHAT_SCRIPT=on a program that whitelists script gets nested calls with no gate. The script call itself is still gated, the calls inside it are not.

I reproduced the call shape with a policy that denies bash: through runTools the nested tools.bash({command: "touch ran"}) is refused (denied by approval rule: tool "bash"), and through executeTool(context.Background(), ep, hub, call, ...) it runs and ran appears in the workspace.

Fail closed here: return an error when episodeFrom(ctx) == nil, and have subharnessEnv.Tool plant the episode and hub with withEpisode/withEventHub. A test through that road next to TestScriptNestedCallMeetsTheSameGate would pin it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 941d770. runScript now refuses to run without an episode, and executeTool puts the episode and hub on the context when the caller hasn't, which covers subharnessEnv.Tool. There's a test through the saved-program path next to TestScriptNestedCallMeetsTheSameGate. Details are under "Review follow-ups" in the PR description.

// AND THE SCRIPT TOOL'S SWITCH, read where a plan run's worker reads it
// (bashbelt_worker.go): a task chat starts is a task worker too, and
// only [Config.mayScript] decides whether this belt carries it.
script: bashExperiment && scriptAsked(),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This applies to quick workers too, and a script in a quick task deadlocks. For a quick worker executeTaskTool holds node.quickIO across the whole call (task_quick_files.go:83), the nested call from the script goes through the same wrapper, and sync.Mutex isn't reentrant. In a probe with a quick node on a bash-belt worker with the switch on, a script with one tools.bash({command: "cat f.txt"}) never returned (a 15s context deadline didn't free it, because the mutex wait ignores it). The same script on a non-quick node returned in 6ms. Either keep script off quick workers' belts (&& node.spec.quick == nil) or stop taking the lock for nested calls.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 941d770. I took your first option: quick workers never carry script. Details are under "Review follow-ups" in the PR description.

Comment thread internal/session/tool_script.go Outdated
// a script that could hand work out would blur the road the conversation chose
// with the step that chose it. The tool's description is written from this
// list ([scriptDescription]).
var scriptOffLimits = []string{

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The description says a script "cannot ask the person or start work", but this denylist leaves plenty of tools that do. For example watch (starts a recurring job on a background context), build_harness, generate_music/generate_video (render jobs), the factory verbs (factory_start, factory_answer, factory_floor), the team verbs (team_send, team_post, team_decide, team_raise), use_service/change_setting, workspace_merge. They still go through approval so it isn't a bypass, but every tool added to the belt later is reachable from a script by default. I'd flip it to an allowlist of what the benchmark actually uses (bash, manual, web_fetch, web_search, read_document, the memory and knowledge reads) and widen it deliberately.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 941d770. It's now an allowlist of reading tools only: bash, read, ls, grep, find, read_document, manual, recall, web_search, web_fetch. Anything else is refused by name. The test now runs through a real turn, so it reaches the allowlist check rather than stopping on a nil episode. Details are under "Review follow-ups" in the PR description.

- New `script` tool: model-written JavaScript (internal/jsrun) calls the belt's
  other tools through the same approval gate as a direct call; only what it
  prints or returns comes back. Up to 4 calls at once; stops at 200 calls,
  10 minutes or 16 MiB. Not Node.js: files and commands go through tools.bash.
- Two switches, both off: CODEAF_TASK_SCRIPT=on for bash-belt task workers
  (plan runs and tasks chat starts, never quick workers), CODEAF_CHAT_SCRIPT=on
  for the chat.
- Every road is gated: executeTool puts the turn's episode and hub on the
  context, so a script reached through a saved program meets the approval
  rules, and a script with no episode refuses to run.
- A script reaches only an allowlist of reading tools: bash, read, ls, grep,
  find, read_document, manual, recall, web_search, web_fetch.
- A script is one step: it counts once against the step cap and in every step
  count; its calls are recorded on that step, with their plan writes. Every
  nested event names its script (Event.FromScript), and every surface (tui3,
  app backend, remote, factory, headless, plan room) draws its calls under it
  instead of as the model's own steps.
- A script's read returns the file, never a held-read pointer, and its results
  carry no job footer or fix-recall line. A finished script says how many
  calls it did not wait for; only calls that ran are counted.
- bash inside a script answers {output, exit_code, truncated,
  full_output_path} and is cut at 1 MiB; other tools answer their text.
- Manual: how-tasks-run.md gains sections for both switches, the allowlist,
  quick tasks, unawaited calls and the unbounded memory and regexp time.
- bench/scriptbench: read-heavy questions with ast- and manual-checked answers.
  Sonnet 5.5, three seeds: on questions needing a manual lookup per page the
  chat with the tool cost 4.5x and 8.7x less for the same answers; where bash
  does the work in one command it changed nothing.
- bench/oneroad: script arms and counters, worker spend from the usage ledger,
  macOS support, harnesses started from an empty environment, the engine
  stopped at the end of a cell, and approval prompts recorded as BLOCKED.
@joshbarrington

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review and the probes. All three blockers and the smaller points are addressed in 941d770. "Review follow-ups" in the PR description goes through each one with its test, and "Not covered and known limits" lists what's still open (no memory or regex limit, and approval inside a script not yet tried live).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants