#!/bin/sh
# pic --mode rpc, Pi's RPC mode, driven over a whole session at a fake
# server: prompt (with an image), steering and follow-ups while a tool runs,
# abort, compact while a turn runs (the abort journaled, then the compaction),
# fork, switch_session, clone, model and thinking changes, bash and
# abort_bash, export_html, get_state, get_messages and the other queries.
# Responses are held to Pi's shapes (rpc-fixtures, from Pi's docs). The
# process holds the journal only while it works, and a crash mid-prompt
# recovers as any pic run's.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
SQL=${SQLITE3:-sqlite3}
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
F=$here/rpc-fixtures
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-rpc.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME/.pic/prompts"
"$PIC" settings cacheRetention none > /dev/null
spid=
pid=
cleanup() {
exec 3>&- 2>/dev/null || :
[ -n "$spid" ] && kill "$spid" 2>/dev/null
[ -n "$pid" ] && kill -9 "$pid" 2>/dev/null
[ -n "${KEEP:-}" ] && { echo "kept $T" >&2; return; }
rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export ANTHROPIC_API_KEY=pic-rpc-test-key PIC_PI_EXPORT=0
n=0
serve() { # SPEC...: a fresh server, journal and workspace
[ -n "$spid" ] && kill "$spid" 2>/dev/null
n=$((n + 1))
mkdir "$T/log$n" "$T/ws$n"
DB="$T/j$n.sqlite"
WS="$T/ws$n"
LOG="$T/log$n"
EV="$T/ev$n"
"$SERVER" "$T/port$n" "$LOG" 120 "$@" &
spid=$!
i=0
while [ ! -s "$T/port$n" ]; do
i=$((i + 1))
[ "$i" -lt 600 ] || fail "server did not start"
sleep 0.05
done
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY",%s}}}' \
"$(cat "$T/port$n")" \
'"models":[{"id":"m"},{"id":"r","reasoning":true,"contextWindow":64000},{"id":"v","input":["text","image"]}]' \
> "$T/models$n.json"
export PIC_MODELS_FILE="$T/models$n.json"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
await() { # FILE PATTERN: wait up to 30s for the fixed string PATTERN in FILE
i=0
until grep -qF -- "$2" "$1" 2>/dev/null; do
i=$((i + 1))
[ "$i" -lt 600 ] || fail "timed out waiting for $2 in $1: $(tail -5 "$1" 2>/dev/null)"
sleep 0.05
done
}
exists() { # FILE: wait up to 30s for it
i=0
until [ -e "$1" ]; do
i=$((i + 1))
[ "$i" -lt 600 ] || fail "timed out waiting for $1: $(cat "$T/err$n" 2>/dev/null)"
sleep 0.05
done
}
start() { # ARGS...: pic --mode rpc ARGS, commands written to fd 3
rm -f "$T/in"
mkfifo "$T/in"
"$PIC" --db "$DB" --workspace "$WS" --model fake/m --mode rpc "$@" < "$T/in" > "$EV" 2> "$T/err$n" &
pid=$!
exec 3> "$T/in"
}
send() { printf '%s\n' "$1" >&3; }
finish() { # close stdin, wait for pic; its status in rc
exec 3>&-
rc=0
wait "$pid" || rc=$?
pid=
}
resp() { # ID: wait for the response to the command with that id, and print it
await "$EV" "\"id\":\"$1\",\"type\":\"response\""
grep -F "\"id\":\"$1\",\"type\":\"response\"" "$EV" | head -1
}
get() { # JSON PATH: the value at PATH (JSON text for objects and arrays)
printf '%s' "$1" > "$T/get.json"
"$SQL" :memory: "SELECT json_extract(CAST(readfile('$T/get.json') AS TEXT), '$2')"
}
keys() { # JSON PATH: its keys, sorted, comma-separated
printf '%s' "$1" > "$T/keys.json"
"$SQL" :memory: "SELECT group_concat(key, ',') FROM (SELECT key FROM json_each(CAST(readfile('$T/keys.json') AS TEXT), '$2') ORDER BY key)"
}
shape() { # FIXTURE JSON PATH [KEY...]: the keys at PATH as in Pi's fixture, less the KEYs pic leaves out
fixture=$1 json=$2 path=$3
shift 3
want=$(keys "$(cat "$F/$fixture")" "$path")
for k in "$@"; do
want=$(printf '%s' "$want" | tr ',' '\n' | grep -vx "$k" | paste -sd, -)
done
got=$(keys "$json" "$path")
if [ "$path" = '$' ]; then # a command's id is the client's
want=$(printf '%s' "$want" | tr ',' '\n' | grep -vx id | paste -sd, -)
got=$(printf '%s' "$got" | tr ',' '\n' | grep -vx id | paste -sd, -)
fi
[ "$got" = "$want" ] || fail "shape of $fixture at $path: got $got, want $want: $json"
}
# Entry seq of the user message whose text is $1, from get_fork_messages output $2.
fork_id() { get "$2" "\$.data.messages[$(get_index "$2" "$1")].entryId"; }
get_index() { # JSON TEXT: index in data.messages of the message with that text
printf '%s' "$1" > "$T/idx.json"
"$SQL" :memory: "SELECT key FROM json_each(CAST(readfile('$T/idx.json') AS TEXT), '\$.data.messages') WHERE json_extract(value, '\$.text') = '$2'"
}
PNG=iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==
# 1 one, 2 hold (two), 3 the steers' turn, 4 the follow-up, 5 hold (abort), 6 hold (compact),
# then text: the summary (two requests: the cut splits a turn), five, the image.
serve "sse:$S/text.sse" "sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/bash_hold.sse" \
"sse:$S/bash_hold.sse" "sse:$S/text.sse" "sse:$S/text.sse" "sse:$S/text.sse"
pic settings compaction '{"keepRecentTokens":1}' > /dev/null
printf 'Review $1 now\n' > "$HOME/.pic/prompts/rev.md"
start
# get_state before anything: Pi's keys, a session id, the model.
r=$(send '{"id":"st0","type":"get_state"}'; resp st0)
shape get_state.json "$r" '$'
shape get_state.json "$r" '$.data' sessionFile sessionName
shape model.json "$(get "$r" '$.data.model')" '$'
sid=$(get "$r" '$.data.sessionId')
[ "$(get "$r" '$.data.isStreaming')" = 0 ] || fail "state: streaming at start: $r"
[ "$(get "$r" '$.data.model.id')" = m ] && [ "$(get "$r" '$.data.model.provider')" = fake ] || fail "state: model: $r"
# While idle the journal is free: another pic opens it.
pic sessions > /dev/null || fail "idle: the journal is held"
printf 'PASS: get_state has Pi'"'"'s shape; idle, the journal is free\n'
# A prompt: accepted, then the run's events, then agent_settled.
send '{"id":"req-1","type":"prompt","message":"one"}'
r=$(resp req-1)
[ "$r" = '{"id":"req-1","type":"response","command":"prompt","success":true,"data":{"disposition":"started"}}' ] || fail "prompt: $r"
shape prompt.json "$r" '$'
await "$EV" '{"type":"agent_settled","aborted":false}'
a=$(grep -n '"command":"prompt"' "$EV" | head -1 | cut -d: -f1)
b=$(grep -n '"type":"agent_start"' "$EV" | head -1 | cut -d: -f1)
c=$(grep -n '"type":"agent_settled"' "$EV" | head -1 | cut -d: -f1)
[ "$a" -lt "$b" ] && [ "$b" -lt "$c" ] || fail "prompt: order response=$a start=$b settled=$c"
grep -q "\"conversation\":\"$sid\"" "$EV" || fail "prompt: not in session $sid"
r=$(send '{"id":"m1","type":"get_messages"}'; resp m1)
[ "$(get "$r" '$.data.messages[0].role')" = user ] && [ "$(get "$r" '$.data.messages[0].content[0].text')" = one ] ||
fail "get_messages: $r"
[ "$(get "$r" '$.data.messages[1].role')" = assistant ] || fail "get_messages: no reply: $r"
r=$(send '{"id":"t1","type":"get_last_assistant_text"}'; resp t1)
[ "$r" = '{"id":"t1","type":"response","command":"get_last_assistant_text","success":true,"data":{"text":"Hello, \"world\""}}' ] ||
fail "get_last_assistant_text: $r"
printf 'PASS: prompt is accepted, runs, settles; get_messages and get_last_assistant_text\n'
# While a tool runs: steering (with a template), a prompt that must say how
# to queue, one that does, a follow-up, and get_state; set_steering_mode all.
send '{"id":"p2","type":"prompt","message":"two"}'
exists "$WS/started"
send '{"id":"sm","type":"set_steering_mode","mode":"all"}'
send '{"id":"s1","type":"steer","message":"/rev the tests"}'
send '{"id":"pn","type":"prompt","message":"no behavior"}'
send '{"id":"ps","type":"prompt","message":"steer two","streamingBehavior":"steer"}'
send '{"id":"f1","type":"follow_up","message":"after all"}'
send '{"id":"st1","type":"get_state"}'
[ "$(resp sm)" = '{"id":"sm","type":"response","command":"set_steering_mode","success":true}' ] || fail "steer mode: $(resp sm)"
[ "$(resp s1)" = '{"id":"s1","type":"response","command":"steer","success":true,"data":{"disposition":"queued"}}' ] || fail "steer: $(resp s1)"
[ "$(resp pn)" = '{"id":"pn","type":"response","command":"prompt","success":false,"error":"Agent is already processing. Specify streamingBehavior ('"'steer' or 'followUp'"') to queue the message."}' ] ||
fail "prompt while streaming: $(resp pn)"
[ "$(resp ps)" = '{"id":"ps","type":"response","command":"prompt","success":true,"data":{"disposition":"queued"}}' ] || fail "prompt steer: $(resp ps)"
[ "$(resp f1)" = '{"id":"f1","type":"response","command":"follow_up","success":true,"data":{"disposition":"queued"}}' ] || fail "follow_up: $(resp f1)"
r=$(resp st1)
[ "$(get "$r" '$.data.isStreaming')" = 1 ] && [ "$(get "$r" '$.data.steeringMode')" = all ] || fail "state while running: $r"
await "$EV" '{"type":"queue_update","steering":["Review the now","steer two"],"followUp":["after all"]}'
touch "$WS/release"
await "$EV" '"followUp":[]}'
i=0
until [ "$(grep -c '"type":"agent_settled"' "$EV")" = 2 ]; do
i=$((i + 1)); [ "$i" -lt 600 ] || fail "steer: did not settle"; sleep 0.05
done
r3="$LOG/3.req"
grep -qF '{"role":"user","content":"Review the now"}' "$r3" && grep -qF '{"role":"user","content":"steer two"}' "$r3" ||
fail "steer: request 3: $(cat "$r3")"
grep -qF '{"role":"user","content":"after all"}' "$LOG/4.req" || fail "follow_up: request 4: $(cat "$LOG/4.req")"
rm -f "$WS/started" "$WS/release"
printf 'PASS: steer, follow_up and prompt with streamingBehavior while a tool runs\n'
# abort: the request is cancelled (journaled), the response follows, the run settles aborted.
send '{"id":"p3","type":"prompt","message":"three"}'
exists "$WS/started"
send '{"type":"abort"}'
await "$EV" '{"type":"agent_settled","aborted":true}'
r=$(grep -F '"command":"abort"' "$EV" | head -1)
[ "$r" = "$(tr -d ' ' < "$F/abort.json")" ] || fail "abort: $r"
pic check > /dev/null || fail "abort: integrity"
pic dump | grep -q "^submission .* failed .*cancelled" || fail "abort: not cancelled: $(pic dump | grep '^submission')"
rm -f "$WS/started"
printf 'PASS: abort cancels durably and answers with Pi'"'"'s shape\n'
# compact while a turn runs: the turn is aborted (cancelled in the journal),
# then the compaction runs and answers with Pi's CompactionResult.
send '{"id":"p4","type":"prompt","message":"four"}'
exists "$WS/started"
send '{"id":"c1","type":"compact","customInstructions":"keep it short"}'
r=$(resp c1)
[ "$(get "$r" '$.success')" = 1 ] || fail "compact: $r"
shape compact.json "$r" '$'
shape compact.json "$r" '$.data'
shape compact.json "$r" '$.data.usage'
get "$r" '$.data.summary' | head -1 | grep -qx 'Hello, "world"' || fail "compact: summary: $r"
s4=$(grep -n '"request":"ask-[^"]*","status":"failed","errorMessage":"cancelled"' "$EV" | tail -1 | cut -d: -f1)
cs=$(grep -n '"type":"compaction_start","reason":"manual"' "$EV" | tail -1 | cut -d: -f1)
ce=$(grep -n '"type":"compaction_end","reason":"manual","result"' "$EV" | tail -1 | cut -d: -f1)
cr=$(grep -n '"id":"c1"' "$EV" | cut -d: -f1)
[ -n "$s4" ] && [ -n "$cs" ] && [ -n "$ce" ] && [ "$s4" -lt "$cs" ] && [ "$cs" -lt "$ce" ] && [ "$ce" -lt "$cr" ] ||
fail "compact: order cancel=$s4 start=$cs end=$ce response=$cr"
grep -q 'keep it short' "$LOG/7.req" || fail "compact: instructions not in the summary request"
pic check > /dev/null || fail "compact: integrity"
pic dump > "$T/dump"
grep -q '^submission .* failed .*cancelled' "$T/dump" || fail "compact: the turn was not cancelled"
[ "$(grep -c '^entry .* compaction ' "$T/dump")" = 1 ] || fail "compact: no compaction entry: $(grep '^entry' "$T/dump")"
r=$(send '{"id":"c2","type":"compact"}'; resp c2)
[ "$r" = '{"id":"c2","type":"response","command":"compact","success":false,"error":"Already compacted"}' ] || fail "compact twice: $r"
r=$(send '{"id":"m2","type":"get_messages"}'; resp m2)
[ "$(get "$r" '$.data.messages[0].role')" = compactionSummary ] || fail "get_messages after compact: $r"
rm -f "$WS/started"
send '{"id":"p5","type":"prompt","message":"five"}'
await "$EV" '"id":"p5"'
i=0
until [ "$(grep -c '"type":"agent_settled"' "$EV")" = 5 ]; do
i=$((i + 1)); [ "$i" -lt 600 ] || fail "after compact: did not settle"; sleep 0.05
done
req=$(grep -l '"content":"five"' "$LOG"/*.req | head -1)
grep -q 'compacted into the following summary' "$req" || fail "after compact: no summary sent: $(cat "$req")"
r=$(send '{"id":"ss","type":"get_session_stats"}'; resp ss)
shape get_session_stats.json "$r" '$.data' sessionFile
shape get_session_stats.json "$r" '$.data.tokens'
shape get_session_stats.json "$r" '$.data.contextUsage'
printf 'PASS: compact mid-turn: the abort is journaled, then the compaction; Pi'"'"'s result shape\n'
# An image with the prompt, on a model that takes images.
r=$(send '{"id":"sv","type":"set_model","provider":"fake","modelId":"v"}'; resp sv)
shape model.json "$(get "$r" '$.data')" '$'
[ -z "$("$PIC" settings defaultModel 2>/dev/null)" ] || fail "set_model saved a default without persist"
r=$(send '{"id":"sp","type":"set_model","provider":"fake","modelId":"v","persist":true}'; resp sp)
[ "$("$PIC" settings defaultModel)" = fake/v ] || fail "set_model persist: default not saved"
"$PIC" settings --unset defaultModel; "$PIC" settings --unset lastModel
send '{"id":"pi","type":"prompt","message":"see this","images":[{"type":"image","data":"'"$PNG"'","mimeType":"image/png"}]}'
await "$EV" '"id":"pi"'
i=0
until [ "$(grep -c '"type":"agent_settled"' "$EV")" = 6 ]; do
i=$((i + 1)); [ "$i" -lt 600 ] || fail "image: did not settle"; sleep 0.05
done
req=$(grep -l 'see this' "$LOG"/*.req | head -1)
grep -qF '"type":"image"' "$req" && grep -qF 'AAAADUlEQVR42mNk' "$req" || fail "image: not sent: $(cat "$req")"
printf 'PASS: prompt carries images\n'
# Models and thinking.
r=$(send '{"id":"req-3","type":"set_model","provider":"invalid","modelId":"model"}'; resp req-3)
[ "$r" = "$(cat "$F/error.json")" ] || fail "set_model error: $r"
r=$(send '{"id":"am","type":"get_available_models"}'; resp am)
for m in m r v; do
get "$r" '$.data.models' | grep -q "\"id\":\"$m\",\"name\":\"$m\",\"api\":\"anthropic-messages\",\"provider\":\"fake\"" ||
fail "available models: no fake/$m: $r"
done
r=$(send '{"id":"sr","type":"set_model","provider":"fake","modelId":"r"}'; resp sr)
[ "$(get "$r" '$.data.reasoning')" = 1 ] || fail "set_model r: $r"
r=$(send '{"id":"tl","type":"get_available_thinking_levels"}'; resp tl)
[ "$r" = '{"id":"tl","type":"response","command":"get_available_thinking_levels","success":true,"data":{"levels":["off","minimal","low","medium","high"]}}' ] ||
fail "thinking levels: $r"
r=$(send '{"id":"th","type":"set_thinking_level","level":"high"}'; resp th)
[ "$r" = '{"id":"th","type":"response","command":"set_thinking_level","success":true}' ] || fail "set_thinking_level: $r"
grep -qF '{"type":"thinking_level_changed","level":"high"}' "$EV" || fail "no thinking_level_changed"
r=$(send '{"id":"ct","type":"cycle_thinking_level"}'; resp ct)
[ "$r" = '{"id":"ct","type":"response","command":"cycle_thinking_level","success":true,"data":{"level":"off"}}' ] || fail "cycle thinking: $r"
r=$(send '{"id":"cm","type":"cycle_model"}'; resp cm)
shape cycle_model.json "$r" '$.data'
[ "$(get "$r" '$.data.model.id')" = v ] || fail "cycle_model: $r"
r=$(send '{"id":"ct2","type":"cycle_thinking_level"}'; resp ct2)
[ "$r" = '{"id":"ct2","type":"response","command":"cycle_thinking_level","success":true,"data":null}' ] || fail "cycle thinking, no reasoning: $r"
r=$(send '{"id":"st2","type":"get_state"}'; resp st2)
[ "$(get "$r" '$.data.model.id')" = v ] && [ "$(get "$r" '$.data.thinkingLevel')" = off ] || fail "state after model changes: $r"
send '{"id":"sm2","type":"set_model","provider":"fake","modelId":"m"}'
resp sm2 > /dev/null
printf 'PASS: set_model, cycle_model, get_available_models, thinking levels\n'
# bash, then abort_bash on a long one.
r=$(send '{"id":"req-1b","type":"bash","command":"echo out; exit 3"}'; resp req-1b)
shape bash.json "$r" '$.data'
[ "$(get "$r" '$.data.output')" = out ] && [ "$(get "$r" '$.data.exitCode')" = 3 ] || fail "bash: $r"
grep -qF '{"type":"bash_execution_update","id":"req-1b","delta":"out' "$EV" || fail "bash: no update"
send '{"id":"b2","type":"bash","command":"touch bash-started; sleep 30","excludeFromContext":true}'
exists "$WS/bash-started"
send '{"id":"ab","type":"abort_bash"}'
r=$(resp b2)
[ "$(get "$r" '$.data.cancelled')" = 1 ] && [ "$(get "$r" '$.data.exitCode')" = '' ] || fail "abort_bash: $r"
[ "$(resp ab)" = '{"id":"ab","type":"response","command":"abort_bash","success":true}' ] || fail "abort_bash response"
pic dump | grep -q "^bash .*echo out; exit 3" || pic dump | grep -q 'echo out; exit 3' || fail "bash: not journaled"
printf 'PASS: bash and abort_bash\n'
# Session commands: name, entries, tree, fork, switch back, clone, new.
r=$(send '{"id":"nm","type":"set_session_name","name":" rpc work "}'; resp nm)
[ "$r" = '{"id":"nm","type":"response","command":"set_session_name","success":true}' ] || fail "name: $r"
r=$(send '{"id":"st3","type":"get_state"}'; resp st3)
shape get_state.json "$r" '$.data' sessionFile
[ "$(get "$r" '$.data.sessionName')" = 'rpc work' ] || fail "name in state: $r"
r=$(send '{"id":"ge","type":"get_entries"}'; resp ge)
shape get_entries.json "$r" '$.data'
leaf=$(get "$r" '$.data.leafId')
first=$(get "$r" '$.data.entries[0].id')
r=$(send '{"id":"ge2","type":"get_entries","since":"'"$first"'"}'; resp ge2)
[ "$(get "$r" '$.data.entries[0].parentId')" = "$first" ] || fail "get_entries since: $r"
r=$(send '{"id":"ge3","type":"get_entries","since":"nope"}'; resp ge3)
[ "$r" = '{"id":"ge3","type":"response","command":"get_entries","success":false,"error":"Entry not found: nope"}' ] || fail "since unknown: $r"
r=$(send '{"id":"gt","type":"get_tree"}'; resp gt)
[ "$(get "$r" '$.data.tree[0].entry.id')" = "$first" ] && [ "$(get "$r" '$.data.leafId')" = "$leaf" ] || fail "get_tree: $r"
f=$(send '{"id":"fm","type":"get_fork_messages"}'; resp fm)
shape get_fork_messages.json "$f" '$.data.messages[0]'
two=$(fork_id two "$f")
[ -n "$two" ] || fail "fork messages: no 'two': $f"
r=$(send '{"id":"fk","type":"fork","entryId":"'"$two"'"}'; resp fk)
[ "$r" = '{"id":"fk","type":"response","command":"fork","success":true,"data":{"text":"two","cancelled":false}}' ] || fail "fork: $r"
shape fork.json "$r" '$.data'
r=$(send '{"id":"st4","type":"get_state"}'; resp st4)
forked=$(get "$r" '$.data.sessionId')
[ "$forked" != "$sid" ] || fail "fork: still in $sid"
r=$(send '{"id":"m3","type":"get_messages"}'; resp m3)
[ "$(get "$r" '$.data.messages[0].content[0].text')" = one ] && ! printf '%s' "$r" | grep -q '"text":"two"' ||
fail "fork: messages: $r"
r=$(send '{"id":"fk2","type":"fork","entryId":"'"$leaf"'"}'; resp fk2)
[ "$r" = '{"id":"fk2","type":"response","command":"fork","success":false,"error":"Invalid entry ID for forking"}' ] || fail "fork bad: $r"
r=$(send '{"id":"sw","type":"switch_session","sessionPath":"'"$sid"'"}'; resp sw)
[ "$r" = '{"id":"sw","type":"response","command":"switch_session","success":true,"data":{"cancelled":false}}' ] || fail "switch: $r"
r=$(send '{"id":"st5","type":"get_state"}'; resp st5)
[ "$(get "$r" '$.data.sessionId')" = "$sid" ] || fail "switch: $r"
r=$(send '{"id":"cl","type":"clone"}'; resp cl)
[ "$r" = '{"id":"cl","type":"response","command":"clone","success":true,"data":{"cancelled":false}}' ] || fail "clone: $r"
r=$(send '{"id":"st6","type":"get_state"}'; resp st6)
[ "$(get "$r" '$.data.sessionId')" != "$sid" ] && [ "$(get "$r" '$.data.messageCount')" -gt 2 ] || fail "clone: $r"
r=$(send '{"id":"ns","type":"new_session"}'; resp ns)
[ "$r" = '{"id":"ns","type":"response","command":"new_session","success":true,"data":{"cancelled":false}}' ] || fail "new: $r"
r=$(send '{"id":"st7","type":"get_state"}'; resp st7)
[ "$(get "$r" '$.data.messageCount')" = 0 ] || fail "new: $r"
r=$(send '{"id":"cl2","type":"clone"}'; resp cl2)
[ "$r" = '{"id":"cl2","type":"response","command":"clone","success":false,"error":"Cannot clone session: no current entry selected"}' ] || fail "clone empty: $r"
send '{"id":"sw2","type":"switch_session","sessionPath":"'"$sid"'"}'
resp sw2 > /dev/null
printf 'PASS: set_session_name, get_entries, get_tree, fork, switch_session, clone, new_session\n'
# archive_session and unarchive_session (pic's): the current conversation, or session; the row's
# archived and archivedMs; pic sessions leaves it out until it is unarchived.
r=$(send '{"id":"arc1","type":"archive_session"}'; resp arc1)
[ "$(get "$r" '$.data.session')" = "$sid" ] && [ "$(get "$r" '$.data.archived')" = 1 ] && [ -n "$(get "$r" '$.data.archivedMs')" ] ||
fail "archive_session: $r"
if pic sessions | grep -q "^$sid "; then fail "archive_session: still listed"; fi
pic sessions archived | grep -q "^$sid " || fail "archive_session: not archived: $(pic sessions archived)"
r=$(send '{"id":"uarc1","type":"unarchive_session","session":"'"$sid"'"}'; resp uarc1)
[ "$r" = '{"id":"uarc1","type":"response","command":"unarchive_session","success":true,"data":{"session":"'"$sid"'","archived":false,"archivedMs":null}}' ] ||
fail "unarchive_session: $r"
r=$(send '{"id":"arcx","type":"archive_session","session":"nosuch"}'; resp arcx)
[ "$(get "$r" '$.success')" = 0 ] || fail "archive_session unknown: $r"
printf 'PASS: archive_session and unarchive_session\n'
# export_html, get_commands, idle steering and clear_queue, the errors.
r=$(send '{"id":"ex","type":"export_html","outputPath":"'"$T/out.html"'"}'; resp ex)
[ "$r" = '{"id":"ex","type":"response","command":"export_html","success":true,"data":{"path":"'"$T/out.html"'"}}' ] || fail "export: $r"
grep -q '<html' "$T/out.html" && grep -q 'five' "$T/out.html" || fail "export: page"
r=$(send '{"id":"gc","type":"get_commands"}'; resp gc)
[ "$(get "$r" '$.data.commands[0].name')" = rev ] && [ "$(get "$r" '$.data.commands[0].source')" = prompt ] &&
[ "$(get "$r" '$.data.commands[0].sourceInfo.scope')" = user ] || fail "get_commands: $r"
r=$(send '{"id":"is","type":"steer","message":"held"}'; resp is)
[ "$r" = '{"id":"is","type":"response","command":"steer","success":true,"data":{"disposition":"queued"}}' ] || fail "idle steer: $r"
r=$(send '{"id":"cq","type":"clear_queue"}'; resp cq)
[ "$r" = '{"id":"cq","type":"response","command":"clear_queue","success":true,"data":{"steering":["held"],"followUp":[]}}' ] || fail "clear_queue: $r"
r=$(send '{"id":"ar","type":"set_auto_retry","enabled":false}'; resp ar)
[ "$r" = '{"id":"ar","type":"response","command":"set_auto_retry","success":true}' ] || fail "auto retry: $r"
r=$(send '{"id":"ac","type":"set_auto_compaction","enabled":true}'; resp ac)
[ "$r" = '{"id":"ac","type":"response","command":"set_auto_compaction","success":true}' ] || fail "auto compaction: $r"
r=$(send '{"id":"un","type":"bogus"}'; resp un)
[ "$r" = '{"id":"un","type":"response","command":"bogus","success":false,"error":"Unknown command: bogus"}' ] || fail "unknown: $r"
r=$(send '{"id":"lg","type":"login"}'; resp lg)
[ "$r" = '{"id":"lg","type":"response","command":"login","success":false,"error":"login needs a provider"}' ] || fail "login: $r"
r=$(send '{"id":"lo","type":"logout","provider":"nobody"}'; resp lo)
[ "$r" = '{"id":"lo","type":"response","command":"logout","success":true,"data":{"removed":false}}' ] || fail "logout: $r"
r=$(send '{"type":"extension_ui_response","id":"x","value":"y"}'; await "$EV" '"command":"extension_ui_response"'; grep -F '"command":"extension_ui_response"' "$EV")
printf '%s' "$r" | grep -q '"success":false,"error":"no question x' || fail "extension ui: $r"
send 'not json'
await "$EV" '{"type":"response","command":"parse","success":false,"error":"Failed to parse command: '
printf 'PASS: export_html, get_commands, idle queue, unsupported and unknown commands, parse errors\n'
finish
[ "$rc" = 0 ] || fail "exit $rc: $(cat "$T/err$n")"
pic check > /dev/null || fail "integrity at the end"
printf 'PASS: stdin closed: pic exits 0, the journal intact\n'
# The command registry: get_commands and get_available_models are answered by
# components, at once while a request runs; an unknown command waits for it to
# end and errors as before.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
start
send '{"id":"rp","type":"prompt","message":"hold"}'
exists "$WS/started"
r=$(send '{"id":"rc","type":"get_commands"}'; resp rc)
[ "$(get "$r" '$.data.commands[0].name')" = rev ] || fail "registry: get_commands while running: $r"
r=$(send '{"id":"rm","type":"get_available_models"}'; resp rm)
printf '%s' "$r" | grep -qF '"id":"m","name":"m","api":"anthropic-messages","provider":"fake"' || fail "registry: get_available_models while running: $r"
send '{"id":"ru","type":"bogus"}'
r=$(send '{"id":"rs","type":"get_state"}'; resp rs)
[ "$(get "$r" '$.data.isStreaming')" = 1 ] || fail "registry: not streaming: $r"
grep -qF '"id":"ru"' "$EV" && fail "registry: an unknown command answered while a request runs"
touch "$WS/release"
r=$(resp ru)
[ "$r" = '{"id":"ru","type":"response","command":"bogus","success":false,"error":"Unknown command: bogus"}' ] || fail "registry: unknown: $r"
grep -q '"type":"agent_end"' "$EV" || fail "registry: the request did not end"
finish
[ "$rc" = 0 ] || fail "registry: exit $rc: $(cat "$T/err$n")"
printf 'PASS: component commands answer while a request runs; an unknown command errors as before\n'
# The commands the terminal interface asks (keel's client seam): any RPC client can ask them too.
mkdir -p "$WS/sub/deep"
printf 'x\n' > "$WS/sub/deep/f.txt"
printf 'x\n' > "$WS/skip.log"
printf '*.log\n' > "$WS/.gitignore"
mkdir -p "$WS/.git" "$WS/.zit" "$WS/.fossil-settings"
printf 'x\n' > "$WS/zit.txt"; printf 'x\n' > "$WS/glob.txt"; printf 'x\n' > "$WS/.git/h.txt"; printf 'x\n' > "$WS/.zit/z.txt"
printf 'agent.txt\n' > "$WS/.picignore"; printf 'x\n' > "$WS/agent.txt"
printf 'zit.txt\n' > "$WS/.zitignore"; printf 'glob.txt\n' > "$WS/.fossil-settings/ignore-glob"
printf 'Be brief.\n' > "$WS/AGENTS.md"
start
r=$(send '{"id":"s1","type":"set_setting","key":"hideThinking","value":"true"}'; resp s1)
[ "$(get "$r" '$.success')" = 1 ] || fail "client: set_setting: $r"
r=$(send '{"id":"s2","type":"get_setting","key":"hideThinking"}'; resp s2)
[ "$(get "$r" '$.data.value')" = true ] || fail "client: get_setting: $r"
r=$(send '{"id":"s3","type":"get_setting","key":"neverSet"}'; resp s3)
[ "$r" = '{"id":"s3","type":"response","command":"get_setting","success":true,"data":{"value":null}}' ] || fail "client: unset: $r"
r=$(send '{"id":"s4","type":"set_setting","key":"compaction","path":"$.enabled","json":"false"}'; resp s4)
r=$(send '{"id":"s5","type":"get_compaction_settings"}'; resp s5)
[ "$(get "$r" '$.data.compaction.enabled')" = 0 ] || fail "client: get_compaction_settings: $r"
r=$(send '{"id":"s6","type":"set_scoped_models","patterns":["fake/*"]}'; resp s6)
r=$(send '{"id":"s7","type":"get_scoped_models"}'; resp s7)
[ "$(get "$r" '$.data.patterns')" = '["fake/*"]' ] || fail "client: scoped models: $r"
r=$(send '{"id":"s8","type":"get_recent_models","limit":3}'; resp s8)
[ "$(get "$r" '$.data.models[0].model')" = fake/m ] || fail "client: recent models: $r"
r=$(send '{"id":"h1","type":"get_help","topic":"rpc"}'; resp h1)
case "$(get "$r" '$.data.text')" in "# "*) ;; *) fail "client: get_help text: $r" ;; esac
r=$(send '{"id":"h2","type":"get_help","topic":"nope"}'; resp h2)
[ "$(get "$r" '$.data.text')" = "" ] && printf '%s' "$r" | grep -q '"topics":\["' || fail "client: get_help unknown: $r"
r=$(send '{"id":"f1","type":"list_files"}'; resp f1)
printf '%s' "$r" | grep -qF '["sub/deep/f.txt",false,3]' || fail "client: list_files: $r"
printf '%s' "$r" | grep -qF '["skip.log",false,1]' || fail "client: list_files left out an ignored file: $r"
for f in zit.txt glob.txt; do printf '%s' "$r" | grep -qF "[\"$f\",false,1]" || fail "client: list_files left out $f: $r"; done
printf '%s' "$r" | grep -q 'agent.txt' && fail "client: list_files kept a .picignore entry: $r"
printf '%s' "$r" | grep -qE '"\.git/|"\.zit/' && fail "client: list_files entered version-control metadata: $r"
r=$(send '{"id":"c1","type":"get_context_files"}'; resp c1)
printf '%s' "$r" | grep -q 'AGENTS.md' || fail "client: get_context_files: $r"
r=$(send '{"id":"p1","type":"get_providers"}'; resp p1)
printf '%s' "$r" | grep -q '"providers":\[".*"fake"' || fail "client: get_providers: $r"
r=$(send '{"id":"t1","type":"get_trust","path":"/nowhere/at/all"}'; resp t1)
[ "$(get "$r" '$.data.trusted')" = -1 ] || fail "client: get_trust: $r"
r=$(send '{"id":"g1","type":"get_setting"}'; resp g1)
[ "$(get "$r" '$.success')" = 0 ] || fail "client: get_setting without a key: $r"
finish
rm -f "$WS/AGENTS.md" "$WS/.gitignore" "$WS/skip.log" "$WS/.zitignore" "$WS/.picignore" "$WS/agent.txt" "$WS/zit.txt" "$WS/glob.txt"
rm -rf "$WS/.git" "$WS/.zit" "$WS/.fossil-settings"
rm -rf "$WS/sub"
printf 'PASS: the client commands: settings, compaction settings, scope, help, files, context, providers, trust\n'
# get_settings: the settings list with each value; set_setting refuses what the list does not allow.
"$PIC" settings --unset lapseMode; "$PIC" settings --unset compaction
start
r=$(send '{"id":"g1","type":"get_settings","setting":"lapseMode"}'; resp g1)
v=$(get "$r" '$.data.version')
[ -n "$v" ] && [ "$v" -ge 0 ] || fail "get_settings: no version: $r"
want='{"id":"lapseMode","key":"lapseMode","field":null,"group":"Context","name":"Lapse mode","kind":"choice","values":["trim","summary"],"labels":["trim","summary"],"unit":null,"default":"trim","defaultLabel":"trim","description":"How a lapse compacts: drop older context with no request, or write Pi'"'"'s summary.","applies":"next request","stored":null,"value":"trim","valid":true}'
[ "$(get "$r" '$.data.settings[0]')" = "$want" ] || fail "get_settings: the row: $(get "$r" '$.data.settings[0]')"
r=$(send '{"id":"g2","type":"get_settings","setting":"compaction.reserveTokens"}'; resp g2)
[ "$(keys "$r" '$.data.settings[0]')" = "applies,default,defaultLabel,description,field,group,id,key,kind,max,min,name,stored,unit,valid,value" ] ||
fail "get_settings: a number row's fields: $(keys "$r" '$.data.settings[0]')"
[ "$(get "$r" '$.data.settings[0].field')" = reserveTokens ] && [ "$(get "$r" '$.data.settings[0].key')" = compaction ] ||
fail "get_settings: a field row: $r"
r=$(send '{"id":"g3","type":"get_settings"}'; resp g3)
[ "$(keys "$r" '$.data')" = settings,version ] || fail "get_settings: $(keys "$r" '$.data')"
printf '%s' "$r" > "$T/all.json"
[ "$("$SQL" :memory: "SELECT json_array_length(CAST(readfile('$T/all.json') AS TEXT), '\$.data.settings')")" = 42 ] || fail "get_settings: not 42 rows"
# Every row refuses a value it does not allow, with a message naming what it does; nothing is stored.
"$SQL" :memory: "SELECT json_extract(value, '\$.id') || ' ' || json_extract(value, '\$.kind') FROM json_each(CAST(readfile('$T/all.json') AS TEXT), '\$.data.settings')" > "$T/rows"
k=0
while read -r sid kind; do
k=$((k + 1))
case $kind in
choice) bad=bogus want='is one of' ;;
number) bad=12x want='is a whole number' ;;
*) bad='two\nlines' want=' is ' ;;
esac
before=$("$PIC" settings "$sid" 2>/dev/null || :)
r=$(send "{\"id\":\"b$k\",\"type\":\"set_setting\",\"key\":\"$sid\",\"value\":\"$bad\"}"; resp "b$k")
[ "$(get "$r" '$.success')" = 0 ] || fail "set_setting took $bad for $sid: $r"
case $(get "$r" '$.error') in *"$want"*) ;; *) fail "set_setting $sid: the message: $r" ;; esac
[ "$("$PIC" settings "$sid" 2>/dev/null || :)" = "$before" ] || fail "set_setting $sid: a refused value was stored"
done < "$T/rows"
[ "$k" = 42 ] || fail "set_setting: tried $k rows"
r=$(send '{"id":"p1","type":"set_setting","key":"compaction","path":"$.reserveTokens","json":"-5"}'; resp p1)
[ "$(get "$r" '$.success')" = 0 ] || fail "set_setting path: took -5: $r"
r=$(send '{"id":"p2","type":"set_setting","key":"compaction","value":"{\"enabled\":\"no\"}"}'; resp p2)
[ "$(get "$r" '$.success')" = 0 ] || fail "set_setting object: took enabled no: $r"
# Allowed values save, a field by its dotted name inside its object; unknown keys pass as before.
r=$(send '{"id":"o1","type":"set_setting","key":"compaction.reserveTokens","value":"5000"}'; resp o1)
[ "$(get "$r" '$.success')" = 1 ] && [ "$("$PIC" settings compaction)" = '{"reserveTokens":5000}' ] || fail "set_setting field: $r $("$PIC" settings compaction)"
r=$(send '{"id":"o2","type":"set_setting","key":"compaction.reserveTokens","value":null}'; resp o2)
[ "$(get "$r" '$.success')" = 1 ] && [ "$("$PIC" settings compaction)" = '{}' ] || fail "set_setting field unset: $r"
r=$(send '{"id":"o3","type":"set_setting","key":"thinkingLevel:fake/m","value":"high"}'; resp o3)
[ "$(get "$r" '$.success')" = 1 ] || fail "set_setting: a per-model level: $r"
r=$(send '{"id":"o4","type":"set_setting","key":"somethingNew","value":"anything at all"}'; resp o4)
[ "$(get "$r" '$.success')" = 1 ] || fail "set_setting: an unknown key: $r"
r=$(send '{"id":"o5","type":"set_setting","key":"compaction","value":"{\"keepRecentTokens\":1,\"modelOverrides\":{}}"}'; resp o5)
[ "$(get "$r" '$.success')" = 1 ] || fail "set_setting: an allowed object: $r"
"$PIC" settings --unset compaction; "$PIC" settings --unset thinkingLevel:fake/m; "$PIC" settings --unset somethingNew
# since: unchanged while nothing is written, the new rows once another process writes.
r=$(send '{"id":"v1","type":"get_settings"}'; resp v1)
v=$(get "$r" '$.data.version')
r=$(send "{\"id\":\"v2\",\"type\":\"get_settings\",\"since\":$v}"; resp v2)
[ "$(get "$r" '$.data')" = "{\"version\":$v,\"unchanged\":true}" ] || fail "get_settings since: $r"
"$PIC" settings lapseMode summary
r=$(send "{\"id\":\"v3\",\"type\":\"get_settings\",\"since\":$v,\"setting\":\"lapseMode\"}"; resp v3)
[ "$(get "$r" '$.data.version')" -gt "$v" ] && [ "$(get "$r" '$.data.settings[0].value')" = summary ] || fail "get_settings since a change: $r"
# A value stored past the list reads as the default, marked not valid.
"$SQL" "$HOME/.pic/pic.sqlite" "INSERT INTO picu_setting(key, value, updated_ms) VALUES('toolExecution', 'sideways', 0)"
r=$(send '{"id":"v4","type":"get_settings","setting":"toolExecution"}'; resp v4)
[ "$(get "$r" '$.data.settings[0].stored')" = sideways ] && [ "$(get "$r" '$.data.settings[0].value')" = parallel ] &&
[ "$(get "$r" '$.data.settings[0].valid')" = 0 ] || fail "get_settings: a bad stored value: $r"
r=$(send '{"id":"v5","type":"get_settings","setting":"nope"}'; resp v5)
[ "$(get "$r" '$.success')" = 0 ] || fail "get_settings: an unknown setting: $r"
finish
"$PIC" settings --unset lapseMode; "$PIC" settings --unset toolExecution
# pic settings runs the same check.
if "$PIC" settings tuiMode wide 2> "$T/cli.err"; then fail "pic settings took tuiMode wide"; fi
grep -qF 'tuiMode is one of fullscreen, regular, not wide' "$T/cli.err" || fail "pic settings: $(cat "$T/cli.err")"
"$PIC" settings compaction.keepRecentTokens 3000 && [ "$("$PIC" settings compaction.keepRecentTokens)" = 3000 ] ||
fail "pic settings: a field by its dotted name"
"$PIC" settings --unset compaction
printf 'PASS: get_settings lists every setting with its value and the change counter; set_setting and pic settings refuse bad values, unknown keys pass\n'
# A crash mid-prompt: the journal recovers as any pic run's; a new RPC
# process continues the conversation once the request is finished.
serve "sse:$S/bash_hold.sse" "sse:$S/text.sse"
start
send '{"id":"p1","type":"prompt","message":"crash me"}'
exists "$WS/started"
kill -9 "$pid"
wait "$pid" 2>/dev/null || :
pid=
exec 3>&-
touch "$WS/release"
i=0
until pic check > /dev/null 2>&1; do
i=$((i + 1)); [ "$i" -lt 600 ] || fail "crash: journal not usable: $(pic check 2>&1)"; sleep 0.05
done
pic dump | grep -q '^submission .* admitted' || fail "crash: the request is not left to finish: $(pic dump | grep '^submission')"
pic --model fake/m run > /dev/null 2>&1 || fail "crash: pic run did not finish it"
pic dump | grep -q '^submission .* answered' || fail "crash: not answered: $(pic dump | grep '^submission')"
pic check > /dev/null || fail "crash: integrity"
start -c
r=$(send '{"id":"m","type":"get_messages"}'; resp m)
printf '%s' "$r" | grep -q '"text":"crash me"' || fail "crash: -c lost the conversation: $r"
finish
printf 'PASS: a crash mid-prompt recovers; --mode rpc -c continues the conversation\n'