#!/bin/sh
# Asks (docs/dev/asks.md): a question a conversation waits on a person for is a pic_ask row that any
# client answers once. A loop or goal the model asked for is one, and its answer is the wake's
# decision; a stopped one withdraws it. A run waiting on an ask sees the answer; a second answer is
# refused with the first; a crash on either side of the answer's commit answers once; a run killed
# while it waits leaves the question open, and the next owner finds the answer. pic --mode rpc
# answers with answer_ask or Pi's extension_ui_response. Usage: test/pic/ask.sh [--no-faults]
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
FAULTS=1
[ "${1:-}" = --no-faults ] && FAULTS=0
here=$(cd "$(dirname "$0")" && pwd)
S=$here/streams
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-ask.XXXXXX")
# pic keeps user state under HOME: never the real one.
export HOME="$T/home"
mkdir -p "$HOME/.pic"
"$PIC" settings cacheRetention none > /dev/null
"$PIC" settings defaultModel fake/m > /dev/null
spid=
pid=
cleanup() {
[ -n "$spid" ] && kill "$spid" 2>/dev/null
[ -n "$pid" ] && kill -9 "$pid" 2>/dev/null
rm -rf -- "$T"
}
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export ANTHROPIC_API_KEY=pic-ask-test-key PIC_PI_EXPORT=0
SQLITE3=${SQLITE3:-sqlite3}
n=0
serve() { # SPEC...: a fresh server, journal and workspace
mkdir "$T/ws$((n + 1))"
DB="$T/j$((n + 1)).sqlite"
WS="$T/ws$((n + 1))"
[ -n "$spid" ] && kill "$spid" 2>/dev/null
n=$((n + 1))
mkdir "$T/log$n"
LOG="$T/log$n"
"$SERVER" "$T/port$n" "$LOG" 90 "$@" &
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","models":[{"id":"m"}]}}}' \
"$(cat "$T/port$n")" > "$T/models$n.json"
export PIC_MODELS_FILE="$T/models$n.json"
}
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
q() { "$SQLITE3" -cmd ".timeout 10000" "$DB" "$1"; }
until_sql() { # SQL VALUE: wait up to 30s for the query to print VALUE
i=0
until [ "$(q "$1" 2> /dev/null)" = "$2" ]; do
i=$((i + 1))
[ "$i" -lt 600 ] || fail "timed out waiting for [$1] = $2: $(q "$1")"
sleep 0.05
done
}
tool_sse() { # NAME JSON: a reply that calls tool NAME with input JSON
esc=$(printf '%s' "$2" | sed 's/\\/\\\\/g; s/"/\\"/g')
printf 'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_01","type":"message","role":"assistant","model":"m","content":[],"stop_reason":null,"usage":{"input_tokens":25,"output_tokens":1}}}\n\n'
printf 'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_g","name":"%s","input":{}}}\n\n' "$1"
printf 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"%s"}}\n\n' "$esc"
printf 'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n'
printf 'event: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":40}}\n\n'
printf 'event: message_stop\ndata: {"type":"message_stop"}\n\n'
}
ask_state() { q "SELECT state || '|' || coalesce(answer, '') || '|' || coalesce(answered_by, '') FROM pic_ask ORDER BY rowid LIMIT 1 OFFSET $(($1 - 1))"; }
aid() { q "SELECT id FROM pic_ask ORDER BY rowid LIMIT 1 OFFSET $(($1 - 1))"; } # the Nth ask's id
# A loop the model asks for is an ask: listed by pic answer with its loop, answered once; the
# answer is the loop's decision, and a second answer is refused with the first.
tool_sse wake '{"action":"loop","prompt":"look again","every":"5m"}' > "$T/loop.sse"
tool_sse wake '{"action":"goal","condition":"it is green"}' > "$T/goal.sse"
serve "sse:$T/loop.sse" "sse:$S/text.sse" "sse:$T/goal.sse" "sse:$S/text.sse" "sse:$T/loop.sse" "sse:$S/text.sse"
pic ask 'watch it' > /dev/null 2> "$T/err" || fail "wake: $(cat "$T/err")"
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
[ "$(q "SELECT ask_key, session_id = '$SID', kind, title, body, state, length(id) FROM pic_ask")" = "wake:1|1|confirm|Start loop L1, every 5m?|look again|open|22" ] ||
fail "wake: the ask: $(q 'SELECT * FROM pic_ask')"
pic answer > "$T/list" || fail "wake: list"
grep -qF "$(aid 1) $SID confirm Start loop L1, every 5m?" "$T/list" || fail "wake: list: $(cat "$T/list")"
[ "$(pic answer --json | "$SQLITE3" :memory: "SELECT json_extract(readfile('/dev/stdin'), '\$[0].wake')")" = L1 ] || fail "wake: list --json: $(pic answer --json)"
if pic answer "$(aid 1)" '"maybe"' 2> "$T/err"; then fail "wake: a text answer to a confirm"; fi
grep -qF 'a confirm is answered true or false' "$T/err" || fail "wake: refused: $(cat "$T/err")"
[ "$(pic answer "$(aid 1)" true)" = "answered $(aid 1)" ] || fail "wake: answer"
[ "$(ask_state 1)" = "answered|true|terminal" ] || fail "wake: answered: $(ask_state 1)"
[ "$(q "SELECT state, json_extract(options, '\$.approval') FROM pic_wake WHERE id = 1")" = "active|approved" ] || fail "wake: not approved: $(q 'SELECT state, options FROM pic_wake')"
[ "$(q "SELECT count(*) FROM pic_inbox WHERE msg_key = 'approval:1'")" = 1 ] || fail "wake: the model's message"
[ "$(pic answer "$(aid 1)" true)" = "answered $(aid 1)" ] || fail "wake: the same answer again"
if pic answer "$(aid 1)" false 2> "$T/err"; then fail "wake: a second answer"; fi
grep -qF '"state":"answered","value":true,"answeredBy":"terminal"' "$T/err" || fail "wake: second: $(cat "$T/err")"
[ "$(q "SELECT state FROM pic_wake WHERE id = 1")" = active ] || fail "wake: the second answer changed it"
[ -z "$(pic answer)" ] || fail "wake: still listed: $(pic answer)"
pic loop stop L1 > /dev/null
# pic loop decline is an answer too, and closes the ask; a stopped loop withdraws its ask
pic ask --session "$SID" 'and a goal' > /dev/null 2> "$T/err" || fail "wake: goal: $(cat "$T/err")"
[ "$(q "SELECT title FROM pic_ask ORDER BY rowid LIMIT 1 OFFSET 1")" = "Start goal G2?" ] || fail "wake: goal's ask: $(q 'SELECT * FROM pic_ask')"
[ "$(pic loop decline G2)" = "declined G2" ] || fail "wake: decline"
[ "$(ask_state 2)" = "answered|false|terminal" ] || fail "wake: declined: $(ask_state 2)"
pic ask --session "$SID" 'once more' > /dev/null 2> "$T/err" || fail "wake: third: $(cat "$T/err")"
pic loop stop L3 > /dev/null
[ "$(ask_state 3)" = "withdrawn||" ] || fail "wake: stopped: $(ask_state 3)"
if pic answer "$(aid 3)" true 2> "$T/err"; then fail "wake: answered a withdrawn ask"; fi
grep -qF '"state":"withdrawn"' "$T/err" || fail "wake: withdrawn: $(cat "$T/err")"
pic check > /dev/null || fail "wake: integrity"
printf 'PASS: a loop or goal the model asks for is an ask, answered once by any client; a stopped one is withdrawn\n'
# pic --mode rpc lists and answers: get_asks, answer_ask, and Pi's extension_ui_response.
serve "sse:$T/loop.sse" "sse:$S/text.sse" "sse:$T/loop.sse" "sse:$S/text.sse"
pic ask 'watch it' > /dev/null 2> "$T/err" || fail "rpc: $(cat "$T/err")"
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
pic ask --session "$SID" 'and again' > /dev/null 2> "$T/err" || fail "rpc: $(cat "$T/err")"
printf '{"id":"a","type":"get_asks"}\n{"id":"b","type":"answer_ask","ask":"%s","value":true}\n{"type":"extension_ui_response","id":"%s","confirmed":false}\n{"id":"d","type":"answer_ask","ask":"%s","value":true}\n' "$(aid 1)" "$(aid 2)" "$(aid 2)" |
pic --mode rpc --session "$SID" > "$T/rpc.out" 2> "$T/err" || fail "rpc: $(cat "$T/err")"
grep -F '"command":"get_asks"' "$T/rpc.out" | grep -qF '"title":"Start loop L1, every 5m?"' || fail "rpc: get_asks: $(cat "$T/rpc.out")"
grep -F '"command":"answer_ask"' "$T/rpc.out" | head -1 | grep -qF '"result":"answered"' || fail "rpc: answer_ask: $(cat "$T/rpc.out")"
grep -F '"command":"extension_ui_response"' "$T/rpc.out" | grep -qF '"success":true' || fail "rpc: extension_ui_response: $(cat "$T/rpc.out")"
grep -F '"command":"answer_ask"' "$T/rpc.out" | tail -1 | grep -qF '"result":"already_answered","standing":{"state":"answered","value":false,"answeredBy":"rpc"}' || fail "rpc: second answer: $(cat "$T/rpc.out")"
[ "$(ask_state 1)|$(ask_state 2)" = "answered|true|rpc|answered|false|rpc" ] || fail "rpc: rows: $(ask_state 1) $(ask_state 2)"
printf 'PASS: pic --mode rpc lists asks and answers them, with answer_ask and extension_ui_response\n'
# A late answer to a question that expired is told so, not that another answer stood.
q "INSERT INTO pic_ask(id, ask_key, session_id, kind, title, created_ms, expires_ms, state, version) VALUES('expiredexpiredexpired1', 'test:late', '$SID', 'confirm', 'Too late?', 1, 2, 'open', (SELECT max(version) + 1 FROM pic_ask))"
[ -z "$(pic answer | grep -F 'Too late?')" ] || fail "expired: still listed"
if pic answer expiredexpiredexpired1 true 2> "$T/err"; then fail "expired: answered"; fi
grep -qF 'question expiredexpiredexpired1 expired unanswered' "$T/err" || fail "expired: $(cat "$T/err")"
[ "$(q "SELECT state, answer IS NULL FROM pic_ask WHERE id = 'expiredexpiredexpired1'")" = "expired|1" ] || fail "expired: row"
printf '{"type":"answer_ask","ask":"expiredexpiredexpired1","value":true}\n' | pic --mode rpc --session "$SID" | grep -qF '"result":"expired"' || fail "expired: rpc"
pic check > /dev/null || fail "expired: integrity"
printf 'PASS: a late answer to an expired question is told it expired\n'
[ "$FAULTS" = 1 ] || { printf 'PASS: ask (release: the asking tool and fault points are dev-only)\n'; exit 0; }
export PIC_TEST_ASK=1
# A run waiting on an ask sees its answer: a select's option, refused when it is not one.
tool_sse ask_person '{"kind":"select","title":"Which branch?","options":["main","dev"]}' > "$T/select.sse"
serve "sse:$T/select.sse" "sse:$S/text.sse"
"$PIC" --db "$DB" --workspace "$WS" ask 'pick one' > "$T/out" 2> "$T/err" &
pid=$!
until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
[ "$(q "SELECT kind, title, json_extract(spec, '\$.options') FROM pic_ask")" = 'select|Which branch?|[{"label":"main"},{"label":"dev"}]' ] || fail "select: $(q 'SELECT * FROM pic_ask')"
if pic answer "$(aid 1)" other 2> "$T/err2"; then fail "select: not an option"; fi
grep -qF 'one of its labels' "$T/err2" || fail "select: refused: $(cat "$T/err2")"
SID=$(q "SELECT session_id FROM pic_ask")
pic attach --session "$SID" --no-follow --format json > "$T/attach.out" 2> "$T/err2" || fail "select: attach: $(cat "$T/err2")"
grep -qF "{\"type\":\"extension_ui_request\",\"id\":\"$(aid 1)\",\"method\":\"select\",\"title\":\"Which branch?\",\"options\":[\"main\",\"dev\"]," "$T/attach.out" ||
fail "select: attach shows: $(cat "$T/attach.out")"
printf '{"type":"extension_ui_response","id":"%s","value":"dev"}\n' "$(aid 1)" | pic attach -i --session "$SID" --format json > /dev/null 2> "$T/err2" ||
fail "select: attach -i: $(cat "$T/err2")"
[ "$(ask_state 1)" = 'answered|"dev"|attach' ] || fail "select: answered from attach: $(ask_state 1) $(cat "$T/err2")"
wait "$pid" || fail "select: the run: $(cat "$T/err")"
pid=
[ "$(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")" = 'answered: "dev"' ] || fail "select: the run saw: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")"
pic check > /dev/null || fail "select: integrity"
printf 'PASS: a run waiting on an ask sees the answer given in pic attach, and an answer that is not one is refused\n'
# Limits: a title is cut to 120 characters, a label to 60; at most 10 options and one default; an
# option may be destructive; a text answer over 4,000 characters is refused.
long=$(printf 'x%.0s' $(seq 1 130))
tool_sse ask_person "{\"kind\":\"select\",\"title\":\"$long\",\"options\":[{\"label\":\"Delete it\",\"destructive\":true},{\"label\":\"Keep it\",\"default\":true},\"$long\"]}" > "$T/weights.sse"
tool_sse ask_person '{"kind":"select","title":"Too many","options":["1","2","3","4","5","6","7","8","9","10","11"]}' > "$T/many.sse"
tool_sse ask_person '{"kind":"select","title":"Two defaults","options":[{"label":"a","default":true},{"label":"b","default":true}]}' > "$T/twodef.sse"
tool_sse ask_person '{"kind":"input","title":"Say it"}' > "$T/say.sse"
serve "sse:$T/many.sse" "sse:$S/text.sse" "sse:$T/twodef.sse" "sse:$S/text.sse" "sse:$T/weights.sse" "sse:$S/text.sse" "sse:$T/say.sse" "sse:$S/text.sse"
pic ask 'many' > /dev/null 2> "$T/err" || fail "limits: many: $(cat "$T/err")"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1" | grep -qF 'a select needs 1 to 10 distinct labels' || fail "limits: 11 options"
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
pic ask --session "$SID" 'two' > /dev/null 2> "$T/err" || fail "limits: two: $(cat "$T/err")"
q "SELECT body FROM pic_entry WHERE kind = 'tool_result' ORDER BY seq DESC LIMIT 1" | grep -qF 'at most one default' || fail "limits: two defaults"
[ "$(q "SELECT count(*) FROM pic_ask")" = 0 ] || fail "limits: asked anyway"
"$PIC" --db "$DB" --workspace "$WS" ask --session "$SID" 'weigh' > /dev/null 2> "$T/err" &
pid=$!
until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
[ "$(q "SELECT length(title), json_extract(spec, '\$.options[0]'), json_extract(spec, '\$.options[1]'), length(json_extract(spec, '\$.options[2].label')) FROM pic_ask")" = '120|{"label":"Delete it","destructive":true}|{"label":"Keep it","default":true}|60' ] ||
fail "limits: weights: $(q 'SELECT title, spec FROM pic_ask')"
[ "$(pic answer "$(aid 1)" 'Keep it')" = "answered $(aid 1)" ] || fail "limits: answer"
wait "$pid" || fail "limits: the run: $(cat "$T/err")"
pid=
"$PIC" --db "$DB" --workspace "$WS" ask --session "$SID" 'say' > /dev/null 2> "$T/err" &
pid=$!
until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
big=$(printf 'y%.0s' $(seq 1 4001))
if pic answer "$(aid 2)" "$big" 2> "$T/err2"; then fail "limits: a long answer"; fi
grep -qF 'at most 4000 characters' "$T/err2" || fail "limits: long: $(cat "$T/err2")"
[ "$(pic answer "$(aid 2)" "${big%y}")" = "answered $(aid 2)" ] || fail "limits: 4000 characters"
wait "$pid" || fail "limits: say: $(cat "$T/err")"
pid=
printf 'PASS: a question'"'"'s texts are cut to their limits, options carry their weight, and an answer over a limit is refused\n'
# A crash on either side of the answer's commit: before, the ask is still open and the run still
# waits; after, it is answered once and the run sees it. A second answer is refused either way.
tool_sse ask_person '{"kind":"input","title":"Name it","placeholder":"a name"}' > "$T/input.sse"
for at in 1 2; do
serve "sse:$T/input.sse" "sse:$S/text.sse"
"$PIC" --db "$DB" --workspace "$WS" ask 'name it' > "$T/out" 2> "$T/err" &
pid=$!
until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
rc=0
env PIC_CRASH_AT="ask_answer:$at" "$PIC" --db "$DB" --workspace "$WS" answer "$(aid 1)" first > /dev/null 2>&1 || rc=$?
[ "$rc" = 77 ] || fail "crash $at: exit $rc"
if [ "$at" = 1 ]; then
[ "$(ask_state 1)" = "open||" ] || fail "crash 1: $(ask_state 1)"
kill -0 "$pid" 2> /dev/null || fail "crash 1: the run stopped waiting"
[ "$(pic answer "$(aid 1)" second)" = "answered $(aid 1)" ] || fail "crash 1: answer again"
want='answered: "second"'
else
[ "$(ask_state 1)" = 'answered|"first"|terminal' ] || fail "crash 2: $(ask_state 1)"
want='answered: "first"'
if pic answer "$(aid 1)" second 2> /dev/null; then fail "crash 2: a second answer"; fi
fi
wait "$pid" || fail "crash $at: the run: $(cat "$T/err")"
pid=
[ "$(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")" = "$want" ] || fail "crash $at: the run saw: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")"
pic check > /dev/null || fail "crash $at: integrity"
done
printf 'PASS: a crash at the answer answers once, and the waiting run sees the one answer\n'
# A run killed while it waits leaves the question open; answered meanwhile, the next owner of the
# request finds the same ask answered and goes on with it.
tool_sse ask_person '{"kind":"confirm","title":"Go on?"}' > "$T/confirm.sse"
serve "sse:$T/confirm.sse" "sse:$S/text.sse"
"$PIC" --db "$DB" --workspace "$WS" ask 'go' > "$T/out" 2> "$T/err" &
pid=$!
until_sql "SELECT count(*) FROM pic_ask WHERE state = 'open'" 1
SID=$(q "SELECT id FROM pic_session ORDER BY updated_ms DESC LIMIT 1")
kill -9 "$pid"
wait "$pid" 2> /dev/null || true
pid=
[ "$(ask_state 1)" = "open||" ] || fail "kill: the ask closed: $(ask_state 1)"
pic answer > "$T/list"
grep -qF "$(aid 1) $SID confirm Go on?" "$T/list" || fail "kill: not listed: $(cat "$T/list")"
[ "$(pic answer "$(aid 1)" true)" = "answered $(aid 1)" ] || fail "kill: answer"
pic run --session "$SID" > /dev/null 2> "$T/err" || fail "kill: resume: $(cat "$T/err")"
[ "$(q "SELECT count(*) FROM pic_ask")" = 1 ] || fail "kill: asked twice: $(q 'SELECT * FROM pic_ask')"
[ "$(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")" = 'answered: true' ] || fail "kill: the run saw: $(q "SELECT body FROM pic_entry WHERE kind = 'tool_result'")"
[ "$(q "SELECT status FROM pic_submission ORDER BY id DESC LIMIT 1")" = answered ] || fail "kill: the request"
pic check > /dev/null || fail "kill: integrity"
printf 'PASS: a run killed while it waits leaves the question open, and the next owner finds the answer\n'
printf 'PASS: ask\n'