From 941d7709144d43d6b43e054cc734691194d179f7 Mon Sep 17 00:00:00 2001 From: Joshua Barrington Date: Wed, 25 Nov 2026 20:56:34 +0100 Subject: [PATCH] script tool: combine tool calls in one JavaScript step, off by default - 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. --- bench/oneroad/README.md | 60 +++ bench/oneroad/cell.sh | 141 +++++- bench/oneroad/collect.py | 7 +- bench/oneroad/grid.sh | 6 +- bench/oneroad/lib/loadavg.sh | 9 + bench/oneroad/lib/road.py | 6 + bench/oneroad/lib/script_use.py | 128 +++++ bench/oneroad/lib/storeprint.py | 22 + bench/oneroad/wave.sh | 6 +- bench/scriptbench/.gitignore | 1 + bench/scriptbench/README.md | 89 ++++ bench/scriptbench/check.py | 213 +++++++++ bench/scriptbench/manual_pages.json | 75 +++ bench/scriptbench/manualtruth/main.go | 50 ++ bench/scriptbench/run.sh | 80 ++++ bench/scriptbench/score.py | 113 +++++ bench/scriptbench/tasks/longest.md | 9 + bench/scriptbench/tasks/manual-find.md | 50 ++ bench/scriptbench/tasks/manual-last.md | 41 ++ bench/scriptbench/tasks/public-defs.md | 11 + bench/scriptbench/tasks/raisers.md | 9 + cmd/codeaf/app.go | 7 + cmd/codeaf/app_test.go | 42 ++ cmd/codeaf/appfactory_stepstream.go | 3 +- cmd/codeaf/appfactory_stepstream_test.go | 16 + cmd/codeaf/appwork.go | 4 + cmd/codeaf/chatv3.go | 13 +- cmd/codeaf/factory_stage.go | 5 + cmd/codeaf/script_surfaces_test.go | 72 +++ docs/changes/unreleased/2815-script-tool.md | 50 ++ internal/config/settings.go | 10 + internal/exec/bare/tools.go | 17 +- internal/jsrun/fuel.go | 45 +- internal/jsrun/host.go | 57 +-- internal/jsrun/machine.go | 104 +++++ internal/jsrun/runner.go | 7 +- internal/jsrun/script.go | 439 ++++++++++++++++++ internal/jsrun/script_calls_test.go | 76 +++ internal/jsrun/script_test.go | 294 ++++++++++++ internal/manual/chat/how-tasks-run.md | 67 +++ internal/plandb/live.go | 26 +- internal/plandb/live_tool_test.go | 28 ++ internal/plandb/persist.go | 6 + internal/remote/server.go | 12 +- internal/remote/weighagain_test.go | 12 +- internal/run/bashworker.go | 101 +++- internal/run/bashworker_script_live_test.go | 52 +++ internal/run/bashworker_script_test.go | 124 +++++ internal/run/bashworker_script_writes_test.go | 61 +++ internal/run/trajectory.go | 19 + internal/session/agent.go | 24 +- internal/session/bashbelt.go | 16 +- internal/session/bashbelt_truncate.go | 30 +- internal/session/bashbelt_worker.go | 1 + internal/session/beltfacts.go | 13 + internal/session/loop.go | 167 ++++--- internal/session/plandb_tasks.go | 22 +- internal/session/prompt.go | 14 +- internal/session/readhandoff.go | 4 +- internal/session/session.go | 22 + internal/session/sessionfile.go | 69 +++ internal/session/task_app_steps.go | 5 + internal/session/task_child_run.go | 20 +- internal/session/task_live.go | 9 + internal/session/task_run.go | 17 +- internal/session/tasklook.go | 19 + internal/session/tool_script.go | 416 +++++++++++++++++ internal/session/tool_script_followup_test.go | 129 +++++ internal/session/tool_script_review_test.go | 281 +++++++++++ internal/session/tool_script_steps_test.go | 170 +++++++ internal/session/tool_script_test.go | 212 +++++++++ internal/session/toolrejection.go | 6 + internal/session/tools.go | 7 +- internal/session/transcriptread.go | 1 + internal/session/userbash.go | 10 +- internal/tui3/app.go | 9 + internal/tui3/feed.go | 44 +- internal/tui3/feed_nested_test.go | 72 +++ internal/tui3/planrail.go | 4 +- internal/tui3/planroom.go | 42 +- internal/tui3/planroom_script_test.go | 98 ++++ internal/tui3/replay.go | 1 + internal/tui3/script_consent_test.go | 57 +++ internal/tui3/task.go | 4 +- internal/tui3/toolview.go | 29 +- 85 files changed, 4706 insertions(+), 233 deletions(-) create mode 100644 bench/oneroad/lib/loadavg.sh create mode 100755 bench/oneroad/lib/script_use.py create mode 100644 bench/oneroad/lib/storeprint.py create mode 100644 bench/scriptbench/.gitignore create mode 100644 bench/scriptbench/README.md create mode 100755 bench/scriptbench/check.py create mode 100644 bench/scriptbench/manual_pages.json create mode 100644 bench/scriptbench/manualtruth/main.go create mode 100755 bench/scriptbench/run.sh create mode 100755 bench/scriptbench/score.py create mode 100644 bench/scriptbench/tasks/longest.md create mode 100644 bench/scriptbench/tasks/manual-find.md create mode 100644 bench/scriptbench/tasks/manual-last.md create mode 100644 bench/scriptbench/tasks/public-defs.md create mode 100644 bench/scriptbench/tasks/raisers.md create mode 100644 cmd/codeaf/script_surfaces_test.go create mode 100644 docs/changes/unreleased/2815-script-tool.md create mode 100644 internal/jsrun/machine.go create mode 100644 internal/jsrun/script.go create mode 100644 internal/jsrun/script_calls_test.go create mode 100644 internal/jsrun/script_test.go create mode 100644 internal/plandb/live_tool_test.go create mode 100644 internal/run/bashworker_script_live_test.go create mode 100644 internal/run/bashworker_script_test.go create mode 100644 internal/run/bashworker_script_writes_test.go create mode 100644 internal/session/tool_script.go create mode 100644 internal/session/tool_script_followup_test.go create mode 100644 internal/session/tool_script_review_test.go create mode 100644 internal/session/tool_script_steps_test.go create mode 100644 internal/session/tool_script_test.go create mode 100644 internal/tui3/feed_nested_test.go create mode 100644 internal/tui3/planroom_script_test.go create mode 100644 internal/tui3/script_consent_test.go diff --git a/bench/oneroad/README.md b/bench/oneroad/README.md index 45fe376b29..52ff05afd9 100644 --- a/bench/oneroad/README.md +++ b/bench/oneroad/README.md @@ -78,6 +78,66 @@ Repeatability rules, all of them load-bearing: green is reported as a failure with its other numbers shown but struck through, because the fastest way to a green suite is always to delete the test. +## Measuring the script tool + +`codeaf-script-flash` and `codeaf-script-crew` are `codeaf-new-flash` and +`codeaf-new-crew` with `CODEAF_TASK_SCRIPT=on` in codeaf's environment and +nothing else changed, so each pair measures the task worker's `script` tool +alone (internal/session/tool_script.go). Run the pairs on the same tasks and +seeds: + +```sh +bench/oneroad/wave.sh codeaf-new-crew codeaf-script-crew +# for example: NEW_BIN=$PWD/bin/codeaf bench/oneroad/wave.sh 21 codeaf-new-crew codeaf-script-crew +``` + +Every codeaf cell's `meta.json` carries, and `collect.py` puts in +`results.csv`: + +- `steps`, `script_steps`, `script_calls`: the workers' tool calls, their + script calls and the calls those scripts made, read from plan-run + trajectories and chat-task transcripts alike (`lib/script_use.py`). Read + these first: a script arm whose workers wrote no scripts measured nothing + about the tool, and its differences are noise. +- `worker_usd`, `worker_tokens_in`, `worker_tokens_out`, + `worker_tokens_cache`, `worker_model_calls`: every model call a task worker + made, from the profile's usage ledger (`v3/usage.jsonl`, the rows on the + worker seat or naming a task: a plan run's workers carry only the seat). This is where the tool's effect on spend shows; compare it between + the pair. The plan store's spend rows are not used: they hold only a plan + run's workers, and a chat task's spend is not in them. +- `tokens_in`, `tokens_out`, `tokens_cache`: the conversation's own model + calls (`lib/road.py`), the same names the peer arms' tokens use. They do + not include the workers. + +`cost_usd` prefers the conversation's call lines when it has them, so it can +leave the workers' bill out; for this comparison read `worker_usd` beside it. +Then compare outcome, tests after and `wall_s_active`. A run calls live models +on the key in `OPENROUTER_API_KEY` and is billed. + +### What the pilots found + +Four pilot cells on `batch` (2026-11-18) wrote one script between them, and +it failed: DeepSeek v4 flash read the tool as Node.js, and Sonnet 5.5 did its +reading in `bash` instead, chaining commands in one call. A grid here would +measure that the tool goes unused. `bench/scriptbench` measures the case it +is for, and found the saving there. + +### The chat-side arm + +`codeaf-chatscript-flash` and `codeaf-chatscript-crew` are the new arms with +`CODEAF_CHAT_SCRIPT=on`: the same tool on the conversation's own belt, the +workers untouched. Run them beside `codeaf-new-*` in the same wave: + +```sh +NEW_BIN=... bench/oneroad/wave.sh batch codeaf-new-crew codeaf-chatscript-crew +``` + +Read `chat_script_steps` and `chat_script_calls` first, for the reason the +worker arm's counts come first. The effect shows in the conversation's own +`tokens_in`, `tokens_out` and `tokens_cache`, beside `worker_*` and `road`: +a chat that can make many calls in one step may do work itself that it would +otherwise have handed to a task, and that is a change of road, not a saving. + ## Reading a comparison honestly - Quote wall clock only beside the verdict. A harness that finishes in half the diff --git a/bench/oneroad/cell.sh b/bench/oneroad/cell.sh index c58570675b..16f44306ff 100755 --- a/bench/oneroad/cell.sh +++ b/bench/oneroad/cell.sh @@ -3,6 +3,10 @@ # # Usage: cell.sh # arm codeaf-new-flash | codeaf-new-crew | codeaf-old-flash | pi | opencode +# | codeaf-script-flash | codeaf-script-crew (the new arms with +# CODEAF_TASK_SCRIPT=on, the script tool's measurement) +# | codeaf-chatscript-flash | codeaf-chatscript-crew (the new arms +# with CODEAF_CHAT_SCRIPT=on, the tool on the chat's own belt) # task 20 | 21 | 22 | 23 | batch # # THE PROTOCOL POINT (bench/oneroad/README.md): the codeaf arms are driven @@ -24,6 +28,17 @@ SEED="${SEED:-s1}" ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ONEROAD="$ROOT" source "$ONEROAD/lib/corpus.sh" +source "$ONEROAD/lib/loadavg.sh" + +# CELL_ENV is the whole environment a harness under test is started with, on +# top of env -i: where programs are, who and where the user is, the locale and +# the temp folder (codeaf names its sockets there). Nothing else from the shell +# that launched the bench — tokens, database URLs, cloud keys — reaches a +# harness, which runs unattended on text from a public repository. +# CELL_ENV_ARGS is for a command run from here; CELL_ENV is the same list +# quoted for the command line tmux hands its own shell. +CELL_ENV_ARGS=("PATH=$PATH" "USER=${USER:-}" "LOGNAME=${LOGNAME:-}" "LANG=${LANG:-en_US.UTF-8}" "SHELL=${SHELL:-/bin/sh}" "TMPDIR=${TMPDIR:-/tmp}") +CELL_ENV="$(printf '%q ' "${CELL_ENV_ARGS[@]}")" ISSUES="${ISSUES:-20 21 22 23}" MODEL="${MODEL:-deepseek/deepseek-v4-flash}" @@ -43,7 +58,12 @@ CELL_SECONDS="${CELL_SECONDS:-3600}" SILENCE_SECONDS="${SILENCE_SECONDS:-180}" POLL="${POLL:-10}" -CELL="$ONEROAD/results/$ARM-$TASK-$SEED" +# THREE OVERRIDES LET ANOTHER BENCHMARK DRIVE THIS CELL (bench/scriptbench): +# RESULTS is where its cells go, PROMPT_FILE is its prompt in place of an +# issue's, and SKIP_SUITE=1 leaves out the test suite for a task whose answer +# is checked by something else. Unset, the one-road cell is unchanged. +RESULTS="${RESULTS:-$ONEROAD/results}" +CELL="$RESULTS/$ARM-$TASK-$SEED" rm -rf "$CELL"; mkdir -p "$CELL" WORK="$CELL/work"; mkdir -p "$WORK" DIR="$WORK/$SLUG" @@ -53,7 +73,9 @@ say() { printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*" | tee -a "$CELL/cell.log"; } # ── the prompt ────────────────────────────────────────────────────────────── say "$ARM/$TASK: fetching issue text" -if [ "$TASK" = "batch" ]; then +if [ -n "${PROMPT_FILE:-}" ]; then + PROMPT="$(cat "$PROMPT_FILE")" || { say "could not read $PROMPT_FILE"; exit 1; } +elif [ "$TASK" = "batch" ]; then PROMPT="$(batch_prompt)" || { say "could not read the issues"; exit 1; } else PROMPT="$(issue_prompt "$TASK")" || { say "could not read issue #$TASK"; exit 1; } @@ -64,20 +86,38 @@ printf '%s' "$PROMPT" > "$CELL/prompt.txt" say "$ARM/$TASK: cloning at $BASE_COMMIT" COMMIT="$(fresh_clone "$DIR")" || { say "clone failed"; exit 1; } echo "$COMMIT" > "$CELL/base-commit" -setup_python "$DIR" -BEFORE="$(run_suite "$DIR" "$CELL/pytest-before.log")" +BEFORE="skipped" +if [ "${SKIP_SUITE:-0}" != "1" ]; then + setup_python "$DIR" + BEFORE="$(run_suite "$DIR" "$CELL/pytest-before.log")" +fi say "$ARM/$TASK: suite before = $BEFORE (passed/failed)" # The load this cell started under. Arms share one machine by design (the # same-wave rule is what keeps provider weather fair), so the contention has to # be on the record rather than argued about afterwards. -cut -d' ' -f1-3 /proc/loadavg > "$CELL/loadavg-before" +loadavg > "$CELL/loadavg-before" # ── the codeaf arms: the real TUI, over tmux ──────────────────────────────── run_codeaf() { - local binary="$1" all_flash="$2" - local profile="$CELL/profile" cellhome="$CELL/home" - mkdir -p "$profile" "$cellhome" + local binary="$1" all_flash="$2" switches="" + # THE SCRIPT ARMS DIFFER BY ONE VARIABLE. A third argument of `script` arms the + # task worker's script tool (internal/session/tool_script.go) and changes + # nothing else, so a script arm beside its new arm measures the tool alone. + [ "${3:-}" = "script" ] && switches="CODEAF_TASK_SCRIPT=on" + # AND THE CHAT'S ARM, on the same terms: `chatscript` arms the tool on the + # conversation's own belt and leaves the workers as the new arm has them. + [ "${3:-}" = "chatscript" ] && switches="CODEAF_CHAT_SCRIPT=on" + # THE PROFILE LIVES AT A SHORT PATH WHILE CODEAF RUNS. codeaf names a socket + # inside it, and a socket path has a 103-byte limit on macOS: under results/ + # the name is too long, codeaf runs the conversation in its own terminal + # instead, and the cell measures a codeaf nobody runs. $CELL/profile points at + # it while the cell runs, and the folder moves back when it ends. + local profile cellhome="$CELL/home" + profile="$(mktemp -d /tmp/oneroad.XXXXXX)" || return 92 + RUN_BIN="$binary" + ln -s "$profile" "$CELL/profile" + mkdir -p "$cellhome" # The disposable brain. This is the same shape the retired UX harness built: # HOME moves as well as the profile, so anything that does not yet honour the profile override lands @@ -117,10 +157,24 @@ PY # `pi -p` and `opencode run --auto` take on the other arms. # --model pins the conversation's own model; the tier rows above (or their # absence) decide everything the machine calls on its own behalf. + # THE CELL'S CODEAF SEES ONLY WHAT IT NEEDS. It runs --yolo on a public + # issue's words, and a worker that runs `env` reads whatever it was handed, + # so it starts from an empty environment (env -i) plus CELL_ENV, never the + # shell that launched the bench. The provider key is NOT among them: it is in + # the profile's config.json above, and on a command line it would be readable + # by anything that lists processes. + # + # AND NO PROCESS ABOVE IT KEEPS THE SHELL'S ENVIRONMENT EITHER. tmux runs + # its command under the server's shell, whose environment is the one that + # started the server; left alive as codeaf's parent, `ps eww` would read it + # back. So that shell `exec`s straight into env -i, and the steps that must + # follow codeaf run from a launcher under the clean environment. + local launch="$CELL/launch.sh" + printf 'cd %q || exit 1\n%q chat --yolo --model %q\necho codeaf-EXITED\nsleep 60\n' \ + "$DIR" "$binary" "$MODEL" > "$launch" tmux new-session -d -s "$SESSION_NAME" -x 200 -y 50 \ - "cd '$DIR' && env HOME='$cellhome' CODEAF_HOME='$profile' CODEAF_PROFILE_DIR='$profile' \ - OPENROUTER_API_KEY='$OPENROUTER_API_KEY' TERM=xterm-256color \ - '$binary' chat --yolo --model '$MODEL'; echo codeaf-EXITED; sleep 60" + "exec env -i $CELL_ENV HOME='$cellhome' CODEAF_HOME='$profile' CODEAF_PROFILE_DIR='$profile' \ + TERM=xterm-256color $switches /bin/sh '$launch'" # The first frame. A surface that never drew one has nothing to type into, and # the pane is kept so the reason is legible rather than inferred. @@ -181,7 +235,7 @@ PY echo wall > "$CELL/settle_reason" return 124 fi - now="$(find "$sessroot" -type f ! -name presence.json -printf '%s %T@ %p\n' 2>/dev/null | sort | md5sum)" + now="$(python3 "$ONEROAD/lib/storeprint.py" "$sessroot" 2>/dev/null | cksum)" screen="$(tmux capture-pane -t "$SESSION_NAME" -p 2>/dev/null)" printf '%s\n' "$screen" > "$CELL/tmux-live.txt" # THE STORE IS THE SIGNAL AND THE SCREEN IS ONLY A VETO ON "working". @@ -190,6 +244,21 @@ PY # had been silent for seven minutes was still being called busy and would # have run to the wall and been recorded DNF. A liveness check must key on # something that STOPS when the work stops; the footer's hint does not. + # A CELL STOPPED AT AN APPROVAL IS BLOCKED, NOT IDLE. --yolo still asks + # before the commands internal/approval's floor names (an absolute + # recursive delete among them), nobody here will answer, and the store + # goes quiet while the prompt waits — which the idle rule below would + # record as a cell that finished. + if printf '%s' "$screen" | grep -q 'needs your ok'; then + say "$ARM/$TASK: blocked at an approval prompt at ${elapsed}s" + printf '%s\n' "$screen" | grep -A2 'needs your ok' | head -3 > "$CELL/approval.txt" + tmux capture-pane -t "$SESSION_NAME" -p > "$CELL/tmux-final.txt" + tmux capture-pane -t "$SESSION_NAME" -p -S -4000 > "$CELL/tmux-scrollback.txt" + tmux kill-session -t "$SESSION_NAME" 2>/dev/null + echo BLOCKED > "$CELL/outcome" + echo approval > "$CELL/settle_reason" + return 0 + fi if [ "$now" = "$last" ]; then quiet=$((quiet + POLL)) else @@ -244,7 +313,8 @@ run_peer() { pi) # bench/run.sh's recorded invocation, checked against pi 0.84.1: -p is # still non-interactive print mode and --provider/--model still pin. - (cd "$DIR" && timeout "$CELL_SECONDS" "$PI_BIN" -p \ + (cd "$DIR" && env -i "${CELL_ENV_ARGS[@]}" HOME="$HOME" OPENROUTER_API_KEY="$OPENROUTER_API_KEY" \ + timeout "$CELL_SECONDS" "$PI_BIN" -p \ --provider openrouter --model "$MODEL" "$PROMPT") ;; opencode) @@ -253,7 +323,8 @@ run_peer() { # stops at the first permission prompt with nobody there to answer and the # cell measures a dialog rather than a harness. --auto is this arm's # equivalent of codeaf's --yolo and pi's -p. - (cd "$DIR" && timeout "$CELL_SECONDS" "$OPENCODE_BIN" run --auto \ + (cd "$DIR" && env -i "${CELL_ENV_ARGS[@]}" HOME="$HOME" OPENROUTER_API_KEY="$OPENROUTER_API_KEY" \ + timeout "$CELL_SECONDS" "$OPENCODE_BIN" run --auto \ -m "openrouter/$MODEL" "$PROMPT") ;; esac @@ -264,6 +335,10 @@ STARTED=$(date +%s) case "$ARM" in codeaf-new-flash) run_codeaf "$NEW_BIN" 1; CODE=$? ;; codeaf-new-crew) run_codeaf "$NEW_BIN" 0; CODE=$? ;; + codeaf-script-flash) run_codeaf "$NEW_BIN" 1 script; CODE=$? ;; + codeaf-script-crew) run_codeaf "$NEW_BIN" 0 script; CODE=$? ;; + codeaf-chatscript-flash) run_codeaf "$NEW_BIN" 1 chatscript; CODE=$? ;; + codeaf-chatscript-crew) run_codeaf "$NEW_BIN" 0 chatscript; CODE=$? ;; codeaf-old-flash) run_codeaf "$OLD_BIN" 1; CODE=$? ;; codeaf-esc-flash) run_codeaf "$ESC_BIN" 1; CODE=$? ;; codeaf-esc-crew) run_codeaf "$ESC_BIN" 0; CODE=$? ;; @@ -284,7 +359,23 @@ case "$ARM" in *) say "unknown arm $ARM"; exit 2 ;; esac WALL=$(( $(date +%s) - STARTED )) -cut -d' ' -f1-3 /proc/loadavg > "$CELL/loadavg-after" +if [ -L "$CELL/profile" ]; then + short="$(readlink "$CELL/profile")" + # THE ENGINE OUTLIVES THE CHAT. codeaf holds the workspace's conversations in + # a daemon that a killed tmux session does not stop; left running, it goes on + # writing into this profile and holds its tasks after the cell has ended. + env -i "${CELL_ENV_ARGS[@]}" HOME="$CELL/home" CODEAF_HOME="$short" CODEAF_PROFILE_DIR="$short" \ + "$RUN_BIN" engine --stop --workspace "$DIR" >> "$CELL/cell.log" 2>&1 + # codeaf writes its last files on the way out, so the folder moves only once + # nothing holds it open. + for _ in $(seq 30); do + lsof +D "$short" >/dev/null 2>&1 || break + sleep 1 + done + sleep 2 + rm "$CELL/profile" && mv "$short" "$CELL/profile" +fi +loadavg > "$CELL/loadavg-after" say "$ARM/$TASK: harness finished, exit $CODE, ${WALL}s" CHANGED="$(changed_files "$DIR")" @@ -306,11 +397,13 @@ LANDED (cd "$DIR" && git diff) > /dev/null 2>&1 (cd "$DIR" && git status --porcelain | grep -vE '\.venv|__pycache__') > "$CELL/status.txt" 2>/dev/null -AFTER="$(run_suite "$DIR" "$CELL/pytest-after.log")" +AFTER="skipped" +[ "${SKIP_SUITE:-0}" != "1" ] && AFTER="$(run_suite "$DIR" "$CELL/pytest-after.log")" say "$ARM/$TASK: suite after = $AFTER, $CHANGED changed file(s)" # ── the road columns, and the parallelism timeline ────────────────────────── ROAD=""; ARMED=""; PARTS=0; PEAK=""; REFUSED=""; COST=""; COST_SRC="" +TOK_IN=""; TOK_OUT=""; TOK_CACHE="" ESCALATED=""; ESC_SEEN=""; ROUTE=""; GRIND=""; PRE_LINE=""; MARKS="" CALLS=""; COST_CALLS=""; ENDPOINTS=""; MARKS_J=""; FORKS=""; COSTROLE=""; CEIL=""; DIVISION=""; DIVWHY="" case "$ARM" in @@ -359,7 +452,8 @@ for name, key in (("ROAD","road"),("ARMED","armed"),("PARTS","parts"), ("COST_CALLS","cost_usd_calls"),("ENDPOINTS","endpoint_mix"), ("MARKS_J","marks"),("FORKS","forks"),("COSTROLE","cost_by_role"), ("CEIL","ceiling_decision"),("DIVISION","division"),("DIVWHY","division_why"), - ("COST","cost_usd"),("COST_SRC","cost_source")): + ("COST","cost_usd"),("COST_SRC","cost_source"), + ("TOK_IN","tokens_in"),("TOK_OUT","tokens_out"),("TOK_CACHE","tokens_cache")): print("%s=%s" % (name, shlex.quote(str(c.get(key, "")))))')" fi else @@ -392,6 +486,14 @@ if [ "$OUTCOME" = "DNF" ]; then SETTLE_NOTE="wall reached with nothing landed" fi fi +# HOW MUCH THE WORKERS USED THE SCRIPT TOOL, AND WHAT THEY SPENT, from their +# trajectories and their runs' plan stores. Every codeaf arm records it, so the +# zeros on a new arm are measured, not assumed. +SCRIPT_USE="" +case "$ARM" in + codeaf-*) SCRIPT_USE="$(python3 "$ONEROAD/lib/script_use.py" "$CELL" 2>>"$CELL/cell.log")" ;; +esac +export SCRIPT_USE TOK_IN TOK_OUT TOK_CACHE SETTLE_REASON="$(cat "$CELL/settle_reason" 2>/dev/null || echo n/a)" [ -n "${SETTLE_NOTE:-}" ] && SETTLE_REASON="$SETTLE_NOTE" ARM="$ARM" TASK="$TASK" SEED="$SEED" WALL="$WALL" CODE="$CODE" CHANGED="$CHANGED" \ @@ -436,6 +538,9 @@ meta = { "endpoint_mix": env["ENDPOINTS"], "marks": env["MARKS_J"], "forks": env["FORKS"], "cost_by_role": env["COSTROLE"], "ceiling_decision": env["CEIL"], "division": env["DIVISION"], "division_why": env["DIVWHY"], + "tokens_in": env.get("TOK_IN", ""), "tokens_out": env.get("TOK_OUT", ""), + "tokens_cache": env.get("TOK_CACHE", ""), + **(json.loads(env.get("SCRIPT_USE") or "{}")), "loadavg_before": open(os.path.join(env["CELL"], "loadavg-before")).read().strip(), "loadavg_after": open(os.path.join(env["CELL"], "loadavg-after")).read().strip(), } @@ -464,7 +569,7 @@ PY # does not depend on the shared file. case "$ARM" in pi|opencode) - python3 "$ONEROAD/lib/competitor_cost.py" "$ONEROAD/results" "$(basename "$CELL")" \ + python3 "$ONEROAD/lib/competitor_cost.py" "$RESULTS" "$(basename "$CELL")" \ >> "$CELL/cell.log" 2>&1 || say "$ARM/$TASK: competitor cost unreadable (meta.json keeps its blank)" ;; esac diff --git a/bench/oneroad/collect.py b/bench/oneroad/collect.py index 96dcd3aae7..f0d3852255 100644 --- a/bench/oneroad/collect.py +++ b/bench/oneroad/collect.py @@ -9,7 +9,12 @@ "changed_files_landed", "stranded_worktree_files", "changed_files_total", "upstream_commits_in_head", "contaminated", "road", "route", "armed", "parts", "peak_workers", "refused", "chat_tool_calls", "checkpoint_marks", "escalated", "escalation_seen_on_pane", "pre_turn_line", - "exit", "model", "base_commit", "loadavg_before", "loadavg_after"] + "exit", "model", "base_commit", "loadavg_before", "loadavg_after", + "steps", "script_steps", "script_calls", + "tokens_in", "tokens_out", "tokens_cache", + "worker_usd", "worker_tokens_in", "worker_tokens_out", + "worker_tokens_cache", "worker_model_calls", + "chat_steps", "chat_script_steps", "chat_script_calls"] def active_wall(cell, row): diff --git a/bench/oneroad/grid.sh b/bench/oneroad/grid.sh index aa7dde3f13..1b618bbf63 100755 --- a/bench/oneroad/grid.sh +++ b/bench/oneroad/grid.sh @@ -6,16 +6,16 @@ MAX_WAVES="${MAX_WAVES:-3}" ARMS="${ARMS:-}" mkdir -p "$ROOT/results" -echo "grid $$ $(date -Is)" >> "$ROOT/results/PIDS" +echo "grid $$ $(date +%Y-%m-%dT%H:%M:%S%z)" >> "$ROOT/results/PIDS" for task in $TASKS; do # Wait for a wave to land before firing the next, so the cap holds without a # scheduler: `jobs -r` is this shell's own count of waves still in the air. while [ "$(jobs -r | wc -l)" -ge "$MAX_WAVES" ]; do sleep 20; done SEED="${SEED:-s1}" bash "$ROOT/wave.sh" "$task" $ARMS > "$ROOT/results/.wave-${WAVE_TAG:-}$task.out" 2>&1 & - echo "wave-${WAVE_TAG:-}$task $! $(date -Is)" >> "$ROOT/results/PIDS" + echo "wave-${WAVE_TAG:-}$task $! $(date +%Y-%m-%dT%H:%M:%S%z)" >> "$ROOT/results/PIDS" sleep 5 done wait python3 "$ROOT/collect.py" >> "$ROOT/results/.collect.out" 2>&1 -echo "grid landed $(date -Is)" >> "$ROOT/results/PIDS" +echo "grid landed $(date +%Y-%m-%dT%H:%M:%S%z)" >> "$ROOT/results/PIDS" diff --git a/bench/oneroad/lib/loadavg.sh b/bench/oneroad/lib/loadavg.sh new file mode 100644 index 0000000000..cd5c90c7bd --- /dev/null +++ b/bench/oneroad/lib/loadavg.sh @@ -0,0 +1,9 @@ +# loadavg prints the one-, five- and fifteen-minute load: /proc on Linux, +# sysctl on macOS, where there is no /proc. +loadavg() { + if [ -r /proc/loadavg ]; then + cut -d' ' -f1-3 /proc/loadavg + else + sysctl -n vm.loadavg 2>/dev/null | tr -d '{}' | awk '{print $1, $2, $3}' + fi +} diff --git a/bench/oneroad/lib/road.py b/bench/oneroad/lib/road.py index 4504b0e750..e9cb3f1cab 100644 --- a/bench/oneroad/lib/road.py +++ b/bench/oneroad/lib/road.py @@ -660,6 +660,12 @@ def main(): "checkpoint_marks": mech["checkpoint_marks"], "calls": calls["calls"], "cost_usd_calls": calls["cost_usd_calls"], + # The conversation's own tokens, under the names the peer arms' tokens + # already use (competitor_cost.py). Task workers' tokens are not here: + # they are in each run's plan store (script_use.py's worker_* columns). + "tokens_in": calls["tokens"]["input"], + "tokens_out": calls["tokens"]["output"], + "tokens_cache": calls["tokens"]["cache_read"], "endpoint_mix": calls["endpoint_mix"], "marks": ",".join(f"{m['rounds']}:{m['decision']}" for m in marks_journal), "mark_decisions": len(marks_journal), diff --git a/bench/oneroad/lib/script_use.py b/bench/oneroad/lib/script_use.py new file mode 100755 index 0000000000..7351cf5281 --- /dev/null +++ b/bench/oneroad/lib/script_use.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""script_use.py — how much a codeaf cell's task workers used the script tool, +and what they spent. + +Usage: script_use.py + +Prints one JSON object: + + steps, script_steps, script_calls + The tool calls the workers made, how many were script calls, and how many + calls those scripts made in turn. Two records hold them, and they never + describe the same worker: + - a plan run's trajectory (/tasks//trajectory.jsonl, + internal/run/trajectory.go): one line per step, a script's calls on it; + - a chat task's transcript (.cell/tasks/*.jsonl): one assistant tool call + per step, and a script's own result line, "script in + after N calls" (internal/session's tool_script.go), for its calls. + chat_steps, chat_script_steps, chat_script_calls + The same three readings for the conversation itself, from its own + transcript (.cell/transcript.jsonl): the chat-side arm's measure, where + CODEAF_CHAT_SCRIPT puts the tool on the conversation's belt. + worker_usd, worker_tokens_in, worker_tokens_out, worker_tokens_cache, + worker_model_calls + Every model call a task worker made: the rows of the profile's usage + ledger (v3/usage.jsonl) on the worker seat or naming a task, once per + row id. A chat task's rows name their task; a plan run's workers' rows + carry only the seat and their run. The ledger + records every call codeaf makes, a chat task's and a plan run's alike; + the plan store's spend rows hold only a plan run's, so a cell whose + tasks chat started read near zero there however much its workers spent. + The conversation's own calls are road.py's tokens_* columns. + +The cell's store copy is read when cell.sh has made one ($CELL/store, taken so +nothing reads a file a process still holds), otherwise the live profile; never +both, which would count everything twice. A cell that ran no task prints +zeros, the honest reading for a turn that ran no task. + +The script arms differ from the new arms by CODEAF_TASK_SCRIPT=on alone, so the +script counts say whether the switch changed the work at all before the worker +spend is read as its effect. +""" +import json, os, re, sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from road import read_jsonl # noqa: E402 + +SCRIPT_LINE = re.compile(r"^script \w+ in \S+ after (\d+) calls?\b") + + +def roots(cell): + store = os.path.join(cell, "store") + first = store if os.path.isdir(store) else os.path.join(cell, "profile") + return [first, os.path.join(cell, "home")] + + +def text_of(content): + """A transcript message's content as text: a string, or its text parts.""" + if isinstance(content, str): + return content + if isinstance(content, list): + return "".join(p.get("text", "") for p in content if isinstance(p, dict)) + return "" + + +def trajectory(path, out): + for step in read_jsonl(path): + if not isinstance(step, dict) or step.get("kind") != "step": + continue + out["steps"] += 1 + if step.get("tool") == "script": + out["script_steps"] += 1 + out["script_calls"] += len(step.get("calls") or []) + + +def transcript(path, out, prefix=""): + scripts = set() + for line in read_jsonl(path): + if not isinstance(line, dict) or line.get("type") != "message": + continue + if line.get("role") == "assistant": + for call in line.get("toolCalls") or []: + out[prefix + "steps"] += 1 + if (call.get("function") or {}).get("name") == "script": + out[prefix + "script_steps"] += 1 + scripts.add(call.get("id")) + elif line.get("role") == "tool" and line.get("toolCallId") in scripts: + ran = SCRIPT_LINE.match(text_of(line.get("content"))) + if ran: + out[prefix + "script_calls"] += int(ran.group(1)) + + +def usage(path, out): + rows = {} + for row in read_jsonl(path): + if isinstance(row, dict) and (row.get("seat") == "worker" or row.get("task")): + rows[row.get("id") or len(rows)] = row + for row in rows.values(): + out["worker_usd"] += float(row.get("usd") or 0) + out["worker_tokens_in"] += int(row.get("in") or 0) + out["worker_tokens_out"] += int(row.get("out") or 0) + out["worker_tokens_cache"] += int(row.get("cache_read") or 0) + out["worker_model_calls"] += int(row.get("calls") or 1) + + +def count(cell): + out = {"steps": 0, "script_steps": 0, "script_calls": 0, + "worker_usd": 0.0, "worker_tokens_in": 0, "worker_tokens_out": 0, + "worker_tokens_cache": 0, "worker_model_calls": 0, + "chat_steps": 0, "chat_script_steps": 0, "chat_script_calls": 0} + for root in roots(cell): + for base, _, names in os.walk(root): + for name in names: + path = os.path.join(base, name) + if name == "trajectory.jsonl": + trajectory(path, out) + elif name.endswith(".jsonl") and os.path.basename(base) == "tasks" \ + and os.path.basename(os.path.dirname(base)) == ".cell": + transcript(path, out) + elif name == "transcript.jsonl" and os.path.basename(base) == ".cell": + transcript(path, out, "chat_") + elif name == "usage.jsonl": + usage(path, out) + out["worker_usd"] = round(out["worker_usd"], 6) + return out + + +if __name__ == "__main__": + print(json.dumps(count(sys.argv[1]))) diff --git a/bench/oneroad/lib/storeprint.py b/bench/oneroad/lib/storeprint.py new file mode 100644 index 0000000000..3fc717a22f --- /dev/null +++ b/bench/oneroad/lib/storeprint.py @@ -0,0 +1,22 @@ +"""storeprint: one line per file under a folder — size, mtime and path, sorted — +for cell.sh's silence detector. It is the portable spelling of +`find -type f ! -name presence.json -printf '%s %T@ %p\n' | sort`, which BSD +find cannot run: on macOS that pipeline printed nothing, every reading matched +the last one, and a cell settled as idle after SILENCE_SECONDS however busy it +was. presence.json is left out for the reason cell.sh gives: it is a heartbeat. +""" +import os +import sys + +lines = [] +for folder, _, files in os.walk(sys.argv[1]): + for name in files: + if name == "presence.json": + continue + path = os.path.join(folder, name) + try: + st = os.stat(path) + except OSError: + continue + lines.append(f"{st.st_size} {st.st_mtime} {path}") +print("\n".join(sorted(lines))) diff --git a/bench/oneroad/wave.sh b/bench/oneroad/wave.sh index 487d222386..b7b7ca90bf 100755 --- a/bench/oneroad/wave.sh +++ b/bench/oneroad/wave.sh @@ -14,11 +14,13 @@ TASK="${1:?usage: wave.sh [arms...]}"; shift ARMS="${*:-codeaf-new-flash codeaf-new-crew codeaf-old-flash pi opencode}" SEED="${SEED:-s1}" +source "$ROOT/lib/loadavg.sh" + mkdir -p "$ROOT/results" # The load at the instant the wave fired. Five cells on one box contend for CPU # during clone, venv and pytest even though the middle of every cell is waiting # on a model, and the discount is only arguable afterwards if the number is here. -printf 'wave %s fired %s loadavg %s\n' "$TASK" "$(date -Is)" "$(cut -d' ' -f1-3 /proc/loadavg)" \ +printf 'wave %s fired %s loadavg %s\n' "$TASK" "$(date +%Y-%m-%dT%H:%M:%S%z)" "$(loadavg)" \ >> "$ROOT/results/waves.log" pids=() @@ -28,5 +30,5 @@ for arm in $ARMS; do sleep 2 done for pid in "${pids[@]}"; do wait "$pid"; done -printf 'wave %s landed %s loadavg %s\n' "$TASK" "$(date -Is)" "$(cut -d' ' -f1-3 /proc/loadavg)" \ +printf 'wave %s landed %s loadavg %s\n' "$TASK" "$(date +%Y-%m-%dT%H:%M:%S%z)" "$(loadavg)" \ >> "$ROOT/results/waves.log" diff --git a/bench/scriptbench/.gitignore b/bench/scriptbench/.gitignore new file mode 100644 index 0000000000..fbca225379 --- /dev/null +++ b/bench/scriptbench/.gitignore @@ -0,0 +1 @@ +results/ diff --git a/bench/scriptbench/README.md b/bench/scriptbench/README.md new file mode 100644 index 0000000000..bb14d74949 --- /dev/null +++ b/bench/scriptbench/README.md @@ -0,0 +1,89 @@ +# scriptbench: does the script tool help where it should? + +The one-road benchmark (`bench/oneroad`) asks for code changes, and its +pilots found that neither model reached for the `script` tool: a weak model +misread it as Node.js, and a strong one already chains commands inside one +`bash` call. This benchmark asks the questions a script is FOR: read many +files, keep a little from each, answer with a number or a list. + +## What it runs + +Three questions about click 8.1.7 (pinned in `run.sh`), each in +`tasks/.md`: + +- `public-defs`: public top-level functions and classes in each module. +- `raisers`: every function whose own body raises one of click's exceptions. +- `longest`: the ten longest functions and methods, with their lengths. + +And two that need many calls through a tool the shell cannot stand in for, +codeaf's own `manual` (the packed chat manual; `codeaf manual` on the command +line reads a different corpus, and run.sh keeps codeaf off the cells' PATH): + +- `manual-last`: the title and last section heading of 29 named pages. +- `manual-find`: which of 40 named pages have a heading with a word starting "delet". + +These are the questions the script tool should win: one script can fetch every +page and return a small table, where calling the tool once per page brings +every page into the conversation. The click questions are the control: a +shell can answer them in one command. + +Each is asked of `codeaf-new-crew` and `codeaf-chatscript-crew` in the same +wave. The pair differs by `CODEAF_CHAT_SCRIPT=on` alone. Every cell is +`bench/oneroad/cell.sh`: the real chat over tmux, an empty environment, the +same counters. + +```sh +NEW_BIN=$PWD/bin/codeaf bench/scriptbench/run.sh # all tasks +NEW_BIN=... SEEDS="s1 s2 s3" bench/scriptbench/run.sh raisers # one task, three seeds +NEW_BIN=... MODEL=deepseek/deepseek-v4-flash bench/scriptbench/run.sh +``` + +The default model is `anthropic/claude-sonnet-5.5`. A run calls live models +on `OPENROUTER_API_KEY` and is billed. + +## What it found + +Sonnet 5.5 (`anthropic/claude-sonnet-5.5`), a binary built from this change with both switches as they ship, 2026-11-18. +Cost is the cell's whole bill from its usage ledger. + +| question | arm | seeds | mean cost | mean input tokens | score | +|---|---|---|---|---|---| +| manual-last | new-crew | 3 | $0.626 | 449k | 1.00 1.00 1.00 | +| manual-last | chatscript-crew | 3 | $0.140 | 171k | 1.00 1.00 1.00 | +| manual-find | new-crew | 3 | $0.968 | 533k | 1.00 1.00 1.00 | +| manual-find | chatscript-crew | 3 | $0.111 | 204k | 0.93 1.00 0.93 | + +The script arm cost 4.5x less on manual-last and 8.7x less on manual-find, the +ranges did not overlap, and wall time was the same (about 110 s). Every script +cell wrote 3 to 7 scripts making 43 to 145 calls; the baseline made one call per +page, several per response. The saving is what the scripts kept out of the +conversation: input tokens fell to about 38%. + +The two 0.93s are one page, `home`, whose heading says "deleting". Those runs +asked for headings containing "delete", "as part of a longer word too", which +invites that match; the question now asks for words starting with "delet", and +the checker agrees. The table scores those runs by the rule they were asked +under. `score.py` uses today's checker, so re-scoring the same replies reads +1.00, 0.93 and 1.00 for the script arm and 0.93 three times for the baseline, +which never matched "deleting" either way. The costs do not change. + +The click questions (one seed each) showed no difference: Sonnet answered each +with one to four `bash` calls running Python's `ast` over the package, and +neither arm wrote a script. Where the shell can do the whole job in one +command, the tool has nothing to add. The one-road pilots (`bench/oneroad`) +found the same on code changes, and a weaker model (DeepSeek v4 flash) did not +use the tool at all. + +## How it is scored + +`check.py` computes every true answer from the source with Python's `ast`, or +from the binary's manual corpus through `manualtruth/`, never from a model, and scores the reply's last ```json block: the share of +modules right, the F1 of the set, the share of the true ten. A reply without +a block scores 0 and says so. Run `check.py truth ` to see an +answer. + +`score.py` writes `results/results.csv` and prints one line per task and +arm. Read `scripts` first: an arm whose chat wrote no script measured nothing +about the tool. Then compare `score`, `usd` and the token columns. `usd` +and the tokens are the cell's whole bill from its own usage ledger, the +conversation and any task together. diff --git a/bench/scriptbench/check.py b/bench/scriptbench/check.py new file mode 100755 index 0000000000..c6371d40e3 --- /dev/null +++ b/bench/scriptbench/check.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""check.py — the true answer to each scriptbench question, and a reply's score. + +Usage: + check.py truth print the true answer as JSON + check.py score score a reply file; prints JSON + +Every answer is computed from the source with Python's own parser (ast), never +from a model, so a score is a fact about the reply. The reply's answer is its +LAST fenced ```json block; a reply without one scores 0 with a reason. + +The tasks (tasks/.md is the prompt each one is asked with): + + public-defs For every module in src/click except __init__.py: how many + top-level functions and classes whose names do not start with + "_". Score: the share of modules whose two counts are both right. + raisers Every function or method in src/click whose own body raises an + exception class defined in src/click/exceptions.py, as + "file.py:Qualified.name" (nested defs joined with "."; a raise + belongs to the innermost def around it). Score: F1 of the sets. + longest The ten longest functions or methods in src/click by lines, + end_lineno - lineno + 1 (the def line to the last line, not its + decorators). Score: the share of the true ten named with the + right line count; a tie at the tenth place accepts any of the + tied defs. + manual-last For each page in manual_pages.json's list: its title and its + last section heading, read from codeaf's manual. Score: the + share of pages with both exactly right (whitespace collapsed). + manual-find Which of manual_pages.json's pages have a section heading + containing a word that starts with "delet", in any case. + Score: F1 of the sets. + +The manual tasks are checked against MANUAL_TRUTH, a file manualtruth/ writes +from the chat corpus the binary under test ships (run.sh makes it); their + argument is not read. +""" +import ast, json, os, re, sys + +SRC = os.path.join("src", "click") + + +def modules(repo): + base = os.path.join(repo, SRC) + return sorted(n for n in os.listdir(base) if n.endswith(".py")) + + +def parse(repo, name): + with open(os.path.join(repo, SRC, name), encoding="utf-8") as fh: + return ast.parse(fh.read()) + + +def defs(tree): + """Every function or method with its dotted qualified name.""" + out = [] + + def walk(node, prefix): + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + name = prefix + child.name + if not isinstance(child, ast.ClassDef): + out.append((name, child)) + walk(child, name + ".") + else: + walk(child, prefix) + + walk(tree, "") + return out + + +def own_nodes(fn): + """The nodes of fn's body that do not belong to a def nested in it.""" + stack = list(fn.body) + while stack: + node = stack.pop() + yield node + for child in ast.iter_child_nodes(node): + if not isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)): + stack.append(child) + + +def exception_names(repo): + tree = parse(repo, "exceptions.py") + return {n.name for n in tree.body if isinstance(n, ast.ClassDef)} + + +def raised_name(node): + exc = node.exc + if isinstance(exc, ast.Call): + exc = exc.func + if isinstance(exc, ast.Name): + return exc.id + if isinstance(exc, ast.Attribute): + return exc.attr + return None + + +HERE = os.path.dirname(os.path.abspath(__file__)) + +# A WORD THAT STARTS WITH "delet", as manual-find asks: "deleting" and +# "Deletion" match, "undelete" does not. +DELET = re.compile(r"\bdelet", re.IGNORECASE) + + +def manual_truth(): + path = os.environ.get("MANUAL_TRUTH") or os.path.join(HERE, "results", "manual-truth.json") + with open(path, encoding="utf-8") as fh: + corpus = json.load(fh) + with open(os.path.join(HERE, "manual_pages.json"), encoding="utf-8") as fh: + return corpus, json.load(fh) + + +def flat(text): + return " ".join(str(text).split()) + + +def truth(task, repo): + if task == "manual-last": + corpus, pages = manual_truth() + return {p: {"title": corpus[p]["title"], "last": corpus[p]["headings"][-1]} + for p in pages[task] if p in corpus} + if task == "manual-find": + corpus, pages = manual_truth() + return sorted(p for p in pages[task] if p in corpus + and any(DELET.search(h) for h in corpus[p]["headings"])) + if task == "public-defs": + answer = {} + for name in modules(repo): + if name == "__init__.py": + continue + body = parse(repo, name).body + fns = sum(isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and not n.name.startswith("_") for n in body) + cls = sum(isinstance(n, ast.ClassDef) and not n.name.startswith("_") for n in body) + answer[name] = {"functions": fns, "classes": cls} + return answer + if task == "raisers": + names = exception_names(repo) + found = set() + for name in modules(repo): + for qual, fn in defs(parse(repo, name)): + if any(isinstance(n, ast.Raise) and raised_name(n) in names for n in own_nodes(fn)): + found.add(f"{name}:{qual}") + return sorted(found) + if task == "longest": + rows = [] + for name in modules(repo): + for qual, fn in defs(parse(repo, name)): + rows.append({"name": f"{name}:{qual}", "lines": fn.end_lineno - fn.lineno + 1}) + rows.sort(key=lambda r: (-r["lines"], r["name"])) + return rows + raise SystemExit(f"unknown task {task}") + + +def answer_of(reply): + blocks = re.findall(r"```json\s*\n(.*?)```", reply, re.S) + if not blocks: + return None, "no json block" + try: + return json.loads(blocks[-1]), "" + except json.JSONDecodeError as err: + return None, f"json does not parse: {err}" + + +def score(task, repo, reply): + got, why = answer_of(reply) + if got is None: + return {"score": 0.0, "why": why} + want = truth(task, repo) + if task == "public-defs": + if not isinstance(got, dict): + return {"score": 0.0, "why": "answer is not an object"} + right = [m for m, counts in want.items() if isinstance(got.get(m), dict) + and got[m].get("functions") == counts["functions"] and got[m].get("classes") == counts["classes"]] + return {"score": round(len(right) / len(want), 4), "right": len(right), "of": len(want), + "wrong": sorted(set(want) - set(right))} + if task == "manual-last": + if not isinstance(got, dict): + return {"score": 0.0, "why": "answer is not an object"} + right = [p for p, w in want.items() if isinstance(got.get(p), dict) + and flat(got[p].get("title", "")) == flat(w["title"]) and flat(got[p].get("last", "")) == flat(w["last"])] + return {"score": round(len(right) / len(want), 4), "right": len(right), "of": len(want), + "wrong": sorted(set(want) - set(right))} + if task in ("raisers", "manual-find"): + if not isinstance(got, list): + return {"score": 0.0, "why": "answer is not a list"} + g, w = {str(x).strip() for x in got}, set(want) + hit = len(g & w) + p = hit / len(g) if g else 0.0 + r = hit / len(w) if w else 0.0 + f1 = 2 * p * r / (p + r) if p + r else 0.0 + return {"score": round(f1, 4), "precision": round(p, 4), "recall": round(r, 4), + "missed": sorted(w - g), "extra": sorted(g - w)} + if task == "longest": + if not isinstance(got, list): + return {"score": 0.0, "why": "answer is not a list"} + tenth = want[9]["lines"] + allowed = {r["name"]: r["lines"] for r in want if r["lines"] >= tenth} + named = {} + for row in got[:10]: + if isinstance(row, dict): + named[str(row.get("name", "")).strip()] = row.get("lines") + hit = sum(1 for n, lines in named.items() if allowed.get(n) == lines) + return {"score": round(min(hit, 10) / 10, 4), "right": hit, + "true_top": want[:10]} + raise SystemExit(f"unknown task {task}") + + +if __name__ == "__main__": + mode, task, repo = sys.argv[1:4] + if mode == "truth": + print(json.dumps(truth(task, repo), indent=1)) + else: + with open(sys.argv[4], encoding="utf-8") as fh: + print(json.dumps(score(task, repo, fh.read()))) diff --git a/bench/scriptbench/manual_pages.json b/bench/scriptbench/manual_pages.json new file mode 100644 index 0000000000..ad8c6a33e0 --- /dev/null +++ b/bench/scriptbench/manual_pages.json @@ -0,0 +1,75 @@ +{ + "manual-last": [ + "a-dev-box-on-your-own-railway", + "add-or-remove-a-computer", + "automations", + "claude-code-provider", + "collections", + "continuing-a-chat-on-another-computer", + "debug-record", + "empty-screen", + "factory-ai-search", + "forking-and-syncing-a-workspace", + "hints-and-tips", + "kept-running", + "linux-workspace-limits", + "making-pictures-audio-and-video", + "opening-files-from-that-machine", + "places", + "quick-switch-models", + "relay-hosted-or-your-own", + "review", + "running-on-another-machine", + "screen", + "services", + "skills-a-turn-used", + "staying-on-that-machine", + "task-rooms-after-restart", + "team-manager", + "telemetry", + "use-this-on-another-computer", + "when-the-connection-drops" + ], + "manual-find": [ + "accounts", + "add-or-remove-a-computer", + "attaching-files", + "choosing-a-folder", + "claude-code-provider", + "closing-a-chat", + "commands", + "continuing-a-chat-on-another-computer", + "coordination-and-workers", + "delegates", + "empty-screen", + "factory-agentfield", + "factory-jira", + "forking-and-syncing-a-workspace", + "giving-a-password-or-token", + "home", + "kept-running", + "lanes", + "lock-out-a-lost-computer", + "making-pictures-audio-and-video", + "naming-a-device", + "openrouter-credits", + "places", + "questions", + "reaching-this-machine-without-ssh", + "relay-hosted-or-your-own", + "relay-what-it-stores-and-sees", + "running-commands-on-windows", + "running-on-another-machine", + "saved-shapes-of-work", + "sec", + "services", + "settings", + "skills-from-other-tools", + "staying-on-that-machine", + "task-controls", + "tasks", + "team-manager", + "teams-page", + "unattended-run-limits" + ] +} diff --git a/bench/scriptbench/manualtruth/main.go b/bench/scriptbench/manualtruth/main.go new file mode 100644 index 0000000000..6de48e913a --- /dev/null +++ b/bench/scriptbench/manualtruth/main.go @@ -0,0 +1,50 @@ +// Command manualtruth prints what scriptbench's manual questions are checked +// against, read through codeaf's own manual package from the chat corpus the +// binary ships, so the checker and the `manual` tool read one corpus. +// +// For every chat page it prints the page's title (its one "# " heading) and its +// section headings in order, as one JSON object keyed by page name. A page with +// text before its first "## " heading has that text parsed as a section titled +// with the page's own title; it is left out of the headings, because the model +// reading the page sees no such heading. +package main + +import ( + "encoding/json" + "os" + "strings" + + "github.com/Agent-Field/codeaf/internal/manual" +) + +type page struct { + Title string `json:"title"` + Headings []string `json:"headings"` +} + +func main() { + corpus := manual.Chat() + out := map[string]page{} + for _, name := range corpus.Pages() { + text, _ := corpus.Page(name) + var p page + for line := range strings.SplitSeq(text, "\n") { + if title, ok := strings.CutPrefix(line, "# "); ok { + p.Title = strings.TrimSpace(title) + break + } + } + for index, section := range corpus.PageSections(name) { + if index == 0 && section.Title == p.Title { + continue + } + p.Headings = append(p.Headings, section.Title) + } + out[name] = p + } + encoder := json.NewEncoder(os.Stdout) + encoder.SetIndent("", " ") + if err := encoder.Encode(out); err != nil { + os.Exit(1) + } +} diff --git a/bench/scriptbench/run.sh b/bench/scriptbench/run.sh new file mode 100755 index 0000000000..295c710111 --- /dev/null +++ b/bench/scriptbench/run.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# run.sh — the script-tool benchmark: read-heavy questions about one pinned +# repository, each asked of a pair of arms in the same wave, each answer scored +# by check.py against the source itself. +# +# Usage: NEW_BIN= bench/scriptbench/run.sh [task ...] +# tasks default to every tasks/*.md; ARMS, SEEDS and MODEL below can be set. +# +# EVERY CELL IS bench/oneroad/cell.sh, so it is driven through the real chat +# over tmux, from an empty environment, with the same counters and the same +# settling rules; this script only hands it a prompt file and a repository and +# leaves the test suite out (SKIP_SUITE=1), because check.py is the judge here. +set -uo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ONEROAD="$HERE/../oneroad" + +: "${NEW_BIN:?set NEW_BIN to the codeaf binary under test}" +export NEW_BIN +export MODEL="${MODEL:-anthropic/claude-sonnet-5.5}" +ARMS="${ARMS:-codeaf-new-crew codeaf-chatscript-crew}" +SEEDS="${SEEDS:-s1}" +TASKS="${*:-$(cd "$HERE/tasks" && ls *.md | sed 's/\.md$//')}" + +# The corpus: click 8.1.7, sixteen modules and about ten thousand lines, pinned +# so every answer check.py computes is the same answer next month. +export REPO="https://github.com/pallets/click" +export BASE_COMMIT="874ca2bc1c30d93a4ac6e36a15ed685eafe89097" +export RESULTS="$HERE/results" +export SKIP_SUITE=1 +# A question answered in words settles fast; an hour would only be paid by a +# cell that has gone wrong. +export CELL_SECONDS="${CELL_SECONDS:-1200}" +export SILENCE_SECONDS="${SILENCE_SECONDS:-60}" +mkdir -p "$RESULTS" + +# THE MANUAL QUESTIONS ARE CHECKED AGAINST THE BINARY'S OWN CORPUS. The truth is +# read through internal/manual from this checkout, so the checkout's chat pages +# must be the ones the binary was built from; a mismatch would score a correct +# reply as wrong, and the run refuses rather than measure that. +REPO_ROOT="$(git -C "$HERE" rev-parse --show-toplevel)" +BIN_REV="$("$NEW_BIN" --version 2>/dev/null | awk '{print $2}')" +if ! git -C "$REPO_ROOT" rev-parse --verify --quiet "$BIN_REV^{commit}" >/dev/null; then + echo "cannot tell which commit $NEW_BIN was built from (its --version names \"$BIN_REV\"); build it with make build from this checkout" >&2 + exit 1 +fi +if ! git -C "$REPO_ROOT" diff --quiet "$BIN_REV" -- internal/manual/chat; then + echo "the manual in this checkout differs from the one $NEW_BIN ($BIN_REV) ships; build it from here" >&2 + exit 1 +fi +export MANUAL_TRUTH="$RESULTS/manual-truth.json" +(cd "$REPO_ROOT" && go run ./bench/scriptbench/manualtruth) > "$MANUAL_TRUTH" || exit 1 + +# NO CODEAF ON THE CELL'S PATH. `codeaf manual` reads a different corpus from +# the `manual` tool, and a model that shelled out to an installed codeaf would +# be answering from the wrong pages through a road this benchmark is not about. +# Every folder holding a codeaf program leaves the path; the binary under test +# is run by its own path. +clean_path="" +IFS=: read -ra path_dirs <<< "$PATH" +for dir in "${path_dirs[@]}"; do + [ -x "$dir/codeaf" ] && continue + clean_path="${clean_path:+$clean_path:}$dir" +done +export PATH="$clean_path" + +for seed in $SEEDS; do + for task in $TASKS; do + # THE SAME-WAVE RULE (bench/oneroad/wave.sh): both arms of a question start + # together, so provider weather falls on the pair or on neither. + pids=() + for arm in $ARMS; do + SEED="$seed" PROMPT_FILE="$HERE/tasks/$task.md" \ + bash "$ONEROAD/cell.sh" "$arm" "$task" > "$RESULTS/.$arm-$task-$seed.out" 2>&1 & + pids+=($!) + sleep 2 + done + for pid in "${pids[@]}"; do wait "$pid"; done + done +done +python3 "$HERE/score.py" "$RESULTS" diff --git a/bench/scriptbench/score.py b/bench/scriptbench/score.py new file mode 100755 index 0000000000..b0288a1f1d --- /dev/null +++ b/bench/scriptbench/score.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""score.py — score every scriptbench cell and write results.csv. + +Usage: score.py + +For each cell: the conversation's last reply (written to reply.txt beside it) +scored by check.py, the script counts from lib/script_use.py, and the cell's +whole bill read from its own usage ledger (v3/usage.jsonl, every row once), +which counts the conversation and any task alike. Then one line per arm and +task: mean score, mean dollars, mean input and output tokens, scripts written. +""" +import csv, glob, json, os, subprocess, sys +from collections import defaultdict + +HERE = os.path.dirname(os.path.abspath(__file__)) +SCRIPT_USE = os.path.join(HERE, "..", "oneroad", "lib", "script_use.py") + + +def text_of(content): + if isinstance(content, str): + return content + if isinstance(content, list): + return "".join(p.get("text", "") for p in content if isinstance(p, dict)) + return "" + + +def last_reply(cell): + found = glob.glob(os.path.join(cell, "profile", "v3", "projects", "*", "*", ".cell", "transcript.jsonl")) + reply = "" + for path in found: + for line in open(path, encoding="utf-8"): + try: + row = json.loads(line) + except json.JSONDecodeError: + continue + if row.get("type") == "message" and row.get("role") == "assistant": + text = text_of(row.get("content")) + if text.strip(): + reply = text + return reply + + +def bill(cell): + rows = {} + for path in glob.glob(os.path.join(cell, "profile", "v3", "usage.jsonl")): + for line in open(path, encoding="utf-8"): + try: + row = json.loads(line) + except json.JSONDecodeError: + continue + rows[row.get("id") or len(rows)] = row + out = {"usd": 0.0, "in": 0, "out": 0, "cache": 0, "model_calls": 0} + for row in rows.values(): + out["usd"] += float(row.get("usd") or 0) + out["in"] += int(row.get("in") or 0) + out["out"] += int(row.get("out") or 0) + out["cache"] += int(row.get("cache_read") or 0) + out["model_calls"] += int(row.get("calls") or 1) + out["usd"] = round(out["usd"], 6) + return out + + +def main(results): + rows = [] + for meta_path in sorted(glob.glob(os.path.join(results, "*", "meta.json"))): + cell = os.path.dirname(meta_path) + meta = json.load(open(meta_path)) + task = meta.get("task") + reply = last_reply(cell) + with open(os.path.join(cell, "reply.txt"), "w", encoding="utf-8") as fh: + fh.write(reply) + repos = glob.glob(os.path.join(cell, "work", "*")) + if not repos: + # A cell that never cloned has nothing to check a reply against. + print(f"skipping {os.path.basename(cell)}: no repository under work/", file=sys.stderr) + continue + repo = repos[0] + checked = json.loads(subprocess.run( + [sys.executable, os.path.join(HERE, "check.py"), "score", task, repo, os.path.join(cell, "reply.txt")], + capture_output=True, text=True, check=True).stdout) + use = json.loads(subprocess.run([sys.executable, SCRIPT_USE, cell], capture_output=True, text=True, check=True).stdout) + cost = bill(cell) + json.dump({"check": checked, "use": use, "bill": cost}, open(os.path.join(cell, "score.json"), "w"), indent=1) + rows.append({ + "arm": meta.get("harness"), "task": task, "seed": meta.get("seed"), "model": meta.get("model"), + "outcome": meta.get("outcome"), "wall_s": meta.get("wall_s"), "score": checked.get("score"), + "usd": cost["usd"], "tokens_in": cost["in"], "tokens_out": cost["out"], "tokens_cache": cost["cache"], + "model_calls": cost["model_calls"], "road": meta.get("road"), + "chat_steps": use.get("chat_steps"), "chat_scripts": use.get("chat_script_steps"), + "chat_script_calls": use.get("chat_script_calls"), + "worker_steps": use.get("steps"), "worker_scripts": use.get("script_steps"), + }) + if not rows: + print("no cells") + return + with open(os.path.join(results, "results.csv"), "w", newline="") as fh: + writer = csv.DictWriter(fh, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + groups = defaultdict(list) + for row in rows: + groups[(row["task"], row["arm"])].append(row) + print(f"{'task':12} {'arm':24} {'n':>2} {'score':>6} {'usd':>7} {'in':>9} {'out':>7} {'calls':>5} {'steps':>5} {'scripts':>7} {'wall':>5}") + for (task, arm), group in sorted(groups.items()): + n = len(group) + mean = lambda k: sum((r[k] or 0) for r in group) / n + print(f"{task:12} {arm:24} {n:>2} {mean('score'):>6.2f} {mean('usd'):>7.3f} {mean('tokens_in'):>9.0f} " + f"{mean('tokens_out'):>7.0f} {mean('model_calls'):>5.0f} {mean('chat_steps'):>5.0f} " + f"{sum(r['chat_scripts'] or 0 for r in group):>7} {mean('wall_s'):>5.0f}") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/bench/scriptbench/tasks/longest.md b/bench/scriptbench/tasks/longest.md new file mode 100644 index 0000000000..8ded9afe1b --- /dev/null +++ b/bench/scriptbench/tasks/longest.md @@ -0,0 +1,9 @@ +Answer this from the source code in this folder: the click library, whose package is src/click. Work in this conversation yourself: do not start tasks and do not change any file. + +Find the ten longest functions or methods in src/click, measured in lines from the `def` line to the function's last line inclusive (decorators not counted). Name each as "file.py:Qualified.name", nesting joined with dots. + +End your reply with exactly one fenced ```json block holding the answer, in this shape: + +```json +[{"name": "example.py:Widget.__init__", "lines": 120}, {"name": "example.py:load", "lines": 95}] +``` diff --git a/bench/scriptbench/tasks/manual-find.md b/bench/scriptbench/tasks/manual-find.md new file mode 100644 index 0000000000..a0af3b31bd --- /dev/null +++ b/bench/scriptbench/tasks/manual-find.md @@ -0,0 +1,50 @@ +Answer this from codeaf's own manual, which the `manual` tool reads: give it a page name to get that page. Work in this conversation yourself: do not start tasks and do not change any file. + +Of these 40 manual pages, which have at least one section heading (a `##` heading) containing a word that starts with "delet" (delete, deleted, deleting, deletion …), in any letter case? + +- accounts +- add-or-remove-a-computer +- attaching-files +- choosing-a-folder +- claude-code-provider +- closing-a-chat +- commands +- continuing-a-chat-on-another-computer +- coordination-and-workers +- delegates +- empty-screen +- factory-agentfield +- factory-jira +- forking-and-syncing-a-workspace +- giving-a-password-or-token +- home +- kept-running +- lanes +- lock-out-a-lost-computer +- making-pictures-audio-and-video +- naming-a-device +- openrouter-credits +- places +- questions +- reaching-this-machine-without-ssh +- relay-hosted-or-your-own +- relay-what-it-stores-and-sees +- running-commands-on-windows +- running-on-another-machine +- saved-shapes-of-work +- sec +- services +- settings +- skills-from-other-tools +- staying-on-that-machine +- task-controls +- tasks +- team-manager +- teams-page +- unattended-run-limits + +End your reply with exactly one fenced ```json block holding the answer, a list of page names, in this shape: + +```json +["example-page", "another-page"] +``` diff --git a/bench/scriptbench/tasks/manual-last.md b/bench/scriptbench/tasks/manual-last.md new file mode 100644 index 0000000000..c545479953 --- /dev/null +++ b/bench/scriptbench/tasks/manual-last.md @@ -0,0 +1,41 @@ +Answer this from codeaf's own manual, which the `manual` tool reads: give it a page name to get that page. Work in this conversation yourself: do not start tasks and do not change any file. + +For each of these 29 manual pages, give the page's title (its one top-level `#` heading) and the heading of its last section (its last `##` heading), each exactly as written: + +- a-dev-box-on-your-own-railway +- add-or-remove-a-computer +- automations +- claude-code-provider +- collections +- continuing-a-chat-on-another-computer +- debug-record +- empty-screen +- factory-ai-search +- forking-and-syncing-a-workspace +- hints-and-tips +- kept-running +- linux-workspace-limits +- making-pictures-audio-and-video +- opening-files-from-that-machine +- places +- quick-switch-models +- relay-hosted-or-your-own +- review +- running-on-another-machine +- screen +- services +- skills-a-turn-used +- staying-on-that-machine +- task-rooms-after-restart +- team-manager +- telemetry +- use-this-on-another-computer +- when-the-connection-drops + +End your reply with exactly one fenced ```json block holding the answer, in this shape: + +```json +{"example-page": {"title": "An example page", "last": "The heading of its last section"}} +``` + +Include every page listed, with its page name as the key. diff --git a/bench/scriptbench/tasks/public-defs.md b/bench/scriptbench/tasks/public-defs.md new file mode 100644 index 0000000000..7712846895 --- /dev/null +++ b/bench/scriptbench/tasks/public-defs.md @@ -0,0 +1,11 @@ +Answer this from the source code in this folder: the click library, whose package is src/click. Work in this conversation yourself: do not start tasks and do not change any file. + +For every module in src/click except __init__.py, count the top-level functions and the top-level classes whose names do not start with an underscore. Top-level means defined directly in the module, not inside a class or another function. + +End your reply with exactly one fenced ```json block holding the answer, in this shape: + +```json +{"example.py": {"functions": 4, "classes": 2}, "other.py": {"functions": 0, "classes": 1}} +``` + +Include every module, with its file name as the key. diff --git a/bench/scriptbench/tasks/raisers.md b/bench/scriptbench/tasks/raisers.md new file mode 100644 index 0000000000..cd997ea7e5 --- /dev/null +++ b/bench/scriptbench/tasks/raisers.md @@ -0,0 +1,9 @@ +Answer this from the source code in this folder: the click library, whose package is src/click. Work in this conversation yourself: do not start tasks and do not change any file. + +List every function and method in src/click whose own body raises one of the exception classes defined in src/click/exceptions.py (for example `raise BadParameter(...)` or `raise Abort()`). A raise inside a function nested in another belongs to the nested function only. Name each as "file.py:Qualified.name", nesting joined with dots, for example "example.py:Widget.check" or "example.py:Widget.parse.inner". + +End your reply with exactly one fenced ```json block holding the answer, in this shape: + +```json +["example.py:Widget.check", "example.py:Widget.parse.inner"] +``` diff --git a/cmd/codeaf/app.go b/cmd/codeaf/app.go index 45ab00baab..2e9b4a479a 100644 --- a/cmd/codeaf/app.go +++ b/cmd/codeaf/app.go @@ -2970,6 +2970,13 @@ func (b *appBackend) pump(a *appAgent, id string, live *appLive, turn uint64, n } titles := map[string]string{} for event := range events { + // A SCRIPT IS ONE CALL ON THE WIRE. The calls it makes are its own + // business: their rows and the live line stay the script's, as they do + // in the chat (internal/tui3's feed). A question one of them raises is + // not a tool event and still goes out. + if event.FromScript() { + continue + } switch event.Kind { case session.EventModelIdentity: if event.ModelIdentity != nil { diff --git a/cmd/codeaf/app_test.go b/cmd/codeaf/app_test.go index 23ffa8bfa1..daa4a61f71 100644 --- a/cmd/codeaf/app_test.go +++ b/cmd/codeaf/app_test.go @@ -2062,3 +2062,45 @@ func TestAppReopenKeepsTheSavedModel(t *testing.T) { t.Fatalf("reopened=%+v, err=%v", reopened, err) } } + +// A SCRIPT IS ONE CALL ON THE WIRE. The calls it makes carry their script as +// their parent; the app draws the script's own row, and its nested calls are +// neither rows of their own nor the agent's live line. +func TestAppDrawsAScriptAsOneCall(t *testing.T) { + conv := &fakeConversation{script: []session.Event{ + {Kind: session.EventToolBegin, CallID: "s", Tool: "script", Hint: "script"}, + {Kind: session.EventToolBegin, CallID: "s-script-1", Parent: "s", Tool: "bash", Hint: "bash ls"}, + {Kind: session.EventToolEnd, CallID: "s-script-1", Parent: "s", Tool: "bash", Hint: "3 lines"}, + {Kind: session.EventToolBegin, CallID: "s-script-2", Parent: "s", Tool: "read", Hint: "read go.mod"}, + {Kind: session.EventToolFailed, CallID: "s-script-2", Parent: "s", Tool: "read", Hint: "no such file"}, + {Kind: session.EventToolEnd, CallID: "s", Tool: "script", Hint: "script finished"}, + {Kind: session.EventTurnDone}, + }} + var mu sync.Mutex + var opens, releases int + rec := newAppRecorder() + backend := newFakeBackend(rec, fakeOpener(conv, &opens, &releases, &mu)) + defer backend.Close() + agent, err := mustCreate(t, backend, appwire.CreateAsk{Workspace: t.TempDir(), Model: "deepseek/deepseek-v4-flash"}) + if err != nil { + t.Fatal(err) + } + if _, err := backend.Send(agent.ID, "look", ""); err != nil { + t.Fatal(err) + } + rec.waitFor(t, 5*time.Second, appTurnDone) + rec.mu.Lock() + defer rec.mu.Unlock() + tools := 0 + for i, event := range rec.events { + if event == appwire.EventTurnTool { + tools++ + } + if c, ok := rec.data[i].(appwire.AgentChanged); ok && strings.Contains(c.Agent.Line, "go.mod") { + t.Errorf("a script's nested call became the agent's live line: %q", c.Agent.Line) + } + } + if tools != 2 { + t.Errorf("the app drew %d tool events for one script; want its begin and end only", tools) + } +} diff --git a/cmd/codeaf/appfactory_stepstream.go b/cmd/codeaf/appfactory_stepstream.go index da8e7f35bb..fb01b438d0 100644 --- a/cmd/codeaf/appfactory_stepstream.go +++ b/cmd/codeaf/appfactory_stepstream.go @@ -113,7 +113,8 @@ func appStepFollowsItsLine(kind session.EventKind) bool { // stageEvent notes one step event, when the app holds its conversation. func (b *appBackend) stageEvent(file string, event session.Event) { - if !appStepToldKind(event.Kind) { + // A script's own call is not a boundary between the step's words. + if !appStepToldKind(event.Kind) || event.FromScript() { return } stream := b.stepStreamOf(appAgentID(file)) diff --git a/cmd/codeaf/appfactory_stepstream_test.go b/cmd/codeaf/appfactory_stepstream_test.go index 6d3af97c71..ecaad79fdb 100644 --- a/cmd/codeaf/appfactory_stepstream_test.go +++ b/cmd/codeaf/appfactory_stepstream_test.go @@ -396,3 +396,19 @@ func TestAStageToldItsEventsWithItsJournal(t *testing.T) { t.Fatalf("heard %+v", got) } } + +// A SCRIPT'S OWN CALL IS NOT A BOUNDARY in a held step's words: the words on +// either side of it are one message. +func TestAScriptsCallDoesNotSplitAStepsWords(t *testing.T) { + backend, rec, transcript, id := heldStepChat(t) + backend.stageEvent(transcript, session.Event{Kind: session.EventTextDelta, Text: "one "}) + backend.stageEvent(transcript, session.Event{Kind: session.EventToolBegin, Tool: "bash", CallID: "s-script-1", Parent: "s"}) + backend.stageEvent(transcript, session.Event{Kind: session.EventToolEnd, Tool: "bash", CallID: "s-script-1", Parent: "s"}) + backend.stageEvent(transcript, session.Event{Kind: session.EventTextDelta, Text: "two"}) + deltas := waitDeltas(t, rec, id, "one two") + for _, d := range deltas[1:] { + if d.Msg != deltas[0].Msg { + t.Fatalf("a script's call split the words into messages %d and %d", deltas[0].Msg, d.Msg) + } + } +} diff --git a/cmd/codeaf/appwork.go b/cmd/codeaf/appwork.go index b7d0bef4e5..dc2ceb8491 100644 --- a/cmd/codeaf/appwork.go +++ b/cmd/codeaf/appwork.go @@ -639,6 +639,10 @@ func appInFlight(entries []session.DisplayEntry) *session.DisplayEntry { // pilot folds one task's call events into its line until the lane closes. func (b *appBackend) pilot(live *appLive, key string, lane <-chan session.Event) { for event := range lane { + // A SCRIPT IS ONE CALL ON THE LINE: its own calls never move it. + if event.FromScript() { + continue + } var call string switch event.Kind { case session.EventToolAnnounced, session.EventToolBegin: diff --git a/cmd/codeaf/chatv3.go b/cmd/codeaf/chatv3.go index a2eef68c13..85e180f832 100644 --- a/cmd/codeaf/chatv3.go +++ b/cmd/codeaf/chatv3.go @@ -3141,6 +3141,15 @@ func runChatV3Once(ctx context.Context, cfg session.Config, workspace, text, lev // session more often than the wall itself is read. const unattendedRunSettleTick = time.Second +// headlessNesting indents a line about a call a script made, so a headless log +// reads as the script's step with its calls under it. +func headlessNesting(event session.Event) string { + if event.FromScript() { + return " " + } + return "" +} + // drainOnceEvents is the one rendering of a headless chat turn, shared by the // first turn, every turn the session wakes, and the connected one-message door. // Reply text alone goes to stdout; every line the door itself says goes to @@ -3167,7 +3176,7 @@ func drainOnceEvents(events <-chan session.Event, stdout, stderr io.Writer) erro case session.EventToolBegin: newline() - fmt.Fprintln(stderr, "tool: "+tui3.ToolGloss(event.Tool, event.Hint)) + fmt.Fprintln(stderr, "tool: "+headlessNesting(event)+tui3.ToolGloss(event.Tool, event.Hint)) case session.EventToolFailed: newline() @@ -3175,7 +3184,7 @@ func drainOnceEvents(events <-chan session.Event, stdout, stderr io.Writer) erro if reason == "" && event.Err != nil { reason = event.Err.Error() } - fmt.Fprintln(stderr, "tool: "+event.Tool+" failed: "+reason) + fmt.Fprintln(stderr, "tool: "+headlessNesting(event)+event.Tool+" failed: "+reason) case session.EventCompacted: newline() diff --git a/cmd/codeaf/factory_stage.go b/cmd/codeaf/factory_stage.go index c9ebefd370..1d4f67a3e0 100644 --- a/cmd/codeaf/factory_stage.go +++ b/cmd/codeaf/factory_stage.go @@ -482,6 +482,11 @@ func (c *stageConversation) drain(events <-chan session.Event) { } for event := range events { tellStageNews(c.file, event) + // A SCRIPT IS ONE CALL IN THE ITEM'S LOG. The calls it made are its own + // data, and a failure it caught is not the stage's. + if event.FromScript() { + continue + } switch event.Kind { case session.EventTextDelta: if c.progress != nil && prose.Len() < 4*1024 { diff --git a/cmd/codeaf/script_surfaces_test.go b/cmd/codeaf/script_surfaces_test.go new file mode 100644 index 0000000000..4eacfef04e --- /dev/null +++ b/cmd/codeaf/script_surfaces_test.go @@ -0,0 +1,72 @@ +package main + +import ( + "bytes" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/session" +) + +// scriptEvents is a script that made two calls, the second of which failed. +func scriptEvents() []session.Event { + return []session.Event{ + {Kind: session.EventToolBegin, Tool: "script", CallID: "s", Hint: "script"}, + {Kind: session.EventToolBegin, Tool: "bash", CallID: "s-script-1", Parent: "s", Hint: "ls", Args: `{"command":"ls"}`}, + {Kind: session.EventToolEnd, Tool: "bash", CallID: "s-script-1", Parent: "s"}, + {Kind: session.EventToolBegin, Tool: "bash", CallID: "s-script-2", Parent: "s", Hint: "cat x", Args: `{"command":"cat x"}`}, + {Kind: session.EventToolFailed, Tool: "bash", CallID: "s-script-2", Parent: "s", Hint: "no such file"}, + {Kind: session.EventToolEnd, Tool: "script", CallID: "s"}, + } +} + +// A STAGE'S LOG CAPTIONS A SCRIPT AS ONE CALL. The calls it made are the +// script's own data, and a failure the script caught is not the stage's. +func TestAStageCaptionsAScriptAsOneCall(t *testing.T) { + c := &stageConversation{captions: make(chan string, 16)} + events := make(chan session.Event, 16) + for _, event := range scriptEvents() { + events <- event + } + close(events) + c.drain(events) + close(c.captions) + var tools []string + for caption := range c.captions { + if strings.HasPrefix(caption, factory.ToolCaptionPrefix) { + tools = append(tools, caption) + } + } + if len(tools) != 1 || !strings.Contains(tools[0], "script") { + t.Errorf("tool captions = %q; want the script's one", tools) + } +} + +// A HEADLESS TURN PRINTS A SCRIPT'S CALLS INDENTED UNDER IT, so the log reads +// as one step with its calls rather than as steps of their own. +func TestAHeadlessTurnIndentsAScriptsCalls(t *testing.T) { + events := make(chan session.Event, 16) + for _, event := range scriptEvents() { + events <- event + } + events <- session.Event{Kind: session.EventTurnDone} + close(events) + var stdout, stderr bytes.Buffer + if err := drainOnceEvents(events, &stdout, &stderr); err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(stderr.String()), "\n") + var top, nested int + for _, line := range lines { + switch { + case strings.HasPrefix(line, "tool: "): + nested++ + case strings.HasPrefix(line, "tool: "): + top++ + } + } + if top != 1 || nested != 3 { + t.Errorf("stderr has %d top-level and %d indented tool lines; want 1 and 3:\n%s", top, nested, stderr.String()) + } +} diff --git a/docs/changes/unreleased/2815-script-tool.md b/docs/changes/unreleased/2815-script-tool.md new file mode 100644 index 0000000000..e5526a8a14 --- /dev/null +++ b/docs/changes/unreleased/2815-script-tool.md @@ -0,0 +1,50 @@ +--- +kind: added +title: A script tool that combines tool calls in one JavaScript step, off by default +pr: 2815 +surface: [engine, chat, docs] +invalidates: + - "Was true: every tool call a bash-belt task made was a step of its own on its trajectory. Is true now: a script is one step, and the calls it made are recorded as calls on that step and drawn under it on the task page and in the live view." + - "Was true: the plan store's live step named only a step number and a command. Is true now: it also names the tool the step is running, so a running script is drawn as a script." +--- + +Both switches are off by default. With `CODEAF_TASK_SCRIPT=on`, a bash-belt task +worker carries `script`, whether a plan run or the chat started the task; with +`CODEAF_CHAT_SCRIPT=on`, the conversation does. A script's JavaScript calls the +other tools through the same approval gate as a direct call, and only what it +prints or returns comes back. It is not Node.js: files and commands go through +`tools.bash`. Up to 4 calls run at once; a script stops after 200 calls, 10 +minutes or 16 MiB of output, and a call refused for its own arguments does not +count. Inside a script, `bash` answers its output and exit code as an object +and every other tool answers its text. A script can call only `bash`, `read`, +`ls`, `grep`, `find`, `read_document`, `manual`, `recall`, `web_search` +and `web_fetch`; every other tool is refused inside one, so a script cannot +edit files, ask the person anything or start work. A script reached through a +saved program meets the same approval rules, and a script with no turn to check +its calls against does not run. A quick task's worker never carries `script`. +A script's memory is not limited. A script that ends without waiting for a +call says how many it left; those still running are cancelled. Inside a script, +`read` always returns the file, never the pointer to bytes the conversation +already holds, and no result carries the background-job footer, which is kept +for the model's next result. The app and the remote surface draw a script as +one call, as the chat does, and the chat draws a script's calls straight under +it even when the model ran other calls beside it. A failing check run inside a +script counts as a check the task ran, a script's count of calls includes only +calls that ran, and words in a script's source are not read as plan writes. A factory item's +log captions a script as one call, and a headless turn prints a script's calls +indented under it. + +A script is one step: it counts once against a task's step limit and in the +step count the worker and the task's room show. The plan writes its `bash` +calls make are recorded as the script step's writes. A script that reads counts +as progress, so a task exploring through scripts is not stopped for making no +progress. In a conversation, a script's `bash` sees up to 1 MiB of output, as a +task's does, although the conversation's own `bash` keeps only the tail, and a +reopened conversation still draws a script's calls under it. + +Measured with `bench/scriptbench` (Sonnet 5.5, three seeds): on questions +that need a `manual` lookup per page, the chat with the tool cost 4.5x and +8.7x less for the same answers. Where `bash` can do the work in one command, +and in `bench/oneroad`'s code changes, models did not use it and it changed +nothing. The benchmark cells also now start every harness from an empty +environment and record a cell stopped at an approval prompt as blocked. diff --git a/internal/config/settings.go b/internal/config/settings.go index ec1d67be04..8d04c6bb23 100644 --- a/internal/config/settings.go +++ b/internal/config/settings.go @@ -1411,6 +1411,16 @@ var OperatorEnvPins = []string{ // whoever set it had forgotten, and an escape hatch must be as easy to // stop using as it was to start. It disappears when the older belt does. "CODEAF_TASK_BELT", + // CODEAF_TASK_SCRIPT arms the script tool on a bash-belt worker + // (internal/session's tool_script.go) while it is measured against the + // belt without it. It is plumbing for CODEAF_TASK_BELT's reason: an + // experiment's switch must be as easy to stop using as it was to start, + // and a saved row would keep a machine on one arm long after whoever set it + // forgot. It flips or disappears once the measurement decides. + "CODEAF_TASK_SCRIPT", + // CODEAF_CHAT_SCRIPT arms the same tool on a conversation's own belt, as a + // separate arm of the same measurement, on CODEAF_TASK_SCRIPT's terms. + "CODEAF_CHAT_SCRIPT", // CODEAF_PLANDB_BIN names the binary a bash-belt worker's `plandb` shim // execs (internal/session's plandb_plan.go) when the running program is // not the codeaf binary — a bench driving the task door in-process is the diff --git a/internal/exec/bare/tools.go b/internal/exec/bare/tools.go index a9b47df221..ba7ca3cfca 100644 --- a/internal/exec/bare/tools.go +++ b/internal/exec/bare/tools.go @@ -438,6 +438,16 @@ func RunBash(ctx context.Context, cwd string, args json.RawMessage, caps Caps, o return newBashTool(cwd, caps).Execute(WithBashOutput(ctx, output), args) } +// BashToolCapped is bash alone, built as [AllToolsCapped] builds it, for a +// caller that needs only the shell; ok is false where bash is not available. +func BashToolCapped(cwd string, caps Caps) (tool Tool, ok bool) { + tools := availableTools([]Tool{newBashTool(cwd, caps.resolve())}) + if len(tools) == 0 { + return Tool{}, false + } + return tools[0], true +} + func newBashTool(cwd string, caps Caps) Tool { caps = caps.resolve() return Tool{ @@ -729,7 +739,7 @@ func newBashTool(cwd string, caps Caps) Tool { observe(exitCode) } if exitCode != 0 { - return appendStatus(text, fmt.Sprintf("Command exited with code %d", exitCode)), true, nil + return appendStatus(text, ExitStatusLine(exitCode)), true, nil } return text, false, nil @@ -749,6 +759,11 @@ func startFailedText(goos string, err error) string { return "Failed to start command: " + reason + "\n" + advice + "\nWindows said: " + err.Error() } +// ExitStatusLine is the status line a non-zero exit appends to bash's output, +// exported so a caller that receives the code as data ([WithBashExit]) can +// take the line back off without spelling it a second time. +func ExitStatusLine(code int) string { return fmt.Sprintf("Command exited with code %d", code) } + // appendStatus mirrors pi's bash.js:appendStatus: join text and status with // "\n\n", or just status if text is empty. func appendStatus(text, status string) string { diff --git a/internal/jsrun/fuel.go b/internal/jsrun/fuel.go index 03faf659e6..9642fecd6d 100644 --- a/internal/jsrun/fuel.go +++ b/internal/jsrun/fuel.go @@ -29,6 +29,10 @@ import ( // [goja.InterruptedError.Value], which is how the reason survives the unwinding. type halt struct{ why string } +// stoppedWhy is the reason a cancelled run gives, wherever the cancellation is +// noticed first: by the watchdog, or by a host whose call came back cancelled. +const stoppedWhy = "it was stopped before it finished." + // watch starts the deadline watchdog and returns the function that stops it. // // IT IS THE ONE OTHER GOROUTINE A RUN HAS, and everything it touches is either @@ -37,8 +41,19 @@ type halt struct{ why string } // reads no part of the recorder and no part of the interpreter's state, which is // what lets the rest of this package state that host calls are serial and mean // it. -func watch(ctx context.Context, vm *goja.Runtime, wall time.Duration) func() { +// +// IT ALSO TELLS whoever is waiting outside the interpreter. An interrupt takes +// effect only while JavaScript runs, and a host waiting on a call in flight +// runs none, so the reason is also handed to told — once, without blocking. +func watch(ctx context.Context, vm *goja.Runtime, wall time.Duration, told chan<- string) func() { done := make(chan struct{}) + tell := func(reason halt) { + vm.Interrupt(reason) + select { + case told <- reason.why: + default: + } + } go func() { timer := time.NewTimer(wall) defer timer.Stop() @@ -50,9 +65,9 @@ func watch(ctx context.Context, vm *goja.Runtime, wall time.Duration) func() { // not finish, which is exactly what Incomplete means. Reporting it // as an error would send the caller's deoptimization path off to do // the work the long way after a person asked for it to stop. - vm.Interrupt(halt{why: "it was stopped before it finished."}) + tell(halt{why: stoppedWhy}) case <-timer.C: - vm.Interrupt(halt{why: fmt.Sprintf("it ran out of time — it had %s.", spellDuration(wall))}) + tell(halt{why: fmt.Sprintf("it ran out of time — it had %s.", spellDuration(wall))}) } }() return func() { close(done) } @@ -64,12 +79,16 @@ func watch(ctx context.Context, vm *goja.Runtime, wall time.Duration) func() { // what the run may DO and a call that has already been made cannot be un-made — // nor un-billed. The step is counted whether the call succeeds or not: a refused // tool and a failed model call are both things the program did. -func (h *host) spendStep() bool { - if h.rec.steps >= h.fuel.steps() { - h.stop(halt{why: fmt.Sprintf("it ran out of room — it had %d steps to work in.", h.fuel.steps())}) +func (m *machine) spendStep() bool { + if m.rec.steps >= m.limits.steps { + why := fmt.Sprintf("it ran out of room — it had %d steps to work in.", m.limits.steps) + if m.limits.stepUnit != "" { + why = fmt.Sprintf("it reached its limit of %d %s.", m.limits.steps, m.limits.stepUnit) + } + m.stop(halt{why: why}) return false } - h.rec.steps++ + m.rec.steps++ return true } @@ -81,12 +100,12 @@ func (h *host) spendStep() bool { // spent, and a budget checked against a second tally would be a budget about a // different run. Zero is no ceiling — a caller that was given no grant does not // get one invented for it. -func (h *host) spendTokens() { - if h.fuel.Tokens <= 0 { +func (m *machine) spendTokens() { + if m.limits.tokens <= 0 { return } - if spent := h.rec.spend.Input + h.rec.spend.Output; spent >= h.fuel.Tokens { - h.stop(halt{why: fmt.Sprintf("it ran out of what it had to spend — %d tokens.", h.fuel.Tokens)}) + if spent := m.rec.spend.Input + m.rec.spend.Output; spent >= m.limits.tokens { + m.stop(halt{why: fmt.Sprintf("it ran out of what it had to spend — %d tokens.", m.limits.tokens)}) } } @@ -97,6 +116,6 @@ func (h *host) spendTokens() { // instructions, so the program gets no further, while a Go panic thrown out of a // bound function would escape the interpreter's own recovery and land in this // package as a crash. The value this host call is about to return is never used. -func (h *host) stop(reason halt) { - h.vm.Interrupt(reason) +func (m *machine) stop(reason halt) { + m.vm.Interrupt(reason) } diff --git a/internal/jsrun/host.go b/internal/jsrun/host.go index 04bc03ee67..d39bc46e8d 100644 --- a/internal/jsrun/host.go +++ b/internal/jsrun/host.go @@ -36,19 +36,24 @@ import ( // calls are ordinary synchronous calls, and a program that wants a sequence // writes a sequence. type host struct { - runner *Runner - ctx context.Context - vm *goja.Runtime - rec *recorder - fuel Fuel - input any - unwatch func() + *machine + runner *Runner + input any } // newHost builds the interpreter for one run and binds the six doors into it. func (r *Runner) newHost(ctx context.Context, input any, rec *recorder) (*host, error) { - vm := goja.New() - h := &host{runner: r, ctx: ctx, vm: vm, rec: rec, fuel: r.bundle.Fuel, input: input} + fuel := r.bundle.Fuel + h := &host{ + machine: newMachine(ctx, rec, limits{ + steps: fuel.steps(), + tokens: fuel.Tokens, + wall: fuel.wall(r.bundle.Manifest.SubharnessInfo), + }), + runner: r, + input: input, + } + vm := h.vm // The Env is handed this bundle's prompt assets where it asked for them, so // that the ref the journal records can be resolved to the text the model @@ -74,18 +79,10 @@ func (r *Runner) newHost(ctx context.Context, input any, rec *recorder) (*host, return nil, fmt.Errorf("%q could not be handed its input: %w", r.bundle.Manifest.Name, err) } - h.unwatch = watch(ctx, vm, h.fuel.wall(r.bundle.Manifest.SubharnessInfo)) + h.watch() return h, nil } -// close stops the watchdog. A run that finished on its own must not leave a -// goroutine waiting to interrupt an interpreter nobody is using. -func (h *host) close() { - if h.unwatch != nil { - h.unwatch() - } -} - // execute evaluates the bundle and reads its answer out. func (h *host) execute() (goja.Value, error) { value, err := h.vm.RunProgram(h.runner.program) @@ -98,18 +95,6 @@ func (h *host) execute() (goja.Value, error) { return value, nil } -// throw raises a JavaScript error inside the program. -// -// A FAILED DOOR IS CATCHABLE AND A SPENT BUDGET IS NOT, and the difference is -// deliberate: a tool that was not there, a prompt that does not exist, a model -// call that failed are all things a program may legitimately have a plan B for, -// so they arrive as ordinary exceptions. Running out of fuel arrives through the -// interrupt (fuel.go), which no `catch` can reach. An error that nobody catches -// ends the run as a fallback, which is [Runner.stopped]'s job. -func (h *host) throw(err error) { - panic(h.vm.NewGoError(err)) -} - // ── ai ────────────────────────────────────────────────────────────────────── // ai is one model call, named by a prompt asset in the bundle. @@ -243,18 +228,6 @@ func (h *host) aiOptions(value goja.Value) (exec.AIOptions, error) { return opts, nil } -// parse hands structured JSON back to the program as a JavaScript value, -// falling back to the text when the bytes will not parse. A model that promised -// a shape and sent something else is the Env's problem to report; this door's -// job is not to lose what did come back. -func (h *host) parse(raw json.RawMessage, fallback string) goja.Value { - var decoded any - if err := json.Unmarshal(raw, &decoded); err != nil { - return h.vm.ToValue(fallback) - } - return h.vm.ToValue(decoded) -} - // ── tool ──────────────────────────────────────────────────────────────────── // tool calls one belt tool, THROUGH THE MANIFEST'S WHITELIST FIRST. diff --git a/internal/jsrun/machine.go b/internal/jsrun/machine.go new file mode 100644 index 0000000000..f0bca26b90 --- /dev/null +++ b/internal/jsrun/machine.go @@ -0,0 +1,104 @@ +package jsrun + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/dop251/goja" +) + +// THE MACHINE: one goja interpreter, its three ceilings and its recorder. +// +// It is what a host runs ON, and nothing about what a host EXPOSES. The saved +// program's host (host.go) binds the six doors of [exec.Env] onto it; anything +// else this package runs binds its own surface onto the same machine and gets +// the same ceilings, the same uncatchable stop and the same journal ordering +// without a second copy of any of them. Keeping the machine free of bundles, +// manifests and prompts is the point of the split: those are facts about a +// saved program, and a machine that knew them could only ever run one. +type machine struct { + ctx context.Context + vm *goja.Runtime + rec *recorder + limits limits + unwatch func() + // halted carries the watchdog's reason to a host waiting outside the + // interpreter (fuel.go's watch). It holds one reason and is never closed. + halted chan string +} + +// limits are the three ceilings with every default already applied. The host +// that builds a machine resolves them ([Fuel.steps], [Fuel.wall]); the machine +// only enforces, so no default is spelled twice. +type limits struct { + // steps is how many host calls the program may make. + steps int + // tokens is the ceiling on the recorder's ledger. Zero is no ceiling. + tokens int + // wall is the deadline the watchdog enforces. + wall time.Duration + // stepUnit names what steps counts in the sentence a spent ceiling gives; + // empty is "steps". A script's ceiling is on tool calls, and calling them + // steps would read as the task's own step budget ending. + stepUnit string +} + +// newMachine builds a fresh interpreter. The watchdog is NOT started here: a +// host binds its surface first, and a host that fails to bind must not leave a +// goroutine waiting to interrupt an interpreter that will never run. +func newMachine(ctx context.Context, rec *recorder, ceilings limits) *machine { + return &machine{ctx: ctx, vm: goja.New(), rec: rec, limits: ceilings, halted: make(chan string, 1)} +} + +// watch starts the deadline watchdog for this machine. +func (m *machine) watch() { + m.unwatch = watch(m.ctx, m.vm, m.limits.wall, m.halted) +} + +// close stops the watchdog. A run that finished on its own must not leave a +// goroutine waiting to interrupt an interpreter nobody is using. +func (m *machine) close() { + if m.unwatch != nil { + m.unwatch() + } +} + +// throw raises a JavaScript error inside the program. +// +// A FAILED DOOR IS CATCHABLE AND A SPENT BUDGET IS NOT, and the difference is +// deliberate: a tool that was not there, a prompt that does not exist, a model +// call that failed are all things a program may legitimately have a plan B for, +// so they arrive as ordinary exceptions. Running out of fuel arrives through the +// interrupt (fuel.go), which no `catch` can reach. An error that nobody catches +// ends the run, and the host that owns the run decides what that means. +func (m *machine) throw(err error) { + panic(m.vm.NewGoError(err)) +} + +// parse hands structured JSON back to the program as a JavaScript value, +// falling back to the text when the bytes will not parse. A door that promised +// a shape and sent something else is the Env's problem to report; this +// machine's job is not to lose what did come back. +func (m *machine) parse(raw json.RawMessage, fallback string) goja.Value { + var decoded any + if err := json.Unmarshal(raw, &decoded); err != nil { + return m.vm.ToValue(fallback) + } + return m.vm.ToValue(decoded) +} + +// interruption reads why the machine was stopped, when it was. A stop that +// carries no [halt] — an interrupt this package did not raise — still ends the +// run, with the plainest true sentence. +func interruption(err error) (string, bool) { + var interrupted *goja.InterruptedError + if !errors.As(err, &interrupted) { + return "", false + } + if stop, ok := interrupted.Value().(halt); ok { + return stop.why, true + } + return "it stopped before it finished.", true +} diff --git a/internal/jsrun/runner.go b/internal/jsrun/runner.go index b34b038fc2..75a995f789 100644 --- a/internal/jsrun/runner.go +++ b/internal/jsrun/runner.go @@ -150,12 +150,7 @@ func (r *Runner) stopped(err error, rec *recorder) (exec.RunResult, bool) { if err == nil { return exec.RunResult{}, false } - var interrupted *goja.InterruptedError - if errors.As(err, &interrupted) { - why := "it stopped before it finished." - if stop, ok := interrupted.Value().(halt); ok { - why = stop.why - } + if why, interrupted := interruption(err); interrupted { return exec.RunResult{Incomplete: why, Report: rec.report, Spend: rec.spend}, true } fellBack := "it stopped partway through — " + brief(err) diff --git a/internal/jsrun/script.go b/internal/jsrun/script.go new file mode 100644 index 0000000000..c2ee3d19d5 --- /dev/null +++ b/internal/jsrun/script.go @@ -0,0 +1,439 @@ +package jsrun + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "sync" + "sync/atomic" + "time" + "unicode" + + "github.com/dop251/goja" +) + +// THE SCRIPT HOST: a model-written program that calls tools, on the same +// machine a saved program runs on. +// +// A saved program is a bundle with a manifest, prompts and a typed answer; a +// script is none of those. It is the body of one async function, it reaches the +// world only through `tools.(args)`, and what it prints or returns is the +// whole of what the model reads back. Everything a tool call does on the way — +// the gate, the fence, the record — belongs to the caller handed in, so this +// file adds no policy of its own: a second gate here would be a gate the +// session's own chokepoint does not know about. +// +// CALLS RUN AT THE SAME TIME, AND ONLY THIS GOROUTINE TOUCHES THE INTERPRETER. +// goja is not safe across goroutines, so a call's own goroutine runs the caller +// and nothing else: it hands its answer back on a channel, and the waiting loop +// in [RunScript] settles the promise here, which runs the script's reactions. +// The loop ends when the script's own promise settles, when nothing is left in +// flight that could settle it, or when the watchdog stops the script. Calls +// still in flight are then cancelled and waited for, so every one of them ends +// recorded and none outlives the script. + +// ScriptCaller runs one tool call for a script. A string answer reaches the +// script as a string; any other JSON-shaped value as the matching JavaScript +// value. An error reaches it as a rejected promise carrying the error's text. +type ScriptCaller func(ctx context.Context, name string, args map[string]any) (any, error) + +// ScriptLimits are a script's ceilings and how many calls it may have out. A zero takes the default below, +// so a caller states only what it means to change. +type ScriptLimits struct { + // Calls is how many tool calls the script may make. + Calls int + // Wall is the deadline for the whole script. + Wall time.Duration + // Output is how many bytes of text the script may produce. It bounds what + // the script holds for the model, and the cut to the model's window is the + // caller's, after this. + Output int + // Parallel is how many calls may be in flight at once; more wait their turn. + Parallel int +} + +// The defaults are backstops against a runaway script, not a shape an author +// should plan around. +const ( + DefaultScriptCalls = 200 + DefaultScriptWall = 10 * time.Minute + DefaultScriptOutput = 16 << 20 + DefaultScriptParallel = 4 +) + +func (l ScriptLimits) resolve() ScriptLimits { + if l.Calls <= 0 { + l.Calls = DefaultScriptCalls + } + if l.Wall <= 0 { + l.Wall = DefaultScriptWall + } + if l.Output <= 0 { + l.Output = DefaultScriptOutput + } + if l.Parallel <= 0 { + l.Parallel = DefaultScriptParallel + } + return l +} + +// ScriptResult is how one script ended. At most one of Failed and Stopped is +// set; neither set is a script that finished. +type ScriptResult struct { + // Output is the text items and the return value in order, then the console + // lines. A script that failed or stopped keeps what it produced before. + Output string + // Failed is the error nobody caught, in one line. + Failed string + // Stopped is why a ceiling or a cancellation ended the script. + Stopped string + // Calls is how many tool calls ran: a call still queued when the script + // ended was cancelled before it ran and is not counted. + Calls int + // Unawaited is how many calls a script that finished had started and not + // waited for: any still running were cancelled when it ended, and their + // answers, errors included, were dropped. + Unawaited int +} + +// neverSettles is the failure for a script whose own promise is still pending +// when nothing it waits on can move: there are no timers, so a promise with no +// call behind it never settles. +const neverSettles = "the script is waiting on something that can never finish" + +// RunScript runs one script. tools is every name the script may call; a name +// that is not a JavaScript identifier is also reachable with its other +// characters written as _. +func RunScript(ctx context.Context, source string, tools []string, call ScriptCaller, ceilings ScriptLimits) ScriptResult { + ceilings = ceilings.resolve() + // THE WRAPPER SHARES THE FIRST LINE, so goja's line numbers in an error are + // the line numbers the model wrote. + program, err := goja.Compile("script", "(async () => {"+source+"\n})()", false) + if err != nil { + return ScriptResult{Failed: brief(err)} + } + + callCtx, cancel := context.WithCancel(ctx) + s := &script{ + machine: newMachine(ctx, &recorder{}, limits{steps: ceilings.Calls, wall: ceilings.Wall, stepUnit: "tool calls"}), + call: call, + callCtx: callCtx, + max: ceilings.Output, + slots: make(chan struct{}, ceilings.Parallel), + done: make(chan finished), + } + if err := s.bind(tools); err != nil { + cancel() + return ScriptResult{Failed: err.Error()} + } + s.watch() + defer s.close() + + var result ScriptResult + value, runErr := s.vm.RunProgram(program) + switch why, stopped := interruption(runErr); { + case stopped: + result.Stopped = why + case runErr != nil: + result.Failed = brief(runErr) + default: + s.await(value, &result) + } + // Every call still out is cancelled and waited for; each returns promptly + // and its answer is dropped, so none outlives the script. + if s.overflow != "" && result.Stopped == "" { + result.Stopped, result.Failed = s.overflow, "" + } + // A FINISHED SCRIPT SAYS WHAT IT LEFT BEHIND. A call started without await + // is cancelled below, and a result that only said "finished" would read as + // if that work had been done. + if result.Stopped == "" && result.Failed == "" { + result.Unawaited = s.inflight + } + cancel() + s.running.Wait() + result.Calls = int(s.ran.Load()) + result.Output = s.output() + return result +} + +// script is one run's host: the machine, the caller, and what the script has +// said so far. +type script struct { + *machine + call ScriptCaller + callCtx context.Context + max int + written int + items []string + console []string + + // slots bounds the calls in flight; done carries each finished call back + // to this goroutine; inflight and running count what is still out, the + // first for the waiting loop and the second for [script.drain]. + slots chan struct{} + done chan finished + inflight int + running sync.WaitGroup + // ran counts the calls that reached the caller. A call is booked against + // the ceiling when the script makes it, but one still queued for a slot + // when the script ends never runs and is not a call made. + ran atomic.Int64 + // overflow is why the output ceiling stopped the script, kept for the + // stop [script.say] makes after the interpreter has finished, where an + // interrupt would reach nothing. + overflow string +} + +// finished is one call's answer on its way back to the interpreter's goroutine. +// Settling it there is an ordinary call into the interpreter, and an interrupt +// raised while the script's reactions run comes back as the error. +type finished struct { + settle func(any) error + answer any + err error + reject func(any) error +} + +// bind puts the script's surface on the machine: tools, text and console. +func (s *script) bind(names []string) error { + tools := s.vm.NewObject() + bound := make(map[string]bool, len(names)) + for _, name := range names { + if err := tools.Set(name, s.tool(name)); err != nil { + return fmt.Errorf("the script could not be given %s: %w", name, err) + } + bound[name] = true + } + // AN ALIAS NEVER TAKES A TOOL'S OWN NAME, nor another alias already given, + // so tools. always reaches the tool spelled x when there is one. + for _, name := range names { + alias := identifier(name) + if bound[alias] { + continue + } + if err := tools.Set(alias, s.tool(name)); err != nil { + return fmt.Errorf("the script could not be given %s: %w", name, err) + } + bound[alias] = true + } + console := s.vm.NewObject() + for _, level := range []string{"log", "info", "warn", "error", "debug"} { + if err := console.Set(level, s.log); err != nil { + return fmt.Errorf("the script could not be given console.%s: %w", level, err) + } + } + for name, value := range map[string]any{"tools": tools, "console": console, "text": s.text} { + if err := s.vm.Set(name, value); err != nil { + return fmt.Errorf("the script could not be given %s: %w", name, err) + } + } + return nil +} + +// tool is one tool's door: it books the call, runs it, and answers a promise. +func (s *script) tool(name string) func(goja.FunctionCall) goja.Value { + return func(call goja.FunctionCall) goja.Value { + // THE ARGUMENTS ARE READ BEFORE THE CALL IS BOOKED: a call turned away + // here never ran, so it spends nothing and is not a call made. + promise, resolve, reject := s.vm.NewPromise() + args, err := callArguments(name, call.Argument(0)) + if err != nil { + _ = reject(s.error(err.Error())) + return s.vm.ToValue(promise) + } + if !s.spendStep() { + return goja.Undefined() + } + s.inflight++ + s.running.Add(1) + go s.run(name, args, resolve, reject) + return s.vm.ToValue(promise) + } +} + +// run is one call on its own goroutine. It touches the caller and the +// channels and never the interpreter. +func (s *script) run(name string, args map[string]any, resolve, reject func(any) error) { + defer s.running.Done() + back := finished{settle: resolve, reject: reject} + select { + case s.slots <- struct{}{}: + // A SLOT FREED BY THE SCRIPT'S ENDING IS NOT AN INVITATION: when both + // cases are ready the select picks either, so the ending is asked again. + if back.err = s.callCtx.Err(); back.err == nil { + s.ran.Add(1) + back.answer, back.err = s.call(s.callCtx, name, args) + } + <-s.slots + case <-s.callCtx.Done(): + back.err = s.callCtx.Err() + } + select { + case s.done <- back: + case <-s.callCtx.Done(): + // The script has ended and nobody reads this answer; [script.drain] + // is waiting for this goroutine to return, and now it does. + } +} + +// await settles finished calls until the script's own promise does, nothing +// is left that could, or the watchdog stops the script. The value is always a +// promise: the source is wrapped in an async function ([RunScript]). +func (s *script) await(value goja.Value, result *ScriptResult) { + promise := value.Export().(*goja.Promise) + for promise.State() == goja.PromiseStatePending { + if s.inflight == 0 { + result.Failed = neverSettles + return + } + select { + case back := <-s.done: + s.inflight-- + // A CANCELLED TURN IS A STOP, whichever news arrives first: the + // call's own cancellation can reach this loop before the watchdog + // does, and it must not read as the script failing. + if s.ctx.Err() != nil { + result.Stopped = stoppedWhy + return + } + err := s.deliver(back) + if why, stopped := interruption(err); stopped { + result.Stopped = why + return + } + if err != nil { + result.Failed = brief(err) + return + } + case why := <-s.halted: + result.Stopped = why + return + } + } + s.settle(promise, result) +} + +// deliver settles one call's promise on the interpreter's goroutine. +func (s *script) deliver(back finished) error { + if back.err != nil { + return back.reject(s.error(back.err.Error())) + } + return back.settle(s.vm.ToValue(back.answer)) +} + +// callArguments reads a call's one argument: an object, or nothing at all. +func callArguments(name string, value goja.Value) (map[string]any, error) { + if value == nil || goja.IsUndefined(value) || goja.IsNull(value) { + return map[string]any{}, nil + } + if args, ok := value.Export().(map[string]any); ok { + return args, nil + } + return nil, fmt.Errorf("tools.%s takes one object of arguments, like {command: \"ls\"}", identifier(name)) +} + +// error is a plain JavaScript Error carrying text, so `e.message` is the +// tool's own words and `String(e)` reads "Error: …". +func (s *script) error(message string) goja.Value { + made, err := s.vm.New(s.vm.Get("Error"), s.vm.ToValue(message)) + if err != nil { + return s.vm.ToValue(message) + } + return made +} + +// text adds one output item. +func (s *script) text(call goja.FunctionCall) goja.Value { + s.say(&s.items, render(call.Argument(0))) + return goja.Undefined() +} + +// log adds one console line, its arguments joined by spaces. +func (s *script) log(call goja.FunctionCall) goja.Value { + parts := make([]string, 0, len(call.Arguments)) + for _, argument := range call.Arguments { + parts = append(parts, render(argument)) + } + s.say(&s.console, strings.Join(parts, " ")) + return goja.Undefined() +} + +// say keeps one line, or stops the script when keeping it would pass the +// output ceiling. The stop is the interrupt, so no catch can write past it. +func (s *script) say(into *[]string, line string) { + if s.written+len(line)+1 > s.max { + s.overflow = fmt.Sprintf("it wrote more than %d bytes of output.", s.max) + s.stop(halt{why: s.overflow}) + return + } + s.written += len(line) + 1 + *into = append(*into, line) +} + +// settle reads the script's own promise once it is no longer pending, which +// [script.await] guarantees. +func (s *script) settle(promise *goja.Promise, result *ScriptResult) { + if promise.State() == goja.PromiseStateRejected { + result.Failed = brief(fmt.Errorf("%s", render(promise.Result()))) + return + } + if returned := promise.Result(); returned != nil && !goja.IsUndefined(returned) { + s.say(&s.items, render(returned)) + } +} + +// output is the items, then the console lines under their own heading. +func (s *script) output() string { + out := strings.Join(s.items, "\n") + if len(s.console) > 0 { + if out != "" { + out += "\n" + } + out += "console:\n" + strings.Join(s.console, "\n") + } + return out +} + +// render writes one value the way a person reads it: a string as itself, an +// error as "Error: message", anything else as JSON. +func render(value goja.Value) string { + if value == nil || goja.IsUndefined(value) { + return "undefined" + } + if goja.IsNull(value) { + return "null" + } + if text, ok := value.Export().(string); ok { + return text + } + if object, ok := value.(*goja.Object); ok && object.ClassName() == "Error" { + return value.String() + } + encoded, err := json.Marshal(value.Export()) + if err != nil { + return value.String() + } + return string(encoded) +} + +// identifier writes a tool name as a JavaScript identifier: every character +// that cannot appear in one becomes _, and a leading digit gets one in front. +func identifier(name string) string { + var b strings.Builder + for i, r := range name { + switch { + case r == '_' || r == '$' || unicode.IsLetter(r): + b.WriteRune(r) + case unicode.IsDigit(r): + if i == 0 { + b.WriteRune('_') + } + b.WriteRune(r) + default: + b.WriteRune('_') + } + } + return b.String() +} diff --git a/internal/jsrun/script_calls_test.go b/internal/jsrun/script_calls_test.go new file mode 100644 index 0000000000..333a15aff3 --- /dev/null +++ b/internal/jsrun/script_calls_test.go @@ -0,0 +1,76 @@ +package jsrun + +import ( + "context" + "fmt" + "strings" + "testing" +) + +// A CALL TURNED AWAY FOR ITS ARGUMENTS NEVER RAN, so it spends nothing of the +// call ceiling and is not reported as a call made. +func TestScriptRejectedArgumentsSpendNoCall(t *testing.T) { + calls := &scriptCalls{} + got := runScript(t, ` +for (let i = 0; i < 5; i++) { try { await tools.bash("ls") } catch (e) {} } +return "done"`, calls, ScriptLimits{Calls: 3}) + if got.Stopped != "" || got.Failed != "" { + t.Fatalf("five rejected calls stopped the script: stopped=%q failed=%q", got.Stopped, got.Failed) + } + if got.Calls != 0 || len(calls.seen) != 0 { + t.Errorf("calls = %d (seen %v), want 0: none of them ran", got.Calls, calls.seen) + } +} + +// THE CALL CEILING IS NAMED AS WHAT IT IS. "Steps" is the task's own unit, and +// a script that says it ran out of steps reads as the task's budget ending. +func TestScriptCallCeilingIsNamedAsCalls(t *testing.T) { + got := runScript(t, `while (true) { await tools.bash({command: "ls"}) }`, &scriptCalls{}, ScriptLimits{Calls: 2}) + if want := fmt.Sprintf("%d tool calls", 2); !strings.Contains(got.Stopped, want) || strings.Contains(got.Stopped, "step") { + t.Errorf("stopped = %q; want it to name %q and not steps", got.Stopped, want) + } +} + +// A CALL STARTED WITHOUT AWAIT IS COUNTED. The script's own promise settles +// first, the call is cancelled, and the result says so rather than reading as +// if the work had been done. +func TestScriptCountsTheCallsItDidNotWaitFor(t *testing.T) { + blocking := func(ctx context.Context, name string, _ map[string]any) (any, error) { + if name == "bash" { + <-ctx.Done() + return nil, ctx.Err() + } + return "ok", nil + } + got := RunScript(context.Background(), `tools.bash({command: "make gen"}); await tools.read_document({path: "a"}); return "started"`, + []string{"bash", "read_document"}, blocking, ScriptLimits{}) + if got.Failed != "" || got.Stopped != "" { + t.Fatalf("failed=%q stopped=%q", got.Failed, got.Stopped) + } + if got.Unawaited != 1 { + t.Errorf("unawaited = %d, want 1", got.Unawaited) + } + every := RunScript(context.Background(), `await tools.read_document({path: "a"}); return "done"`, + []string{"bash", "read_document"}, blocking, ScriptLimits{}) + if every.Unawaited != 0 { + t.Errorf("a script that waited for everything reports %d unawaited", every.Unawaited) + } +} + +// A CALL CANCELLED BEFORE IT RAN IS NOT A CALL MADE. Fifty calls fired without +// await while four slots run: the ones still queued when the script ended +// never ran, and the count says so. +func TestScriptCountsOnlyTheCallsThatRan(t *testing.T) { + blocking := func(ctx context.Context, _ string, _ map[string]any) (any, error) { + <-ctx.Done() + return nil, ctx.Err() + } + got := RunScript(context.Background(), `for (let i = 0; i < 50; i++) tools.bash({command: "x"}); return "fired"`, + []string{"bash"}, blocking, ScriptLimits{Parallel: 4}) + if got.Calls > 4 { + t.Errorf("calls = %d; at most 4 ran, the rest were cancelled waiting", got.Calls) + } + if got.Unawaited != 50 { + t.Errorf("unawaited = %d, want 50", got.Unawaited) + } +} diff --git a/internal/jsrun/script_test.go b/internal/jsrun/script_test.go new file mode 100644 index 0000000000..c7125907d0 --- /dev/null +++ b/internal/jsrun/script_test.go @@ -0,0 +1,294 @@ +package jsrun + +import ( + "context" + "errors" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// A SCRIPTED CALLER AND NOTHING ELSE, for fake_test.go's reason: these tests +// are about what the script host does with answers, not where answers come from. +type scriptCalls struct { + answers map[string]any + fail map[string]error + seen []string +} + +func (s *scriptCalls) call(_ context.Context, name string, args map[string]any) (any, error) { + s.seen = append(s.seen, name) + if err := s.fail[name]; err != nil { + return nil, err + } + if answer, ok := s.answers[name]; ok { + return answer, nil + } + return name + " answered", nil +} + +func runScript(t *testing.T, source string, calls *scriptCalls, limits ScriptLimits) ScriptResult { + t.Helper() + return RunScript(context.Background(), source, []string{"bash", "read_document", "web-search"}, calls.call, limits) +} + +func TestScriptReturnsTextAndCallResults(t *testing.T) { + calls := &scriptCalls{answers: map[string]any{ + "bash": map[string]any{"output": "a\nb\n", "exit_code": 1}, + }} + got := runScript(t, ` +const run = await tools.bash({command: "grep x"}); +text("exit " + run.exit_code); +console.log("lines", run.output.trim().split("\n").length); +return {doc: await tools.read_document({path: "a.pdf"})}; +`, calls, ScriptLimits{}) + if got.Failed != "" || got.Stopped != "" { + t.Fatalf("the script did not finish: failed=%q stopped=%q", got.Failed, got.Stopped) + } + for _, want := range []string{"exit 1", `{"doc":"read_document answered"}`, "lines 2"} { + if !strings.Contains(got.Output, want) { + t.Errorf("output is missing %q:\n%s", want, got.Output) + } + } + if got.Calls != 2 { + t.Errorf("calls = %d, want 2", got.Calls) + } +} + +func TestScriptReachesANameThatIsNotAnIdentifier(t *testing.T) { + calls := &scriptCalls{} + got := runScript(t, `return [await tools.web_search({q: "x"}), await tools["web-search"]({q: "y"})];`, calls, ScriptLimits{}) + if got.Failed != "" { + t.Fatalf("failed: %s", got.Failed) + } + if len(calls.seen) != 2 || calls.seen[0] != "web-search" || calls.seen[1] != "web-search" { + t.Errorf("calls reached %v, want web-search twice", calls.seen) + } +} + +func TestScriptRefusedCallRejectsAndCanBeCaught(t *testing.T) { + calls := &scriptCalls{fail: map[string]error{"bash": errors.New("denied by the policy: bash")}} + got := runScript(t, ` +const settled = await Promise.allSettled([tools.bash({command: "rm -rf x"}), tools.read_document({path: "a"})]); +try { await tools.bash({command: "again"}) } catch (e) { text("caught: " + e.message) } +return settled.map(s => s.status); +`, calls, ScriptLimits{}) + if got.Failed != "" { + t.Fatalf("a caught refusal failed the script: %s", got.Failed) + } + for _, want := range []string{"caught: denied by the policy: bash", `["rejected","fulfilled"]`} { + if !strings.Contains(got.Output, want) { + t.Errorf("output is missing %q:\n%s", want, got.Output) + } + } +} + +func TestScriptUncaughtErrorFailsWithPartialOutput(t *testing.T) { + calls := &scriptCalls{fail: map[string]error{"bash": errors.New("Command timed out after 5 seconds")}} + got := runScript(t, `text("before"); await tools.bash({command: "sleep 9"}); text("after");`, calls, ScriptLimits{}) + if !strings.Contains(got.Failed, "Command timed out after 5 seconds") { + t.Errorf("failed = %q, want the tool's own text", got.Failed) + } + if !strings.Contains(got.Output, "before") || strings.Contains(got.Output, "after") { + t.Errorf("output = %q, want only what came before the failure", got.Output) + } +} + +func TestScriptCompileErrorFailsWithoutCalling(t *testing.T) { + calls := &scriptCalls{} + got := runScript(t, `await tools.bash({command: "x"}) +++ ;`, calls, ScriptLimits{}) + if got.Failed == "" || len(calls.seen) != 0 { + t.Errorf("failed = %q, calls = %v; want a compile failure and no calls", got.Failed, calls.seen) + } +} + +func TestScriptCallCeilingCannotBeCaught(t *testing.T) { + calls := &scriptCalls{} + got := runScript(t, ` +for (let i = 0; i < 10; i++) { try { await tools.bash({command: "echo " + i}) } catch (e) {} } +text("escaped the ceiling"); +`, calls, ScriptLimits{Calls: 3}) + if !strings.Contains(got.Stopped, "3") || strings.Contains(got.Output, "escaped") { + t.Errorf("stopped = %q, output = %q; want an uncatchable stop at 3 calls", got.Stopped, got.Output) + } + if len(calls.seen) != 3 { + t.Errorf("calls reached %d, want 3", len(calls.seen)) + } +} + +func TestScriptWallDeadlineStopsALoopThatCallsNothing(t *testing.T) { + got := runScript(t, `while (true) {}`, &scriptCalls{}, ScriptLimits{Wall: 50 * time.Millisecond}) + if !strings.Contains(got.Stopped, "ran out of time") { + t.Errorf("stopped = %q, want the deadline", got.Stopped) + } +} + +func TestScriptCancelledContextStopsIt(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + calls := &scriptCalls{} + caller := func(c context.Context, name string, args map[string]any) (any, error) { + cancel() + return calls.call(c, name, args) + } + got := RunScript(ctx, `await tools.bash({}); while (true) {}`, []string{"bash"}, caller, ScriptLimits{}) + if !strings.Contains(got.Stopped, "stopped before it finished") { + t.Errorf("stopped = %q, want the cancellation", got.Stopped) + } +} + +func TestScriptOutputCeilingStopsIt(t *testing.T) { + got := runScript(t, `for (;;) text("0123456789")`, &scriptCalls{}, ScriptLimits{Output: 100}) + if !strings.Contains(got.Stopped, "100 bytes") { + t.Errorf("stopped = %q, want the output ceiling", got.Stopped) + } + if len(got.Output) > 100 { + t.Errorf("output kept %d bytes past a 100-byte ceiling", len(got.Output)) + } +} + +func TestScriptWaitingOnNothingFailsAtOnce(t *testing.T) { + got := runScript(t, `await new Promise(() => {});`, &scriptCalls{}, ScriptLimits{Wall: time.Minute}) + if !strings.Contains(got.Failed, "can never finish") { + t.Errorf("failed = %q, want the never-settles failure", got.Failed) + } +} + +func TestScriptNonObjectArgumentsReject(t *testing.T) { + calls := &scriptCalls{} + got := runScript(t, `await tools.bash("ls")`, calls, ScriptLimits{}) + if !strings.Contains(got.Failed, "one object of arguments") || len(calls.seen) != 0 { + t.Errorf("failed = %q, calls = %v; want a refusal before any call", got.Failed, calls.seen) + } +} + +// THE CONCURRENCY TESTS USE BARRIERS, NOT CLOCKS: a caller waits until enough +// calls are inside at once, so a host that ran them one at a time fails by its +// own deadline rather than by a timing guess. + +func TestScriptCallsRunAtTheSameTimeUpToTheCap(t *testing.T) { + var inside, most atomic.Int32 + release := make(chan struct{}) + var once sync.Once + caller := func(ctx context.Context, name string, _ map[string]any) (any, error) { + now := inside.Add(1) + defer inside.Add(-1) + for { + seen := most.Load() + if now <= seen || most.CompareAndSwap(seen, now) { + break + } + } + if now == 3 { + once.Do(func() { close(release) }) + } + select { + case <-release: + return name, nil + case <-ctx.Done(): + return nil, ctx.Err() + } + } + got := RunScript(context.Background(), ` +const answers = await Promise.all([1, 2, 3, 4, 5, 6].map(() => tools.bash({}))); +return answers.length; +`, []string{"bash"}, caller, ScriptLimits{Parallel: 3, Wall: 5 * time.Second}) + if got.Failed != "" || got.Stopped != "" || got.Output != "6" { + t.Fatalf("the calls did not run together: output=%q failed=%q stopped=%q", got.Output, got.Failed, got.Stopped) + } + if most.Load() != 3 { + t.Errorf("at most %d calls ran at once, want the cap of 3", most.Load()) + } +} + +func TestScriptStopsWaitingAtItsDeadlineAndCancelsItsCalls(t *testing.T) { + var started, returned atomic.Int32 + caller := func(ctx context.Context, _ string, _ map[string]any) (any, error) { + started.Add(1) + defer returned.Add(1) + <-ctx.Done() + return nil, ctx.Err() + } + got := RunScript(context.Background(), `await Promise.all([tools.bash({}), tools.bash({})])`, + []string{"bash"}, caller, ScriptLimits{Wall: 50 * time.Millisecond}) + if !strings.Contains(got.Stopped, "ran out of time") { + t.Errorf("stopped = %q, want the deadline", got.Stopped) + } + if started.Load() != 2 || returned.Load() != 2 { + t.Errorf("started %d, returned %d by the time the script ended; every call must end first", started.Load(), returned.Load()) + } +} + +func TestScriptCancelledWhileWaitingCancelsItsCalls(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + var returned atomic.Int32 + caller := func(c context.Context, _ string, _ map[string]any) (any, error) { + defer returned.Add(1) + cancel() + <-c.Done() + return nil, c.Err() + } + got := RunScript(ctx, `await tools.bash({})`, []string{"bash"}, caller, ScriptLimits{Wall: time.Minute}) + if !strings.Contains(got.Stopped, "stopped before it finished") || returned.Load() != 1 { + t.Errorf("stopped = %q, returned = %d; want the cancellation and the call ended", got.Stopped, returned.Load()) + } +} + +func TestScriptCeilingInAContinuationStopsIt(t *testing.T) { + calls := &scriptCalls{} + got := runScript(t, ` +await tools.bash({}); +await tools.bash({}); +for (;;) {} +`, calls, ScriptLimits{Wall: 50 * time.Millisecond}) + if !strings.Contains(got.Stopped, "ran out of time") || len(calls.seen) != 2 { + t.Errorf("stopped = %q after %d calls; want the deadline after 2", got.Stopped, len(calls.seen)) + } +} + +// A RETURN VALUE PAST THE OUTPUT CEILING STOPS THE SCRIPT, and says so. It is +// kept after the interpreter has finished, where an interrupt reaches nothing, +// so the reason is recorded rather than raised. +func TestScriptReturnPastTheOutputCeilingSaysSo(t *testing.T) { + got := runScript(t, `return "x".repeat(200)`, &scriptCalls{}, ScriptLimits{Output: 100}) + if !strings.Contains(got.Stopped, "100 bytes") { + t.Errorf("stopped = %q, failed = %q; want the output ceiling named", got.Stopped, got.Failed) + } +} + +// A NAME IS NEVER TAKEN BY ANOTHER TOOL'S ALIAS, whichever is bound first. +func TestScriptAliasNeverReplacesAToolsOwnName(t *testing.T) { + for _, names := range [][]string{{"foo_bar", "foo-bar"}, {"foo-bar", "foo_bar"}} { + var seen []string + caller := func(_ context.Context, name string, _ map[string]any) (any, error) { + seen = append(seen, name) + return name, nil + } + got := RunScript(context.Background(), `return await tools.foo_bar({})`, names, caller, ScriptLimits{}) + if len(seen) != 1 || seen[0] != "foo_bar" { + t.Errorf("names %v: tools.foo_bar reached %v (output %q)", names, seen, got.Output) + } + } +} + +// A CALL STILL WAITING FOR A SLOT WHEN THE SCRIPT ENDS NEVER STARTS. There is +// one slot and every call holds it until the script's context ends, so at most +// one call can pass the slot before the ending; any other gets the slot only +// after it, and must not start. Counting entries, not their timing, keeps this +// exact. +func TestScriptQueuedCallsDoNotStartAfterItEnds(t *testing.T) { + for i := 0; i < 50; i++ { + var entered atomic.Int32 + caller := func(ctx context.Context, _ string, _ map[string]any) (any, error) { + entered.Add(1) + <-ctx.Done() + return nil, ctx.Err() + } + RunScript(context.Background(), `tools.bash({}); tools.bash({}); tools.bash({}); return 1`, + []string{"bash"}, caller, ScriptLimits{Parallel: 1}) + if n := entered.Load(); n > 1 { + t.Fatalf("run %d: %d calls started; the queued ones began after the script ended", i, n) + } + } +} diff --git a/internal/manual/chat/how-tasks-run.md b/internal/manual/chat/how-tasks-run.md index 68e56eb455..1850f7317d 100644 --- a/internal/manual/chat/how-tasks-run.md +++ b/internal/manual/chat/how-tasks-run.md @@ -3598,6 +3598,73 @@ A child reads the overall ask for requirements it owns. Delegation instructions for the parent remain the parent's coordination work; a child repeats them only when its own work order assigns coordination. +## Can a task run several tools in one step — the script tool, CODEAF_TASK_SCRIPT + +A task worker on the bash belt can carry a `script` tool. The worker writes a +short JavaScript program that calls its other tools, and only what the program +prints or returns goes back to the model. One step can make several calls and +keep only the lines that matter from a large result. + +The tool is off by default while it is measured. Start codeaf with +`CODEAF_TASK_SCRIPT=on` to give task workers the tool; any other value, or +none, leaves it off. This switch does not put the tool on the conversation's +own tools (`CODEAF_CHAT_SCRIPT` does, below), and a task on the older node +belt (`CODEAF_TASK_BELT=node`) never carries it. + +A script is one step of the task: it counts once against the task's step +limit and in the step count the worker and the task's room show, and the +task's page and its live view list the calls it made under it, indented. A +script that reads counts as progress, as a `bash` command that reads does, so +a worker exploring through scripts is not stopped for making no progress. + +## Script tool rules and limits — what a script can call, bash in a script + +These rules hold for a task's script and a conversation's alike. + +- Each call goes through the same approval rules as a call the worker makes + directly. A refused call fails inside the script with the refusal's text. +- A script can call only `bash`, `read`, `ls`, `grep`, `find`, + `read_document`, `manual`, `recall`, `web_search` and `web_fetch`, where + the belt has them. Every other tool, `script` included, fails inside the + script: editing, asking you and starting work stay the model's own steps. +- Inside a script, `bash` answers the command's output, its exit code and + whether the output was cut. A script sees up to 1 MiB of one command's + output, and a non-zero exit does not fail the script. A command that timed + out or was stopped fails inside the script with bash's own words. A command + moved to the background answers no exit code, and its output names the job. +- Every other tool answers its text, as the worker would read it; a script + that knows a tool answers JSON parses it itself. +- A script is not Node.js: there is no `require`, `fs`, `process`, network + or timer such as `setTimeout`. It reaches files and commands only through tools, mostly + `await tools.bash({command: "..."})`. +- A script stops after 200 tool calls, 10 minutes or 16 MiB of output, and + says which limit it reached. A call turned away for its own arguments never + ran and does not count toward the 200. +- What the script returns is cut to the usual result limit, with the whole + output saved to a file the result names. +- Up to 4 calls run at the same time; more wait their turn. When a script + ends, calls still running are cancelled, and the result says how many + calls it did not wait for. +- A script's memory is not limited, and the 10-minute limit cannot stop one + regular expression match partway, so a very large value can use up + codeaf's memory first. +- A quick task's worker never carries `script`. + +## The script tool in a conversation — CODEAF_CHAT_SCRIPT + +Start codeaf with `CODEAF_CHAT_SCRIPT=on` to put the same `script` tool on the +conversation's own tools, as a separate experiment from `CODEAF_TASK_SCRIPT`. +Any other value, or none, leaves it off. It changes nothing for tasks: each +switch arms one side only. + +The chat's script follows the same rules as a task's (see "Script tool rules +and limits"). Each call it makes goes through the approval rules, so a call that +needs your approval stops the script until you answer, up to the script's 10 +minutes. Its `bash` calls see up to 1 MiB of output, although the +conversation's own `bash` keeps only the last part that fits. The calls are +drawn indented under the script in the conversation, and still are after the +conversation is reopened. + ## Where does my task work An ordinary code task works in its own copy of the repository the work is about, diff --git a/internal/plandb/live.go b/internal/plandb/live.go index c546ad0c8a..9e31910851 100644 --- a/internal/plandb/live.go +++ b/internal/plandb/live.go @@ -26,7 +26,11 @@ import ( // is the honest answer for a task that is running nothing, which is why a // reader draws nothing rather than a zero step. type LiveStep struct { - Step int + Step int + // Tool is the tool the step is running, as the belt began it; empty for a + // writer that names none, which a surface reads as the bash step every + // older writer publishes. + Tool string Command string Since time.Time } @@ -48,6 +52,12 @@ func (l LiveStep) Empty() bool { return l.Step == 0 } // The moment is the store's own clock, the same one a spend row is stamped // with, so two readings of one run's present cannot disagree about now. func (s *Store) SetLive(taskID string, step int, command string) error { + return s.SetLiveCall(taskID, step, "", command) +} + +// SetLiveCall is [Store.SetLive] naming the tool the step is running, so a +// surface draws a step in flight as what it is. +func (s *Store) SetLiveCall(taskID string, step int, tool, command string) error { s.mu.Lock() defer s.mu.Unlock() tx, err := s.beginWrite() @@ -55,9 +65,9 @@ func (s *Store) SetLive(taskID string, step int, command string) error { return err } defer tx.Rollback() - if _, err := tx.Exec(`INSERT INTO live (task_id, step, command, since) VALUES (?, ?, ?, ?) - ON CONFLICT(task_id) DO UPDATE SET step = excluded.step, command = excluded.command, since = excluded.since`, - bareTaskID(taskID), step, command, formatTime(s.now().UTC())); err != nil { + if _, err := tx.Exec(`INSERT INTO live (task_id, step, tool, command, since) VALUES (?, ?, ?, ?, ?) + ON CONFLICT(task_id) DO UPDATE SET step = excluded.step, tool = excluded.tool, command = excluded.command, since = excluded.since`, + bareTaskID(taskID), step, tool, command, formatTime(s.now().UTC())); err != nil { return err } return tx.Commit() @@ -102,22 +112,22 @@ func (s *Store) LiveSteps() map[string]LiveStep { if s.closed || s.rdb == nil { return out } - rows, err := s.rdb.Query(`SELECT task_id, step, command, since FROM live`) + rows, err := s.rdb.Query(`SELECT task_id, step, tool, command, since FROM live`) if err != nil { return out } defer rows.Close() for rows.Next() { - var id, command, since string + var id, tool, command, since string var step int - if rows.Scan(&id, &step, &command, &since) != nil { + if rows.Scan(&id, &step, &tool, &command, &since) != nil { return out } moment, err := parseTime(since) if err != nil { continue } - out[id] = LiveStep{Step: step, Command: command, Since: moment} + out[id] = LiveStep{Step: step, Tool: tool, Command: command, Since: moment} } return out } diff --git a/internal/plandb/live_tool_test.go b/internal/plandb/live_tool_test.go new file mode 100644 index 0000000000..7077609af6 --- /dev/null +++ b/internal/plandb/live_tool_test.go @@ -0,0 +1,28 @@ +package plandb + +import ( + "path/filepath" + "testing" +) + +// A LIVE STEP KEEPS THE TOOL IT IS RUNNING, and one published without a tool +// reads back with none — the bash step every older writer publishes. +func TestLiveStepKeepsItsTool(t *testing.T) { + store, err := Open(filepath.Join(t.TempDir(), "plan.db"), "live", "root", "Live", "keep the tool") + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err := store.SetLiveCall(store.RootID(), 2, "script", `{"source":"return 1"}`); err != nil { + t.Fatal(err) + } + if live := store.Live(store.RootID()); live.Tool != "script" || live.Step != 2 { + t.Errorf("live = %#v, want step 2 running script", live) + } + if err := store.SetLive(store.RootID(), 3, "go test ./..."); err != nil { + t.Fatal(err) + } + if live := store.Live(store.RootID()); live.Tool != "" || live.Command != "go test ./..." { + t.Errorf("live = %#v, want a bash step with no tool", live) + } +} diff --git a/internal/plandb/persist.go b/internal/plandb/persist.go index 9f3de0aa6a..f3ddff1733 100644 --- a/internal/plandb/persist.go +++ b/internal/plandb/persist.go @@ -219,6 +219,7 @@ var schemaStatements = []string{ `CREATE TABLE IF NOT EXISTS live ( task_id TEXT PRIMARY KEY, step INTEGER NOT NULL, + tool TEXT NOT NULL DEFAULT '', command TEXT NOT NULL, since TEXT NOT NULL )`, @@ -361,6 +362,11 @@ func migrateColumns(tx *sql.Tx) error { if err := ensureColumn(tx, "meta", "stopped", "INTEGER", "0"); err != nil { return err } + // THE LIVE STEP'S TOOL arrived with the script tool: a file written before + // it still opens, each live row reading back with no tool — a bash step. + if err := ensureColumn(tx, "live", "tool", "TEXT", "''"); err != nil { + return err + } for _, table := range []string{"tasks", "notes", "contexts"} { for _, column := range []string{"project", "chat"} { if err := ensureColumn(tx, table, column, "TEXT", "''"); err != nil { diff --git a/internal/remote/server.go b/internal/remote/server.go index de45ac9f8f..6c0bf68db5 100644 --- a/internal/remote/server.go +++ b/internal/remote/server.go @@ -1571,10 +1571,14 @@ func factsMoved(kind session.EventKind) bool { // token column — saw a big file read join the conversation one whole step late. // The next request is the first moment the results are certainly in, and its // first word is the first event this pump sees from it. -func (sess *Session) weighsAgainLocked(kind session.EventKind) bool { - switch kind { +func (sess *Session) weighsAgainLocked(event session.Event) bool { + switch event.Kind { case session.EventToolEnd, session.EventToolFailed: - sess.weighOwed = true + // A script's own call ends inside the script's step: its result never + // joins the conversation, so only the script's end owes a weighing. + if !event.FromScript() { + sess.weighOwed = true + } case session.EventTurnDone, session.EventError: // The turn's own end states the facts whole, results and all. sess.weighOwed = false @@ -1727,7 +1731,7 @@ func (sess *Session) emit(id, generation uint64, event session.Event) { } sess.held.raise(wire, id, drawn) } - weighs := sess.weighsAgainLocked(event.Kind) + weighs := sess.weighsAgainLocked(event) sess.mu.Unlock() // THE FACTS GO FIRST, AHEAD OF THE EVENT THAT MOVED THEM. A surface settles diff --git a/internal/remote/weighagain_test.go b/internal/remote/weighagain_test.go index d08b45dda2..e306e1b6fb 100644 --- a/internal/remote/weighagain_test.go +++ b/internal/remote/weighagain_test.go @@ -27,8 +27,18 @@ func TestTheWeightIsStatedAgainWhenTheNextRequestSpeaks(t *testing.T) { {session.EventTurnDone, false}, {session.EventTextDelta, false}, } { - if got := sess.weighsAgainLocked(step.kind); got != step.want { + if got := sess.weighsAgainLocked(session.Event{Kind: step.kind}); got != step.want { t.Fatalf("step %d (%v): weighs again = %v, want %v", i, step.kind, got, step.want) } } } + +// A SCRIPT'S OWN CALLS END INSIDE ONE STEP. Their results never join the +// conversation, so their end owes no new weighing; only the script's does. +func TestAScriptsNestedEndOwesNoWeighing(t *testing.T) { + sess := &Session{} + sess.weighsAgainLocked(session.Event{Kind: session.EventToolEnd, Parent: "s"}) + if sess.weighsAgainLocked(session.Event{Kind: session.EventReasoning}) { + t.Fatal("a script's nested call end owed the next request a weighing") + } +} diff --git a/internal/run/bashworker.go b/internal/run/bashworker.go index b16bb39265..dddb4fa28b 100644 --- a/internal/run/bashworker.go +++ b/internal/run/bashworker.go @@ -322,6 +322,16 @@ func (w *BashWorker) Run(ctx context.Context, task plandb.Task) (rep Report, run banked = spent bankSpend(runCtx, spent) } + // A SCRIPT'S OWN CALL IS NOT A STEP. The step is the script, and + // its end — which comes after every call it made — is what the cap, + // the same-action law and the live step read. Each finished call is + // kept for that step's line instead (tool_script.go names the parent). + if event.FromScript() { + if event.Kind == session.EventToolEnd || event.Kind == session.EventToolFailed { + rec.nest(event) + } + continue + } switch event.Kind { case session.EventToolBegin: // A LIVE STEP IS TRUE ONLY WHILE ITS COMMAND RUNS. The begin event is @@ -332,17 +342,15 @@ func (w *BashWorker) Run(ctx context.Context, task plandb.Task) (rep Report, run // [stepCommand] reads off the event, and the moment the store stamps. // The step's own end line clears it, and so does every ending below, // so a task that is not running a command never claims a present. - _ = w.store.SetLive(task.ID, stepNumber+1, stepCommand(event)) + _ = w.store.SetLiveCall(task.ID, stepNumber+1, event.Tool, stepCommand(event)) case session.EventToolEnd, session.EventToolFailed: // THE CAP IS THE LAST STEP COUNTED. The step handshake keeps the // next action behind this decision. Any remaining end events are // drained without extending the record past its bound. - if capped { - continue - } // THE SAME-ACTION LAW ENDS THE RECORD WHERE IT FELL, before the // acknowledgement permits another action. - if stalled { + if capped || stalled { + rec.drop(event.CallID) continue } steps++ @@ -1047,6 +1055,28 @@ type stepRecorder struct { taskID string children map[string]bool spilled int + // calls are a script's ended calls by the script call's id; the script's + // own step, which ends after them, takes its own. + calls map[string][]StepCall +} + +// drop lets go of the calls of a step that will not be recorded — one the cap +// or the same-action law ended before its line was written. +func (r *stepRecorder) drop(parent string) { delete(r.calls, parent) } + +// nest keeps one call a script made, for the script's own step. +func (r *stepRecorder) nest(event session.Event) { + if r.calls == nil { + r.calls = map[string][]StepCall{} + } + r.calls[event.Parent] = append(r.calls[event.Parent], StepCall{ + Tool: event.Tool, + Command: stepCommand(event), + Observation: observationHead(event.Output), + ExitCode: exitCodeOf(event), + Failed: event.Kind == session.EventToolFailed, + NotRun: event.HarnessMade, + }) } // record appends one step line: the command the model spelled, the head of @@ -1061,33 +1091,66 @@ func (r *stepRecorder) record(n int, event session.Event) error { Command: command, Observation: observationHead(event.Output), FullOutput: r.takeSpill(), - Writes: planVerbs(command), + Writes: planVerbs(stepWritesText(event, command) + "\n" + nestedBash(r.calls[event.CallID])), Children: r.takeChildren(), + Calls: r.calls[event.CallID], NotRun: event.HarnessMade, Refused: event.HarnessMade && event.Refused, } + delete(r.calls, event.CallID) // THE COMMAND'S OWN EXIT IS RECORDED FROM THE EVENT, and only for a bash // command the belt actually ran: an ended bash tool exited zero, a failed one // exited non-zero (the belt appends "Command exited with code N", read back // here when it survived the output cap, otherwise a plain non-zero). A harness // refusal never ran the command and a non-bash tool has no exit, so both leave // the field nil, which a reader treats as unknown rather than as a zero. - if event.Tool == "bash" { - switch event.Kind { - case session.EventToolEnd: - zero := 0 - step.ExitCode = &zero - case session.EventToolFailed: - if !event.HarnessMade { - code := 1 - if parsed, ok := exitStatusFromOutput(event.Output); ok { - code = parsed - } - step.ExitCode = &code + step.ExitCode = exitCodeOf(event) + return appendTrajectory(r.storeDir, r.taskID, step) +} + +// stepWritesText is the step's own text read for plandb verbs: its command, +// or nothing for a script, whose source runs nothing itself. A word in a +// script's comment or string is not a command; its bash calls are read +// instead ([nestedBash]). +func stepWritesText(event session.Event, command string) string { + if event.Tool == session.ScriptToolName { + return "" + } + return command +} + +// nestedBash is the commands of a script's bash calls, one per line: a plan +// write a script made went through one of them. +func nestedBash(calls []StepCall) string { + var commands []string + for _, call := range calls { + if call.Tool == "bash" && !call.NotRun { + commands = append(commands, call.Command) + } + } + return strings.Join(commands, "\n") +} + +// exitCodeOf is a bash call's exit status read off its end, by the rule above; +// nil for every other tool and for a call the harness answered. +func exitCodeOf(event session.Event) *int { + if event.Tool != "bash" { + return nil + } + switch event.Kind { + case session.EventToolEnd: + zero := 0 + return &zero + case session.EventToolFailed: + if !event.HarnessMade { + code := 1 + if parsed, ok := exitStatusFromOutput(event.Output); ok { + code = parsed } + return &code } } - return appendTrajectory(r.storeDir, r.taskID, step) + return nil } // exitStatusFromOutput reads the exit code the belt appended to a failed diff --git a/internal/run/bashworker_script_live_test.go b/internal/run/bashworker_script_live_test.go new file mode 100644 index 0000000000..0bb4e7e293 --- /dev/null +++ b/internal/run/bashworker_script_live_test.go @@ -0,0 +1,52 @@ +package run_test + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/run" +) + +// A RUNNING SCRIPT IS PUBLISHED AS A SCRIPT. The live step carries the tool the +// belt began, so a page draws the step in flight as what it is rather than as +// a bash command spelled in JSON. +func TestBashWorkerPublishesAScriptAsItsLiveTool(t *testing.T) { + t.Setenv("CODEAF_TASK_BELT", "bash") + t.Setenv("CODEAF_TASK_SCRIPT", "on") + t.Setenv("CODEAF_PLANDB_BIN", realPlandbDoor(t)) + store := runOpenStore(t) + workspace := t.TempDir() + release := filepath.Join(workspace, "release") + source := "await tools.bash({command: " + jsonString("while [ ! -f "+release+" ]; do sleep 0.02; done") + "})" + args, _ := json.Marshal(map[string]string{"source": source}) + seat := &seat{script: []step{ + func(context.Context, []ai.Message) (*ai.Response, error) { + return &ai.Response{Choices: []ai.Choice{{Message: ai.Message{Role: "assistant", ToolCalls: []ai.ToolCall{{ + ID: "script-1", Type: "function", Function: ai.ToolCallFunction{Name: "script", Arguments: string(args)}, + }}}}}}, nil + }, + func(context.Context, []ai.Message) (*ai.Response, error) { + return toolReply(finishCommand("root", "the script ran")), nil + }, + }} + worker := run.NewBashWorker(store, workspace, "test/model", seat) + done := make(chan error, 1) + go func() { + _, err := worker.Run(run.WithStepsPerTask(runContext(t), 9), *store.Task(store.RootID())) + done <- err + }() + live := waitForLiveStep(t, store, store.RootID()) + if live.Tool != "script" { + t.Errorf("the live step's tool = %q, want script", live.Tool) + } + if err := os.WriteFile(release, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := <-done; err != nil { + t.Fatalf("the worker's run failed: %v", err) + } +} diff --git a/internal/run/bashworker_script_test.go b/internal/run/bashworker_script_test.go new file mode 100644 index 0000000000..db842c7bae --- /dev/null +++ b/internal/run/bashworker_script_test.go @@ -0,0 +1,124 @@ +package run + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/plandb" + "github.com/Agent-Field/codeaf/internal/session" +) + +// scriptSeat answers every request with one script call that makes two bash +// calls of its own, the second exiting 4. +type scriptSeat struct{} + +func (scriptSeat) CompleteWithMessages(_ context.Context, _ []ai.Message, _ ...ai.Option) (*ai.Response, error) { + args := `{"source":"await tools.bash({command: \"echo one\"}); const r = await tools.bash({command: \"echo two; exit 4\"}); return r.exit_code"}` + return &ai.Response{Choices: []ai.Choice{{Message: ai.Message{Role: "assistant", ToolCalls: []ai.ToolCall{{ + ID: "script-1", Type: "function", Function: ai.ToolCallFunction{Name: "script", Arguments: args}, + }}}}}}, nil +} + +// A SCRIPT IS ONE STEP. Its nested calls are recorded on that step, never as +// steps of their own, so they spend nothing of the step cap and a page drawn +// from the record can hang them under the script that made them. +func TestBashWorkerRecordsAScriptAsOneStepWithItsCalls(t *testing.T) { + t.Setenv("CODEAF_TASK_BELT", "bash") + t.Setenv("CODEAF_TASK_SCRIPT", "on") + root := t.TempDir() + t.Setenv("CODEAF_HOME", root) + stub := filepath.Join(root, "stub-codeaf") + if err := os.WriteFile(stub, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("CODEAF_PLANDB_BIN", stub) + store, err := plandb.Open(filepath.Join(root, "plan.db"), "script", "root", "Script", "Run a script") + if err != nil { + t.Fatal(err) + } + defer store.Close() + worker := NewBashWorker(store, root, "test/model", scriptSeat{}) + ctx, cancel := context.WithTimeout(WithStepsPerTask(t.Context(), 1), 20*time.Second) + defer cancel() + report, runErr := worker.Run(ctx, *store.Task(store.RootID())) + if runErr == nil || !strings.Contains(runErr.Error(), "after 1 step") || report.Steps != 1 { + t.Fatalf("the script was not counted as one step: report=%+v err=%v", report, runErr) + } + steps, err := Trajectory(root, store.RootID()) + if err != nil { + t.Fatal(err) + } + if len(steps) != 1 || steps[0].Tool != "script" { + t.Fatalf("want one script step, got %+v", steps) + } + calls := steps[0].Calls + if len(calls) != 2 { + t.Fatalf("the script step carries %d calls, want 2: %+v", len(calls), calls) + } + if calls[0].Tool != "bash" || calls[0].Command != "echo one" || calls[0].ExitCode == nil || *calls[0].ExitCode != 0 { + t.Errorf("first call recorded as %+v", calls[0]) + } + if calls[1].Command != "echo two; exit 4" || calls[1].ExitCode == nil || *calls[1].ExitCode != 4 || !strings.Contains(calls[1].Observation, "two") { + t.Errorf("second call recorded as %+v", calls[1]) + } +} + +// bigScriptSeat makes one script call whose nested bash is cut at the +// script's width, then returns a short answer that is not cut. +type bigScriptSeat struct{} + +func (bigScriptSeat) CompleteWithMessages(_ context.Context, _ []ai.Message, _ ...ai.Option) (*ai.Response, error) { + args := `{"source":"const r = await tools.bash({command: \"head -c 1100000 /dev/zero | tr '\\\\0' x\"}); return r.truncated ? 'cut' : 'whole'"}` + return &ai.Response{Choices: []ai.Choice{{Message: ai.Message{Role: "assistant", ToolCalls: []ai.ToolCall{{ + ID: "script-1", Type: "function", Function: ai.ToolCallFunction{Name: "script", Arguments: args}, + }}}}}}, nil +} + +// A SCRIPT STEP'S WHOLE OUTPUT IS ITS OWN. A nested bash cut at the script's +// width files its output too, and the step must not take that file as the +// script's. +func TestBashWorkerScriptStepDoesNotTakeANestedCallsFile(t *testing.T) { + t.Setenv("CODEAF_TASK_BELT", "bash") + t.Setenv("CODEAF_TASK_SCRIPT", "on") + root := t.TempDir() + t.Setenv("CODEAF_HOME", root) + stub := filepath.Join(root, "stub-codeaf") + if err := os.WriteFile(stub, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("CODEAF_PLANDB_BIN", stub) + store, err := plandb.Open(filepath.Join(root, "plan.db"), "script", "root", "Script", "Run a script") + if err != nil { + t.Fatal(err) + } + defer store.Close() + worker := NewBashWorker(store, root, "test/model", bigScriptSeat{}) + ctx, cancel := context.WithTimeout(WithStepsPerTask(t.Context(), 1), 30*time.Second) + defer cancel() + _, _ = worker.Run(ctx, *store.Task(store.RootID())) + steps, err := Trajectory(root, store.RootID()) + if err != nil || len(steps) != 1 { + t.Fatalf("steps = %+v, err = %v", steps, err) + } + if !strings.Contains(steps[0].Observation, "cut") { + t.Fatalf("the nested bash was not cut, so this proves nothing: %q", steps[0].Observation) + } + if steps[0].FullOutput != "" { + t.Errorf("the script step names %q as its whole output; that file is a nested call's", steps[0].FullOutput) + } +} + +// A STEP THAT IS NOT RECORDED LEAVES NO CALLS BEHIND. +func TestStepRecorderDropsTheCallsOfAStepItSkips(t *testing.T) { + var rec stepRecorder + rec.nest(session.Event{Kind: session.EventToolEnd, Tool: "bash", Parent: "p", Args: `{"command":"ls"}`}) + rec.drop("p") + if len(rec.calls) != 0 { + t.Errorf("a skipped step's calls are still held: %+v", rec.calls) + } +} diff --git a/internal/run/bashworker_script_writes_test.go b/internal/run/bashworker_script_writes_test.go new file mode 100644 index 0000000000..db17993a5b --- /dev/null +++ b/internal/run/bashworker_script_writes_test.go @@ -0,0 +1,61 @@ +package run + +import ( + "path/filepath" + "testing" + + "github.com/Agent-Field/codeaf/internal/plandb" + + "github.com/Agent-Field/codeaf/internal/session" +) + +// A PLAN WRITE A SCRIPT MADE IS THE SCRIPT STEP'S WRITE. The step's command is +// the script's source, so the plandb verbs its bash calls ran are read off them. +func TestScriptStepRecordsThePlanWritesOfItsCalls(t *testing.T) { + store, err := plandb.Open(filepath.Join(t.TempDir(), "plan.db"), "script", "root", "Script", "Run a script") + if err != nil { + t.Fatal(err) + } + defer store.Close() + root, task := filepath.Dir(store.Path()), store.RootID() + rec := stepRecorder{store: store, storeDir: root, taskID: task, children: childrenOf(store, task)} + rec.nest(session.Event{Kind: session.EventToolEnd, Tool: "bash", Parent: "s", Args: `{"command":"plandb note 'found it'"}`}) + rec.nest(session.Event{Kind: session.EventToolEnd, Tool: "bash", Parent: "s", Args: `{"command":"plandb add 'next'"}`}) + if err := rec.record(1, session.Event{Kind: session.EventToolEnd, Tool: "script", CallID: "s", Args: `{"source":"return 1"}`}); err != nil { + t.Fatal(err) + } + steps, err := Trajectory(root, task) + if err != nil || len(steps) != 1 { + t.Fatalf("steps = %+v, err = %v", steps, err) + } + got := map[string]bool{} + for _, verb := range steps[0].Writes { + got[verb] = true + } + if !got["note"] || !got["add"] { + t.Errorf("writes = %v; want the script's plandb note and add", steps[0].Writes) + } +} + +// A SCRIPT'S SOURCE IS NOT A PLAN WRITE. Words in it that name a plandb verb +// ran nothing; only its bash calls' commands are read. +func TestScriptSourceWordsAreNotPlanWrites(t *testing.T) { + store, err := plandb.Open(filepath.Join(t.TempDir(), "plan.db"), "script", "root", "Script", "Run a script") + if err != nil { + t.Fatal(err) + } + defer store.Close() + root, task := filepath.Dir(store.Path()), store.RootID() + rec := stepRecorder{store: store, storeDir: root, taskID: task, children: childrenOf(store, task)} + source := `{"source":"// then plandb done\ntext(\"run plandb add next\")"}` + if err := rec.record(1, session.Event{Kind: session.EventToolEnd, Tool: "script", CallID: "s", Args: source}); err != nil { + t.Fatal(err) + } + steps, err := Trajectory(root, task) + if err != nil || len(steps) != 1 { + t.Fatalf("steps = %+v, err = %v", steps, err) + } + if len(steps[0].Writes) != 0 { + t.Errorf("writes = %v; a script's source ran no plandb command", steps[0].Writes) + } +} diff --git a/internal/run/trajectory.go b/internal/run/trajectory.go index c90b79ac22..ae1b1f754d 100644 --- a/internal/run/trajectory.go +++ b/internal/run/trajectory.go @@ -83,6 +83,11 @@ type Step struct { // off the store after the command rather than parsed out of its output. Children []string `json:"children,omitempty"` + // Calls are the tool calls a script step made, in the order they ended + // (internal/session's tool_script.go). They are not steps: they spend + // nothing of the step cap, and a page hangs them under the script's row. + Calls []StepCall `json:"calls,omitempty"` + // NotRun is established by the engine when the ended tool event is an // answer the harness wrote rather than a call the belt ran. The requested // command and the answer remain in the record; a surface reads this fact and @@ -288,3 +293,17 @@ func RecordTaskTrajectoryOrder() func() { previous := taskTrajectoryOrdering.Swap(true) return func() { taskTrajectoryOrdering.Store(previous) } } + +// StepCall is one call a script made, recorded on the script's step. +type StepCall struct { + Tool string `json:"tool"` + Command string `json:"command"` + Observation string `json:"observation,omitempty"` + // ExitCode is a bash call's exit status, recorded as a step's is; nil for + // every other tool and for a call nothing ran. + ExitCode *int `json:"exit_code,omitempty"` + // Failed says the call ended in an error; NotRun that the harness answered + // it and nothing ran. + Failed bool `json:"failed,omitempty"` + NotRun bool `json:"not_run,omitempty"` +} diff --git a/internal/session/agent.go b/internal/session/agent.go index 36066243eb..ee56a7bda8 100644 --- a/internal/session/agent.go +++ b/internal/session/agent.go @@ -59,6 +59,10 @@ func New(config Config) (*Agent, error) { // which service this conversation was using. launchModel := config.Model config.Model, _ = roles.SplitEffort(config.Model) + // THE CHAT'S SCRIPT SWITCH IS READ HERE AND NOWHERE ELSE, so only a + // session built through this door can carry it: a child built inside a + // session goes through [Agent.newChildAgent] and never reads it. + config.chatScript = chatScriptAsked() // AND THE REQUEST ROAD IS THE CALLER'S WHEN IT SAID ONE. A caller that has // already resolved its provider — the bash-belt worker seat, handed this // conversation's account-aware completer — hands it in rather than have one @@ -5198,7 +5202,9 @@ func (h *eventHub) send(event Event) (landed bool) { return false } event.ReplayCursor = h.replayCursor - if event.Kind == EventToolEnd || event.Kind == EventToolFailed { + // A SCRIPT'S OWN CALL IS NOT ONE OF THE TURN'S CALLS: the step frame reads + // this count, and the step is the script (tool_script.go). + if (event.Kind == EventToolEnd || event.Kind == EventToolFailed) && !event.FromScript() { h.finishedCalls++ } // The backlog is written BEFORE the fan-out and under the same lock, so what @@ -5968,6 +5974,22 @@ func shapeInto(messages []ai.Message, journal *sessionFile, steps *map[int]facto ToolProcess: result.process, At: journal.written(msg), }) + // AND THE CALLS A SCRIPT MADE FOLLOW IT, as the live window drew + // them: the journal's nested lines are the only record of them. + for _, nested := range journal.nested(call.ID) { + entries = append(entries, DisplayEntry{ + Role: "tool", + RunID: run, + Tool: nested.Tool, + CallID: nested.CallID, + Args: nested.Args, + Output: nested.Output, + Answered: true, + ToolResult: ToolResultNested, + Took: journal.took(nested.CallID), + At: journal.written(msg), + }) + } } } return entries diff --git a/internal/session/bashbelt.go b/internal/session/bashbelt.go index f4ae208fe1..23e29794b4 100644 --- a/internal/session/bashbelt.go +++ b/internal/session/bashbelt.go @@ -63,6 +63,9 @@ func (a *Agent) bashBelt() []bare.Tool { if hand := a.branchBash(); hand.Name != "" { tools = append(tools, hand) } + if a.config.mayScript() { + tools = append(tools, a.scriptTool()) + } tools = append(tools, a.documentTool(), a.jobsTool(), a.manualTool()) // ASK IS OFF THIS BELT. A bash-belt worker coordinates through the plan CLI // and reports through `plandb done`; there is no consent gate to reach the @@ -120,13 +123,7 @@ func (a *Agent) bashBelt() []bare.Tool { // and promotion door (Decision 6: background and jobs stay, because a worker // nobody watches must not hold its node on a clock). func (a *Agent) branchBash() bare.Tool { - hand := bare.Tool{} - for _, tool := range bare.AllToolsCapped(a.config.Workspace, bashBeltSourceCaps()) { - if tool.Name == "bash" { - hand = tool - break - } - } + hand := a.wideBash() if hand.Name == "" { return hand } @@ -163,6 +160,11 @@ func (a *Agent) truncatingBash(inner bare.Tool) bare.Tool { g.planPulse() } } + // A SCRIPT'S BASH IS CUT AT THE SCRIPT'S WIDTH, because the + // script reads it before the model does (tool_script.go). + if probe := scriptBashFrom(ctx); probe != nil { + return a.cutScriptBash(probe, text), isError, nil + } return a.cutBashResult(text), isError, nil }, } diff --git a/internal/session/bashbelt_truncate.go b/internal/session/bashbelt_truncate.go index 3c0c5b3fcf..d7dc23a5b8 100644 --- a/internal/session/bashbelt_truncate.go +++ b/internal/session/bashbelt_truncate.go @@ -35,22 +35,30 @@ const bashSpillName = "action-%06d.txt" // command's exit said: a timeout's own status line is the tail of the text and // survives the cut, which is exactly where it belongs. func (a *Agent) cutBashResult(text string) string { - caps := a.resultCaps() - if len(text) <= caps.MaxBytes { - return text + cut, _, _ := a.cutBashAt(text, a.resultCaps().MaxBytes, bashSpillName) + return cut +} + +// cutBashAt is the cut at any byte cap: the window's for the model, a script's +// wider one for a script ([scriptBashBytes]), each filing under its own name +// pattern. It answers whether it cut and the file that holds the whole output, +// empty when it could not be filed. +func (a *Agent) cutBashAt(text string, max int, spillName string) (string, bool, string) { + if len(text) <= max { + return text, false, "" } - head := utf8SafeCut(text, caps.MaxBytes/2) - tail := utf8SafeTail(text, caps.MaxBytes-caps.MaxBytes/2) + head := utf8SafeCut(text, max/2) + tail := utf8SafeTail(text, max-max/2) // AND THE WHOLE OUTPUT IS NOT THROWN AWAY. Where it can be filed it is // filed beside this node's journal and the marker names the file; where // there is no journal to sit beside, the temp directory takes it, because // the one thing the cut must never do is hand the model a path into the // working copy it is standing in. - path, err := a.spillBashOutput(text) + path, err := a.spillBashOutput(text, spillName) if err != nil { - return text[:head] + "\n" + fmt.Sprintf(bashTruncationMarker, "unavailable") + "\n" + tail + return text[:head] + "\n" + fmt.Sprintf(bashTruncationMarker, "unavailable") + "\n" + tail, true, "" } - return text[:head] + "\n" + fmt.Sprintf(bashTruncationMarker, path) + "\n" + tail + return text[:head] + "\n" + fmt.Sprintf(bashTruncationMarker, path) + "\n" + tail, true, path } // utf8SafeCut answers the longest prefix of s at or under max bytes that ends @@ -84,7 +92,7 @@ func utf8SafeTail(s string, max int) string { // directory rather than from a counter, because a worker's life is one // directory and reading it is the one source of truth for what is already // there; the exclusive create closes the race the scan leaves open. -func (a *Agent) spillBashOutput(text string) (string, error) { +func (a *Agent) spillBashOutput(text, spillName string) (string, error) { dir := a.logDirectory() if dir == "" { return "", fmt.Errorf("no directory to file the output in") @@ -93,13 +101,13 @@ func (a *Agent) spillBashOutput(text string) (string, error) { if entries, err := os.ReadDir(dir); err == nil { for _, entry := range entries { var n int - if _, err := fmt.Sscanf(entry.Name(), "action-%06d.txt", &n); err == nil && n >= next { + if _, err := fmt.Sscanf(entry.Name(), spillName, &n); err == nil && n >= next { next = n + 1 } } } for attempt := 0; attempt < 1000; attempt++ { - path := fmt.Sprintf(filepath.Join(dir, bashSpillName), next) + path := fmt.Sprintf(filepath.Join(dir, spillName), next) file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) if err == nil { _, writeErr := file.WriteString(text) diff --git a/internal/session/bashbelt_worker.go b/internal/session/bashbelt_worker.go index 2727ef5ea4..8efc964631 100644 --- a/internal/session/bashbelt_worker.go +++ b/internal/session/bashbelt_worker.go @@ -74,6 +74,7 @@ func NewBeltWorker(config Config, completer Completer, task *plandb.Task, storeP } config.InTask = true config.bashBelt = true + config.script = scriptAsked() // AND IT ACTS AS ITS OWN WORKER, never as the conversation: the run named // it ([Config.WorkerDID]), and its commands carry that name. if config.WorkerDID != "" { diff --git a/internal/session/beltfacts.go b/internal/session/beltfacts.go index 10446b302d..1ac05d38ed 100644 --- a/internal/session/beltfacts.go +++ b/internal/session/beltfacts.go @@ -319,6 +319,19 @@ func (c Config) mayProposeSubharness() bool { // on. func (c Config) mayBashBelt() bool { return c.InTask && c.bashBelt && !c.readingTask() } +// mayScript is the script tool's predicate: a bash-belt worker whose switch was +// on when it was built (tool_script.go), unless it is a quick task's. +// +// A QUICK WORKER HOLDS ITS NODE'S LOCK FOR THE WHOLE OF EACH CALL +// ([Agent.executeTaskTool]), and a script's nested call takes the same lock +// again; the mutex is not reentrant, so the script would wait forever. +func (c Config) mayScript() bool { return c.mayBashBelt() && c.script && c.quickItems == nil } + +// mayChatScript is the script tool's predicate on a conversation's belt: a +// session that is not a task, built by [New] with CODEAF_CHAT_SCRIPT on +// (tool_script.go). +func (c Config) mayChatScript() bool { return c.chatScript && !c.InTask } + // ── the facts ─────────────────────────────────────────────────────────────── // beltFact is one run of session-facts bullets that names a tool, together with diff --git a/internal/session/loop.go b/internal/session/loop.go index a1568bd636..ad70eb2ec8 100644 --- a/internal/session/loop.go +++ b/internal/session/loop.go @@ -3648,20 +3648,7 @@ func (a *Agent) runToolsWarm(ctx context.Context, ep *episode, calls []ai.ToolCa } for index, call := range calls { rendered[index] = argsText(call) - service, serviceName := a.serviceOf(call.Function.Name), "" - if service != "" { - serviceName = a.serviceName(service) - } - hub.send(a.clientToolEvent(Event{ - Kind: EventToolBegin, - Tool: call.Function.Name, - Hint: a.gloss(call), - Args: rendered[index], - CallID: call.ID, - Batch: batch, - Service: service, - ServiceName: serviceName, - })) + hub.send(a.toolBeginEvent(call, rendered[index], batch)) } // THE NARRATOR ARMS BESIDE THE WORK, not after a long silence. A half-second @@ -3768,51 +3755,75 @@ func (a *Agent) runToolsWarm(ctx context.Context, ep *episode, calls []ai.ToolCa // tool more than once, because neither its name nor completion order identifies // the row. for index, call := range calls { - if results[index].isError { - a.sendBeltStep(ctx, hub, Event{ - Kind: EventToolFailed, - Err: results[index].err, - Tool: call.Function.Name, - Hint: clip(firstLine(results[index].text), hintLimit), - Args: rendered[index], - Output: capOutput(results[index].text), - CallID: call.ID, - Exit: resultExit(results[index].text), - // WHOSE FAILURE THIS WAS travels with it. Everything counting - // steps out of band — the runner's no-progress ledger above all — - // reads events and not results, so a fact kept only on the result - // is a fact no counter can act on (withdrawn.go). - HarnessMade: results[index].harness, - // AN ATTEMPTED ACTION A DOOR REFUSED is the one harness-made - // answer with a veto's author on it ([episode.preAction]); a - // correction about the reply's form has none. - Refused: results[index].harness && results[index].refusedBy != "", - // AND WHETHER THE TOOL TURNED THE ARGUMENTS AWAY BEFORE IT RAN, as a - // typed fact from the handler's own validation return. - RejectedBeforeRun: results[index].rejected, - ToolInvoked: results[index].invoked, - MediaAttempt: results[index].attempt, - }) - continue - } - // A successful tool's hint is empty: the result belongs to the model, - // and the person already read what the call was going to do. Output is - // there for a person who asks to see it anyway. - a.sendBeltStep(ctx, hub, Event{ - Kind: EventToolEnd, - ToolInvoked: results[index].invoked, - MediaAttempt: results[index].attempt, - ToolProcess: results[index].process, - Tool: call.Function.Name, - Args: rendered[index], - Output: capOutput(results[index].text), - CallID: call.ID, - Exit: resultExit(results[index].text), - }) + a.sendBeltStep(ctx, hub, toolEndEvent(call, rendered[index], results[index])) } return results } +// toolBeginEvent is one call's begin, the same for a call the model made and +// one a script made (tool_script.go), so the two rows carry the same facts. +func (a *Agent) toolBeginEvent(call ai.ToolCall, rendered, batch string) Event { + service, serviceName := a.serviceOf(call.Function.Name), "" + if service != "" { + serviceName = a.serviceName(service) + } + return a.clientToolEvent(Event{ + Kind: EventToolBegin, + Tool: call.Function.Name, + Hint: a.gloss(call), + Args: rendered, + CallID: call.ID, + Batch: batch, + Service: service, + ServiceName: serviceName, + }) +} + +// toolEndEvent is one call's end, built from its result — one builder for the +// batch and for a script's calls, so a field added here reaches both. +func toolEndEvent(call ai.ToolCall, rendered string, result toolResult) Event { + if result.isError { + return Event{ + Kind: EventToolFailed, + Err: result.err, + Tool: call.Function.Name, + Hint: clip(firstLine(result.text), hintLimit), + Args: rendered, + Output: capOutput(result.text), + CallID: call.ID, + Exit: resultExit(result.text), + // WHOSE FAILURE THIS WAS travels with it. Everything counting + // steps out of band — the runner's no-progress ledger above all — + // reads events and not results, so a fact kept only on the result + // is a fact no counter can act on (withdrawn.go). + HarnessMade: result.harness, + // AN ATTEMPTED ACTION A DOOR REFUSED is the one harness-made + // answer with a veto's author on it ([episode.preAction]); a + // correction about the reply's form has none. + Refused: result.harness && result.refusedBy != "", + // AND WHETHER THE TOOL TURNED THE ARGUMENTS AWAY BEFORE IT RAN, as a + // typed fact from the handler's own validation return. + RejectedBeforeRun: result.rejected, + ToolInvoked: result.invoked, + MediaAttempt: result.attempt, + } + } + // A successful tool's hint is empty: the result belongs to the model, + // and the person already read what the call was going to do. Output is + // there for a person who asks to see it anyway. + return Event{ + Kind: EventToolEnd, + ToolInvoked: result.invoked, + MediaAttempt: result.attempt, + ToolProcess: result.process, + Tool: call.Function.Name, + Args: rendered, + Output: capOutput(result.text), + CallID: call.ID, + Exit: resultExit(result.text), + } +} + // resultExitRe is the status line a shell call's result ends with when its // command exited with a code other than zero. var resultExitRe = regexp.MustCompile(`Command exited with code (-?\d+)`) @@ -3870,6 +3881,17 @@ func (a *Agent) executeTool(ctx context.Context, ep *episode, hub *eventHub, cal a.toolsInFlight.Add(1) defer a.toolsInFlight.Add(-1) a.wakeBudgetForWork() + // THE TURN RIDES ON THE CONTEXT FROM HERE, whichever road called: a tool + // that makes calls of its own (tool_script.go) reaches the gate through + // these two. A saved program's tool() passes them only as parameters + // (subharness_env.go), and a script it called once ran its nested calls + // with no approval rules at all. + if episodeFrom(ctx) != ep { + ctx = withEpisode(ctx, ep) + } + if eventHubFrom(ctx) != hub { + ctx = withEventHub(ctx, hub) + } result := a.dispatchTool(ctx, ep, hub, call, rendered) // Only a call that RAN counts: a door that refused it before it ran, or a // hand withdrawn off the belt, is the harness's own answer and rides on @@ -3932,22 +3954,22 @@ func (a *Agent) executeRecorded(ctx context.Context, tool bare.Tool, args json.R // dispatchTool is the dispatch itself: find the hand, ask the doors, run it. func (a *Agent) dispatchTool(ctx context.Context, ep *episode, hub *eventHub, call ai.ToolCall, rendered string) toolResult { if err := a.jobBudgetBlock(); err != nil { - return a.finishToolResult(ep, call, toolResult{text: err.Error(), isError: true, harness: true}) + return a.finishToolResult(ctx, ep, call, toolResult{text: err.Error(), isError: true, harness: true}) } // A reading cannot ask, including through consent or an off-belt call. // Refuse before pre-action can open a question or capture a file. if refusal := a.readingToolRefusal(call.Function.Name); refusal != "" { - return a.finishToolResult(ep, call, toolResult{text: refusal, isError: true, harness: true}) + return a.finishToolResult(ctx, ep, call, toolResult{text: refusal, isError: true, harness: true}) } for _, tool := range a.beltTools() { if tool.Name != call.Function.Name { continue } if invalid := invalidBashArguments(call.Function.Name, json.RawMessage(call.Function.Arguments)); invalid != "" { - return a.finishToolResult(ep, call, toolResult{text: invalid, isError: true, rejected: true}) + return a.finishToolResult(ctx, ep, call, toolResult{text: invalid, isError: true, rejected: true}) } if err := a.waitWorkspaceReady(ctx, call.Function.Name); err != nil { - return a.finishToolResult(ep, call, toolResult{text: err.Error(), isError: true, harness: true}) + return a.finishToolResult(ctx, ep, call, toolResult{text: err.Error(), isError: true, harness: true}) } running, refused, allowed := ep.preAction(ctx, hub, call) if !allowed { @@ -3966,8 +3988,11 @@ func (a *Agent) dispatchTool(ctx context.Context, ep *episode, hub *eventHub, ca args := json.RawMessage(running.Function.Arguments) // A read for bytes this conversation already has is answered from above, // not from the disk (heldreads.go) — the gate above already judged it. - if pointer, held := a.heldClaim(call.Function.Name, args); held { - return a.finishToolResult(ep, call, toolResult{text: pointer}) + // A script's read is answered from the disk: it cannot see the + // transcript a pointer points at (tool_script.go's withScriptParent). + nested := inScript(ctx) + if pointer, held := a.heldClaim(call.Function.Name, args); held && !nested { + return a.finishToolResult(ctx, ep, call, toolResult{text: pointer}) } started := time.Now() // THE CALL'S OWN ID TRAVELS WITH IT. It is what lets a tool still @@ -3978,7 +4003,7 @@ func (a *Agent) dispatchTool(ctx context.Context, ep *episode, hub *eventHub, ca // start carries it exactly as the batch does. callCtx := withCallID(ctx, call.ID) if hub != nil && (a.config.LiveToolOutput || a.liveOutputWanted.Load() > 0) { - callCtx = bare.WithBashOutput(callCtx, &shellOutput{hub: hub, id: call.ID, tool: call.Function.Name, bytes: liveToolOutputBytes, lines: liveToolOutputLines}) + callCtx = bare.WithBashOutput(callCtx, &shellOutput{hub: hub, id: call.ID, parent: scriptParentFrom(ctx), tool: call.Function.Name, bytes: liveToolOutputBytes, lines: liveToolOutputLines}) } // THE CALL-LOCAL MARK a handler's argument refusal sets (toolrejection.go): // planted here so it lives and dies with this one call. @@ -4019,13 +4044,14 @@ func (a *Agent) dispatchTool(ctx context.Context, ep *episode, hub *eventHub, ca Tool: call.Function.Name, Args: rendered, CallID: call.ID, + Parent: scriptParentFrom(ctx), Took: took, }) } if err != nil { // Harness-level failure: the model sees the Go error as the tool // result, the same shape a thrown error takes on the wire. - return a.finishToolResult(ep, call, toolResult{text: err.Error(), isError: true, invoked: invocation.Load(), attempt: attempt.Load()}) + return a.finishToolResult(ctx, ep, call, toolResult{text: err.Error(), isError: true, invoked: invocation.Load(), attempt: attempt.Load()}) } // AND THE LAST THING THAT HAPPENS TO A RESULT IS THE ERROR→FIX SIDECAR // (fixrecall.go). A failure this machine has seen before leaves with one @@ -4043,10 +4069,13 @@ func (a *Agent) dispatchTool(ctx context.Context, ep *episode, hub *eventHub, ca if process != nil && !isError && ctx.Err() == nil { became = process.Load() } - result := a.finishToolResult(ep, call, toolResult{text: text, isError: isError, invoked: invocation.Load(), rejected: isError && rejection.RejectedBeforeRun(), attempt: attempt.Load(), process: became, interruption: interruption}) + result := a.finishToolResult(ctx, ep, call, toolResult{text: text, isError: isError, invoked: invocation.Load(), rejected: isError && rejection.RejectedBeforeRun(), attempt: attempt.Load(), process: became, interruption: interruption}) // The held-range ledger records on the FINISHED text — exactly the bytes // the transcript will carry — and only on a result that ran (heldreads.go). - a.heldNote(call.Function.Name, args, result.text, isError) + // A script's read never reaches the transcript, so it holds nothing. + if !nested { + a.heldNote(call.Function.Name, args, result.text, isError) + } return result } // ── TAKEN, OR NEVER HELD ── @@ -4108,8 +4137,14 @@ func (a *Agent) dispatchTool(ctx context.Context, ep *episode, hub *eventHub, ca // a test — cannot return a credential without passing this line. A worker that // ran `gh auth token` put a live OAuth token in two task journals in plain text // before it existed. -func (a *Agent) finishToolResult(ep *episode, call ai.ToolCall, result toolResult) toolResult { +func (a *Agent) finishToolResult(ctx context.Context, ep *episode, call ai.ToolCall, result toolResult) toolResult { result.text = redact.Secrets(result.text) + // A SCRIPT'S CALL IS REDACTED AND NOTHING MORE. The fix-recall line and the + // job footer are written for the model; in a script's data they corrupt + // what it parses, and the footer would be spent before the model read it. + if inScript(ctx) { + return result + } body := result.text rejected, invoked, attempt := result.rejected, result.invoked, result.attempt result = a.withJobState(ep, ep.noteToolOutcome(call, result)) diff --git a/internal/session/plandb_tasks.go b/internal/session/plandb_tasks.go index 7f6e98f0eb..f0d426f627 100644 --- a/internal/session/plandb_tasks.go +++ b/internal/session/plandb_tasks.go @@ -243,8 +243,12 @@ type PlanTaskModel struct { // imports this one, so the step line is decoded here from the same JSON shape. // The two must move together, and the run engine's own file is the definition. type PlanStep struct { - Kind string `json:"kind"` - Step int `json:"step"` + Kind string `json:"kind"` + Step int `json:"step"` + // Tool is the action the step took, as internal/run's Step records it; + // empty on records written before the field and on the belt's bash steps + // a surface draws the way it always has. + Tool string `json:"tool,omitempty"` Command string `json:"command"` Observation string `json:"observation,omitempty"` FullOutput string `json:"full_output,omitempty"` @@ -267,6 +271,20 @@ type PlanStep struct { // PURPOSE: its absence is false, so a step from an engine built before the // field, and a step no display facts were made for, draws its head as it did. ObservationHeadWithheld bool `json:"observation_head_withheld,omitempty"` + // Calls are the tool calls a script step made, mirrored from + // internal/run's StepCall; a page hangs them under the step. + Calls []PlanCall `json:"calls,omitempty"` +} + +// PlanCall is one call a script step made: the session's mirror of +// internal/run's StepCall, with the same JSON names. +type PlanCall struct { + Tool string `json:"tool"` + Command string `json:"command"` + Observation string `json:"observation,omitempty"` + ExitCode *int `json:"exit_code,omitempty"` + Failed bool `json:"failed,omitempty"` + NotRun bool `json:"not_run,omitempty"` } // PlanCommandPart is one quote-aware command part and the facts only the diff --git a/internal/session/prompt.go b/internal/session/prompt.go index c19fffda7c..84019502fe 100644 --- a/internal/session/prompt.go +++ b/internal/session/prompt.go @@ -322,7 +322,7 @@ func renderSystemAt(config Config, now time.Time) string { // requirement rather than follow a doctrine that promises it. out.WriteString("You are codeaf. Shell commands are unavailable here. Explain the shell requirement from Project, and do not claim to run commands. The manual tool can explain Windows setup.\n") } else { - out.WriteString(bashWorkerPage()) + out.WriteString(bashWorkerDoctrine(config)) if config.AttributionOff { out.WriteString("\n\n") out.WriteString(exec.AttributionOffLaw) @@ -417,6 +417,18 @@ func renderSystemAt(config Config, now time.Time) string { // ── the bash worker's page ────────────────────────────────────────────────── +// bashWorkerDoctrine is [bashWorkerPage] with the paragraph for each hand this +// worker carries beyond the page's own: today only the script tool, which is +// named only where the belt has it, because a page naming a tool the belt lacks +// is the prompt lying. +func bashWorkerDoctrine(config Config) string { + page := bashWorkerPage() + if config.mayScript() { + page += "\n\n" + scriptWorkerRule + } + return page +} + // bashWorkerPage composes the page a bash-belt worker opens message[0] on: the // loop policy it works by and the belt's doctrine (the plan CLI and the shell // idioms), and nothing else. [renderSystemAt] appends the project footer after diff --git a/internal/session/readhandoff.go b/internal/session/readhandoff.go index bd2b7f9a2b..3523fb9e90 100644 --- a/internal/session/readhandoff.go +++ b/internal/session/readhandoff.go @@ -209,7 +209,7 @@ func (a *Agent) handoffReadSweep(ctx context.Context, ep *episode, hub *eventHub if hub != nil { hub.send(Event{Kind: EventToolFinished, Tool: call.Function.Name, Args: rendered[index], CallID: call.ID, Took: took}) } - byID[call.ID] = a.finishToolResult(ep, call, toolResult{text: sweepMovedWord, harness: true}) + byID[call.ID] = a.finishToolResult(ctx, ep, call, toolResult{text: sweepMovedWord, harness: true}) } for index, call := range rest { byID[call.ID] = restResults[index] @@ -272,7 +272,7 @@ func (a *Agent) handoffReadSweep(ctx context.Context, ep *episode, hub *eventHub if index == 0 { text = sweepHandoffWord(id) + "\n\n" + answer } - byID[call.ID] = a.finishToolResult(ep, call, toolResult{text: text, harness: true}) + byID[call.ID] = a.finishToolResult(ctx, ep, call, toolResult{text: text, harness: true}) if hub != nil { hub.send(Event{ Kind: EventToolEnd, Tool: call.Function.Name, CallID: call.ID, diff --git a/internal/session/session.go b/internal/session/session.go index c3efd33d4f..aac38d2db2 100644 --- a/internal/session/session.go +++ b/internal/session/session.go @@ -1029,6 +1029,13 @@ type Event struct { // the same field with two answers. CallID string + // Parent is the id of the script call this call was made from, on every + // event a call a script made raises (tool_script.go), and empty on every + // call the model made itself. A reader that counts the model's steps skips + // a call with a parent: the step is the script. Read it through + // [Event.FromScript]. + Parent string `json:"Parent,omitempty"` + // Exit is the exit code a call's result reports, on EventToolEnd and // EventToolFailed, and nil when it reports none. Exit *int `json:"Exit,omitempty"` @@ -1272,6 +1279,11 @@ type Event struct { ModelNote string } +// FromScript says whether this event is about a call a script made rather +// than one the model made itself ([Event.Parent]): the one test every reader +// that counts or draws the model's steps asks. +func (e Event) FromScript() bool { return e.Parent != "" } + // Usage is token and cost accounting for one turn or the session total. type Usage struct { Input int @@ -2483,6 +2495,16 @@ type Config struct { //. bashBelt bool + // script arms the script tool on a bash-belt worker. It is set with + // bashBelt, from CODEAF_TASK_SCRIPT, and read only through + // [Config.mayScript]. + script bool + + // chatScript arms the script tool on a conversation's own belt. [New] sets + // it from CODEAF_CHAT_SCRIPT, so a child built inside a session never has + // it, and it is read only through [Config.mayChatScript]. + chatScript bool + // reviseDesign is the one extra hand a design thread has, and the whole of // what puts revise_design on its belt (tools_harness.go). It carries the // change, in the person's own words, to the design loop parked on the diff --git a/internal/session/sessionfile.go b/internal/session/sessionfile.go index b56d0dddbc..82b134be0f 100644 --- a/internal/session/sessionfile.go +++ b/internal/session/sessionfile.go @@ -11,6 +11,7 @@ import ( "io" "os" "path/filepath" + "slices" "sort" "strconv" "strings" @@ -186,6 +187,12 @@ type sessionEntry struct { // file written before the line existed. Took *journalTook `json:"took,omitempty"` + // Nested is ONE CALL A SCRIPT MADE (tool_script.go). The model read only + // the script's result, so no message carries the call, and a reopened + // conversation draws it under its script from this line alone. Absent from + // every line that is not one, and from every file written before it existed. + Nested *journalNested `json:"nested,omitempty"` + // Pace is ONE TURN'S DECOMPOSITION: how long the person waited to be sent // anywhere, how long they then waited for a word, and the worst gap between a // tool result and the next request. Absent from every line that is not one, @@ -1005,6 +1012,17 @@ type journalTook struct { DurationMS int64 `json:"durationMs"` } +// journalNested is ONE CALL A SCRIPT MADE as the journal holds it: the script +// call it came from, its own id, and the row a person was shown — its rendered +// arguments and its output capped as the live row's was. +type journalNested struct { + Parent string `json:"parent"` + CallID string `json:"callId"` + Tool string `json:"tool"` + Args string `json:"args,omitempty"` + Output string `json:"output,omitempty"` +} + // journalFlight is ONE REQUEST'S LIFE, written at its two ends: once when it // goes out and once when it comes back, whichever way it came back. // @@ -1239,6 +1257,11 @@ type sessionFile struct { // no duration, which is the lie a room opened after landing used to tell. tooks map[string]journalTook + // nesteds is THE CALLS EACH SCRIPT MADE, in the order they ended, keyed by + // the script call's id ([journalNested]). It lives here for the tooks' + // reason: the model never read these calls, so no message holds them. + nesteds map[string][]journalNested + // stamps is when each message's line was written (entrytime.go). stamps *stampIndex @@ -1509,6 +1532,33 @@ func (s *sessionFile) appendTook(callID string, took time.Duration) { s.writeLine(sessionEntry{Type: "took", Took: &mark, Timestamp: stamp()}) } +// appendNested journals one call a script made and indexes it under its +// script, so the live record and a reopened one draw the same rows. +func (s *sessionFile) appendNested(mark journalNested) { + if s == nil || strings.TrimSpace(mark.Parent) == "" || strings.TrimSpace(mark.CallID) == "" { + return + } + s.mu.Lock() + if s.nesteds == nil { + s.nesteds = make(map[string][]journalNested, 1) + } + s.nesteds[mark.Parent] = append(s.nesteds[mark.Parent], mark) + s.mu.Unlock() + s.writeLine(sessionEntry{Type: "nested", Nested: &mark, Timestamp: stamp()}) +} + +// nested answers the calls one script made, in the order they ended; none for +// a call that is not a script, a file with no journal, and every file written +// before the line existed. +func (s *sessionFile) nested(parent string) []journalNested { + if s == nil || parent == "" { + return nil + } + s.mu.Lock() + defer s.mu.Unlock() + return slices.Clone(s.nesteds[parent]) +} + // rememberSteer marks one message as a splice, in a map the caller owns — the // file's, under its lock, or the one a replay is still building. It is // [rememberNote]'s twin and keeps its shape on purpose: the two facts are @@ -1757,6 +1807,7 @@ func openSessionFile(path, cwd, model, id string) (*sessionFile, replayedSession journal.steers = replayed.steers journal.captions = replayed.captions journal.tooks = replayed.tooks + journal.nesteds = replayed.nesteds journal.stamps = replayed.stamps if journal.stamps == nil { journal.stamps = &stampIndex{} @@ -1948,6 +1999,9 @@ func readJournal(reader io.Reader, path string, rebuild bool) (replayedSession, // one call's duration that is not carried by any message (see // [sessionFile.tooks]). tooks := make(map[string]journalTook) + // And the nested index, for the tooks' reason: a script's calls are not + // carried by any message (see [sessionFile.nesteds]). + nesteds := make(map[string][]journalNested) replyTags := make(map[string][]TaskReplyTag) delivered := make(map[string]bool) noteDeliveries := make(map[string][]string) @@ -2173,6 +2227,17 @@ func readJournal(reader io.Reader, path string, rebuild bool) (replayedSession, continue } tooks[mark.CallID] = mark + case "nested": + // ONE CALL A SCRIPT MADE. It rebuilds no message — the model read + // only the script's result — so it only indexes, under its script. + if entry.Nested == nil { + continue + } + mark := *entry.Nested + if strings.TrimSpace(mark.Parent) == "" || strings.TrimSpace(mark.CallID) == "" { + continue + } + nesteds[mark.Parent] = append(nesteds[mark.Parent], mark) case "steer": // A STEER THAT FELL THROUGH, and nothing is rebuilt from it // ([sessionFile.appendSteerFellThrough]). Those words never reached @@ -2387,6 +2452,7 @@ func readJournal(reader io.Reader, path string, rebuild bool) (replayedSession, steers: steers, captions: captions, tooks: tooks, + nesteds: nesteds, usage: spent, created: created, requests: requests, @@ -2598,6 +2664,9 @@ type replayedSession struct { // tooks is how long each call ran, keyed by the call's own id — the index // [sessionFile.tooks] is opened holding. tooks map[string]journalTook + // nesteds is the calls each script made, keyed by the script call's id — + // the index [sessionFile.nesteds] is opened holding. + nesteds map[string][]journalNested // stamps is when each message's line was written (entrytime.go). stamps *stampIndex // unread is the 1-based line of the file this reading could not get past, and diff --git a/internal/session/task_app_steps.go b/internal/session/task_app_steps.go index 80e1fc2aa9..80d4175308 100644 --- a/internal/session/task_app_steps.go +++ b/internal/session/task_app_steps.go @@ -100,6 +100,10 @@ type AppTaskStep struct { // Call is the provider's id for the call, and "" where the record never had // one. A live end pairs on it. Call string + // Parent is the call id of the script that made this call, and "" for a + // call the model made itself ([Event.Parent]). A surface hangs a step with + // a parent under that script rather than drawing it as a step of its own. + Parent string // Tool is the engine's REGISTERED tool name ("bash", "read", "edit"), and "" // where the record does not name one. A surface reads the kind off this // through the engine's own family and never off the words of a gloss. @@ -247,6 +251,7 @@ func (l *taskLive) openStep(event Event, at time.Time) { step := AppTaskStep{ ID: appLiveStepID(event, len(l.calls)), Call: event.CallID, + Parent: event.Parent, Tool: strings.TrimSpace(event.Tool), Category: toolEventCategory(event), Target: appStepText(event.Hint), diff --git a/internal/session/task_child_run.go b/internal/session/task_child_run.go index 92676980ad..b2a7819a08 100644 --- a/internal/session/task_child_run.go +++ b/internal/session/task_child_run.go @@ -404,6 +404,14 @@ func (r *childRun) drain(events <-chan Event) { // clock that bounds the wait for its next event. func (r *childRun) observe(event Event) { r.room.publish(event) + // A SCRIPT'S OWN CALL IS NOT A STEP: the script is, and its end comes after + // every call it made. A check it ran is still a check the node ran. + if event.FromScript() { + if event.Kind == EventToolEnd || event.Kind == EventToolFailed { + r.noteCheck(event) + } + return + } switch event.Kind { case EventToolBegin: r.batchBegan() @@ -457,6 +465,14 @@ func (r *childRun) tellSpend() { home.emitTaskUpdate(r.node.notice()) } +// noteCheck records a finished call that ran the node's work — a build, a +// test — whether the model made it or a script did. +func (r *childRun) noteCheck(event Event) { + if checkingTools[event.Tool] && !event.HarnessMade { + r.ranCheck = true + } +} + // step reads ONE FINISHED TOOL CALL, which is the only unit available from out // here: the child's model round-trips are inside its own loop, and this side of // the wall sees the calls they produce. @@ -486,9 +502,7 @@ func (r *childRun) step(event Event) { // (withdrawn.go's [checkingTools]). A harness-made failure does not // count: an answer this side of the wall wrote is not the node // having run anything. - if checkingTools[event.Tool] && !event.HarnessMade { - r.ranCheck = true - } + r.noteCheck(event) // ALL THREE QUESTIONS ARE ASKED OF EVERY STEP, and each is // asked before any of them is read, because two of them RECORD // as they answer. The worktree fingerprint has to be refreshed diff --git a/internal/session/task_live.go b/internal/session/task_live.go index ffebc67d4c..9011324823 100644 --- a/internal/session/task_live.go +++ b/internal/session/task_live.go @@ -130,6 +130,15 @@ func (l *taskLive) record(event Event) { // disagree about when it happened. at := time.Now() l.recordStep(event, at) + // A SCRIPT'S OWN CALL IS NARRATED AND NOT COUNTED. The step count is the + // node's threshold unit and the script is the step, and the call in flight + // stays the script until the script ends (tool_script.go). + if event.FromScript() { + if event.Kind == EventToolBegin { + l.push(" " + taskLiveCall(event)) + } + return + } switch event.Kind { case EventTextDelta: l.write(event.Text) diff --git a/internal/session/task_run.go b/internal/session/task_run.go index 97401b6afa..bfac59dab2 100644 --- a/internal/session/task_run.go +++ b/internal/session/task_run.go @@ -7085,6 +7085,12 @@ func taughtSomething(event Event, ledger *progressLedger) bool { if event.HarnessMade || !couldHaveTaught(event) { return false } + // A SCRIPT'S ANSWER IS JUDGED WITHOUT ITS OWN STATUS LINE, which carries + // the script's duration: the same findings at a different speed are the + // same answer, and a spin must not read as news because its clock moved. + if event.Tool == ScriptToolName { + event.Output = scriptReportBody(event.Output) + } return freshAnswer(event, ledger) } @@ -7100,8 +7106,13 @@ func taughtSomething(event Event, ledger *progressLedger) bool { // this clause a node that measured its three clips before joining them was three // steps nearer being stopped for making no progress — the precise punishment for // exploring that [knowledgeTools] was widened to the whole read-only belt to end. +// +// A SCRIPT IS BASH'S CASE ONE LEVEL UP. Its calls are the node's reading as +// much as a bash command's are, and they never reach this counter on their own +// (a nested call is not a step), so the script's answer is what the node +// learned from them. func couldHaveTaught(event Event) bool { - if event.Tool == "bash" || knowledgeTools[event.Tool] { + if event.Tool == "bash" || event.Tool == ScriptToolName || knowledgeTools[event.Tool] { return true } return savingTools[event.Tool] && !producedAFile(event.Tool, event.Args) @@ -8010,6 +8021,10 @@ func (a *Agent) newTaskAgentOn(ctx context.Context, dir string, node *TaskNode, // never be handed the belt, and at the landing's gate, which keeps the // experiment's work unaudited (workTaskNode). bashBelt: bashExperiment, + // 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(), // ── THE TWO THINGS A QUICK WORKER HAS THAT NOTHING ELSE DOES ───────── // // THE CLAIM IT MADE ABOUT FILES, armed as the ordinary write bound: this diff --git a/internal/session/tasklook.go b/internal/session/tasklook.go index 6e34d47933..b526407554 100644 --- a/internal/session/tasklook.go +++ b/internal/session/tasklook.go @@ -113,6 +113,25 @@ func withEpisode(ctx context.Context, ep *episode) context.Context { return context.WithValue(ctx, episodeCarrier{}, ep) } +// withEventHub puts the batch's hub on the context beside the episode, for the +// one tool that makes calls of its own: a script's nested call has to raise its +// rows and questions on the turn's hub, exactly as the call would at the top +// level (tool_script.go). +func withEventHub(ctx context.Context, hub *eventHub) context.Context { + if hub == nil { + return ctx + } + return context.WithValue(ctx, eventHubCarrier{}, hub) +} + +type eventHubCarrier struct{} + +// eventHubFrom answers the batch's hub, or nil where there is none. +func eventHubFrom(ctx context.Context) *eventHub { + hub, _ := ctx.Value(eventHubCarrier{}).(*eventHub) + return hub +} + // episodeFrom answers the turn's episode, or nil where there is none — a tool // called from a test, or from a path that runs no turn. Every reader treats nil // as "no memory", so nothing here can fail a call. diff --git a/internal/session/tool_script.go b/internal/session/tool_script.go new file mode 100644 index 0000000000..2248bb71ef --- /dev/null +++ b/internal/session/tool_script.go @@ -0,0 +1,416 @@ +package session + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/env" + "github.com/Agent-Field/codeaf/internal/exec/bare" + "github.com/Agent-Field/codeaf/internal/jsrun" +) + +// THE SCRIPT TOOL: a JavaScript step that calls the belt's other tools and hands +// back only what it prints or returns, on a task worker's belt or a +// conversation's, each behind its own switch +// (internal/manual/chat/how-tasks-run.md states its rules and limits). +// +// EVERY NESTED CALL GOES THROUGH [Agent.executeTool], the one chokepoint every +// call in this program passes — the job budget, pre-action, the approval +// policy, the seat's record — exactly as a saved program's tool() does +// (subharness_env.go). A gate written here would be a second gate, so this file +// decides only what a script may NAME, and the session decides everything else. + +// ScriptToolName is the tool's one name, read by the belt, the tests and the +// surfaces outside this package that draw or record a script step. +const ScriptToolName = "script" + +// scriptCallable are the tools a script may call; every other tool on the belt +// is refused inside one. The tool's description and the manual are written from +// this list ([scriptDescription]). +// +// IT IS AN ALLOWLIST, NOT A DENYLIST. A script is for reading many things and +// keeping part of each, which is what these tools do. Asking the person, +// starting work that outlives the step (a task, a chat, a watch, a render, a +// factory or team verb) and changing settings stay steps the model takes +// itself. A denylist of those left every tool added to the belt later +// reachable from a script by default; this list grows only on purpose. A +// script inside a script would be an interpreter nobody bounded, so script is +// never on it. +var scriptCallable = []string{ + "bash", "read", "ls", "grep", "find", "read_document", + "manual", "recall", "web_search", "web_fetch", +} + +// scriptSpillName is the file a script's bash files its whole output in when +// the script-wide cut fires. It is not the step's own name (bashSpillName): the +// run's recorder takes the newest action file as the step's whole output, and a +// script's call is not the step. +const scriptSpillName = "script-call-%06d.txt" + +// scriptBashBytes is how much of one bash call's output a script sees. It is +// wider than the model's window on purpose: the point of a script is to filter +// what the model would never read whole, and what the script returns is cut to +// the window afterwards. +const scriptBashBytes = 1 << 20 + +// scriptSwitch is the variable that arms the tool. It is plumbing rather than a +// settings row for CODEAF_TASK_BELT's reason (internal/config's settings.go): +// an experiment's switch must be as easy to stop using as it was to start. +const scriptSwitch = "CODEAF_TASK_SCRIPT" + +// chatScriptSwitch arms the tool on a conversation's own belt, measured apart +// from the worker's switch so each arm changes one thing. +const chatScriptSwitch = "CODEAF_CHAT_SCRIPT" + +// scriptAsked and chatScriptAsked read the two switches. Only "on" arms one +// while the tool is measured; anything else, unset included, leaves it off. +func scriptAsked() bool { return switchedOn(scriptSwitch) } +func chatScriptAsked() bool { return switchedOn(chatScriptSwitch) } + +func switchedOn(name string) bool { + return strings.EqualFold(strings.TrimSpace(env.Get(name)), "on") +} + +// scriptDescription says in its second sentence what the sandbox is NOT. A +// pilot's worker read "JavaScript" as Node, wrote require('fs') and failed +// before its first call, because the one sentence saying otherwise came last; +// a worked example closes it. +var scriptDescription = "Run JavaScript that calls your other tools; only what it prints or returns comes back. " + + "Not Node.js: no require, import, fs, process, network or timers. Files and commands go through await tools.bash({command}). " + + "Use it for several calls in one step, or to filter large output down to what matters. " + + "The source is an async function body, so top-level await and return work. " + + "tools.(args) takes the arguments you would pass directly; write a character an identifier cannot hold as _. " + + "bash resolves to {output, exit_code, truncated, full_output_path} whatever the exit code (exit_code is null when the command was moved to the background, and output then names its job), and rejects if it timed out or was stopped; " + + "other tools resolve to their text. A refusal or error rejects with the tool's own text. " + + "text(value) and console.log add output. A script can call only these tools, where you have them: " + strings.Join(scriptCallable, ", ") + "; every other tool is refused inside one. " + + "Example: for (const f of (await tools.bash({command: \"rg -l parse_date src\"})).output.trim().split(\"\\n\")) " + + "text(f + \": \" + (await tools.bash({command: \"rg -n 'def parse_date' \" + f})).output.trim());" + +const scriptSchema = `{"type":"object","properties":{"source":{"type":"string","description":"JavaScript: the body of an async function."}},"required":["source"],"additionalProperties":false}` + +// scriptWorkerRule is the worker page's one paragraph about the tool. It gives +// bash and script one job each, so the belt does not teach two ways to say one +// thing (bashbelt.go's concern about a belt that carried both). +const scriptWorkerRule = "## Combining tool calls\n\n" + + "Use `script` to combine several tool calls in one step or to filter a large\n" + + "result before you read it. A script is not Node.js: it reaches files and\n" + + "commands only through `await tools.bash({command})`." + +// scriptTool is the tool as the belt carries it. +func (a *Agent) scriptTool() bare.Tool { + return bare.Tool{ + Name: ScriptToolName, + Description: scriptDescription, + Schema: json.RawMessage(scriptSchema), + Execute: a.runScript, + } +} + +// runScript runs one script on the turn that called it. +// +// THE TURN RIDES IN ON THE CONTEXT: the episode and the hub every call carries +// from [Agent.executeTool] are what a nested call needs to be the same call it +// would have been at the top level, and the script call's own id names its +// nested calls, so a reader can find the parent of each. +func (a *Agent) runScript(ctx context.Context, args json.RawMessage) (string, bool, error) { + var in struct { + Source string `json:"source"` + } + 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) + // A SCRIPT ALWAYS HAS A PARENT ID. A provider may send a call with none, + // and an empty parent would make every nested call read as the model's + // own step, and two such scripts mint the same nested ids. + if parent == "" { + parent = fmt.Sprintf("script-%d", scriptSerial.Add(1)) + } + // NO TURN, NO SCRIPT. A nil episode skips the whole pre-action chain, the + // approval rules included ([episode.preAction]), so a road that reaches + // here without one would run every nested call unchecked. It fails closed. + if ep == nil { + return "script cannot run here: its calls could not be checked against the approval rules", true, nil + } + var made atomic.Int64 + caller := func(ctx context.Context, name string, args map[string]any) (any, error) { + id := fmt.Sprintf("%s-script-%d", parent, made.Add(1)) + return a.scriptCall(ctx, ep, hub, parent, id, name, args) + } + started := time.Now() + result := jsrun.RunScript(ctx, in.Source, a.scriptNames(), caller, jsrun.ScriptLimits{}) + text, isError := scriptReport(result, time.Since(started)) + return a.cutBashResult(text), isError, nil +} + +// scriptNames is every belt tool, the ones a script may not call included: a +// script that reaches for one is told why it cannot, in a sentence, rather than +// meeting a bare "is not a function". +func (a *Agent) scriptNames() []string { + belt := a.beltTools() + names := make([]string, 0, len(belt)) + for _, tool := range belt { + names = append(names, tool.Name) + } + return names +} + +// scriptCall runs one nested call and answers what the script receives. A +// name the belt does not carry is answered by dispatch, as it is at the top +// level; the names a script can reach are the belt's own ([Agent.scriptNames]) +// that [scriptCallable] allows. +func (a *Agent) scriptCall(ctx context.Context, ep *episode, hub *eventHub, parent, id, name string, args map[string]any) (any, error) { + if !slices.Contains(scriptCallable, name) { + return nil, fmt.Errorf("%s cannot be called from a script; a script can call %s", name, strings.Join(scriptCallable, ", ")) + } + body, err := json.Marshal(args) + if err != nil { + return nil, fmt.Errorf("the arguments for %s cannot be written down: %w", name, err) + } + call := ai.ToolCall{ID: id, Type: "function", Function: ai.ToolCallFunction{Name: name, Arguments: string(body)}} + ctx = withScriptParent(ctx, parent) + var probe *scriptBash + if name == "bash" { + ctx, probe = withScriptBash(ctx) + } + rendered := argsText(call) + if hub != nil { + begin := a.toolBeginEvent(call, rendered, "") + begin.Parent = parent + hub.send(begin) + } + result := a.executeTool(ctx, ep, hub, call, rendered) + // AND THE JOURNAL KEEPS IT, because no message does: the model read only + // the script's result, and a reopened conversation draws this call under + // its script from this line alone ([sessionFile.appendNested]). + // THE END CARRIES ITS PARENT, so a reader that counts the model's steps + // leaves it out and a reader that draws them hangs it under its script. It + // goes out on the hub directly and never as a belt step: the step the run + // worker acknowledges is the script's own. It is built once, and the + // journal keeps the output it carries. + end := a.clientToolEvent(toolEndEvent(call, rendered, result)) + end.Parent = parent + a.file.appendNested(journalNested{Parent: parent, CallID: id, Tool: name, Args: rendered, Output: end.Output}) + if hub != nil { + hub.send(end) + } + if probe != nil { + return probe.answer(result) + } + return scriptValue(result) +} + +// scriptValue is what the script receives from any tool but bash: the tool's +// text, or its text as the error. +// +// TEXT IS NOT GUESSED INTO A SHAPE. A log line that starts with "[" or a JSON +// file read for its words would come back as an array or object the script did +// not ask for, and its .split would throw; the script parses what it knows is +// JSON itself. +func scriptValue(result toolResult) (any, error) { + if result.isError { + return nil, errors.New(result.text) + } + return result.text, nil +} + +// scriptReport is the script tool's result: one line saying how it ended, the +// output, and the reason when it did not finish. +func scriptReport(result jsrun.ScriptResult, took time.Duration) (string, bool) { + ending, closing := "finished", "" + switch { + case result.Failed != "": + ending, closing = "failed", "script error: "+result.Failed + case result.Stopped != "": + ending, closing = "stopped", "script stopped: "+result.Stopped + } + // ONE BUILDER, because the output can be megabytes and is cut to the window + // right after this: it is copied once here and not once per join. + var text strings.Builder + text.Grow(len(result.Output) + len(closing) + 160) + fmt.Fprintf(&text, "script %s in %s after %d call%s", ending, took.Round(time.Millisecond), result.Calls, plural(result.Calls)) + unawaited := "" + if result.Unawaited > 0 { + unawaited = fmt.Sprintf("the script did not wait for %d call%s; any still running were cancelled and their answers dropped", result.Unawaited, plural(result.Unawaited)) + } + for _, part := range []string{result.Output, unawaited, closing} { + if part != "" { + text.WriteString("\n") + text.WriteString(part) + } + } + return text.String(), closing != "" +} + +// scriptReportBody is a script's result without the status line +// [scriptReport] opens it with, which carries the script's duration and call +// count: what the script found is everything after it. +func scriptReportBody(text string) string { + if !strings.HasPrefix(text, ScriptToolName+" ") { + return text + } + _, body, _ := strings.Cut(text, "\n") + return body +} + +// cutScriptBash is a script's bash output cut at the script's width +// ([scriptBashBytes]), the outcome recorded on the call's probe so the script +// is told whether it was cut and where the whole output is. +func (a *Agent) cutScriptBash(probe *scriptBash, text string) string { + cut, truncated, path := a.cutBashAt(text, scriptBashBytes, scriptSpillName) + probe.cut(truncated, path) + return cut +} + +// scriptWideBash is the conversation's bash, which keeps only the tail that +// fits the window, with a second road for a call a script makes: the whole +// output, cut at the script's width as a task worker's script's is +// ([Agent.truncatingBash]). Without it a chat's script filters a tail it is +// told is the whole output. A conversation without the chat switch keeps the +// one road. +func (a *Agent) scriptWideBash(capped bare.Tool) bare.Tool { + if !a.config.mayChatScript() { + return capped + } + out := capped + out.Execute = func(ctx context.Context, args json.RawMessage) (string, bool, error) { + probe := scriptBashFrom(ctx) + if probe == nil { + return capped.Execute(ctx, args) + } + // THE WIDE TOOL IS BUILT WHEN A SCRIPT RUNS BASH, not each time the + // belt is composed: most compositions never reach a script, and one + // built now reads the workspace as it stands now. + wide := a.wideBash() + if wide.Name == "" { + return capped.Execute(ctx, args) + } + text, isError, err := wide.Execute(ctx, args) + if err != nil { + return text, isError, err + } + return a.cutScriptBash(probe, text), isError, nil + } + return out +} + +type scriptParentKey struct{} + +// scriptSerial numbers the scripts whose call came with no id, for the +// parent id [Agent.runScript] gives them. +var scriptSerial atomic.Int64 + +// withScriptParent marks a call a script made, by the script's own call id. +// +// A NESTED CALL'S RESULT IS READ BY THE SCRIPT, NOT THE MODEL. What the +// chokepoint adds for the model's sake is wrong here: a pointer to bytes the +// transcript holds ([Agent.heldClaim]) points at a transcript the script cannot +// see, a read the script made never reaches the transcript and so is not held, +// and the job footer would corrupt the data and be spent before the model saw +// it ([Agent.finishToolResult]). +func withScriptParent(ctx context.Context, parent string) context.Context { + return context.WithValue(ctx, scriptParentKey{}, parent) +} + +// inScript says whether the call on this context is one a script made. +func inScript(ctx context.Context) bool { return scriptParentFrom(ctx) != "" } + +// scriptParentFrom is the call id of the script that made the call on this +// context, or "" for a call the model made itself. Every event the call raises +// carries it ([Event.Parent]). +func scriptParentFrom(ctx context.Context) string { + parent, _ := ctx.Value(scriptParentKey{}).(string) + return parent +} + +// wideBash is bash built with the bash belt's wide source caps +// ([bashBeltSourceCaps]), so the whole output reaches the script-wide cut. It +// holds the output in memory as a bash-belt worker's bash does, bounded by +// bash's own run ceiling; or the zero tool where bare carries no bash. +func (a *Agent) wideBash() bare.Tool { + tool, _ := bare.BashToolCapped(a.config.Workspace, bashBeltSourceCaps()) + return tool +} + +// scriptBash is what one bash call inside a script learns about its own run: +// the exit status bare saw, and whether the script-wide cut fired. It is locked +// because a call moved to the background finishes on another goroutine after +// the script has read it. +type scriptBash struct { + mu sync.Mutex + exit *int + truncated bool + path string +} + +type scriptBashKey struct{} + +// withScriptBash marks one nested bash call: bare reports its exit status as +// data ([bare.WithBashExit]) and [Agent.truncatingBash] cuts it at +// [scriptBashBytes] rather than at the window. +func withScriptBash(ctx context.Context) (context.Context, *scriptBash) { + probe := &scriptBash{} + ctx = bare.WithBashExit(ctx, func(code int) { + probe.mu.Lock() + defer probe.mu.Unlock() + probe.exit = &code + }) + return context.WithValue(ctx, scriptBashKey{}, probe), probe +} + +func scriptBashFrom(ctx context.Context) *scriptBash { + probe, _ := ctx.Value(scriptBashKey{}).(*scriptBash) + return probe +} + +// cut records the script-wide cut's outcome. +func (b *scriptBash) cut(truncated bool, path string) { + b.mu.Lock() + defer b.mu.Unlock() + b.truncated, b.path = truncated, path +} + +// answer is what the script receives for its bash call. A command that ran +// resolves whatever its exit; one that never ran or never finished rejects with +// bash's own words; one moved to the background resolves with no exit code. +func (b *scriptBash) answer(result toolResult) (any, error) { + b.mu.Lock() + defer b.mu.Unlock() + if b.exit == nil && result.isError { + return nil, errors.New(result.text) + } + output, exit := result.text, any(nil) + if b.exit != nil { + output, exit = withoutExitStatus(result.text, *b.exit), *b.exit + } + answer := map[string]any{"output": output, "exit_code": exit, "truncated": b.truncated} + if b.path != "" { + answer["full_output_path"] = b.path + } + return answer, nil +} + +// withoutExitStatus removes the status line bare appends to a non-zero exit, so +// the output is the command's own. The code is known, so the line is matched +// exactly, in bare's own spelling ([bare.ExitStatusLine]), and never parsed. +func withoutExitStatus(text string, code int) string { + if code == 0 { + return text + } + // THE LAST STATUS LINE COMES OFF WHEREVER IT SITS: a line the session adds + // after the command's — the fence's (procexec.WithFenceLine) — stays. + status := bare.ExitStatusLine(code) + at := strings.LastIndex(text, status) + if at < 0 { + return text + } + return strings.TrimSuffix(text[:at], "\n\n") + text[at+len(status):] +} diff --git a/internal/session/tool_script_followup_test.go b/internal/session/tool_script_followup_test.go new file mode 100644 index 0000000000..50bdd2b118 --- /dev/null +++ b/internal/session/tool_script_followup_test.go @@ -0,0 +1,129 @@ +package session + +import ( + "context" + "path/filepath" + "strings" + "testing" + + "github.com/Agent-Field/agentfield/sdk/go/ai" +) + +// chatScriptConfig is a conversation with the chat's script switch on. +func chatScriptConfig(config *Config) { config.chatScript = true } + +// THE CHAT'S SCRIPT SEES WHAT A WORKER'S SCRIPT SEES. The conversation's own +// bash keeps the last lines that fit the window; a script reading through it +// would filter a tail it was told was whole. +func TestChatScriptSeesBashOutputPastTheModelsCap(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, chatScriptConfig) + if caps := agent.resultCaps(); caps.MaxLines >= 20000 && caps.MaxBytes >= 108894 { + t.Skipf("the window caps (%d lines, %d bytes) do not bind on seq 1 20000", caps.MaxLines, caps.MaxBytes) + } + result := runScriptCall(t, agent, ` +const run = await tools.bash({command: "seq 1 20000"}); +const lines = run.output.split("\n").filter(Boolean); +return lines.length + " " + lines[0] + " " + run.truncated; +`) + if !strings.Contains(result.text, "20000 1 false") { + t.Errorf("the chat's script did not see the whole output:\n%s", result.text) + } +} + +// A SCRIPT IS TOLD WHEN ITS BASH OUTPUT WAS CUT, on either belt, and the cut +// keeps less than the command printed. +func TestScriptBashSaysWhenItsOutputWasCut(t *testing.T) { + for name, configure := range map[string]func(*Config){"worker": scriptWorkerConfig(t), "chat": chatScriptConfig} { + t.Run(name, func(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, configure) + result := runScriptCall(t, agent, ` +const run = await tools.bash({command: "head -c 1500000 /dev/zero | tr '\\0' a"}); +return run.truncated + " " + (run.output.length < 1500000); +`) + if !strings.Contains(result.text, "true true") { + t.Errorf("a cut output was not reported as cut:\n%s", result.text) + } + }) + } +} + +// A SCRIPT THAT READS IS A STEP THAT LEARNED SOMETHING, and the same answer +// again is a spin even though the script's own clock moved between the two. +func TestAScriptThatReadsIsProgressAndTheSameAnswerAgainIsNot(t *testing.T) { + seen := newProgressLedger() + step := func(took string) bool { + return taughtSomething(Event{ + Kind: EventToolEnd, Tool: ScriptToolName, Args: `{"source":"return 1"}`, + Output: "script finished in " + took + " after 2 calls\nparse.go: func parseDate", + }, seen) + } + if !step("12ms") { + t.Fatal("a script's first answer read as no progress") + } + if step("15ms") { + t.Fatal("the same answer from the same script read as new because its duration changed") + } +} + +// A REOPENED CONVERSATION KEEPS A SCRIPT'S CALLS UNDER IT, as the live window +// drew them: the journal holds them, because no message does. +func TestAReopenedConversationKeepsAScriptsCallsUnderIt(t *testing.T) { + path := filepath.Join(t.TempDir(), "session.jsonl") + completer := &scriptedCompleter{steps: []step{ + func(context.Context, []ai.Message) (*ai.Response, error) { + return toolResponse("call-s", ScriptToolName, `{"source":"await tools.bash({command: \"echo one\"}); await tools.bash({command: \"exit 3\"}); return 'ok'"}`), nil + }, + func(context.Context, []ai.Message) (*ai.Response, error) { + return textResponse("done"), nil + }, + }} + agent, _ := newTestAgent(t, completer, func(config *Config) { + chatScriptConfig(config) + config.SessionFile = path + }) + collect(t, mustSubmit(t, agent, "run the script")) + if err := agent.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + for name, entries := range map[string][]DisplayEntry{ + "reopened": reopen(t, path).Transcript(), + "detached": ReadTranscript(path).Entries, + } { + at := -1 + for i, e := range entries { + if e.Role == "tool" && e.CallID == "call-s" { + at = i + } + } + if at < 0 || at+2 >= len(entries) { + t.Fatalf("%s: the script row or its calls are missing: %+v", name, entries) + } + first, second := entries[at+1], entries[at+2] + if !first.ToolResult.Nested() || !second.ToolResult.Nested() { + t.Fatalf("%s: the rows after the script are not its nested calls: %+v %+v", name, first, second) + } + if first.Tool != "bash" || !strings.Contains(first.Args, "echo one") || !strings.Contains(first.Output, "one") { + t.Errorf("%s: the first nested call reads %+v", name, first) + } + if !strings.Contains(second.Args, "exit 3") { + t.Errorf("%s: the second nested call reads %+v", name, second) + } + } +} + +// THE APP'S STEP LIST NAMES EACH SCRIPT CALL'S PARENT, so a surface can hang it +// under its script instead of drawing it as a step of its own. +func TestTaskLiveStepsNameTheScriptTheyCameFrom(t *testing.T) { + live := &taskLive{} + live.record(Event{Kind: EventToolBegin, Tool: ScriptToolName, CallID: "s"}) + live.record(Event{Kind: EventToolBegin, Tool: "bash", CallID: "s-script-1", Parent: "s"}) + live.record(Event{Kind: EventToolEnd, Tool: "bash", CallID: "s-script-1", Parent: "s"}) + live.record(Event{Kind: EventToolEnd, Tool: ScriptToolName, CallID: "s"}) + parents := map[string]string{} + for _, step := range live.liveSteps(10) { + parents[step.Call] = step.Parent + } + if parents["s"] != "" || parents["s-script-1"] != "s" { + t.Errorf("step parents = %v; want the script's call under s and the script under nothing", parents) + } +} diff --git a/internal/session/tool_script_review_test.go b/internal/session/tool_script_review_test.go new file mode 100644 index 0000000000..bafa82641d --- /dev/null +++ b/internal/session/tool_script_review_test.go @@ -0,0 +1,281 @@ +package session + +import ( + "context" + "encoding/json" + "io" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/approval" + "github.com/Agent-Field/codeaf/internal/exec" + "github.com/Agent-Field/codeaf/internal/jsrun" +) + +// These tests pin the fixes from the review of #2815. Each fails without its fix. + +// A SAVED PROGRAM'S SCRIPT MEETS THE SAME GATE. The program road hands the +// episode and hub to [Agent.executeTool] as parameters rather than on the +// context, and a script reached that way once ran its nested calls with no +// approval rules at all. +func TestASavedProgramsScriptMeetsTheSameGate(t *testing.T) { + agent, workspace := newTestAgent(t, &scriptedCompleter{}, func(config *Config) { config.chatScript = true }) + agent.SetApprovalPolicy(&approval.Policy{Default: approval.ActionAllow, Tools: map[string]approval.Action{"bash": approval.ActionDeny}}) + env := &subharnessEnv{ + agent: agent, manifest: exec.Manifest{Whitelist: []string{ScriptToolName}}, + ep: agent.newEpisode(), hub: newEventHub(), + } + result, err := env.Tool(context.Background(), ScriptToolName, map[string]any{"source": ` +try { await tools.bash({command: "touch ran"}) } catch (e) { return "refused: " + e.message } +return "it ran"; +`}) + if err != nil { + t.Fatalf("the program's script call failed: %v", err) + } + if !strings.Contains(result.Text, "refused: ") { + t.Errorf("a denied nested call through a saved program did not reject:\n%s", result.Text) + } + if _, err := os.Stat(filepath.Join(workspace, "ran")); err == nil { + t.Error("the denied command ran") + } +} + +// A SCRIPT WITH NO TURN TO CHECK ITS CALLS AGAINST DOES NOT RUN. A nil episode +// skips the whole pre-action chain, so a road that reaches the script without +// one must fail closed rather than run every call unchecked. +func TestAScriptOutsideATurnRefusesToRun(t *testing.T) { + agent, workspace := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + call := ai.ToolCall{ID: "call-1", Type: "function", Function: ai.ToolCallFunction{ + Name: ScriptToolName, Arguments: `{"source":"await tools.bash({command: \"touch ran\"}); return \"it ran\""}`, + }} + result := agent.executeTool(context.Background(), nil, nil, call, argsText(call)) + if !result.isError || strings.Contains(result.text, "it ran") { + t.Errorf("a script with no turn ran:\n%s", result.text) + } + if _, err := os.Stat(filepath.Join(workspace, "ran")); err == nil { + t.Error("a script with no turn ran its command") + } +} + +// A QUICK WORKER DOES NOT CARRY SCRIPT. It runs every call under the node's +// quick lock, and a script's nested call would wait on that lock forever. +func TestAQuickWorkerDoesNotCarryScript(t *testing.T) { + worker := scriptWorkerConfig(t) + quick, _ := newTestAgent(t, &scriptedCompleter{}, func(config *Config) { + worker(config) + config.quickItems = func(int, []string) string { return "" } + }) + if beltNameSet(quick.beltTools())[ScriptToolName] { + t.Error("a quick worker carries script") + } + if strings.Contains(bashWorkerDoctrine(quick.config), scriptWorkerRule) { + t.Error("a quick worker's page names script") + } +} + +// A SCRIPT CALLS ONLY WHAT IS ALLOWED, AND EVERYTHING ELSE ON THE BELT IS +// REFUSED. Every tool the chat's belt carries outside [scriptCallable] is +// tried, so a tool added to the belt later is refused until it is allowed on +// purpose. +func TestChatScriptReachesOnlyTheToolsItIsAllowed(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, func(config *Config) { config.chatScript = true }) + plain := regexp.MustCompile(`^[a-z][a-z0-9_]*$`) + var refused []string + for name := range beltNameSet(agent.beltTools()) { + if !slices.Contains(scriptCallable, name) && plain.MatchString(name) { + refused = append(refused, name) + } + } + slices.Sort(refused) + for _, want := range []string{"propose_task", "watch", "edit", ScriptToolName} { + if !slices.Contains(refused, want) { + t.Fatalf("the chat's belt lacks %s; the test would prove nothing about it", want) + } + } + names, _ := json.Marshal(refused) + result := runScriptCall(t, agent, ` +const out = []; +for (const name of `+string(names)+`) { + try { await tools[name]({}); out.push(name + ": reached") } catch (e) { out.push(name + ": " + e.message) } +} +return out.join("\n"); +`) + for _, name := range refused { + if !strings.Contains(result.text, name+": "+name+" cannot be called from a script") { + t.Errorf("a chat script's call to %s was not refused", name) + } + } + if strings.Contains(result.text, ": reached") { + t.Errorf("a script reached a tool it is not allowed:\n%s", result.text) + } +} + +// A SCRIPT'S READ IS THE FILE, NEVER A POINTER. The held-read shortcut answers +// a read whose bytes the transcript already holds with a one-line pointer; a +// script cannot see the transcript, so it would parse the pointer as the file. +func TestAScriptsReadOfAHeldFileReturnsTheFile(t *testing.T) { + agent, workspace := newTestAgent(t, &scriptedCompleter{}, nil) + path := filepath.Join(workspace, "page.md") + writeFile(t, path, "one\ntwo\nthree\n") + if first := readHeld(t, agent, "c1", heldArgs(path, 0, 0)); !strings.Contains(first.text, "three") { + t.Fatalf("the direct read did not run: %.80q", first.text) + } + call := ai.ToolCall{ID: "s-script-1", Function: ai.ToolCallFunction{Name: "read", Arguments: heldArgs(path, 0, 0)}} + nested := agent.executeTool(withScriptParent(context.Background(), "s"), agent.newEpisode(), nil, call, "") + if strings.HasPrefix(nested.text, "[already read] ") || !strings.Contains(nested.text, "three") { + t.Errorf("a script's read was answered with a pointer: %.80q", nested.text) + } +} + +// AND WHAT A SCRIPT READ IS NOT HELD. Its bytes never reach the transcript, so +// a later direct read of the same file must read the file. +func TestAScriptsReadDoesNotMakeALaterReadAPointer(t *testing.T) { + agent, workspace := newTestAgent(t, &scriptedCompleter{}, nil) + path := filepath.Join(workspace, "page.md") + writeFile(t, path, "one\ntwo\nthree\n") + call := ai.ToolCall{ID: "s-script-1", Function: ai.ToolCallFunction{Name: "read", Arguments: heldArgs(path, 0, 0)}} + agent.executeTool(withScriptParent(context.Background(), "s"), agent.newEpisode(), nil, call, "") + if direct := readHeld(t, agent, "c1", heldArgs(path, 0, 0)); strings.HasPrefix(direct.text, "[already read] ") { + t.Errorf("a direct read pointed at bytes only a script saw: %.80q", direct.text) + } +} + +// A SCRIPT'S RESULT CARRIES NO JOB FOOTER, and does not use up the footer the +// model is owed: the next result the model reads still carries it. +func TestAScriptsCallLeavesTheJobFooterForTheModel(t *testing.T) { + agent, _ := jobsAgent(t) + id := startJob(t, agent, "sleep 5") + defer agent.jobs.kill(context.Background(), id) + ep := agent.newEpisode() + call := ai.ToolCall{ID: "s-script-1", Function: ai.ToolCallFunction{Name: "bash", Arguments: "{}"}} + if nested := agent.finishToolResult(withScriptParent(context.Background(), "s"), ep, call, toolResult{text: "{}"}); nested.text != "{}" { + t.Errorf("a script's result carried the job footer:\n%q", nested.text) + } + direct := agent.finishToolResult(context.Background(), ep, ai.ToolCall{ID: "c1", Function: call.Function}, toolResult{text: "one"}) + if !strings.Contains(direct.text, "running ") { + t.Errorf("the model's next result lost the job footer:\n%q", direct.text) + } +} + +// THE REPORT SAYS WHAT A FINISHED SCRIPT DID NOT WAIT FOR. +func TestScriptReportNamesTheCallsItDidNotWaitFor(t *testing.T) { + text, isError := scriptReport(jsrun.ScriptResult{Output: "started", Calls: 1, Unawaited: 1}, 0) + if isError || !strings.Contains(text, "did not wait for 1 call;") { + t.Errorf("the report does not name the unawaited call:\n%s", text) + } +} + +// A SCRIPT CALLED WITH NO ID STILL NAMES A PARENT. A provider that sends an +// empty call id once left every nested call looking like the model's own, and +// two such scripts minted the same ids. +func TestAScriptWithNoCallIDStillNamesItsCallsParent(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + hub := newEventHub() + events := hub.subscribe() + go func() { + body, _ := json.Marshal(map[string]string{"source": `await tools.bash({command: "echo one"})`}) + for range 2 { + agent.runTools(context.Background(), []ai.ToolCall{{ + Type: "function", Function: ai.ToolCallFunction{Name: ScriptToolName, Arguments: string(body)}, + }}, hub) + } + hub.close() + }() + parents, ids := map[string]bool{}, map[string]bool{} + for _, ev := range collect(t, events) { + if ev.Kind != EventToolBegin || ev.Tool != "bash" { + continue + } + if ev.Parent == "" { + t.Errorf("a nested call of a script with no id names no parent (id %q)", ev.CallID) + } + parents[ev.Parent], ids[ev.CallID] = true, true + } + if len(parents) != 2 || len(ids) != 2 { + t.Errorf("two scripts gave %d parents and %d call ids; want 2 and 2", len(parents), len(ids)) + } +} + +// EVERY EVENT A NESTED CALL RAISES NAMES ITS SCRIPT, the live output and the +// finish as well as the begin and the end. +func TestEveryEventOfANestedCallNamesItsScript(t *testing.T) { + worker := scriptWorkerConfig(t) + agent, _ := newTestAgent(t, &scriptedCompleter{}, func(config *Config) { + worker(config) + config.LiveToolOutput = true + }) + hub := newEventHub() + events := hub.subscribe() + go func() { + body, _ := json.Marshal(map[string]string{"source": `await tools.bash({command: "echo one"})`}) + agent.runTools(context.Background(), []ai.ToolCall{{ + ID: "call-1", Type: "function", Function: ai.ToolCallFunction{Name: ScriptToolName, Arguments: string(body)}, + }}, hub) + hub.close() + }() + seen := map[EventKind]bool{} + for _, ev := range collect(t, events) { + if !strings.HasPrefix(ev.CallID, "call-1-script-") { + continue + } + seen[ev.Kind] = true + if ev.Parent != "call-1" { + t.Errorf("a nested call's %v event names parent %q", ev.Kind, ev.Parent) + } + } + for _, kind := range []EventKind{EventToolOutput, EventToolFinished} { + if !seen[kind] { + t.Errorf("the nested call raised no %v event; the test proves nothing about it", kind) + } + } +} + +// A FAILED CHECK INSIDE A SCRIPT IS STILL A CHECK THE NODE RAN. +func TestAFailedCheckInsideAScriptIsACheckTheNodeRan(t *testing.T) { + run := &childRun{log: io.Discard} + run.observe(Event{Kind: EventToolFailed, Tool: "bash", CallID: "s-script-1", Parent: "s"}) + if !run.ranCheck { + t.Error("a script's failing test run did not count as a check the node ran") + } +} + +// A NESTED CALL THAT NEEDS APPROVAL ASKS THE PERSON, AND THE ANSWER DECIDES +// IT: the script waits for the answer, runs the call on yes and is refused on no. +func TestAChatScriptsCallThatNeedsApprovalWaitsForTheAnswer(t *testing.T) { + for _, allow := range []bool{true, false} { + source := `try { await tools.bash({command: "touch ran"}); return "it ran" } catch (e) { return "refused: " + e.message }` + body, err := json.Marshal(map[string]string{"source": source}) + if err != nil { + t.Fatal(err) + } + completer := &scriptedCompleter{steps: []step{ + func(context.Context, []ai.Message) (*ai.Response, error) { + return toolResponse("call-s", ScriptToolName, string(body)), nil + }, + func(context.Context, []ai.Message) (*ai.Response, error) { return textResponse("done"), nil }, + }} + agent, workspace := newTestAgent(t, completer, func(config *Config) { + config.chatScript = true + config.AskConsent = true + config.ApprovalPolicy = &approval.Policy{Default: approval.ActionAllow, Tools: map[string]approval.Action{"bash": approval.ActionPrompt}} + }) + events := drainAnswering(t, mustSubmit(t, agent, "run it"), func(request Event) { + agent.ResolveConsent(request.ID, allow) + }) + if asked := countKind(events, EventConsentRequest); asked != 1 { + t.Fatalf("allow=%v: the nested call asked %d times, want once; events %v", allow, asked, kinds(events)) + } + _, statErr := os.Stat(filepath.Join(workspace, "ran")) + if allow && statErr != nil { + t.Error("an approved nested call did not run") + } + if !allow && statErr == nil { + t.Error("a declined nested call ran") + } + } +} diff --git a/internal/session/tool_script_steps_test.go b/internal/session/tool_script_steps_test.go new file mode 100644 index 0000000000..1d8491c3cb --- /dev/null +++ b/internal/session/tool_script_steps_test.go @@ -0,0 +1,170 @@ +package session + +import ( + "context" + "encoding/json" + "fmt" + "os" + "strings" + "testing" + "time" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/jsrun" +) + +// A SCRIPT IS ONE STEP TO EVERY COUNTER THE MODEL IS SHOWN. The hub's count of +// finished calls feeds the worker's "step N/M" frame, so a script that made two +// bash calls must leave it at one, the same unit the runner caps. +func TestScriptNestedCallsAreNotCountedAsFinishedCalls(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + body, err := json.Marshal(map[string]string{"source": `await tools.bash({command: "true"}); await tools.bash({command: "true"}); return "ok"`}) + if err != nil { + t.Fatal(err) + } + hub := newEventHub() + agent.runTools(context.Background(), []ai.ToolCall{{ + ID: "call-1", Type: "function", + Function: ai.ToolCallFunction{Name: ScriptToolName, Arguments: string(body)}, + }}, hub) + if hub.finishedCalls != 1 { + t.Errorf("finishedCalls = %d after one script that made two calls, want 1", hub.finishedCalls) + } +} + +// THE ROOM'S STEP COUNT AND ITS CALL IN FLIGHT ARE THE SCRIPT'S. A nested end +// neither counts a step nor clears the script from "what is it doing". +func TestTaskLiveCountsAScriptOnceAndKeepsItInFlight(t *testing.T) { + live := &taskLive{} + live.record(Event{Kind: EventToolBegin, Tool: ScriptToolName, CallID: "s"}) + for _, kind := range []EventKind{EventToolBegin, EventToolEnd, EventToolBegin, EventToolFailed} { + live.record(Event{Kind: kind, Tool: "bash", CallID: "s-script-1", Parent: "s"}) + } + if got := live.state(0); got.Steps != 0 || got.Call == "" { + t.Errorf("mid-script the room reads steps=%d call=%q; want 0 and the script", got.Steps, got.Call) + } + live.record(Event{Kind: EventToolEnd, Tool: ScriptToolName, CallID: "s"}) + if got := live.state(0).Steps; got != 1 { + t.Errorf("steps = %d after one script, want 1", got) + } +} + +// ONLY BASH ANSWERS A SHAPE. Every other tool answers text, and a text that +// happens to start with a bracket stays the text the tool wrote. +func TestScriptNonBashResultStaysText(t *testing.T) { + for _, text := range []string{"[INFO] started", `{"a":1}`, "[1, 2]"} { + got, err := scriptValue(toolResult{text: text}) + if err != nil || got != text { + t.Errorf("scriptValue(%q) = %#v, %v; want the text unchanged", text, got, err) + } + } + if _, err := scriptValue(toolResult{text: "no such file", isError: true}); err == nil || err.Error() != "no such file" { + t.Errorf("a failed call answered %v, want its own text as the error", err) + } +} + +// THE DESCRIPTION NAMES EVERY TOOL A SCRIPT MAY CALL, read off the list. +func TestScriptDescriptionNamesEveryCallableTool(t *testing.T) { + description := scriptDescription + for _, name := range scriptCallable { + if !strings.Contains(description, name) { + t.Errorf("the description does not say a script can call %s", name) + } + } +} + +// THE SANDBOX IS SAID FIRST, AND SHOWN. A worker that read "JavaScript" as Node +// wrote require('fs') and failed before its first call; the description now +// says what is missing before anything else, and carries a script that works. +func TestScriptDescriptionSaysItIsNotNodeAndShowsAWorkingScript(t *testing.T) { + if at := strings.Index(scriptDescription, "Not Node.js: no require"); at < 0 || at > 120 { + t.Errorf("the description does not open by saying it is not Node (at %d): %q", at, scriptDescription) + } + if !strings.Contains(scriptDescription, "await tools.bash({command:") { + t.Error("the description shows no call through tools.bash") + } + if !strings.Contains(scriptWorkerRule, "not Node.js") { + t.Error("the worker page does not say a script is not Node") + } +} + +// THE MANUAL STATES THE LIMITS THE CODE ENFORCES. A changed constant fails here +// until the page says the new number. +func TestScriptManualStatesTheEnforcedLimits(t *testing.T) { + raw, err := os.ReadFile("../manual/chat/how-tasks-run.md") + if err != nil { + t.Fatal(err) + } + page := string(raw) + facts := []string{ + fmt.Sprintf("%d tool calls", jsrun.DefaultScriptCalls), + fmt.Sprintf("%d minutes", int(jsrun.DefaultScriptWall/time.Minute)), + fmt.Sprintf("%d MiB of output", jsrun.DefaultScriptOutput>>20), + fmt.Sprintf("up to %d MiB of one command's", scriptBashBytes>>20), + fmt.Sprintf("Up to %d calls run at the same time", jsrun.DefaultScriptParallel), + } + for _, name := range scriptCallable { + facts = append(facts, "`"+name+"`") + } + for _, want := range facts { + if !strings.Contains(page, want) { + t.Errorf("internal/manual/chat/how-tasks-run.md does not say %q", want) + } + } +} + +// A TASK CHAT STARTS IS A TASK WORKER TOO. A node worker built on the bash belt +// with the switch on carries script, as a plan run's worker does; without the +// switch it does not. +func TestChatTaskWorkerOnTheBashBeltCarriesScriptWithTheSwitch(t *testing.T) { + for _, on := range []bool{true, false} { + t.Setenv(home.EnvVar, t.TempDir()) + t.Setenv("CODEAF_TASK_BELT", "bash") + t.Setenv(scriptSwitch, map[bool]string{true: "on", false: ""}[on]) + agent := openIdentityAgent(t, identityPlace(t, "7777777777777777"), nil) + graph := stubbedGraph(agent, func(*TaskNode) {}) + id := graph.reserve() + graph.admit(id, taskSpec{title: "Fix", brief: "Fix the bug", acceptance: "fixed", model: "test/model", depth: 1}) + worker, err := agent.newTaskAgent(context.Background(), t.TempDir(), graph.node(id), "") + if err != nil { + t.Fatalf("worker construction: %v", err) + } + if !worker.config.mayBashBelt() { + worker.Close() + t.Fatal("the worker is not on the bash belt, so this proves nothing") + } + if got := beltNameSet(worker.beltTools())[ScriptToolName]; got != on { + t.Errorf("switch on=%v: the chat task's worker carries script = %v", on, got) + } + worker.Close() + } +} + +// THE CHAT'S ARM IS ITS OWN SWITCH. A conversation built with it carries +// script; a task never does, whatever the field says. The chat's page adds no +// line for it: the tool's description says all of it, and a page line would be +// paid on every request of every conversation, armed or not. +func TestChatBeltCarriesScriptOnlyWithTheChatSwitch(t *testing.T) { + on, _ := newTestAgent(t, &scriptedCompleter{}, func(config *Config) { config.chatScript = true }) + if !beltNameSet(on.beltTools())[ScriptToolName] { + t.Error("a conversation with the chat switch does not carry script") + } + off, _ := newTestAgent(t, &scriptedCompleter{}, nil) + if beltNameSet(off.beltTools())[ScriptToolName] { + t.Error("a conversation without the chat switch carries script") + } + if (Config{chatScript: true, InTask: true}).mayChatScript() { + t.Error("a task is allowed the chat's script") + } +} + +// THE SWITCH IS READ AT THE DOOR THAT BUILDS A CONVERSATION. +func TestChatScriptSwitchReadsOnlyOn(t *testing.T) { + for value, want := range map[string]bool{"on": true, " ON ": true, "": false, "1": false, "off": false} { + t.Setenv(chatScriptSwitch, value) + if got := chatScriptAsked(); got != want { + t.Errorf("CODEAF_CHAT_SCRIPT=%q armed = %v, want %v", value, got, want) + } + } +} diff --git a/internal/session/tool_script_test.go b/internal/session/tool_script_test.go new file mode 100644 index 0000000000..ab0920d22d --- /dev/null +++ b/internal/session/tool_script_test.go @@ -0,0 +1,212 @@ +package session + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/approval" + "github.com/Agent-Field/codeaf/internal/exec/bare" + procexec "github.com/Agent-Field/codeaf/internal/executor" +) + +// scriptWorkerConfig is a bash-belt worker with the script switch on. +func scriptWorkerConfig(t *testing.T) func(*Config) { + t.Helper() + worker := bashBeltWorkerConfig(t) + return func(config *Config) { + worker(config) + config.script = true + } +} + +// runScriptCall sends one script call through the real batch and answers its result. +func runScriptCall(t *testing.T, agent *Agent, source string) toolResult { + t.Helper() + body, err := json.Marshal(map[string]string{"source": source}) + if err != nil { + t.Fatal(err) + } + results := agent.runTools(context.Background(), []ai.ToolCall{{ + ID: "call-1", Type: "function", + Function: ai.ToolCallFunction{Name: ScriptToolName, Arguments: string(body)}, + }}, newEventHub()) + if len(results) != 1 { + t.Fatalf("the batch answered %d results for one call", len(results)) + } + return results[0] +} + +func TestScriptToolIsOnTheWorkerBeltOnlyWithTheSwitch(t *testing.T) { + on, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + if !beltNameSet(on.beltTools())[ScriptToolName] { + t.Error("a bash-belt worker with the switch on does not carry script") + } + off, _ := newTestAgent(t, &scriptedCompleter{}, bashBeltWorkerConfig(t)) + if beltNameSet(off.beltTools())[ScriptToolName] { + t.Error("a bash-belt worker with the switch off carries script") + } + conversation, _ := newTestAgent(t, &scriptedCompleter{}, func(config *Config) { config.script = true }) + if beltNameSet(conversation.beltTools())[ScriptToolName] { + t.Error("a conversation carries script; the switch is for task workers only") + } +} + +// THE STATUS LINE COMES OFF WHEREVER THE FENCE PUT ITS OWN AFTER IT: the exit +// code is the script's as data, and the output is the command's own. +func TestScriptBashOutputLosesTheStatusLineBeforeAFenceLine(t *testing.T) { + text := procexec.WithFenceLine("found nothing\n\n" + bare.ExitStatusLine(2)) + got := withoutExitStatus(text, 2) + if strings.Contains(got, "Command exited") || !strings.Contains(got, "found nothing") { + t.Errorf("withoutExitStatus(%q) = %q", text, got) + } +} + +func TestScriptWorkerPageNamesTheToolOnlyWhenTheBeltHasIt(t *testing.T) { + on, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + if !strings.Contains(bashWorkerDoctrine(on.config), scriptWorkerRule) { + t.Error("a worker carrying script reads a page that does not say when to use it") + } + off, _ := newTestAgent(t, &scriptedCompleter{}, bashBeltWorkerConfig(t)) + if strings.Contains(bashWorkerDoctrine(off.config), "`script`") { + t.Error("a worker without script reads a page that names it") + } +} + +func TestScriptBashResolvesStructuredWhateverTheExit(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + result := runScriptCall(t, agent, ` +const run = await tools.bash({command: "printf 'hi\\n'; exit 3"}); +return {output: run.output, exit: run.exit_code, truncated: run.truncated}; +`) + if result.isError { + t.Fatalf("a non-zero exit failed the script:\n%s", result.text) + } + if !strings.Contains(result.text, `{"exit":3,"output":"hi\n","truncated":false}`) { + t.Errorf("the script did not see bash's structure with the status line removed:\n%s", result.text) + } +} + +func TestScriptSeesBashOutputPastTheModelsCap(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + if caps := agent.resultCaps(); caps.MaxBytes >= 108894 { + t.Skipf("the window cap (%d bytes) does not bind on seq 1 20000", caps.MaxBytes) + } + result := runScriptCall(t, agent, ` +const run = await tools.bash({command: "seq 1 20000"}); +return run.output.split("\n").filter(Boolean).length + " " + run.truncated; +`) + if !strings.Contains(result.text, "20000 false") { + t.Errorf("the script did not see the whole output:\n%s", result.text) + } +} + +// TestScriptBashCallsRunAtTheSameTime proves concurrency through the real gate +// without a clock: each command succeeds only if it sees the other's file while +// it is still running, so calls made one after another both exit 1. +func TestScriptBashCallsRunAtTheSameTime(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + wait := func(mine, theirs string) string { + return "touch " + mine + "; for i in $(seq 200); do [ -f " + theirs + " ] && exit 0; sleep 0.05; done; exit 1" + } + result := runScriptCall(t, agent, ` +const runs = await Promise.all([tools.bash({command: `+strconv.Quote(wait("a", "b"))+`}), tools.bash({command: `+strconv.Quote(wait("b", "a"))+`})]); +return runs.map(r => r.exit_code).join(","); +`) + if !strings.Contains(result.text, "\n0,0") { + t.Errorf("the two calls did not run at the same time:\n%s", result.text) + } +} + +// A SCRIPT'S CALLS ARE ANNOUNCED AS ITS OWN. Each nested call begins and ends +// on the turn's hub naming the script call as its parent, so a reader that +// counts the model's steps can leave it out and a page can hang it under its +// script (internal/run's bashworker.go reads exactly this). +func TestScriptNestedCallsAreAnnouncedWithTheirParent(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + hub := newEventHub() + events := hub.subscribe() + go func() { + body, _ := json.Marshal(map[string]string{"source": `await tools.bash({command: "echo one"}); await tools.bash({command: "exit 2"})`}) + agent.runTools(context.Background(), []ai.ToolCall{{ + ID: "call-1", Type: "function", + Function: ai.ToolCallFunction{Name: ScriptToolName, Arguments: string(body)}, + }}, hub) + hub.close() + }() + var begins, ends, fails int + for _, ev := range collect(t, events) { + if ev.Parent == "" { + continue + } + if ev.Parent != "call-1" || !strings.HasPrefix(ev.CallID, "call-1-script-") { + t.Errorf("a nested event names parent %q and id %q", ev.Parent, ev.CallID) + } + switch ev.Kind { + case EventToolBegin: + begins++ + case EventToolEnd: + ends++ + case EventToolFailed: + fails++ + } + } + if begins != 2 || ends != 1 || fails != 1 { + t.Errorf("nested events: %d begins, %d ends, %d failures; want 2, 1, 1", begins, ends, fails) + } +} + +func TestScriptNestedCallMeetsTheSameGate(t *testing.T) { + agent, workspace := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + agent.SetApprovalPolicy(&approval.Policy{Default: approval.ActionAllow, Tools: map[string]approval.Action{"bash": approval.ActionDeny}}) + result := runScriptCall(t, agent, ` +try { await tools.bash({command: "touch ran"}) } catch (e) { return "refused: " + e.message } +return "it ran"; +`) + if !strings.Contains(result.text, "refused: ") { + t.Errorf("a denied nested call did not reject:\n%s", result.text) + } + if _, err := os.Stat(filepath.Join(workspace, "ran")); err == nil { + t.Error("the denied command ran") + } +} + +func TestScriptCannotCallScript(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + result := runScriptCall(t, agent, ` +try { await tools.script({source: "return 1"}) } catch (e) { return e.message } +`) + if !strings.Contains(result.text, "script cannot be called from a script") { + t.Errorf("a script reached script:\n%s", result.text) + } +} + +func TestScriptOutputIsCutAtTheWindowCap(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + limit := agent.resultCaps().MaxBytes + result := runScriptCall(t, agent, `return "x".repeat(`+strconv.Itoa(limit*2)+`)`) + if len(result.text) > limit+512 { + t.Errorf("the script's output reached the model at %d bytes past a %d-byte cap", len(result.text), limit) + } + if !strings.Contains(result.text, "[output truncated") { + t.Errorf("a cut output does not say it was cut:\n%.300s", result.text) + } +} + +func TestScriptFailureReportsTheError(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{}, scriptWorkerConfig(t)) + result := runScriptCall(t, agent, `text("partial"); throw new Error("boom")`) + if !result.isError { + t.Error("an uncaught error did not fail the call") + } + for _, want := range []string{"script failed", "partial", "script error: Error: boom"} { + if !strings.Contains(result.text, want) { + t.Errorf("the result is missing %q:\n%s", want, result.text) + } + } +} diff --git a/internal/session/toolrejection.go b/internal/session/toolrejection.go index fdf84fa5a5..9fe77f466c 100644 --- a/internal/session/toolrejection.go +++ b/internal/session/toolrejection.go @@ -122,6 +122,11 @@ const ( // ToolResultMediaAttempt: this occurrence made at least one render record // carrying its own run and call id (media_attempt.go). ToolResultMediaAttempt + // ToolResultNested: a script made this call, not the model, and a surface + // draws it under the script entry it follows (tool_script.go). It rides + // this byte rather than a field of its own for the reason the media + // attempt does: DisplayEntry's size is a budget. + ToolResultNested ) func (f ToolResultFlags) Invoked() bool { return f&ToolResultInvoked != 0 } @@ -129,6 +134,7 @@ func (f ToolResultFlags) RejectedBeforeRun() bool { return f&ToolResultRejectedB func (f ToolResultFlags) HarnessMade() bool { return f&ToolResultHarnessMade != 0 } func (f ToolResultFlags) Refused() bool { return f&ToolResultRefused != 0 } func (f ToolResultFlags) MediaAttempt() bool { return f&ToolResultMediaAttempt != 0 } +func (f ToolResultFlags) Nested() bool { return f&ToolResultNested != 0 } func (f toolResultFacts) flags() ToolResultFlags { var flags ToolResultFlags if f.invoked { diff --git a/internal/session/tools.go b/internal/session/tools.go index 9e9f9c8203..b905077dc6 100644 --- a/internal/session/tools.go +++ b/internal/session/tools.go @@ -190,7 +190,7 @@ func (a *Agent) belt() []bare.Tool { for index, tool := range tools { switch tool.Name { case "bash": - tools[index] = a.backgroundBash(a.publishingBash(tool)) + tools[index] = a.backgroundBash(a.publishingBash(a.scriptWideBash(tool))) case "read": tools[index] = a.pdfRead(tool) case "edit": @@ -240,6 +240,11 @@ func (a *Agent) belt() []bare.Tool { } tools = append(tools, a.documentTool(), a.jobsTool(), a.manualTool()) tools = append(tools, a.askTool()) + // script, on a conversation that asked for it (tool_script.go): the same + // tool a task worker carries, measured on the chat's own belt. + if a.config.mayChatScript() { + tools = append(tools, a.scriptTool()) + } // request_secret, only where a person can answer: headless, a credential // question has nobody to type into it, and a verb that can only ever come // back "nobody to ask" is a verb this belt does not carry. diff --git a/internal/session/transcriptread.go b/internal/session/transcriptread.go index bf639a19fd..5325fa0909 100644 --- a/internal/session/transcriptread.go +++ b/internal/session/transcriptread.go @@ -248,6 +248,7 @@ func transcriptFrom(replayed replayedSession, err error) Record { steers: replayed.steers, captions: replayed.captions, tooks: replayed.tooks, + nesteds: replayed.nesteds, stamps: replayed.stamps, } overlap := replayed.overlap diff --git a/internal/session/userbash.go b/internal/session/userbash.go index f075297db6..1540110657 100644 --- a/internal/session/userbash.go +++ b/internal/session/userbash.go @@ -102,8 +102,10 @@ func displayToolOutput(id, output string) string { // runner still owns final truncation and the full spill file. Incomplete UTF-8 // is retained across writes so remote JSON frames cannot corrupt split runes. type shellOutput struct { - hub *eventHub - id, tool string + hub *eventHub + id, tool string + // parent is the script that made the call, or "" ([Event.Parent]). + parent string bytes, lines int pending []byte cut bool @@ -129,12 +131,12 @@ func (w *shellOutput) Write(p []byte) (int, error) { } } if end > 0 { - w.hub.send(Event{Kind: EventToolOutput, Tool: w.tool, CallID: w.id, Text: strings.ToValidUTF8(string(w.pending[:end]), "�")}) + w.hub.send(Event{Kind: EventToolOutput, Tool: w.tool, CallID: w.id, Parent: w.parent, Text: strings.ToValidUTF8(string(w.pending[:end]), "�")}) } w.pending = append(w.pending[:0], w.pending[end:]...) if w.cut { w.pending = nil - w.hub.send(Event{Kind: EventToolOutput, Tool: w.tool, CallID: w.id, Text: "\n[Live output limit reached; the final result includes the saved output path.]\n"}) + w.hub.send(Event{Kind: EventToolOutput, Tool: w.tool, CallID: w.id, Parent: w.parent, Text: "\n[Live output limit reached; the final result includes the saved output path.]\n"}) } return n, nil } diff --git a/internal/tui3/app.go b/internal/tui3/app.go index a448986d6b..5d8c493f77 100644 --- a/internal/tui3/app.go +++ b/internal/tui3/app.go @@ -404,6 +404,10 @@ type entry struct { // at a time and must not ask what surrounds it — the same law the answer // hierarchy is stamped under ([app.deckRows]). brief bool + // nested says this tool row is a call a script made, drawn one indent under + // the script row it follows (toolview.go). Set where the fact is known + // (replay.go), for brief's reason. + nested bool // decision is what the person answered when this call was asked about — // "allowed" or "denied", dim, beside the row's stat (consent.go). It is // empty for every call the policy did not stop. @@ -6711,6 +6715,11 @@ func (a *app) applyEvent(ev session.Event, lump bool) tea.Cmd { // that no longer exists. a.awaited = time.Now() case session.EventToolEnd, session.EventToolFailed, session.EventCompacted: + // A SCRIPT'S OWN CALL ENDING CLOSES NOTHING: the script is still running, + // no request is out, and the script's own end is the batch's. + if ev.FromScript() { + break + } // The batch has closed, or the pass has, and in both cases the loop's // very next act is another request. Timing from HERE and not from the // turn's start is the difference between a wait and a three-minute diff --git a/internal/tui3/feed.go b/internal/tui3/feed.go index 7dcf5f3a58..df8d1ba319 100644 --- a/internal/tui3/feed.go +++ b/internal/tui3/feed.go @@ -2,6 +2,7 @@ package tui3 import ( "errors" + "slices" "strings" "time" @@ -678,6 +679,42 @@ func (f *feed) announceTool(ev session.Event) { f.touch() } +// nestedAt is where a call a script made goes: straight after its script's +// row and the calls already drawn under it, so a batch's other rows never sit +// between a script and its calls, and the live view draws what a reopened +// conversation draws (session's shapeInto). A call with no parent, or whose +// script has no row here, goes at the end. +func (f *feed) nestedAt(parent string) int { + if parent == "" { + return len(f.entries) + } + for at := len(f.entries) - 1; at >= 0; at-- { + if f.entries[at].kind != entryTool || f.entries[at].callID != parent { + continue + } + at++ + for at < len(f.entries) && f.entries[at].kind == entryTool && f.entries[at].nested { + at++ + } + return at + } + return len(f.entries) +} + +// insertEntry puts one entry at a position, moving the live and thinking +// pointers that sit at or after it so they still name their own entries. +func (f *feed) insertEntry(at int, e entry) { + f.entries = slices.Insert(f.entries, at, e) + if at < len(f.entries)-1 { + if f.live >= at { + f.live++ + } + if f.think >= at { + f.think++ + } + } +} + // beginTool is EXECUTION STARTED. It adopts the row the announcement drew — // the same call, one line, which is the whole point of announcing it — and // starts that row's clock. A begin nobody announced draws its own row, which is @@ -710,10 +747,13 @@ func (f *feed) beginTool(ev session.Event) { return } f.closeLive() - f.entries = append(f.entries, entry{ + f.insertEntry(f.nestedAt(ev.Parent), entry{ kind: entryTool, tool: ev.Tool, text: ev.Hint, turn: f.turn, open: session.IsUserBashCall(ev.CallID), status: toolRunning, began: f.now(), detail: toolDetail{Args: ev.Args}, + // A SCRIPT'S CALL IS NEVER ANNOUNCED, so this is the one door its row + // comes through, and it hangs under the script (toolview.go). + nested: ev.FromScript(), // AND THE ROW MINTED HERE TAKES THE ID TOO. Every other door onto a tool // row records it and this one did not, which left the rows drawn for a // provider that does not stream its calls — and for a surface that @@ -871,7 +911,7 @@ func (f *feed) closeTool(ev session.Event, status toolState, why string) { } f.entries = append(f.entries, entry{ kind: entryTool, tool: ev.Tool, text: why, turn: f.turn, status: toolFailed, - open: !refused, + open: !refused, nested: ev.FromScript(), detail: toolDetail{Args: ev.Args, Output: sentence}, }) f.follow() diff --git a/internal/tui3/feed_nested_test.go b/internal/tui3/feed_nested_test.go new file mode 100644 index 0000000000..9e58ef0cf3 --- /dev/null +++ b/internal/tui3/feed_nested_test.go @@ -0,0 +1,72 @@ +package tui3 + +import ( + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/session" +) + +// A SCRIPT'S CALL IS DRAWN UNDER ITS SCRIPT LIVE, as it is on the plan page: +// the event's parent is the fact, and the row carries it. +func TestFeedDrawsAScriptsCallNested(t *testing.T) { + f := &feed{live: -1, think: -1} + f.ingest(session.Event{Kind: session.EventToolBegin, Tool: "script", CallID: "s"}) + f.ingest(session.Event{Kind: session.EventToolBegin, Tool: "bash", CallID: "s-script-1", Parent: "s"}) + f.ingest(session.Event{Kind: session.EventToolEnd, Tool: "bash", CallID: "s-script-1", Parent: "s"}) + f.ingest(session.Event{Kind: session.EventToolBegin, Tool: "bash", CallID: "s-script-2", Parent: "s"}) + f.ingest(session.Event{Kind: session.EventToolFailed, Tool: "bash", CallID: "s-script-2", Parent: "s", Output: "boom"}) + var script, nested int + for _, e := range f.entries { + if e.kind != entryTool { + continue + } + if e.nested { + nested++ + } else { + script++ + } + } + if script != 1 || nested != 2 { + t.Errorf("rows: %d top-level, %d nested; want 1 and 2", script, nested) + } +} + +// A SCRIPT'S OWN CALL ENDING IS NOT THE BATCH ENDING. The script is still +// running, so no request is out and the wait for the model must not start; +// the script's own end starts it. +func TestAScriptsOwnCallEndingDoesNotStartTheWaitForTheModel(t *testing.T) { + a := newWaitingApp(t, 0) + a.awaited = time.Time{} + drive(t, a, streamEventMsg{gen: a.gen, ev: session.Event{Kind: session.EventToolEnd, Tool: "bash", CallID: "s-script-1", Parent: "s"}}) + if !a.awaited.IsZero() { + t.Fatal("a script's own call ending started the wait for the model while the script still ran") + } + drive(t, a, streamEventMsg{gen: a.gen, ev: session.Event{Kind: session.EventToolEnd, Tool: "script", CallID: "s"}}) + if a.awaited.IsZero() { + t.Fatal("the script's own end did not start the wait for the model") + } +} + +// A SCRIPT'S CALLS HANG UNDER THE SCRIPT, NOT UNDER THE ROW ABOVE THEM. When +// the model batches a script with another call, both rows begin first; the +// script's calls then go straight after the script, as a reopened +// conversation draws them. +func TestFeedHangsAScriptsCallsUnderTheScriptInABatch(t *testing.T) { + f := &feed{live: -1, think: -1} + f.ingest(session.Event{Kind: session.EventToolBegin, Tool: "script", CallID: "s"}) + f.ingest(session.Event{Kind: session.EventToolBegin, Tool: "read", CallID: "r"}) + f.ingest(session.Event{Kind: session.EventToolBegin, Tool: "bash", CallID: "s-script-1", Parent: "s"}) + f.ingest(session.Event{Kind: session.EventToolBegin, Tool: "bash", CallID: "s-script-2", Parent: "s"}) + var order []string + for _, e := range f.entries { + if e.kind == entryTool { + order = append(order, e.callID) + } + } + want := []string{"s", "s-script-1", "s-script-2", "r"} + if strings.Join(order, " ") != strings.Join(want, " ") { + t.Errorf("rows = %v, want %v", order, want) + } +} diff --git a/internal/tui3/planrail.go b/internal/tui3/planrail.go index a97a814f42..859206ae95 100644 --- a/internal/tui3/planrail.go +++ b/internal/tui3/planrail.go @@ -17,7 +17,6 @@ package tui3 // it rather than a zero. import ( - "encoding/json" "hash/fnv" "sort" "strings" @@ -113,8 +112,7 @@ func planRailNode(row session.PlanTaskRow) *taskNode { node.title = taskTitleOf(node.label, "", node.id) if row.Live.Step > 0 { if command := strings.TrimSpace(planDisplayCommand(row.Live.Command, row.LiveParts)); command != "" { - args, _ := json.Marshal(map[string]string{"command": command}) - node.tool, node.toolBegan = taskCallWord("bash", string(args), ""), row.Live.Since + node.tool, node.toolBegan = taskCallWord("bash", bashArgs(command), ""), row.Live.Since } } return node diff --git a/internal/tui3/planroom.go b/internal/tui3/planroom.go index e5b6621edd..60e4f5e730 100644 --- a/internal/tui3/planroom.go +++ b/internal/tui3/planroom.go @@ -168,6 +168,24 @@ func planRoomShape(page session.PlanTaskPage) string { return b.String() } +// bashArgs is a command as the bash tool's arguments, the shape every bash row +// is drawn from. +func bashArgs(command string) string { + raw, _ := json.Marshal(map[string]string{"command": command}) + return string(raw) +} + +// stepRow is the tool and arguments a recorded step or call is drawn with: a +// bash command, or a row from before the store named its tool, as bash's +// arguments built from its display command; any other tool, a script above +// all, with the arguments it recorded. +func stepRow(tool, recorded, display string) (string, string) { + if tool == "" || tool == "bash" { + return "bash", bashArgs(display) + } + return tool, recorded +} + // planRoomEntries is the page's transcript, built as a record and replayed // through the one door every transcript becomes blocks through // ([app.roomRecord]), so a step is drawn exactly as the conversation draws a @@ -184,11 +202,10 @@ func (a *app) planRoomEntries(page session.PlanTaskPage) ([]entry, int) { if brief := strings.TrimSpace(page.Description); brief != "" { add(session.DisplayEntry{Role: "user", Text: requestDisplayFor(brief)}) } - call := func(step int, command, output string, answered bool) { - args, _ := json.Marshal(map[string]string{"command": command}) + call := func(id, tool, args, output string, answered bool, flags session.ToolResultFlags) { add(session.DisplayEntry{ - Role: "tool", Tool: "bash", CallID: "step-" + itoa(step), - Args: string(args), Output: output, Answered: answered, + Role: "tool", Tool: tool, CallID: id, + Args: args, Output: output, Answered: answered, ToolResult: flags, }) } for _, step := range page.Steps { @@ -214,13 +231,26 @@ func (a *app) planRoomEntries(page session.PlanTaskPage) ([]entry, int) { if step.ObservationHeadWithheld { output = "" } - call(step.Step, command, output, true) + // A SCRIPT STEP IS DRAWN AS ITSELF, with its arguments; every other step + // keeps the bash row it has always had. + id := "step-" + itoa(step.Step) + tool, args := stepRow(step.Tool, step.Command, command) + call(id, tool, args, output, true, 0) + // AND THE CALLS A STEP MADE HANG UNDER IT, each as the tool it was + // (internal/run's StepCall). + for k, nested := range step.Calls { + tool, args := stepRow(nested.Tool, nested.Command, nested.Command) + call(id+"-call-"+itoa(k+1), tool, args, nested.Observation, true, session.ToolResultNested) + } } // THE LIVE STEP IS DRAWN ONE STEP EARLY, as a call in flight, and only // where the store says there is one ([plandb.LiveStep.Empty]). if live := page.Live; !live.Empty() && live.Step > 0 { if command := planDisplayCommand(live.Command, page.Row.LiveParts); command != "" { - call(live.Step, command, "", false) + // A SCRIPT IN FLIGHT IS DRAWN AS ITSELF, from the tool the live step + // names; every other live step keeps its bash row. + tool, args := stepRow(live.Tool, live.Command, command) + call("step-"+itoa(live.Step), tool, args, "", false, 0) } } for _, entry := range page.Worker { diff --git a/internal/tui3/planroom_script_test.go b/internal/tui3/planroom_script_test.go new file mode 100644 index 0000000000..fa5c0f8387 --- /dev/null +++ b/internal/tui3/planroom_script_test.go @@ -0,0 +1,98 @@ +package tui3 + +import ( + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/session" +) + +// scriptStepPage is a run task whose one step is a script that made two calls. +func scriptStepPage() session.PlanTaskPage { + root := session.PlanTaskRow{ID: "t-root", Title: "Root", Status: "running"} + return session.PlanTaskPage{Row: root, Steps: []session.PlanStep{{ + Kind: "step", Step: 1, Tool: "script", + Command: `{"source":"const r = await tools.bash({command: \"echo one\"})"}`, + Calls: []session.PlanCall{ + {Tool: "bash", Command: "echo one", Observation: "one"}, + {Tool: "read_document", Command: `{"path":"brief.pdf"}`}, + }, + }}} +} + +// A SCRIPT STEP DRAWS AS ITSELF, AND ITS CALLS FOLLOW IT MARKED NESTED. The +// record keeps the calls on the script's step (internal/run's StepCall); the +// room draws each as the tool it was, right after the script that made it. +func TestPlanRoomEntriesPutAScriptsCallsUnderItsStep(t *testing.T) { + page := scriptStepPage() + a, _ := planAppWith(t, []session.PlanTaskRow{page.Row}, nil) + entries, _ := a.planRoomEntries(page) + var tools []entry + for _, e := range entries { + if e.kind == entryTool { + tools = append(tools, e) + } + } + if len(tools) != 3 { + t.Fatalf("want the script and its two calls, got %d tool rows: %+v", len(tools), tools) + } + want := []struct { + tool string + nested bool + args string + }{{"script", false, "tools.bash"}, {"bash", true, "echo one"}, {"read_document", true, "brief.pdf"}} + for i, w := range want { + got := tools[i] + if got.tool != w.tool || got.nested != w.nested || !strings.Contains(got.detail.Args, w.args) { + t.Errorf("row %d = tool %q nested %v args %q; want %q nested %v with %q", i, got.tool, got.nested, got.detail.Args, w.tool, w.nested, w.args) + } + } +} + +// A SCRIPT IN FLIGHT IS DRAWN AS A SCRIPT, from the tool the live step names. +func TestPlanRoomDrawsALiveScriptAsAScript(t *testing.T) { + root := session.PlanTaskRow{ID: "t-root", Title: "Root", Status: "running"} + root.Live.Step, root.Live.Tool, root.Live.Command = 2, "script", `{"source":"return 1"}` + page := session.PlanTaskPage{Row: root, Live: root.Live} + a, _ := planAppWith(t, []session.PlanTaskRow{root}, nil) + entries, _ := a.planRoomEntries(page) + for _, e := range entries { + if e.kind == entryTool { + if e.tool != "script" || e.status != toolRunning { + t.Errorf("the live step is drawn as %q (%v), want a running script", e.tool, e.status) + } + return + } + } + t.Fatal("no live row") +} + +// A NESTED ROW IS THE SAME ROW, SHIFTED RIGHT AND NO WIDER. It sits under the +// script that made it and still fits the frame it is drawn in. +func TestNestedToolRowIsIndentedAndFitsItsWidth(t *testing.T) { + page := scriptStepPage() + a, _ := planAppWith(t, []session.PlanTaskRow{page.Row}, nil) + entries, _ := a.planRoomEntries(page) + at := -1 + for i, e := range entries { + if e.kind == entryTool && e.nested { + at = i + break + } + } + if at < 0 { + t.Fatal("no nested row") + } + const width = 100 + nested := a.toolRows(deck{entries: entries}, at, true, width)[0].text + flat := append([]entry(nil), entries...) + flat[at].nested = false + plainRow := a.toolRows(deck{entries: flat}, at, true, width)[0].text + lead := func(s string) int { return len(s) - len(strings.TrimLeft(plain(s), " ")) } + if got, base := lead(plain(nested)), lead(plain(plainRow)); got != base+nestedIndentCols { + t.Errorf("a nested row leads with %d spaces, want %d (%d + %d)\n%q\n%q", got, base+nestedIndentCols, base, nestedIndentCols, plain(nested), plain(plainRow)) + } + if w := len([]rune(plain(nested))); w > width { + t.Errorf("a nested row is %d cells wide in a %d-cell frame: %q", w, width, plain(nested)) + } +} diff --git a/internal/tui3/replay.go b/internal/tui3/replay.go index 6d77c34b8d..21bad4dc53 100644 --- a/internal/tui3/replay.go +++ b/internal/tui3/replay.go @@ -743,6 +743,7 @@ func (a *app) replayBlocks(entries []session.DisplayEntry, shape replayShape) ([ // pairs the end that arrives a second later with the row already // standing, or the same call is drawn twice. callID: e.CallID, + nested: e.ToolResult.Nested(), // AND THE STEP'S OWN TITLE COMES BACK WITH IT. The narration and // the family it named were journaled against this call // (session's DisplayEntry.Caption), so a reopened conversation diff --git a/internal/tui3/script_consent_test.go b/internal/tui3/script_consent_test.go new file mode 100644 index 0000000000..3211be83f7 --- /dev/null +++ b/internal/tui3/script_consent_test.go @@ -0,0 +1,57 @@ +package tui3 + +import ( + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/session" +) + +// AN APPROVAL ASKED FROM INSIDE A SCRIPT IS ASKED ON THE SCRIPT'S CALL'S ROW. +// The call began before the gate asked, so its row is already under the +// script; the question parks that row, raises the card, and draws no row of +// its own. The script and the batch's other call keep running. +func TestAnApprovalInsideAScriptIsAskedOnTheNestedRow(t *testing.T) { + a := newWaitingApp(t, 0) + a.width, a.height = 140, 30 + drive(t, a, + streamEventMsg{gen: a.gen, ev: session.Event{Kind: session.EventToolBegin, Tool: "script", CallID: "s", Hint: "script"}}, + streamEventMsg{gen: a.gen, ev: session.Event{Kind: session.EventToolBegin, Tool: "read", CallID: "r", Hint: "go.mod"}}, + streamEventMsg{gen: a.gen, ev: session.Event{Kind: session.EventToolBegin, Tool: "bash", CallID: "s-script-1", Parent: "s", Hint: "touch x", Args: `{"command":"touch x"}`}}, + streamEventMsg{gen: a.gen, ev: session.Event{Kind: session.EventConsentRequest, ID: 7, Tool: "bash", CallID: "s-script-1", Args: `{"command":"touch x"}`, Rule: "bash"}}, + ) + var order []string + status := map[string]toolState{} + nested := map[string]bool{} + for _, e := range a.entries { + if e.kind == entryTool { + order = append(order, e.callID) + status[e.callID], nested[e.callID] = e.status, e.nested + } + } + if got := strings.Join(order, " "); got != "s s-script-1 r" { + t.Fatalf("rows = %q; want the script, its call under it, then the read, and no row drawn for the question", got) + } + if status["s-script-1"] != toolConsent || !nested["s-script-1"] { + t.Errorf("the nested call's row is status %v, nested %v; want it asking, under its script", status["s-script-1"], nested["s-script-1"]) + } + if status["s"] == toolConsent || status["r"] == toolConsent { + t.Errorf("a row other than the asking call is asking: script %v, read %v", status["s"], status["r"]) + } + head, ok := a.questionHead() + if !ok || head.question.Subject.CallID != "s-script-1" { + t.Fatalf("the card is %+v (raised %v); want it about the nested call", head.question.Subject, ok) + } + var touch, read = -1, -1 + for i, line := range plainRows(a) { + if touch < 0 && strings.Contains(line, "touch x") { + touch = i + } + if read < 0 && strings.Contains(line, "go.mod") { + read = i + } + } + if touch < 0 || read < 0 || touch > read { + t.Errorf("the asking call is drawn at row %d and the read at %d; want it under the script, above the read:\n%s", touch, read, strings.Join(plainRows(a), "\n")) + } +} diff --git a/internal/tui3/task.go b/internal/tui3/task.go index f1a504af1e..0feb4c4585 100644 --- a/internal/tui3/task.go +++ b/internal/tui3/task.go @@ -1034,7 +1034,9 @@ func (a *app) pilotEvent(msg taskPilotMsg) tea.Cmd { if pilot == nil || pilot.gen != msg.gen { return nil } - if node := a.tasks[msg.id]; node != nil { + if node := a.tasks[msg.id]; node != nil && !msg.ev.FromScript() { + // A script's own calls leave the node's word on the script, which is + // what the node is doing until it ends. switch msg.ev.Kind { case session.EventToolAnnounced: // ASKED FOR, NOT STARTED — so the name changes and the clock does not diff --git a/internal/tui3/toolview.go b/internal/tui3/toolview.go index c6c81ecc00..c6466cf32b 100644 --- a/internal/tui3/toolview.go +++ b/internal/tui3/toolview.go @@ -165,6 +165,26 @@ const ( // "… N more lines" foot of a capped expansion is a DIFFERENT click target from // the line it hangs under: one lifts the cap, the other closes the call. func (a *app) toolRows(d deck, i int, last bool, width int) []row { + e := &d.entries[i] + // A SCRIPT'S CALL IS LAID OUT NARROWER AND SHIFTED RIGHT, so it sits under + // the script row it follows and still adds up to the frame's width. The + // shift is spaces, not a mark, so no glyph bypasses the repertoire. + if e.nested { + return a.toolRowsAt(d, i, last, width-nestedIndentCols, nestedIndent) + } + return a.toolRowsAt(d, i, last, width, "") +} + +// nestedIndent is how far a script's call sits right of its script's row. +const ( + nestedIndent = " " + nestedIndentCols = len(nestedIndent) +) + +// toolRowsAt is [app.toolRows] at a given width, every row led by indent. The +// indent rides the stem the block already prefixes, so a nested row costs no +// second string per row per frame. +func (a *app) toolRowsAt(d deck, i int, last bool, width int, indent string) []row { e := &d.entries[i] hit := hitTool if replayInert(e) { @@ -193,8 +213,15 @@ func (a *app) toolRows(d deck, i int, last bool, width int) []row { // spinner, the count-up, the pointer's own brightness — so it is built fresh // here; what hangs under it is evidence about a payload that arrived once. line, keep := a.toolLineLayout(e, i, last, width) + if indent != "" { + line = indent + line + if keep != (hudSpan{}) { + keep.from += len(indent) + keep.to += len(indent) + } + } out := []row{{text: line, entry: i, hit: hit, keep: keep}} - stem := a.pal.railCont() + stem := indent + a.pal.railCont() // THE INDENT LAW COSTS THE BLOCK ITS TWO CELLS TOO, and it is subtracted here // for the reason [app.toolLine] subtracts it: render.go's pass shoves every // work row two columns right AFTER layout, so a block laid out to the frame's