#!/bin/sh
# The codemode tool (src/codemode.c): off by default and on with the setting or PIC_CODEMODE; a
# script's calls run as calls nested in its own, at once; Pi's result format, options and limits;
# the worker has no timers, network or files and cannot start scripts; Ctrl-C and a killed pic
# leave a script failed or unknown, never run again. --no-faults: the release build (it has no
# crash points; nothing here needs them).
set -eu
PIC=${PIC:?set PIC to the pic binary}
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-codemode.XXXXXX")
export HOME="$T/home"
mkdir -p "$HOME"
trap 'touch "$T"/*-ws/release 2>/dev/null; rm -rf -- "$T"' EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
await() { i=0; while [ ! -e "$1" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "timed out waiting for $1"; sleep 0.1; done; }
HOLD='i=0; while [ ! -e release ] && [ $i -lt 1200 ]; do sleep 0.1; i=$((i + 1)); done'
# workers: whether a codemode worker of this pic is running.
workers() { ps -A -o command | awk -v w="$PIC __codemode-worker" '$0 == w { f = 1 } END { exit !f }'; }
fresh() { DB="$T/$1.sqlite"; WS="$T/$1-ws"; mkdir "$WS"; printf 'hello\n' > "$WS/notes.txt"; }
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
# script NAME JSON: a reply calling codemode with that input, then "done"
script() { printf 'tool raw codemode %s\ntext done\n' "$2" > "$T/$1.script"; }
run() { # run NAME JSON: a fresh journal, the script run to the answer
fresh "$1"
script "$1" "$2"
pic submit job-1 'go' > /dev/null
pic run --script "$T/$1.script" 2> "$T/$1.err" || fail "$1: run: $(cat "$T/$1.err")"
pic check > /dev/null || fail "$1: integrity check"
}
result() { sqlite3 "$DB" "SELECT result FROM pic_effect WHERE tool = 'codemode'"; }
is_error() { sqlite3 "$DB" "SELECT is_error FROM pic_effect WHERE tool = 'codemode'"; }
has() { result | grep -qF -- "$1" || fail "$2: result lacks '$1': $(result)"; }
# Off by default: not declared, and a call is refused as any tool not in play.
fresh off
script off '{"script":"return 1"}'
pic submit job-1 'go' > /dev/null
pic run --script "$T/off.script" 2> /dev/null || fail "off: run"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_session, json_each(tools) WHERE json_extract(value, '\$.name') = 'codemode'")" = 0 ] ||
fail "off: codemode declared"
[ "$(result)" = "Tool codemode not found" ] || fail "off: $(result)"
printf 'PASS: off by default\n'
# The setting turns it on for new conversations; its description lists the tools in play.
"$PIC" settings codemode true
fresh on
pic submit job-1 'go' > /dev/null
script on '{"script":"return 1"}'
pic run --script "$T/on.script" 2> /dev/null || fail "on: run"
desc=$(sqlite3 "$DB" "SELECT json_extract(value, '\$.description') FROM pic_session, json_each(tools) WHERE json_extract(value, '\$.name') = 'codemode'")
printf '%s' "$desc" | grep -q '^Run JavaScript that calls other tools' || fail "on: description: $desc"
printf '%s' "$desc" | grep -qF 'read(args: { limit?: number; offset?: number; path: string; }): Promise<string>;' ||
printf '%s' "$desc" | grep -qF 'read(args: {' || fail "on: no read declaration: $desc"
printf '%s' "$desc" | grep -qF '### `codemode`' && fail "on: codemode lists itself"
printf '%s' "$desc" | grep -qF 'Read the contents of a file' || fail "on: read is listed without its own description"
printf '%s' "$desc" | grep -qF 'CREATE TABLE' && fail "on: a tool's description is not its own"
"$PIC" settings | grep -q '^codemode' || fail "on: codemode is not among the settings"
"$PIC" settings --unset codemode
# set_codemode (the terminal's /codemode): this process and what it starts, and the open
# conversation, whose frozen tools gain codemode or lose it.
fresh switch
printf 'text first\n' > "$T/switch.script"
pic submit job-1 'go' > /dev/null
pic run --script "$T/switch.script" 2> /dev/null || fail "switch: run"
sid=$(sqlite3 "$DB" 'SELECT session_id FROM pic_submission')
declared() { sqlite3 "$DB" "SELECT count(*) FROM pic_session, json_each(tools) WHERE json_extract(value, '\$.name') = 'codemode'"; }
[ "$(declared)" = 0 ] || fail "switch: declared before"
printf '{"id":"c1","type":"set_codemode","enabled":true}\n' | perl -e 'alarm 30; exec @ARGV' \
"$PIC" --db "$DB" --workspace "$WS" --mode rpc --session "$sid" > "$T/switch.out" 2>&1 || true
grep -q '"id":"c1","type":"response","command":"set_codemode","success":true,"data":{"enabled":true}' "$T/switch.out" ||
fail "switch: on: $(cat "$T/switch.out")"
[ "$(declared)" = 1 ] || fail "switch: not declared after set_codemode"
printf '{"id":"c2","type":"set_codemode","enabled":false}\n' | perl -e 'alarm 30; exec @ARGV' \
"$PIC" --db "$DB" --workspace "$WS" --mode rpc --session "$sid" > "$T/switch.out" 2>&1 || true
grep -q '"success":true,"data":{"enabled":false}' "$T/switch.out" || fail "switch: off: $(cat "$T/switch.out")"
[ "$(declared)" = 0 ] || fail "switch: still declared after set_codemode off"
pic check > /dev/null || fail "switch: integrity"
printf 'PASS: set_codemode switches the open conversation\n'
export PIC_CODEMODE=on
printf 'PASS: the setting turns it on, and it lists the tools in play\n'
# A script's calls run at once, nested in its call; the result is Pi's.
run basic '{"script":"const [a, b] = await Promise.all([tools.bash({command: \"echo hi\"}), tools.read({path: \"notes.txt\"})]);\ntext(a); text(b); console.log(\"n\", typeof ALL_TOOLS.length); return {x: 1};"}'
[ "$(result | head -1)" = 'Script completed' ] || fail "basic: $(result)"
result | sed -n 2p | grep -qE '^Wall time [0-9]+\.[0-9] seconds$' || fail "basic: wall time: $(result)"
[ "$(result | sed -n 3p)" = 'Output:' ] || fail "basic: header: $(result)"
has '==> text 1/3 <==' basic
has '{"x":1}' basic
has "$(printf '<console_output>\nn number\n</console_output>')" basic
[ "$(is_error)" = 0 ] || fail "basic: is_error"
[ "$(sqlite3 "$DB" "SELECT group_concat(position || ' ' || tool || ' ' || state || ' ' || call_id, ',') FROM pic_nested_effect")" = \
'1 bash done toolu_fake_0_0/1,2 read done toolu_fake_0_0/2' ] || fail "basic: nested: $(sqlite3 "$DB" 'SELECT * FROM pic_nested_effect')"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_entry WHERE kind = 'tool_result'")" = 1 ] || fail "basic: inner results reached the transcript"
sid=$(sqlite3 "$DB" 'SELECT session_id FROM pic_submission')
printf '{"id":"m1","type":"get_messages"}\n' | perl -e 'alarm 30; exec @ARGV' \
"$PIC" --db "$DB" --workspace "$WS" --mode rpc --session "$sid" > "$T/basic.rpc" 2>&1 || true
grep -qF '"nestedCalls":{"calls":[{"id":"toolu_fake_0_0/1","name":"bash","status":"ok"},{"id":"toolu_fake_0_0/2","name":"read","status":"ok"}],"complete":true}' \
"$T/basic.rpc" || fail "basic: no nestedCalls on the tool result: $(grep -o 'toolResult.\{0,300\}' "$T/basic.rpc" | head -1)"
printf 'PASS: a script runs its calls nested, at once, with Pi'"'"'s result and nestedCalls\n'
# An inner write or edit keeps the file as found, so /rewind puts back what a script changed; an
# inner bash keeps its whole output for read, as a call of the model's does.
run history '{"script":"tools.write({path: \"new.txt\", content: \"made\\n\"});\ntools.edit({path: \"notes.txt\", edits: [{oldText: \"hello\", newText: \"bye\"}]});\nreturn tools.bash({command: \"seq 1 5000\"})"}'
[ "$(cat "$WS/notes.txt")" = bye ] && [ -f "$WS/new.txt" ] || fail "history: the script did not change the files"
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_file_change WHERE effect_id < 0")" = 2 ] || fail "history: no file history for inner calls"
n=$(sqlite3 "$DB" "SELECT id FROM pic_nested_effect WHERE tool = 'bash'")
sqlite3 "$DB" "SELECT result FROM pic_nested_effect WHERE id = $n" | grep -q "pic:nested/$n" || fail "history: bash does not name its whole output"
[ "$(sqlite3 "$DB" "SELECT sqlar_uncompress(data, sz) FROM pic_output WHERE effect_id = -$n" | grep -c .)" = 5000 ] ||
fail "history: the inner bash's whole output is not kept"
script history2 "{\"script\":\"return tools.read({path: \\\"pic:nested/$n\\\", offset: 4999})\"}"
printf 'tool raw codemode %s\ntext done\n' "$(head -1 "$T/history2.script" | sed 's/^tool raw codemode //')" > "$T/history2.script"
pic submit job-2 'more' > /dev/null
pic run --script "$T/history2.script" 2> /dev/null || fail "history: second run"
sqlite3 "$DB" "SELECT result FROM pic_effect ORDER BY id DESC LIMIT 1" | grep -q '^5000' ||
fail "history: read of the whole output: $(sqlite3 "$DB" 'SELECT result FROM pic_effect ORDER BY id DESC LIMIT 1')"
sid=$(sqlite3 "$DB" "SELECT session_id FROM pic_submission WHERE request_key = 'job-1'")
pic rewind "$sid" --list | grep -q '"text":"go","files":2' || fail "history: rewind does not count the script's files: $(pic rewind "$sid" --list | tr '\n' ' ') $(sqlite3 "$DB" 'SELECT id, effect_id, path FROM pic_file_change' | tr '\n' ' ')"
pic rewind "$sid" --to "$(sqlite3 "$DB" "SELECT min(seq) FROM pic_entry WHERE kind = 'user'")" --files > /dev/null ||
fail "history: rewind"
[ "$(cat "$WS/notes.txt")" = hello ] && [ ! -e "$WS/new.txt" ] || fail "history: rewind missed the script's files"
pic check > /dev/null || fail "history: integrity"
printf 'PASS: inner writes and edits rewind; an inner bash keeps its whole output\n'
# Calls return values; parallel() runs them at once, results in order; Pi-style await and
# Promise.all of values still work, one call after another; the journal has them in program order.
run sync '{"script":"const t0 = Date.now();\nconst [a, b] = parallel([() => tools.bash({command: \"sleep 1; echo a\"}), {tool: \"bash\", args: {command: \"sleep 1; echo b\"}}]);\nconst together = Date.now() - t0;\nconst c = tools.read({path: \"notes.txt\"});\nconst [d] = await Promise.all([tools.bash({command: \"echo d\"})]);\nconst settled = parallel([{tool: \"bash\", args: {command: \"exit 2\"}}, {tool: \"read\", args: {path: \"notes.txt\"}}], {settled: true}).map((r) => r.status);\nreturn [a, b, c.trim(), d, together < 1900, settled]"}'
has '["a","b","hello","d",true,["rejected","fulfilled"]]' sync
[ "$(sqlite3 "$DB" "SELECT group_concat(position || tool, ' ') FROM (SELECT * FROM pic_nested_effect ORDER BY position)")" = \
'1bash 2bash 3read 4bash 5bash 6read' ] || fail "sync: program order: $(sqlite3 "$DB" 'SELECT position, tool FROM pic_nested_effect')"
run parbad '{"script":"parallel([() => 1])"}'
has 'must make exactly one tool call and return it' parbad
printf 'PASS: calls return values; parallel() runs them at once, in order\n'
# The deadline cuts a running inner call, as the bash deadline does, and the script times out.
fresh cut
script cut '{"script":"// @options: {\"timeout_ms\": 1000}\ntools.bash({command: \"sleep 20; touch late\"}); text(\"after\")"}'
pic submit job-1 'go' > /dev/null
start=$(date +%s)
pic run --script "$T/cut.script" 2> /dev/null || fail "cut: run"
[ $(( $(date +%s) - start )) -lt 10 ] || fail "cut: the inner call ran past the deadline"
has 'Script timed out: Execution timed out after 1000 ms' cut
result | grep -qx after && fail "cut: the script went on past its deadline"
sleep 1
[ ! -e "$WS/late" ] || fail "cut: the inner command outlived the deadline"
pic check > /dev/null || fail "cut: integrity"
printf 'PASS: the deadline cuts a running inner call\n'
# Events: the inner calls with Pi's parentToolCallId.
fresh events
script events '{"script":"await tools.read({path: \"notes.txt\"})"}'
pic submit job-1 'go' > /dev/null
pic --json run --script "$T/events.script" > "$T/events.out" 2> /dev/null || fail "events: run"
grep -q '"type":"tool_execution_start","toolCallId":"toolu_fake_0_0/1","toolName":"read","args":{"path":"notes.txt"},"parentToolCallId":"toolu_fake_0_0"}' \
"$T/events.out" || fail "events: no nested start: $(grep tool_execution "$T/events.out")"
grep -q '"type":"tool_execution_end","toolCallId":"toolu_fake_0_0/1",.*"parentToolCallId":"toolu_fake_0_0"}' "$T/events.out" ||
fail "events: no nested end"
printf 'PASS: inner calls carry parentToolCallId\n'
# Failures keep partial output and list the calls made.
run toolfail '{"script":"text(\"before\"); await tools.bash({command: \"echo nope; exit 3\"})"}'
[ "$(result | head -1)" = 'Script failed' ] && [ "$(is_error)" = 1 ] || fail "toolfail: $(result)"
has before toolfail
has 'Script error:' toolfail
has 'Tool calls made before the failure (they are not undone): bash (error)' toolfail
run syntax '{"script":"syntax error here("}'
has 'SyntaxError' syntax
has 'No tool calls were made.' syntax
run stalled '{"script":"await new Promise(() => {})"}'
has 'The script is waiting on a promise that can never settle' stalled
run options '{"script":"// @options: {\"bad\": 1}\nreturn 1"}'
[ "$(result)" = '@options only supports `max_output_tokens` and `timeout_ms`; got `bad`' ] || fail "options: $(result)"
run misplaced '{"script":"return 1\n// @options: {}"}'
has 'line must be the first line of the input; found one on line 2' misplaced
run noscript '{"code":"return 1"}'
[ "$(result)" = 'codemode input must be a JSON object with script, the JavaScript source as a string' ] || fail "noscript: $(result)"
printf 'PASS: failures keep their output and name the calls made\n'
# Limits: the deadline, memory, the stack, output tokens (the whole kept for read).
run timeout '{"script":"// @options: {\"timeout_ms\": 300}\ntry { while (true) {} } catch (e) { text(\"caught\") }"}'
has 'Script timed out: Execution timed out after 300 ms' timeout
result | grep -q caught && fail "timeout: the script caught its deadline"
run memory '{"script":"const a = []; for (;;) a.push(\"x\".repeat(1e6))"}'
has 'InternalError: out of memory' memory
run stack '{"script":"function f() { return f() } f()"}'
has 'InternalError: stack overflow' stack
run tokens '{"script":"// @options: {\"max_output_tokens\": 10}\nfor (let i = 0; i < 20; i++) text(\"line \" + i)"}'
has 'Warning: truncated output (original token count:' tokens
has '[Full output: pic:output/1 (read with offset/limit)]' tokens
[ "$(sqlite3 "$DB" "SELECT sqlar_uncompress(data, sz) FROM pic_output WHERE effect_id = 1" | grep -c '^line ')" = 20 ] ||
fail "tokens: the whole output is not kept"
printf 'PASS: the deadline, heap, stack and output limits\n'
# The sandbox: no timers, network, files or OS; codemode cannot call itself.
run sandbox '{"script":"return [typeof setTimeout, typeof fetch, typeof require, typeof std, typeof os, typeof process, \"codemode\" in tools]"}'
has '["undefined","undefined","undefined","undefined","undefined","undefined",false]' sandbox
run self '{"script":"await tools.codemode({script: \"1\"})"}'
has 'tools.codemode does not exist' self
printf 'PASS: no timers, network, files or nested scripts\n'
# At most 256 recorded inner calls; the rest reject.
"$PIC" settings toolExecution sequential
run many '{"script":"const r = parallel(Array.from({length: 260}, () => ({tool: \"read\", args: {path: \"notes.txt\"}})), {settled: true});\nreturn r.filter((x) => x.status === \"rejected\").map((x) => x.reason.message)"}'
"$PIC" settings --unset toolExecution
[ "$(sqlite3 "$DB" "SELECT count(*) FROM pic_nested_effect")" = 256 ] || fail "many: $(sqlite3 "$DB" 'SELECT count(*) FROM pic_nested_effect') inner calls"
has '["a script may make at most 256 tool calls","a script may make at most 256 tool calls","a script may make at most 256 tool calls","a script may make at most 256 tool calls"]' many
printf 'PASS: 256 recorded inner calls\n'
# Beside another call of the same reply (codemode runs alone: one worker at a time), its calls still nest.
fresh par
printf 'tool raw codemode {"script":"return await tools.bash({command: \\"echo inner\\"})"}\tbash echo top\ntext done\n' > "$T/par.script"
pic submit job-1 'go' > /dev/null
pic run --script "$T/par.script" 2> /dev/null || fail "par: run"
pic check > /dev/null || fail "par: integrity"
has inner par
[ "$(sqlite3 "$DB" "SELECT state FROM pic_nested_effect")" = done ] || fail "par: nested"
printf 'PASS: a script in a parallel batch\n'
# Ctrl-C to pic's group: the running inner command is aborted, the script fails, the request is
# cancelled, and no worker is left.
fresh ctrlc
script ctrlc "{\"script\":\"await tools.bash({command: \\\"touch running; $HOLD\\\"})\"}"
pic submit job-1 'go' > /dev/null
perl -e '$SIG{INT} = "DEFAULT"; setpgrp(0, 0); exec @ARGV or die' "$PIC" --db "$DB" --workspace "$WS" \
run --script "$T/ctrlc.script" 2>/dev/null &
leader=$!
await "$WS/running"
kill -INT -"$leader"
wait "$leader" 2>/dev/null || true
pic check > /dev/null || fail "ctrlc: integrity"
pic dump | grep -q '^submission 1 job-1 failed | .* error=cancelled' || fail "ctrlc: not cancelled: $(pic dump | grep '^submission')"
[ "$(sqlite3 "$DB" "SELECT state FROM pic_effect WHERE tool = 'codemode'")" = done ] || fail "ctrlc: script $(pic dump | grep '^effect')"
has 'Script aborted' ctrlc
workers && fail "ctrlc: a worker was left running"
printf 'PASS: Ctrl-C aborts a script and leaves no worker\n'
# pic killed mid-script: the next pic makes it unknown with its inner calls listed, and runs
# nothing again; the worker dies with its call.
fresh killed
script killed "{\"script\":\"await tools.bash({command: \\\"echo once >> ledger\\\"}); await tools.bash({command: \\\"touch running; $HOLD\\\"})\"}"
pic submit job-1 'go' > /dev/null
"$PIC" --db "$DB" --workspace "$WS" run --script "$T/killed.script" 2>/dev/null &
victim=$!
await "$WS/running"
kill -9 "$victim"
wait "$victim" 2>/dev/null || true
pic run --script "$T/killed.script" 2>/dev/null || fail "killed: resume"
pic check > /dev/null || fail "killed: integrity"
[ "$(sqlite3 "$DB" "SELECT state FROM pic_effect WHERE tool = 'codemode'")" = unknown ] || fail "killed: $(pic dump | grep '^effect')"
has 'outcome unknown' killed
has '1. bash: finished' killed
has '2. bash: outcome unknown, not re-run' killed
[ "$(wc -l < "$WS/ledger" | tr -d ' ')" = 1 ] || fail "killed: the first command ran again"
touch "$WS/release"
i=0
while workers && [ "$i" -lt 50 ]; do sleep 0.1; i=$((i + 1)); done
[ "$i" -lt 50 ] || fail "killed: the worker outlived its pic"
printf 'PASS: a killed pic leaves the script unknown, its inner calls listed, nothing run twice\n'