#!/bin/sh
# The terminal interface when a reply is refused for its key, on a
# pseudo-terminal against a fake server: the swap prompt offers what fits the
# failure (another key with the cost of an uncached re-send, another model, a
# wait for a limit, a new login for a refused key, Esc to stop); s retries
# with the other key and the journal records which key each reply used; w
# waits instead of asking again; l opens the login; Esc stops; nothing is
# sent again until a choice; the footer names the key and warns of a dead
# one; /key lists the keys with their state. --no-faults (the release
# build): skipped, since the keys are stored with PIC_TEST_PASSPHRASE, which
# only the dev build reads.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
DRIVE=${DRIVE:?set DRIVE to the pty_drive binary}
SQLITE3=${SQLITE3:-sqlite3}
if [ "${1:-}" = --no-faults ]; then
printf 'SKIP: keyprompt needs the dev build (PIC_TEST_PASSPHRASE)\n'
exit 0
fi
S=$(cd "$(dirname "$0")/../pic/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-keyprompt.XXXXXX")
T=$(cd "$T" && pwd -P)
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
mkdir "$T/ws" "$T/log" "$T/home"
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
unset PIC_TEST_PASSPHRASE
PASS="pic-keyprompt-pass-$$"
K1="pic-keyprompt-one-$$"
K2="pic-keyprompt-two-$$"
export HOME="$T/home" PIC_MODELS_FILE="$T/models.json" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 T
export PIC_NO_NATIVE_CLIPBOARD=1
printf '{"type":"error","error":{"type":"billing_error","message":"Your credit balance is too low to access the Anthropic API."}}' > "$T/billing.json"
printf '{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}' > "$T/auth.json"
printf '{"type":"error","error":{"type":"rate_limit_error","message":"rate limited"}}' > "$T/rate.json"
# 1 out of credit, 2 the swap's reply, 3 limited for 15 minutes, 4 refused, then replies
"$SERVER" "$T/port" "$T/log" 120 "status:402:$T/billing.json" "sse:$S/text.sse" "head:429:$T/rate.json:retry-after: 900" \
"status:401:$T/auth.json" "sse:$S/text.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server"; sleep 0.05; done
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$FAKE_API_KEY","models":[{"id":"m","contextWindow":200000,"cost":{"input":3,"output":15}}]}}}' \
"$(cat "$T/port")" > "$T/models.json"
printf '%s\n' "$K1" | PIC_TEST_PASSPHRASE="$PASS" "$PIC" --db "$T/j" --workspace "$T/ws" login fake > /dev/null 2> "$T/login.err" ||
fail "login: $(cat "$T/login.err")"
printf '%s\n' "$K2" | PIC_TEST_PASSPHRASE="$PASS" "$PIC" --db "$T/j" --workspace "$T/ws" auth login fake --as second > /dev/null 2> "$T/login.err" ||
fail "login --as: $(cat "$T/login.err")"
requests() { ls "$T/log" | wc -l | tr -d ' '; }
sent_key() { sed -n 's/^x-api-key: //p' "$T/log/$1.req" | tr -d '\r'; }
drive() { # NAME: pic on a pseudo-terminal, the script on stdin
name=$1
shift
"$DRIVE" "$T/$name.tx" 100 30 "$PIC" --tui-mode regular --db "$T/j" --workspace "$T/ws" --model fake/m "$@" ||
fail "$name: $(perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$T/$name.tx" | grep -v '^\s*$' | tail -12)"
}
drive prompt <<EOF
expect pic fake/m
send hello\r
expect Passphrase for pic's credential store:
send $PASS\r
expect The key "default" is out of credit. Nothing was lost.
expect s retry with "second"
expect m another model
expect esc stop
waitfile \$T/log/1.req
wait 500
send s
expect Requests to fake use the key "second" now.
expect Hello, "world"
expect key second
expect ! out of credit: default
send again\r
expect Limited until
expect w wait and continue
expect s switch key
send w
expect Waiting until
wait 800
send \e
expect interrupted request dropped
send third\r
expect fake refused the key "second" (HTTP 401).
expect l log in again
send l
expect API key "second" for fake:
send \e
wait 300
send \e
expect interrupted request dropped
send /key\r
expect Keys
expect default API key out of credit since
expect refused since
send \e
wait 200
send \x04\x04
expect pic: conversation
EOF
[ "$(requests)" = 4 ] || fail "prompt: $(requests) requests (a refusal was sent again without a choice)"
[ "$(sent_key 1)" = "$K1" ] && [ "$(sent_key 2)" = "$K2" ] || fail "prompt: s did not retry with the other key"
[ "$("$SQLITE3" "$T/j" "SELECT group_concat(state || ':' || coalesce(credential, '-'), ',') FROM (SELECT * FROM pic_generation ORDER BY id)")" = \
"failed:fake,done:fake:second,failed:fake:second,failed:fake:second" ] ||
fail "journal: $("$SQLITE3" "$T/j" "SELECT state, credential FROM pic_generation ORDER BY id")"
[ "$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT value FROM picu_setting WHERE key = 'activeKey:fake'")" = second ] || fail "s: not active"
"$PIC" --db "$T/j" --workspace "$T/ws" check > /dev/null || fail "journal integrity"
! grep -aqF -- "$K1" "$T/prompt.tx" && ! grep -aqF -- "$K2" "$T/prompt.tx" || fail "a key reached the screen"
printf 'PASS: the swap prompt: s retries with the other key, w waits, l opens the login, Esc stops; never on its own\n'
printf 'PASS: the footer names the key and warns of a dead one; /key lists the keys with their state\n'