Skip to content
pi-c Artifact [38e2166b13]
Login

Artifact [38e2166b13]

Artifact 38e2166b137beca4342a5e861a63bd18e38c861cd63862ade1e644d1b1f5a754:


#!/bin/sh
# The Messages API provider end to end against a local fake server: request
# shape, replay of content, retries, failures, a cut stream, a crash
# mid-stream, and that the API key never reaches pic's database or output.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
FAULTS=yes # --no-faults: skip cases that need crash hooks (the release build has none)
[ "${1:-}" = --no-faults ] && FAULTS=no
STREAMS=$(cd "$(dirname "$0")/streams" && pwd)
CHAT=$(cd "$(dirname "$0")/chat-streams" && pwd)
RESP=$(cd "$(dirname "$0")/responses-streams" && pwd)
GEM=$(cd "$(dirname "$0")/gemini-streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-provider.XXXXXX")
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; }
# Runs pic with a crash hook and requires the hook's own exit status (77), so
# an unrelated failure cannot pass for the crash.
expect_crash() {
    point=$1
    shift
    rc=0
    env PIC_CRASH_AT="$point" "$PIC" --db "$DB" --workspace "$WS" "$@" 2>/dev/null || rc=$?
    [ "$rc" = 77 ] || fail "expected a crash at $point, got exit $rc"
}

# Settings and the model catalog come from here, never the real ~/.pic.
mkdir "$T/home"
export HOME="$T/home" PIC_MODEL_CATALOG=offline
SENTINEL="pic-sentinel-key-$$-7f3a9c"
export DEEPSEEK_API_KEY="pic-sentinel-key-$$-7f3a9c"
export ANTHROPIC_API_KEY="$SENTINEL" OPENROUTER_API_KEY="$SENTINEL" OPENAI_API_KEY="$SENTINEL" GEMINI_API_KEY="$SENTINEL"

serve() { # serve NAME SPEC...: start a fake server for the next case
    [ -n "$spid" ] && kill "$spid" 2>/dev/null && wait "$spid" 2>/dev/null || true
    LOG="$T/$1-log"
    mkdir "$LOG"
    rm -f "$T/port"
    shift
    "$SERVER" "$T/port" "$LOG" 60 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port" ]; do
        i=$((i + 1))
        [ "$i" -lt 100 ] || fail "server did not start"
        sleep 0.05
    done
    URL="http://127.0.0.1:$(cat "$T/port")/v1/messages"
}
fresh() { DB="$T/$1.sqlite"; WS="$T/$1-ws"; mkdir "$WS"; }
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
run() { pic run --provider anthropic --model anthropic/test-model --api-url "$URL" 2>> "$T/stderr"; }
case_() { # case_ NAME SPEC...: fresh journal, fake server, one submission
    fresh "$1"
    serve "$@"
    pic submit job-1 'make notes' > /dev/null
}
status() { pic dump | sed -n 's/^submission 1 job-1 \([a-z]*\) .*/\1/p'; }
failed_generations() { pic dump | grep -c '^generation .* failed' || true; }
requests() { ls "$LOG" | wc -l | tr -d ' '; }

# A text answer, and the request that asked for it.
case_ text "sse:$STREAMS/text.sse"
run > "$T/out" || fail "text: run failed"
[ "$(status)" = answered ] || fail "text: $(status)"
pic dump | grep -q 'answer | \[{"type":"text","text":"Hello, \\"world\\"\\n"}\]$' || fail "text: answer not verbatim"
req="$LOG/1.req"
grep -q '^POST /v1/messages HTTP/1.1' "$req" || fail "text: request line"
grep -q '^anthropic-version: 2026-10-21' "$req" || fail "text: version header"
grep -q "^x-api-key: $SENTINEL" "$req" || fail "text: key not sent"
grep -q '"model":"test-model"' "$req" || fail "text: model"
grep -q '"stream":true' "$req" || fail "text: stream"
grep -q '"messages":\[{"role":"user","content":\[{"type":"text","text":"make notes","cache_control":{"type":"ephemeral"}}\]}\]' "$req" || fail "text: messages"
grep -q '"name":"write"' "$req" && grep -q '"name":"bash"' "$req" || fail "text: tools"
pic dump | grep -q '^generation 1 1.0.1 done stop=stop' || fail "text: generation"
printf 'PASS: text answer and request shape\n'

# Project instructions from the workspace and its ancestors reach the system
# prompt, outermost first, with the working directory.
case_ instructions "sse:$STREAMS/text.sse"
mkdir "$WS/inner"
printf 'outer rule\n' > "$WS/AGENTS.md"
printf 'inner rule\n' > "$WS/inner/CLAUDE.md"
"$PIC" --db "$DB" --workspace "$WS/inner" run --provider anthropic --model anthropic/test-model --api-url "$URL" 2>> "$T/stderr" ||
    fail "instructions: run failed"
grep -q 'AGENTS.md\\">\\nouter rule\\n\\n</project_instructions>\\n\\n<project_instructions path=\\"[^"]*/inner/CLAUDE.md\\">\\ninner rule' "$LOG/1.req" ||
    fail "instructions: not in the system prompt in order"
grep -q '<cwd>\\n[^"]*/inner\\n</cwd>' "$LOG/1.req" || fail "instructions: cwd"
printf 'PASS: project instructions and cwd in the system prompt\n'

# A tool turn: the call runs, then the next request replays the assistant
# content verbatim and returns the result under its call id.
case_ tool "sse:$STREAMS/tool_use.sse" "sse:$STREAMS/text.sse"
run || fail "tool: run failed"
[ "$(cat "$WS/notes.txt")" = hi ] || fail "tool: file not written"
grep -q '{"role":"assistant","content":\[{"type":"text","text":"Writing it."},{"type":"tool_use","id":"toolu_01","name":"write","input":{"path":"notes.txt","content":"hi"}}\]}' "$LOG/2.req" ||
    fail "tool: assistant content not replayed verbatim"
grep -q '{"role":"user","content":\[{"type":"tool_result","tool_use_id":"toolu_01","content":"Successfully wrote to notes.txt","is_error":false,"cache_control":{"type":"ephemeral"}}\]}' "$LOG/2.req" ||
    fail "tool: tool result not sent"
printf 'PASS: tool call runs and its result is sent back under its id\n'

# Switching models mid-conversation (Pi's cross-provider rules). Turn 1 comes
# from model-a with thinking and a tool call whose id Anthropic would refuse;
# pic stops after the call's result (a crash hook, so dev builds only).
# Turn 2 to the same model replays turn 1 verbatim, thinking and all; turn 2
# to model-b gets it rebuilt from the neutral form: no thinking, and the id
# normalised the same way in the call and in its result.
if [ "$FAULTS" = yes ]; then
    for target in model-a model-b; do
        case_ "switch-$target" "sse:$STREAMS/thinking_tool.sse" "sse:$STREAMS/text.sse"
        expect_crash after-result:1 run --model anthropic/model-a --api-url "$URL"
        "$PIC" --db "$DB" --workspace "$WS" run --model "anthropic/$target" --api-url "$URL" 2>> "$T/stderr" ||
            fail "switch to $target: run failed"
        [ "$(status)" = answered ] || fail "switch to $target: $(status)"
        if [ "$target" = model-a ]; then
            grep -q '{"role":"assistant","content":\[{"type":"thinking","thinking":"Write it.","signature":"SIG-A-123"},{"type":"tool_use","id":"call|item.1"' "$LOG/2.req" ||
                fail "switch: same model did not get the turn verbatim"
            grep -q '"tool_use_id":"call|item.1"' "$LOG/2.req" || fail "switch: same model result id"
        else
            if grep -q '"type":"thinking"' "$LOG/2.req"; then fail "switch: another model got the thinking"; fi
            grep -q '{"role":"assistant","content":\[{"type":"tool_use","id":"call_item_1","name":"write","input":{"path":"t.txt","content":"x"}}\]}' "$LOG/2.req" ||
                fail "switch: call not rebuilt with a normalised id"
            grep -q '"tool_use_id":"call_item_1"' "$LOG/2.req" || fail "switch: result id not normalised to match"
        fi
        pic dump | grep -q "^entry 2 1 assistant | .*\"toolCall\",\"id\":\"call|item.1\"" || fail "switch: neutral form"
        pic check > /dev/null || fail "switch: integrity"
    done
    printf 'PASS: a turn goes verbatim to its own model and converted to another\n'
fi

# Two calls in one turn go back as one user message with two results.
case_ parallel "sse:$STREAMS/parallel_tools.sse" "sse:$STREAMS/text.sse"
run || fail "parallel: run failed"
grep -q '"tool_use_id":"toolu_a".*},{"type":"tool_result","tool_use_id":"toolu_b"' "$LOG/2.req" ||
    fail "parallel: results not grouped in call order"
printf 'PASS: parallel calls answered in one message, in order\n'

# Thinking blocks and their signatures go back byte for byte.
case_ thinking "sse:$STREAMS/thinking.sse"
run || fail "thinking: run failed"
pic dump | grep -q '{"type":"thinking","thinking":"Two plus two.","signature":"EqQBCgIYAhIM1gbcDa9GJwZA2b3h"},{"type":"thinking","thinking":"","signature":"EmwKAhgBEgy3va3pzix/LafPsn4a","redacted":true}' || fail "thinking: neutral form"
printf 'PASS: thinking blocks journaled verbatim\n'

# 429 and 503 are retried within the generation, honouring Retry-After.
case_ retry status:429:- status:503:- "sse:$STREAMS/text.sse"
run || fail "retry: run failed"
[ "$(status) $(failed_generations) $(requests)" = "answered 0 3" ] || fail "retry: $(status) $(failed_generations) $(requests)"
printf 'PASS: 429 and 5xx retried before the stream\n'

# Persistent 5xx: four tries per generation, three generations, then failed.
case_ exhausted status:500:-
if run; then fail "exhausted: succeeded"; fi
[ "$(status) $(failed_generations) $(requests)" = "failed 3 12" ] || fail "exhausted: $(status) $(failed_generations) $(requests)"
printf 'PASS: server errors retried, then the submission fails\n'

# 401 is not retried, and the API's message is kept.
printf '{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}' > "$T/401.json"
case_ unauthorized "status:401:$T/401.json"
if run; then fail "401: succeeded"; fi
[ "$(status) $(failed_generations) $(requests)" = "failed 1 1" ] || fail "401: $(status) $(failed_generations) $(requests)"
pic dump | grep -q 'error=HTTP 401: invalid x-api-key$' || fail "401: message lost"
printf 'PASS: 401 fails at once with the API message\n'

# A stream cut mid-way fails that generation; the turn is asked again and no
# tool call from the partial message runs.
case_ cut "cut:$STREAMS/tool_use.sse:700" "sse:$STREAMS/text.sse"
run || fail "cut: run failed"
[ "$(status) $(failed_generations) $(requests)" = "answered 1 2" ] || fail "cut: $(status) $(failed_generations) $(requests)"
[ ! -e "$WS/notes.txt" ] || fail "cut: a tool from the partial stream ran"
pic dump | grep -q '^generation 1 1.0.1 failed | stream failed' || fail "cut: error not recorded"
printf 'PASS: a cut stream is retried as a new attempt\n'

# A malformed stream is a failed attempt too.
case_ malformed "sse:$STREAMS/malformed.sse" "sse:$STREAMS/text.sse"
run || fail "malformed: run failed"
[ "$(status) $(failed_generations)" = "answered 1" ] || fail "malformed: $(status) $(failed_generations)"
printf 'PASS: a malformed stream is retried\n'

# A refusal fails the submission without running anything.
case_ refusal "sse:$STREAMS/refusal.sse"
if run; then fail "refusal: succeeded"; fi
[ "$(status)" = failed ] || fail "refusal: $(status)"
printf 'PASS: a refusal fails the submission\n'

# Tool input cut by max_tokens reaches the tool as bad input and is reported.
case_ max_tokens "sse:$STREAMS/max_tokens.sse" "sse:$STREAMS/text.sse"
run || fail "max_tokens: run failed"
grep -q '"content":"write needs string inputs path and content","is_error":true' "$LOG/2.req" ||
    fail "max_tokens: bad input not reported to the model"
printf 'PASS: truncated tool input is rejected by the tool, not run\n'

# pic killed while the stream is in flight: the attempt is failed on restart
# and the turn is asked again.
case_ midstream "hang:$STREAMS/tool_use.sse:400" "sse:$STREAMS/text.sse"
"$PIC" --db "$DB" --workspace "$WS" run --provider anthropic --model anthropic/test-model --api-url "$URL" 2>/dev/null &
victim=$!
i=0
while [ ! -s "$LOG/1.req" ]; do
    i=$((i + 1))
    [ "$i" -lt 100 ] || fail "midstream: request never arrived"
    sleep 0.05
done
sleep 0.5
kill -9 "$victim"
wait "$victim" 2>/dev/null || true
run || fail "midstream: restart failed"
[ "$(status) $(failed_generations)" = "answered 1" ] || fail "midstream: $(status) $(failed_generations)"
pic dump | grep -q '^generation 1 1.0.1 failed | interrupted before the reply was recorded$' ||
    fail "midstream: attempt not marked interrupted"
pic check > /dev/null || fail "midstream: integrity"
printf 'PASS: a crash mid-stream is recovered as a failed attempt\n'

# Without a key nothing is sent and the error says what to set.
case_ nokey "sse:$STREAMS/text.sse"
# env, not a prefix on the pic function: POSIX sh lets such an assignment persist.
if env ANTHROPIC_API_KEY= "$PIC" --db "$DB" --workspace "$WS" run --api-url "$URL" 2> "$T/nokey.err"; then
    fail "nokey: succeeded"
fi
grep -q 'ANTHROPIC_API_KEY is not set' "$T/nokey.err" || fail "nokey: $(cat "$T/nokey.err")"
[ "$(requests)" = 0 ] || fail "nokey: a request was sent"
printf 'PASS: a missing key sends nothing\n'

# ---- Chat Completions (OpenRouter, OpenAI, compatible servers)
chat() { pic run --model openrouter/test/model --api-url "$URL" 2>> "$T/stderr"; }

case_ chat-text "sse:$CHAT/text.sse"
chat > "$T/out" || fail "chat text: run failed"
[ "$(status)" = answered ] || fail "chat text: $(status)"
pic dump | grep -q 'answer | \[{"type":"text","text":"Hello, \\"world\\"\\n"}\]$' || fail "chat text: answer"
req="$LOG/1.req"
grep -q "^Authorization: Bearer $SENTINEL" "$req" || fail "chat text: key not sent as a bearer token"
grep -q '"model":"test/model"' "$req" || fail "chat text: model"
grep -q '"messages":\[{"role":"system","content":"You are a coding assistant' "$req" || fail "chat text: system message"
grep -q '{"role":"user","content":"make notes"}' "$req" || fail "chat text: user message"
grep -q '"tools":\[{"type":"function","function":{"name":"read"' "$req" || fail "chat text: tools"
grep -q '"stream_options":{"include_usage":true}' "$req" || fail "chat text: usage requested"
pic dump | grep -q '^generation 1 1.0.1 done stop=stop' || fail "chat text: generation"
printf 'PASS: chat: text answer and request shape\n'

case_ chat-tools "sse:$CHAT/tools.sse" "sse:$CHAT/text.sse"
chat || fail "chat tools: run failed"
[ "$(cat "$WS/notes.txt")" = hi ] || fail "chat tools: first call did not run"
grep -q '{"role":"assistant","content":null,"tool_calls":\[{"id":"call_a","type":"function","function":{"name":"write","arguments":"{\\"path\\":\\"notes.txt\\",\\"content\\":\\"hi\\"}"}},{"id":"call_b"' "$LOG/2.req" ||
    fail "chat tools: turn not replayed verbatim"
grep -q '{"role":"tool","tool_call_id":"call_a","content":"Successfully wrote to notes.txt"},{"role":"tool","tool_call_id":"call_b","content":"' "$LOG/2.req" ||
    fail "chat tools: results not sent as tool messages in order"
printf 'PASS: chat: parallel calls run and go back as tool messages\n'

case_ chat-reasoning "sse:$CHAT/reasoning_tool.sse" "sse:$CHAT/text.sse"
chat || fail "chat reasoning: run failed"
grep -q '"tool_calls":\[{"id":"call_r".*\],"reasoning_content":"Check it."}' "$LOG/2.req" ||
    fail "chat reasoning: reasoning not replayed under its own field"
printf 'PASS: chat: reasoning goes back under the field it came in\n'

case_ chat-nofinish "sse:$CHAT/no_finish.sse" "sse:$CHAT/text.sse"
chat || fail "chat no finish: run failed"
[ "$(status) $(failed_generations)" = "answered 1" ] || fail "chat no finish: $(status) $(failed_generations)"
case_ chat-error "sse:$CHAT/error.sse" "sse:$CHAT/text.sse"
chat || fail "chat error: run failed"
[ "$(status) $(failed_generations)" = "answered 1" ] || fail "chat error: $(status) $(failed_generations)"
pic dump | grep -q '^generation 1 1.0.1 failed | stream failed: Upstream overloaded$' || fail "chat error: message"
case_ chat-filter "sse:$CHAT/content_filter.sse"
if chat; then fail "chat filter: succeeded"; fi
[ "$(status)" = failed ] || fail "chat filter: $(status)"
printf 'PASS: chat: broken streams retried, a content filter fails the submission\n'

# Across providers, both ways: an Anthropic turn continued by a Chat model,
# and a Chat turn continued by an Anthropic model.
if [ "$FAULTS" = yes ]; then
    case_ cross-a2c "sse:$STREAMS/thinking_tool.sse" "sse:$CHAT/text.sse"
    expect_crash after-result:1 run --model anthropic/model-a --api-url "$URL"
    chat || fail "a2c: run failed"
    [ "$(status)" = answered ] || { pic dump >&2; ls "$LOG" >&2; fail "a2c: $(status)"; }
    if grep -qi 'thinking\|SIG-A' "$LOG/2.req"; then fail "a2c: Anthropic thinking sent to a Chat model"; fi
    grep -q '{"role":"assistant","content":null,"tool_calls":\[{"id":"call_item_1","type":"function","function":{"name":"write","arguments":"{\\"path\\":\\"t.txt\\",\\"content\\":\\"x\\"}"}}\]}' "$LOG/2.req" ||
        fail "a2c: call not rebuilt for Chat Completions"
    grep -q '{"role":"tool","tool_call_id":"call_item_1","content":"Successfully wrote to t.txt"}' "$LOG/2.req" ||
        fail "a2c: result id not normalised to match"

    case_ cross-c2a "sse:$CHAT/reasoning_tool.sse" "sse:$STREAMS/text.sse"
    expect_crash after-result:1 run --model openrouter/test/model --api-url "$URL"
    pic run --model anthropic/model-x --api-url "$URL" 2>> "$T/stderr" || fail "c2a: run failed"
    [ "$(status)" = answered ] || fail "c2a: $(status)"
    if grep -q 'reasoning_content\|Check it' "$LOG/2.req"; then fail "c2a: Chat reasoning sent to Anthropic"; fi
    grep -q '{"role":"assistant","content":\[{"type":"tool_use","id":"call_r","name":"bash","input":{"command":"true"}}\]}' "$LOG/2.req" ||
        fail "c2a: call not rebuilt for the Messages API"
    grep -q '"tool_use_id":"call_r"' "$LOG/2.req" || fail "c2a: result id"
    pic check > /dev/null || fail "cross: integrity"
    printf 'PASS: a conversation moves between Anthropic and Chat Completions both ways\n'
fi

# ---- OpenAI Responses
printf '{"providers":{"openai":{"modelOverrides":{"test-reasoner":{"reasoning":true}}}}}' > "$T/models.json"
export PIC_MODELS_FILE="$T/models.json"
resp() { pic run --model "openai/${1:-test-model}" --api-url "$URL" 2>> "$T/stderr"; }

case_ resp-text "sse:$RESP/reasoning_text.sse"
resp > "$T/out" || fail "responses text: run failed"
[ "$(status)" = answered ] || fail "responses text: $(status)"
req="$LOG/1.req"
grep -q "^Authorization: Bearer $SENTINEL" "$req" || fail "responses text: bearer key"
grep -q '"input":\[{"role":"system","content":"You are a coding assistant' "$req" || fail "responses text: system item"
grep -q '{"role":"user","content":\[{"type":"input_text","text":"make notes"}\]}' "$req" || fail "responses text: user item"
grep -q '"store":false' "$req" || fail "responses text: store"
grep -q '"tools":\[{"type":"function","name":"read","description"' "$req" || fail "responses text: flat tools"
if grep -q '"include"\|"reasoning":{' "$req"; then fail "responses text: reasoning requested for a non-reasoning model"; fi
pic dump | grep -q 'answer | \[{"type":"thinking","thinking":"Plan the fix.","signature":"{\\"type\\":\\"reasoning\\"' ||
    fail "responses text: neutral thinking"
printf 'PASS: responses: text answer and request shape\n'

case_ resp-tools "sse:$RESP/tools.sse" "sse:$RESP/reasoning_text.sse"
resp test-reasoner || fail "responses tools: run failed"
[ "$(cat "$WS/notes.txt")" = hi ] || fail "responses tools: call did not run"
grep -q '"include":\["reasoning.encrypted_content"\],"reasoning":{"effort":"medium","summary":"auto"}' "$LOG/1.req" ||
    fail "responses tools: reasoning not requested"
grep -q '{"role":"developer","content":"You are a coding assistant' "$LOG/1.req" || fail "responses tools: developer role"
grep -q '{"type":"reasoning","id":"rs_1","summary":\[{"type":"summary_text","text":"Plan the fix."}\],"encrypted_content":"ENC-RS-1"},{"type":"function_call","id":"fc_1","call_id":"call_1"' "$LOG/2.req" ||
    fail "responses tools: items not replayed verbatim"
grep -q '{"type":"function_call_output","call_id":"call_1","output":"Successfully wrote to notes.txt"},{"type":"function_call_output","call_id":"call_2"' "$LOG/2.req" ||
    fail "responses tools: outputs not under the call ids"
printf 'PASS: responses: reasoning items and calls replayed, outputs under call ids\n'

case_ resp-failed "sse:$RESP/failed.sse" "sse:$RESP/reasoning_text.sse"
resp || fail "responses failed: run failed"
[ "$(status) $(failed_generations)" = "answered 1" ] || fail "responses failed: $(status) $(failed_generations)"
pic dump | grep -q 'failed | stream failed: The model failed$' || fail "responses failed: message"
printf 'PASS: responses: a failed response is retried\n'

if [ "$FAULTS" = yes ]; then
    case_ cross-a2r "sse:$STREAMS/thinking_tool.sse" "sse:$RESP/reasoning_text.sse"
    expect_crash after-result:1 run --model anthropic/model-a --api-url "$URL"
    resp || fail "a2r: run failed"
    if grep -q 'SIG-A\|"thinking"' "$LOG/2.req"; then fail "a2r: Anthropic thinking sent to Responses"; fi
    grep -q '{"type":"function_call","call_id":"call_item_1","name":"write","arguments":"{\\"path\\":\\"t.txt\\",\\"content\\":\\"x\\"}"}' "$LOG/2.req" ||
        fail "a2r: call not rebuilt as a function_call"
    grep -q '{"type":"function_call_output","call_id":"call_item_1","output":"Successfully wrote to t.txt"}' "$LOG/2.req" ||
        fail "a2r: output id not normalised to match"

    case_ cross-r2a "sse:$RESP/tools.sse" "sse:$STREAMS/text.sse"
    expect_crash after-result:2 run --model openai/test-reasoner --api-url "$URL"
    pic run --model anthropic/model-x --api-url "$URL" 2>> "$T/stderr" || fail "r2a: run failed"
    [ "$(status)" = answered ] || fail "r2a: $(status)"
    if grep -q 'ENC-RS\|Plan the fix' "$LOG/2.req"; then fail "r2a: Responses reasoning sent to Anthropic"; fi
    grep -q '{"type":"tool_use","id":"call_1_fc_1","name":"write","input":{"path":"notes.txt","content":"hi"}},{"type":"tool_use","id":"call_2_fc_2"' "$LOG/2.req" ||
        fail "r2a: calls not rebuilt for the Messages API"
    grep -q '"tool_use_id":"call_1_fc_1"' "$LOG/2.req" || fail "r2a: result id"
    pic check > /dev/null || fail "responses cross: integrity"
    printf 'PASS: a conversation moves between Anthropic and Responses both ways\n'
fi

# ---- Gemini (google-generative-ai)
gem() { pic run --model "google/${1:-test-model}" --api-url "$URL" 2>> "$T/stderr"; }

case_ gem-text "sse:$GEM/thinking_text.sse"
gem > "$T/out" || fail "gemini text: run failed"
[ "$(status)" = answered ] || fail "gemini text: $(status)"
req="$LOG/1.req"
grep -q "^x-goog-api-key: $SENTINEL" "$req" || fail "gemini text: key header"
if grep -qi "^Authorization\|^x-api-key" "$req"; then fail "gemini text: wrong auth header"; fi
grep -q '"systemInstruction":{"parts":\[{"text":"You are a coding assistant' "$req" || fail "gemini text: system instruction"
grep -q '"contents":\[{"role":"user","parts":\[{"text":"make notes"}\]}\]' "$req" || fail "gemini text: user content"
grep -q '"tools":\[{"functionDeclarations":\[{"name":"read","description":.*"parametersJsonSchema":{"type":"object"' "$req" ||
    fail "gemini text: function declarations"
grep -q '"generationConfig":{"maxOutputTokens":16384}' "$req" || fail "gemini text: generationConfig"
pic dump | grep -q 'answer | \[{"type":"thinking","thinking":"\*\*Plan\*\*\\nCheck the file.","signature":"c2lnLXRob3VnaHQ="}' ||
    fail "gemini text: neutral thinking"
printf 'PASS: gemini: text answer and request shape\n'

# Tool calls: thought parts and signatures go back to the model that made
# them; results are functionResponse parts of one user turn, named by tool.
case_ gem-tools "sse:$GEM/agent_tools.sse" "sse:$GEM/text.sse"
gem gemini-2.5-flash || fail "gemini tools: run failed"
[ "$(cat "$WS/notes.txt")" = hi ] || fail "gemini tools: call did not run"
grep -q '"thinkingConfig":{"includeThoughts":true,"thinkingBudget":8192}' "$LOG/1.req" || fail "gemini tools: thinking not requested"
grep -q '{"role":"model","parts":\[{"thought":true,"text":"Plan the write.","thoughtSignature":"c2lnLXRob3VnaDE="},{"functionCall":{"name":"write","args":{"path":"notes.txt","content":"hi"}},"thoughtSignature":"c2lnLWNhbGwx"},{"functionCall":{"name":"bash","args":{"command":"true"}}}\]}' "$LOG/2.req" ||
    fail "gemini tools: parts not replayed with signatures"
grep -q '{"role":"user","parts":\[{"functionResponse":{"name":"write","response":{"output":"Successfully wrote to notes.txt"}}},{"functionResponse":{"name":"bash"' "$LOG/2.req" ||
    fail "gemini tools: results not one user turn named by tool"
if grep -q '"id"' "$LOG/2.req"; then fail "gemini tools: ids sent to a model that takes none"; fi
printf 'PASS: gemini: thoughts and signatures replayed, results grouped under the tool names\n'

# Gemini 3 and later take ids on calls and responses, and a level not a budget.
case_ gem-ids "sse:$GEM/agent_tools.sse" "sse:$GEM/text.sse"
gem gemini-3-flash-preview || fail "gemini ids: run failed"
grep -q '"thinkingConfig":{"includeThoughts":true,"thinkingLevel":"MEDIUM"}' "$LOG/1.req" || fail "gemini ids: thinking level"
grep -q '"functionCall":{"name":"write","args":{"path":"notes.txt","content":"hi"},"id":"write_1"}' "$LOG/2.req" || fail "gemini ids: call id"
grep -q '"functionResponse":{"name":"write","response":{"output":"Successfully wrote to notes.txt"},"id":"write_1"}' "$LOG/2.req" ||
    fail "gemini ids: response id"
printf 'PASS: gemini: ids and thinking level for Gemini 3\n'

case_ gem-error "sse:$GEM/error.sse" "sse:$GEM/truncated.sse" "sse:$GEM/text.sse"
gem || fail "gemini error: run failed"
[ "$(status) $(failed_generations)" = "answered 2" ] || fail "gemini error: $(status) $(failed_generations)"
pic dump | grep -q 'failed | stream failed: The model is overloaded' || fail "gemini error: message"
pic dump | grep -q 'failed | stream failed: stream ended without a finish reason' || fail "gemini error: no finish reason"
case_ gem-safety "sse:$GEM/safety.sse"
if gem; then fail "gemini safety: succeeded"; fi
pic dump | grep -q 'Provider stopped with: SAFETY' || fail "gemini safety: message"
printf '{"error":{"code":400,"message":"API key not valid. Please pass a valid API key.","status":"INVALID_ARGUMENT"}}' > "$T/gem400.json"
case_ gem-400 "status:400:$T/gem400.json"
if gem; then fail "gemini 400: succeeded"; fi
[ "$(status) $(failed_generations) $(requests)" = "failed 1 1" ] || fail "gemini 400: $(status) $(failed_generations) $(requests)"
pic dump | grep -q 'error=HTTP 400: API key not valid' || fail "gemini 400: message"
case_ gem-429 "status:429:$T/gem400.json" "sse:$GEM/text.sse"
gem || fail "gemini 429: run failed"
[ "$(status) $(requests)" = "answered 2" ] || fail "gemini 429: $(status) $(requests)"
printf 'PASS: gemini: broken streams retried, a block or a bad key fails, 429 is retried\n'

case_ gem-length "sse:$GEM/max_tokens.sse"
gem || fail "gemini length: run failed"
pic dump | grep -q 'length' || fail "gemini length: stop reason"
printf 'PASS: gemini: MAX_TOKENS is a length stop\n'

# Across providers, both ways: an Anthropic turn continued by Gemini, and a
# Gemini turn continued by an Anthropic model.
if [ "$FAULTS" = yes ]; then
    case_ cross-a2g "sse:$STREAMS/thinking_tool.sse" "sse:$GEM/text.sse"
    expect_crash after-result:1 run --model anthropic/model-a --api-url "$URL"
    gem gemini-2.5-flash || fail "a2g: run failed"
    [ "$(status)" = answered ] || { pic dump >&2; fail "a2g: $(status)"; }
    if grep -q 'SIG-A\|Write it\|"thought"' "$LOG/2.req"; then fail "a2g: Anthropic thinking sent to Gemini"; fi
    grep -q '{"role":"model","parts":\[{"functionCall":{"name":"write","args":{"path":"t.txt","content":"x"}}}\]}' "$LOG/2.req" ||
        fail "a2g: call not rebuilt as a functionCall"
    grep -q '{"role":"user","parts":\[{"functionResponse":{"name":"write","response":{"output":"Successfully wrote to t.txt"}}}\]}' "$LOG/2.req" ||
        fail "a2g: result not a functionResponse"

    case_ cross-g2a "sse:$GEM/agent_tools.sse" "sse:$STREAMS/text.sse"
    expect_crash after-result:1 run --model google/gemini-2.5-flash --api-url "$URL"
    pic run --model anthropic/model-x --api-url "$URL" 2>> "$T/stderr" || fail "g2a: run failed"
    [ "$(status)" = answered ] || fail "g2a: $(status)"
    if grep -q 'c2lnLXRob3VnaDE\|Plan the write\|thoughtSignature' "$LOG/2.req"; then fail "g2a: Gemini thinking sent to Anthropic"; fi
    grep -q '{"type":"tool_use","id":"write_1","name":"write","input":{"path":"notes.txt","content":"hi"}},{"type":"tool_use","id":"bash_2"' "$LOG/2.req" ||
        fail "g2a: calls not rebuilt for the Messages API"
    grep -q '"tool_use_id":"write_1"' "$LOG/2.req" || fail "g2a: result id"
    pic check > /dev/null || fail "gemini cross: integrity"
    printf 'PASS: a conversation moves between Anthropic and Gemini both ways\n'
fi

# ---- Thinking levels (Pi's streamSimple and the adapters' thinking options)
printf '{"providers":{"anthropic":{"modelOverrides":{"test-budget":{"reasoning":true,"maxTokens":100000}}},"openrouter":{"modelOverrides":{"test/reasoner":{"reasoning":true}}},"openai":{"modelOverrides":{"test-reasoner":{"reasoning":true}}}}}' > "$T/models.json"
export PIC_MODELS_FILE="$T/models.json"
think() { # think NAME STREAM MODEL [pic options]: one request; the log is in $LOG
    name=$1 stream=$2 model=$3
    shift 3
    case_ "think-$name" "sse:$stream"
    pic "$@" run --model "$model" --api-url "$URL" 2>> "$T/stderr" || fail "thinking $name: run failed"
}
has() { grep -q "$2" "$LOG/1.req" || fail "thinking $1: missing $2"; }
lacks() { if grep -q "$2" "$LOG/1.req"; then fail "thinking $1: unexpected $2"; fi; }

# Adaptive models (forceAdaptiveThinking): thinking adaptive plus an effort.
think adaptive-default "$STREAMS/text.sse" anthropic/claude-opus-5-5
has adaptive-default '"thinking":{"type":"adaptive","display":"summarized"}'
has adaptive-default '"output_config":{"effort":"medium"}'
has adaptive-default '"max_tokens":64000'
lacks adaptive-default '"budget_tokens"'
think adaptive-high "$STREAMS/text.sse" anthropic/claude-opus-5-5 --thinking high
has adaptive-high '"thinking":{"type":"adaptive","display":"summarized"}'
has adaptive-high '"output_config":{"effort":"high"}'
think adaptive-xhigh "$STREAMS/text.sse" anthropic/claude-fable-5-2 --thinking xhigh
has adaptive-xhigh '"output_config":{"effort":"xhigh"}'
printf 'PASS: thinking: adaptive models send adaptive thinking and an effort\n'

# Budget models: a token budget inside max_tokens; off is thinking disabled.
think budget-low "$STREAMS/text.sse" anthropic/claude-haiku-4-5 --thinking low
has budget-low '"thinking":{"type":"enabled","budget_tokens":2048,"display":"summarized"}'
has budget-low '"max_tokens":64000'
lacks budget-low '"output_config"'
think budget-default "$STREAMS/text.sse" anthropic/claude-haiku-4-5
has budget-default '"budget_tokens":8192'
think budget-xhigh "$STREAMS/text.sse" anthropic/claude-haiku-4-5 --thinking high
has budget-xhigh '"budget_tokens":16384'
think budget-raised "$STREAMS/text.sse" anthropic/test-budget --thinking low
has budget-raised '"max_tokens":66048'
has budget-raised '"budget_tokens":2048'
think budget-off "$STREAMS/text.sse" anthropic/claude-haiku-4-5 --thinking off
has budget-off '"thinking":{"type":"disabled"}'
lacks budget-off '"budget_tokens"'
think plain "$STREAMS/text.sse" anthropic/test-model
lacks plain '"thinking"'
printf 'PASS: thinking: budget models get a budget in max_tokens; off disables; plain models send none\n'

# Unsupported levels are refused with the supported ones; none is sent.
case_ think-refused "sse:$STREAMS/text.sse"
if pic --thinking xhigh run --model anthropic/claude-haiku-4-5 --api-url "$URL" 2> "$T/refused.err"; then fail "thinking: unsupported level accepted"; fi
grep -q 'supported: off, minimal, low, medium, high)' "$T/refused.err" || fail "thinking refused: $(cat "$T/refused.err")"
if pic --thinking low run --model anthropic/test-model --api-url "$URL" 2> "$T/refused.err"; then fail "thinking: level accepted for a model without reasoning"; fi
grep -q 'supported: off)' "$T/refused.err" || fail "thinking refused (plain): $(cat "$T/refused.err")"
if pic --thinking loud run --model anthropic/test-model --api-url "$URL" 2> "$T/refused.err"; then fail "thinking: unknown level accepted"; fi
grep -q 'unknown thinking level loud (off, minimal, low, medium, high, xhigh, max)' "$T/refused.err" || fail "thinking unknown: $(cat "$T/refused.err")"
[ "$(requests)" = 0 ] || fail "thinking refused: a request was sent"
printf 'PASS: thinking: an unsupported level is refused with the supported list\n'

# Chat Completions by thinkingFormat.
think chat-openrouter "$CHAT/text.sse" openrouter/test/reasoner
has chat-openrouter '"reasoning":{"effort":"medium"}'
lacks chat-openrouter '"reasoning_effort"'
think chat-openrouter-off "$CHAT/text.sse" openrouter/test/reasoner --thinking off
has chat-openrouter-off '"reasoning":{"effort":"none"}'
think chat-deepseek "$CHAT/text.sse" deepseek/deepseek-v4-pro
has chat-deepseek '"thinking":{"type":"enabled"}'
has chat-deepseek '"reasoning_effort":"high"' # medium is not offered: clamped up
think chat-deepseek-max "$CHAT/text.sse" deepseek/deepseek-v4-pro --thinking max
has chat-deepseek-max '"reasoning_effort":"max"'
think chat-deepseek-off "$CHAT/text.sse" deepseek/deepseek-v4-pro --thinking off
has chat-deepseek-off '"thinking":{"type":"disabled"}'
lacks chat-deepseek-off '"reasoning_effort"'
printf 'PASS: thinking: chat formats send reasoning, thinking and reasoning_effort as Pi does\n'

# Responses: reasoning.effort.
think resp-default "$RESP/reasoning_text.sse" openai/test-reasoner
has resp-default '"reasoning":{"effort":"medium","summary":"auto"}'
think resp-high "$RESP/reasoning_text.sse" openai/test-reasoner --thinking high
has resp-high '"reasoning":{"effort":"high","summary":"auto"}'
think resp-off "$RESP/reasoning_text.sse" openai/test-reasoner --thinking off
has resp-off '"reasoning":{"effort":"none"}'
lacks resp-off '"include"'
printf 'PASS: thinking: responses send reasoning.effort\n'

# Thinking levels (Pi's streamSimple and the Google adapter).
think gem-budget-default "$GEM/text.sse" google/gemini-2.5-flash
has gem-budget-default '"thinkingConfig":{"includeThoughts":true,"thinkingBudget":8192}'
think gem-budget-high "$GEM/text.sse" google/gemini-2.5-pro --thinking high
has gem-budget-high '"thinkingBudget":32768'
think gem-budget-lite "$GEM/text.sse" google/gemini-2.5-flash-lite --thinking minimal
has gem-budget-lite '"thinkingBudget":512'
think gem-off "$GEM/text.sse" google/gemini-2.5-flash --thinking off
has gem-off '"thinkingConfig":{"thinkingBudget":0}'
lacks gem-off 'includeThoughts'
think gem-level-low "$GEM/text.sse" google/gemini-3.1-pro-preview --thinking low
has gem-level-low '"thinkingConfig":{"includeThoughts":true,"thinkingLevel":"LOW"}'
think gem-level-high "$GEM/text.sse" google/gemini-3-flash-preview --thinking high
has gem-level-high '"thinkingLevel":"HIGH"'
think gem-plain "$GEM/text.sse" google/test-model
lacks gem-plain 'thinkingConfig'
printf 'PASS: thinking: gemini sends a budget or a level as Pi does, off sends a zero budget\n'

# Settings: the model's saved level, then the default, clamped to the model.
mkdir -p "$HOME/.pic"
"$PIC" settings defaultThinkingLevel high && "$PIC" settings thinkingLevel:anthropic/claude-haiku-4-5 low || fail "settings: not saved"
think set-model "$STREAMS/text.sse" anthropic/claude-haiku-4-5
has set-model '"budget_tokens":2048'
think set-default "$STREAMS/text.sse" anthropic/claude-opus-5-5
has set-default '"output_config":{"effort":"high"}'
think set-flag "$STREAMS/text.sse" anthropic/claude-haiku-4-5 --thinking medium
has set-flag '"budget_tokens":8192'
"$PIC" settings --unset thinkingLevel:anthropic/claude-haiku-4-5 && "$PIC" settings defaultThinkingLevel off || fail "settings: not saved"
think set-clamp "$STREAMS/text.sse" anthropic/claude-opus-5-5
has set-clamp '"output_config":{"effort":"low"}' # off is not offered: the next level up
"$PIC" settings --unset defaultThinkingLevel || fail "settings: not removed"
printf 'PASS: thinking: settings supply the level, clamped to the model, and --thinking wins\n'

# The level in effect is in agent_start.
case_ think-event "sse:$STREAMS/text.sse"
pic --json --thinking high run --model anthropic/claude-opus-5-5 --api-url "$URL" > "$T/ev" 2>> "$T/stderr" || fail "thinking event: run failed"
grep -q '"type":"agent_start",.*"thinkingLevel":"high"}' "$T/ev" || fail "thinking event: $(head -1 "$T/ev")"
printf 'PASS: thinking: agent_start carries the level\n'

unset PIC_MODELS_FILE

# ---- Prompt caching (Pi's cacheRetention): breakpoints, lifetimes, stable prefix
cc='"cache_control":{"type":"ephemeral"}'
cc1h='"cache_control":{"type":"ephemeral","ttl":"1h"}'
count() { grep -o "$2" "$LOG/$1.req" | wc -l | tr -d ' '; }
cached() { # cached NAME STREAM MODEL [settings value]: one request, retention from the setting
    name=$1 stream=$2 model=$3
    case_ "cache-$name" "sse:$stream"
    pic run --model "$model" --api-url "$URL" 2>> "$T/stderr" || fail "cache $name: run failed"
}
# Short (the default): three breakpoints, none with a ttl, and no beta header.
cached short "$STREAMS/text.sse" anthropic/test-model
req="$LOG/1.req"
grep -q '"system":\[{"type":"text","text":"You are a coding assistant[^}]*'"$cc"'}\]' "$req" || fail "cache short: system breakpoint"
grep -q "\"input_schema\":{[^}]*}[^]]*$cc}\\]" "$req" || grep -q "$cc}\\],\"messages\"" "$req" || fail "cache short: last tool breakpoint"
[ "$(count 1 '"cache_control"')" = 3 ] || fail "cache short: want 3 breakpoints, got $(count 1 '"cache_control"')"
[ "$(count 1 '"ttl"')" = 0 ] || fail "cache short: ttl sent"
grep -q '"text":"make notes",'"$cc"'}' "$req" || fail "cache short: user message breakpoint"
if grep -qi '^anthropic-beta' "$req"; then fail "cache short: beta header sent"; fi
# Long: the same three, each with ttl 1h, from the setting.
"$PIC" settings cacheRetention long || fail "cache: setting not saved"
cached long "$STREAMS/text.sse" anthropic/test-model
[ "$(count 1 "$cc1h")" = 3 ] || fail "cache long: want 3 one-hour breakpoints"
# The environment variable is Pi's PI_CACHE_RETENTION; the setting wins over it.
"$PIC" settings --unset cacheRetention
export PI_CACHE_RETENTION=long
cached env "$STREAMS/text.sse" anthropic/test-model
[ "$(count 1 "$cc1h")" = 3 ] || fail "cache env: PI_CACHE_RETENTION=long ignored"
"$PIC" settings cacheRetention short
cached envshort "$STREAMS/text.sse" anthropic/test-model
[ "$(count 1 '"ttl"')" = 0 ] || fail "cache: setting short did not win over the environment"
unset PI_CACHE_RETENTION
# none: no breakpoints at all.
"$PIC" settings cacheRetention none
cached none "$STREAMS/text.sse" anthropic/test-model
[ "$(count 1 '"cache_control"')" = 0 ] || fail "cache none: breakpoints sent"
"$PIC" settings --unset cacheRetention
printf 'PASS: cache: Messages breakpoints on system, last tool and last message; short, long (1h), none\n'

# Two turns: the system prompt and tools are byte-identical, the earlier
# messages are replayed unchanged, and the breakpoint moves to the last message.
case_ cache-prefix "sse:$STREAMS/text.sse" "sse:$STREAMS/text.sse"
run > /dev/null || fail "cache prefix: turn 1"
pic submit job-2 'and more' --session latest > /dev/null
run > /dev/null || fail "cache prefix: turn 2"
sys_tools() { sed -n 's/.*\("system":.*"messages":\).*/\1/p' "$LOG/$1.req"; }
[ -n "$(sys_tools 1)" ] && [ "$(sys_tools 1)" = "$(sys_tools 2)" ] || fail "cache prefix: system and tools differ between turns"
grep -q '{"role":"user","content":"make notes"},{"role":"assistant","content":\[{"type":"text","text":"Hello' "$LOG/2.req" || fail "cache prefix: turn 2 does not extend turn 1's messages"
grep -q '"text":"and more","cache_control":{"type":"ephemeral"}' "$LOG/2.req" || fail "cache prefix: breakpoint not on the last message"
[ "$(count 2 '"cache_control"')" = 3 ] || fail "cache prefix: turn 2 breakpoints moved wrongly"
printf 'PASS: cache: system, tools and earlier messages are byte-identical across turns\n'

# 1-hour cache writes are reported the way Pi reads them and kept in usage.
cat > "$T/cw.sse" <<'EOS'
event: message_start
data: {"type":"message_start","message":{"id":"msg_02","type":"message","role":"assistant","model":"m","content":[],"stop_reason":null,"usage":{"input_tokens":5,"cache_creation_input_tokens":300,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":100,"ephemeral_1h_input_tokens":200},"output_tokens":1}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":4}}

event: message_stop
data: {"type":"message_stop"}

EOS
cached usage "$T/cw.sse" anthropic/test-model
if command -v sqlite3 > /dev/null; then
    u=$(sqlite3 "$DB" 'SELECT usage FROM pic_generation')
    case "$u" in *'"cache_creation_input_tokens":300'*'"ephemeral_1h_input_tokens":200'*) ;; *) fail "cache usage: 1h writes not kept: $u" ;; esac
fi
printf 'PASS: cache: usage keeps cache_creation.ephemeral_1h_input_tokens\n'

# OpenRouter's anthropic/... models take Pi's markers in Chat Completions form.
cached or-short "$CHAT/text.sse" openrouter/anthropic/test-model
req="$LOG/1.req"
grep -q '"role":"system","content":\[{"type":"text","text":"You are a coding assistant[^}]*'"$cc"'}\]' "$req" || grep -q '"role":"developer","content":\[{"type":"text","text":"You are' "$req" || fail "cache or: system marker"
grep -q '"content":\[{"type":"text","text":"make notes",'"$cc"'}\]' "$req" || fail "cache or: last message marker"
grep -q "\"parameters\":{[^]]*$cc}\\]" "$req" || grep -q "$cc}\\],\"stream_options\"\\|$cc}\\]}\$" "$req" || fail "cache or: last tool marker"
[ "$(count 1 '"cache_control"')" = 3 ] || fail "cache or: want 3 markers, got $(count 1 '"cache_control"')"
if grep -q '"prompt_cache_key"' "$req"; then fail "cache or: prompt_cache_key sent to OpenRouter on short"; fi
"$PIC" settings cacheRetention long
cached or-long "$CHAT/text.sse" openrouter/anthropic/test-model
[ "$(count 1 "$cc1h")" = 3 ] || fail "cache or long: want 3 one-hour markers"
grep -q '"prompt_cache_key":"[0-9a-f]\{8\}"' "$LOG/1.req" && grep -q '"prompt_cache_retention":"24h"' "$LOG/1.req" || fail "cache or long: key and 24h retention"
"$PIC" settings cacheRetention none
cached or-none "$CHAT/text.sse" openrouter/anthropic/test-model
[ "$(count 1 '"cache_control"')" = 0 ] || fail "cache or none: markers sent"
"$PIC" settings --unset cacheRetention
# Other Chat Completions servers get no markers; long adds the key and 24h.
cached chat-plain "$CHAT/text.sse" deepseek/deepseek-v4-pro
[ "$(count 1 '"cache_control"')" = 0 ] || fail "cache chat: markers sent to a plain server"
lacks_req() { if grep -q "$2" "$LOG/1.req"; then fail "cache $1: unexpected $2"; fi; }
lacks_req chat-plain '"prompt_cache'
"$PIC" settings cacheRetention long
cached chat-long "$CHAT/text.sse" deepseek/deepseek-v4-pro
grep -q '"prompt_cache_key":"[0-9a-f]\{8\}"' "$LOG/1.req" && grep -q '"prompt_cache_retention":"24h"' "$LOG/1.req" || fail "cache chat long: key and 24h retention"
"$PIC" settings --unset cacheRetention
# api.openai.com over Chat Completions: the key even on short, 24h only on long.
printf '{"providers":{"oai":{"baseUrl":"https://api.openai.com/v1","api":"openai-completions","apiKey":"$OPENAI_API_KEY","models":[{"id":"m"}]}}}' > "$T/oai.json"
PIC_MODELS_FILE="$T/oai.json" cached chat-openai "$CHAT/text.sse" oai/m
grep -q '"prompt_cache_key":"[0-9a-f]\{8\}"' "$LOG/1.req" || fail "cache chat openai: no prompt_cache_key"
lacks_req chat-openai '"prompt_cache_retention"'
unset PIC_MODELS_FILE
printf 'PASS: cache: Chat Completions on api.openai.com sends prompt_cache_key on short\n'
printf 'PASS: cache: Chat Completions markers (OpenRouter anthropic), prompt_cache_key and 24h retention\n'

# Responses: the key always, 24h retention on long, neither on none.
cached resp-short "$RESP/reasoning_text.sse" openai/test-model
grep -q '"prompt_cache_key":"[0-9a-f]\{8\}"' "$LOG/1.req" || fail "cache resp: no prompt_cache_key"
lacks_req resp-short '"prompt_cache_retention"'
"$PIC" settings cacheRetention long
cached resp-long "$RESP/reasoning_text.sse" openai/test-model
grep -q '"prompt_cache_key":"[0-9a-f]\{8\}"' "$LOG/1.req" && grep -q '"prompt_cache_retention":"24h"' "$LOG/1.req" || fail "cache resp long: key and 24h"
"$PIC" settings cacheRetention none
cached resp-none "$RESP/reasoning_text.sse" openai/test-model
lacks_req resp-none '"prompt_cache'
"$PIC" settings --unset cacheRetention
printf 'PASS: cache: Responses prompt_cache_key and prompt_cache_retention\n'

# The key went to the server and nowhere else: not the database, its WAL, or
# anything pic printed.
kill "$spid" 2>/dev/null || true
wait "$spid" 2>/dev/null || true
spid=
grep -rl "$SENTINEL" "$T"/*-log > /dev/null || fail "leak: sentinel never sent (test is broken)"
for f in "$T"/*.sqlite* "$T/stderr" "$T/out" "$T"/*.err; do
    [ -e "$f" ] || continue
    if grep -q "$SENTINEL" "$f"; then fail "leak: key found in $f"; fi
done
printf 'PASS: the API key never reaches the journal or output\n'