#!/bin/sh
# The provider's own web search, against the fake server: the request declares the provider's
# server tool where pic's web_search function would be, the reply's search and citations are kept
# for replay and shown as text without control characters, and the conversation's permission
# mode, the webSearch setting, offline and --exclude-tools decide whether it is declared at all.
set -eu
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
N=$(cd "$(dirname "$0")/native-streams" && pwd)
T=$(cd "$(mktemp -d "${TMPDIR:-/tmp}/pic-websearchnative.XXXXXX")" && 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; }
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
mkdir "$T/home"
export HOME="$T/home" PIC_PI_EXPORT=0 PIC_MODEL_CATALOG=offline
KEY="native-test-key-$$"
export GROQ_API_KEY=$KEY ANTHROPIC_API_KEY=$KEY OPENAI_API_KEY=$KEY XAI_API_KEY=$KEY OPENROUTER_API_KEY=$KEY GEMINI_API_KEY=$KEY
"$PIC" settings loops.tool false > /dev/null

n=0
fresh() { n=$((n + 1)); DB="$T/$n.sqlite"; WS="$T/ws$n"; mkdir "$WS"; }
pic() { "$PIC" --db "$DB" --workspace "$WS" "$@"; }
serve() { # serve SPEC...: a fresh fake server; URL is its address
    [ -n "$spid" ] && kill "$spid" 2>/dev/null && wait "$spid" 2>/dev/null || :
    rm -rf "$T/log" "$T/port"
    mkdir "$T/log"
    "$SERVER" "$T/port" "$T/log" 60 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server"; sleep 0.05; done
    URL="http://127.0.0.1:$(cat "$T/port")/v1"
}
# ask MODEL SPEC...: a conversation of one question to MODEL against a fake serving SPEC; the
# requests are in $T/log. Flags go in $FLAGS and the request path in $API_PATH; sh keeps a variable
# set in front of a function call, so every ask resets them.
ask() {
    model=$1
    shift
    fresh
    serve "$@"
    # shellcheck disable=SC2086
    pic ${FLAGS:-} submit job 'what is C' > /dev/null
    # shellcheck disable=SC2086
    pic ${FLAGS:-} run --model "$model" --api-url "$URL${API_PATH:-/messages}" > "$T/out" 2> "$T/err" || { cat "$T/err" >&2; fail "$model: run failed"; }
    FLAGS= API_PATH=
}
declared() { grep -q "$1" "$T/log/1.req"; }
# decoded: the text of every answer's blocks, JSON escapes resolved, as a screen would show it.
decoded() { "$(dirname "$SERVER")/sqlite3" "$DB" "SELECT json_extract(j.value,'\$.text') FROM pic_entry e, json_each(e.body) j WHERE e.kind = 'answer' AND json_valid(e.body)"; }
# clean TEXT WHAT: no control, C1 or bidi byte in TEXT (a transcript).
clean() {
    ! printf '%s\n' "$1" | LC_ALL=C grep -q "$(printf '[\001-\010\013-\037\177]')" || fail "$2: a control byte reached the transcript"
    ! printf '%s\n' "$1" | LC_ALL=C grep -q "$(printf '\302[\200-\237]')" || fail "$2: a C1 control reached the transcript"
    ! printf '%s\n' "$1" | LC_ALL=C grep -q "$(printf '\342\200[\216\217\252-\256]\|\342\201[\246-\251]')" || fail "$2: a bidi control reached the transcript"
}

# Anthropic: the server tool replaces the web_search function, in the request that asks. With a
# provider key present and no Brave key the session's default tool list is the usual one plus
# web_search, and the model sees the provider's tool in its place.
ask anthropic/test-model "sse:$N/anthropic.sse"
NAMES=$("$(dirname "$SERVER")/sqlite3" "$DB" "SELECT group_concat(json_extract(value,'\$.name'),' ') FROM pic_session, json_each(tools)")
[ "$NAMES" = "read bash edit write send_message web_fetch web_search" ] || fail "the default tool list is: $NAMES"
grep -q '"type":"web_search_20250305"' "$T/log/1.req" || fail "anthropic: no server tool: $(head -c 600 "$T/log/1.req")"
! grep -q '"name":"web_search","description"' "$T/log/1.req" || fail "anthropic: the function was declared too"
grep -q '"name":"read"' "$T/log/1.req" || fail "anthropic: the other tools went missing"
printf 'PASS: anthropic declares its own search\n'

# The reply: the search and the citation are in the journal verbatim (for replay) and the
# transcript shows them as text without control characters.
D=$(pic dump)
NATIVE=$("$(dirname "$SERVER")/sqlite3" "$DB" "SELECT native FROM pic_entry WHERE native IS NOT NULL")
printf '%s\n' "$NATIVE" | grep -qF '"type":"server_tool_use"' || fail "anthropic: the search was not kept"
printf '%s\n' "$NATIVE" | grep -qF '"encrypted_content":"ENC1"' || fail "anthropic: the results were not kept"
printf '%s\n' "$NATIVE" | grep -qF '"citations":[{"type":"web_search_result_location"' || fail "anthropic: the citation was not kept"
printf '%s\n' "$D" | grep -qF 'C is a language.' || fail "anthropic: no text"
printf '%s\n' "$D" | grep -qF 'Searched the web for: c language' || fail "anthropic: no search line in the transcript"
printf '%s\n' "$D" | grep -qF 'https://example.org/c' || fail "anthropic: no source in the transcript"
clean "$D" anthropic
clean "$(decoded)" "anthropic (decoded)"
printf 'PASS: anthropic search and citations are kept and shown\n'

# The next request sends the search back verbatim, so the provider can continue from it.
ask anthropic/test-model "sse:$N/anthropic.sse" "sse:$(dirname "$N")/streams/text.sse"
pic submit job2 'and more' --session latest > /dev/null
pic run --model anthropic/test-model --api-url "$URL/messages" > /dev/null 2>&1 || fail "anthropic: the second request failed"
grep -q '"type":"server_tool_use","id":"srvtoolu_01","name":"web_search","input":{"query":"c language"}' "$T/log/2.req" || fail "anthropic: the search was not replayed: $(grep -o "server_tool_use.\{0,120\}" "$T/log/2.req" | head -2)"
grep -q '"encrypted_content":"ENC1"' "$T/log/2.req" || fail "anthropic: the results were not replayed"
grep -q '"citations":\[{"type":"web_search_result_location"' "$T/log/2.req" || fail "anthropic: the citation was not replayed"
printf 'PASS: anthropic search is replayed from the journal, not searched again\n'

# When the provider's search is not declared: the function is, so pic gates it as it does any call.
for c in "--permission-mode ask-all" "--permission-mode read-only"; do
    FLAGS=$c ask anthropic/test-model "sse:$N/anthropic.sse"
    ! declared '"type":"web_search_20250305"' || fail "$c: the provider's search was declared"
    declared '"name":"web_search","description"' || fail "$c: the function was not declared"
done
FLAGS="--permission-mode ask-edits" ask anthropic/test-model "sse:$N/anthropic.sse"
declared '"type":"web_search_20250305"' || fail "ask-edits: not declared"
printf 'PASS: modes that ask or refuse changes get the function, which pic gates\n'

"$PIC" settings webSearch brave > /dev/null
ask anthropic/test-model "sse:$N/anthropic.sse"
! declared '"type":"web_search_20250305"' || fail "webSearch brave with no Brave key: the provider's search was declared"
declared '"name":"web_search","description"' || fail "webSearch brave with no Brave key: no function (Stack Overflow answers it)"
export BRAVE_API_KEY=brave-test-key
ask anthropic/test-model "sse:$N/anthropic.sse"
! declared '"type":"web_search_20250305"' || fail "webSearch brave: declared"
declared '"name":"web_search","description"' || fail "webSearch brave: no function"
unset BRAVE_API_KEY
"$PIC" settings --unset webSearch > /dev/null
"$PIC" settings offline true > /dev/null
ask anthropic/test-model "sse:$N/anthropic.sse"
! declared '"type":"web_search_20250305"' || fail "offline: declared"
"$PIC" settings --unset offline > /dev/null
FLAGS="--exclude-tools web_search" ask anthropic/test-model "sse:$N/anthropic.sse"
! declared 'web_search' || fail "--exclude-tools: still declared"
printf 'PASS: webSearch brave, offline and --exclude-tools turn the provider search off\n'

# OpenAI and xAI (Responses): {"type":"web_search"} beside the function tools; the search call
# and its citations are kept, shown as text, and the next request sends the reasoning item and the
# search call after it back together, as the API requires.
for model in openai/test-model xai/test-model; do
    API_PATH=/responses ask "$model" "sse:$N/responses.sse" "sse:$(dirname "$N")/responses-streams/reasoning_text.sse"
    grep -q '"tools":\[{"type":"function","name":"read"' "$T/log/1.req" || fail "$model: the function tools went missing"
    grep -q '{"type":"web_search"}' "$T/log/1.req" || fail "$model: no server tool: $(grep -o "\"tools\".\{0,200\}" "$T/log/1.req" | head -c 600)"
    ! grep -q '"name":"web_search"' "$T/log/1.req" || fail "$model: the function was declared too"
    D=$(pic dump)
    printf '%s\n' "$D" | grep -qF 'Searched the web for: c language' || fail "$model: no search line in the transcript"
    printf '%s\n' "$D" | grep -qF 'C is a language.' || fail "$model: no answer text"
    printf '%s\n' "$D" | grep -qF 'https://example.net/iso' || fail "$model: no source in the transcript"
    clean "$D" "$model"
    clean "$(decoded)" "$model (decoded)"
    NATIVE=$("$(dirname "$SERVER")/sqlite3" "$DB" "SELECT native FROM pic_entry WHERE native IS NOT NULL")
    printf '%s\n' "$NATIVE" | grep -qF '"type":"web_search_call"' || fail "$model: the search call was not kept"
    printf '%s\n' "$NATIVE" | grep -qF '"type":"url_citation"' || fail "$model: the citations were not kept"
    pic submit job2 'and more' --session latest > /dev/null
    pic run --model "$model" --api-url "$URL/responses" > /dev/null 2>&1 || fail "$model: the second request failed"
    grep -q '"text":"C is a language."' "$T/log/2.req" || fail "$model: the answer was not replayed"
    grep -q '"encrypted_content":"ENC-RS-W"[^]]*"type":"web_search_call"' "$T/log/2.req" || fail "$model: the reasoning item and the search call after it were not sent back as a pair"
done
printf 'PASS: responses: openai and xai search natively, kept and replayed\n'


# OpenRouter (Chat Completions): its server tool in the tools array, and the citations the stream
# brings are shown as a source list. The assistant message goes back as it came (no annotations).
API_PATH=/chat/completions ask openrouter/test/model "sse:$N/openrouter.sse" "sse:$(dirname "$N")/chat-streams/text.sse"
grep -q '{"type":"openrouter:web_search"}' "$T/log/1.req" || fail "openrouter: no server tool: $(grep -o '"tools".\{0,200\}' "$T/log/1.req" | head -c 500)"
grep -q '{"type":"openrouter:web_search"}\]' "$T/log/1.req" || fail "openrouter: the server tool is not last"
! grep -q '"name":"web_search"' "$T/log/1.req" || fail "openrouter: the function was declared too"
D=$(pic dump)
printf '%s\n' "$D" | grep -qF 'C is a language.' || fail "openrouter: no answer text"
printf '%s\n' "$D" | grep -qF 'Sources:' || fail "openrouter: no source list"
printf '%s\n' "$D" | grep -qF 'https://example.net/iso' || fail "openrouter: no source in the transcript"
clean "$D" openrouter
clean "$(decoded)" "openrouter (decoded)"
pic submit job2 'and more' --session latest > /dev/null
pic run --model openrouter/test/model --api-url "$URL/chat/completions" > /dev/null 2>&1 || fail "openrouter: the second request failed"
grep -q '"role":"assistant","content":"C is a language."' "$T/log/2.req" || fail "openrouter: the answer was not replayed as it came"
printf 'PASS: openrouter searches natively, sources shown\n'

# Gemini 3 (Google Search grounding): googleSearch beside the function declarations, with the
# server-side tool parts asked for; the search and its sources are shown as text; the next request
# sends every part back as it came (ids and thought signatures), and the function call's id is the
# one its result carries.
G=$(dirname "$N")/gemini-streams
GP=/models/gemini-3-flash-preview:streamGenerateContent
API_PATH=$GP ask google/gemini-3-flash-preview "sse:$G/search.sse" "sse:$G/text.sse"
grep -q '"tools":\[{"functionDeclarations":\[{"name":"read"' "$T/log/1.req" || fail "gemini: the function tools went missing: $(grep -o '"tools".\{0,200\}' "$T/log/1.req")"
grep -q '{"googleSearch":{}}\]' "$T/log/1.req" || fail "gemini: no googleSearch: $(grep -o '"tools".\{0,200\}' "$T/log/1.req")"
grep -q '"toolConfig":{"includeServerSideToolInvocations":true}' "$T/log/1.req" || fail "gemini: server-side tool parts not asked for"
! grep -q '"name":"web_search"' "$T/log/1.req" || fail "gemini: the function was declared too"
D=$(pic dump)
printf '%s\n' "$D" | grep -qF 'Searched the web for: c language, c standard' || fail "gemini: no search line in the transcript"
printf '%s\n' "$D" | grep -qF 'C is a language.' || fail "gemini: no answer text"
printf '%s\n' "$D" | grep -qF 'https://example.net/iso' || fail "gemini: no source in the transcript"
clean "$D" gemini
clean "$(decoded)" "gemini (decoded)"
pic submit job2 'and more' --session latest > /dev/null
pic run --model google/gemini-3-flash-preview --api-url "$URL$GP" > /dev/null 2>&1 || fail "gemini: the second request failed"
grep -qF '{"role":"model","parts":[{"toolCall":{"toolType":"GOOGLE_SEARCH_WEB","args":{"queries":["c language","c standard"]},"id":"a7b3k9p2"},"thoughtSignature":"c2lnLXRj"},{"toolResponse":{"toolType":"GOOGLE_SEARCH_WEB","response":{"search_suggestions":"<div class=\"chips\">c language</div>"},"id":"a7b3k9p2"},"thoughtSignature":"c2lnLXRy"},{"text":"C is a language.","thoughtSignature":"c2lnLXR4"}]}' "$T/log/2.req" ||
    fail "gemini: the parts were not sent back as they came: $(grep -o '"role":"model".\{0,250\}' "$T/log/2.req")"
! grep -q 'Searched the web for' "$T/log/2.req" || fail "gemini: the search went back as text too"
printf 'PASS: gemini 3 searches with Google Search, parts kept and replayed\n'

# A search, then a function call without an id: the call goes back with the id its result carries.
fresh
serve "sse:$G/search_tool.sse" "sse:$G/text.sse"
pic submit job 'write notes' > /dev/null
pic run --model google/gemini-3-flash-preview --api-url "$URL$GP" > /dev/null 2>&1 || fail "gemini tool: run failed"
grep -qF '{"toolResponse":{"toolType":"GOOGLE_SEARCH_WEB","response":{"search_suggestions":"<div/>"},"id":"t1"},"thoughtSignature":"c2lnLXRy"},{"text":"Writing it."},{"functionCall":{"name":"write","args":{"path":"notes.txt","content":"hi"},"id":"write_1"},"thoughtSignature":"c2lnLWNhbGw="}' "$T/log/2.req" ||
    fail "gemini tool: parts: $(grep -o '"role":"model".\{0,250\}' "$T/log/2.req")"
grep -q '"functionResponse":{"name":"write","response":{"output":"[^"]*"},"id":"write_1"}' "$T/log/2.req" || fail "gemini tool: the result's id: $(grep -o '"functionResponse".\{0,200\}' "$T/log/2.req")"
printf 'PASS: gemini: a function call beside a search keeps its id\n'

# A native functionCall with no matching neutral toolCall is left untouched (never "id":null).
fresh
serve "sse:$G/search.sse"
pic submit job 'what is C' > /dev/null
pic run --model google/gemini-3-flash-preview --api-url "$URL$GP" > /dev/null 2>&1 || fail "gemini null id: turn 1"
"$(dirname "$SERVER")/sqlite3" "$DB" "UPDATE pic_entry SET native = json_insert(native,'\$[#]',json('{\"functionCall\":{\"name\":\"write\",\"args\":{\"path\":\"notes.txt\",\"content\":\"hi\"}},\"thoughtSignature\":\"c2lnLWNhbGw=\"}')) WHERE kind = 'answer'"
serve "sse:$G/text.sse"
pic submit job2 'continue' --session latest > /dev/null
pic run --model google/gemini-3-flash-preview --api-url "$URL$GP" > /dev/null 2>&1 || fail "gemini null id: turn 2"
! grep -q '"id":null' "$T/log/1.req" || fail "gemini null id: wrote id:null: $(grep -o '"functionCall".\{0,120\}' "$T/log/1.req")"
grep -qF '"functionCall":{"name":"write","args":{"path":"notes.txt","content":"hi"}}' "$T/log/1.req" || fail "gemini null id: functionCall altered"
printf 'PASS: gemini: unmatched native functionCall never gets id:null\n'

# webSearch brave after a Gemini search: the function is declared and the search goes back as text.
export BRAVE_API_KEY=brave-test-key
API_PATH=$GP ask google/gemini-3-flash-preview "sse:$G/search.sse" "sse:$G/text.sse"
pic submit job2 'and more' --session latest > /dev/null
"$PIC" settings webSearch brave > /dev/null
pic run --model google/gemini-3-flash-preview --api-url "$URL$GP" > /dev/null 2>&1 || fail "gemini brave: the second request failed"
"$PIC" settings --unset webSearch > /dev/null
! grep -q 'googleSearch\|toolCall\|toolResponse\|includeServerSideToolInvocations' "$T/log/2.req" || fail "gemini brave: server-side parts or the search were sent"
grep -q '"name":"web_search"' "$T/log/2.req" || fail "gemini brave: no function"
grep -q 'Searched the web for: c language' "$T/log/2.req" || fail "gemini brave: the query is not in the history"
unset BRAVE_API_KEY
printf 'PASS: gemini: with the search off, past searches go back as text\n'

# A search call may carry the queries it made as a list instead of one query.
sed 's/"query":"c language"/"queries":["c language","c standard"]/g' "$N/responses.sse" > "$T/queries.sse"
API_PATH=/responses ask openai/test-model "sse:$T/queries.sse"
pic dump | grep -qF 'Searched the web for: c language, c standard' || fail "queries: $(pic dump | head -5 | cut -c1-200)"
printf 'PASS: responses: a list of queries is shown\n'

# The tool is offered for every model: one with no search of its own and no Brave key gets the
# function, which Stack Overflow answers.
for m in groq/test-model anthropic/test-model; do
    fresh
    serve "sse:$(dirname "$N")/chat-streams/text.sse"
    pic submit job 'what is C' > /dev/null
    case $m in groq/*) P=/chat/completions ;; *) P=/messages ;; esac
    pic run --model "$m" --api-url "$URL$P" > /dev/null 2>&1 || :
    OFFERED=$("$(dirname "$SERVER")/sqlite3" "$DB" "SELECT group_concat(json_extract(value,'\$.name'),' ') FROM pic_session, json_each(tools)")
    printf '%s' "$OFFERED" | grep -qw web_search || fail "$m: web_search not offered"
done
printf 'PASS: web_search is offered for a model that can use it\n'

# Gemini before 3 and providers with no search of their own get the function, not a server tool.
export BRAVE_API_KEY=brave-test-key # the function is offered to a model with no search of its own only with a key
for m in google/gemini-2.5-flash groq/test-model; do
    case $m in google/*) P=/models/x:streamGenerateContent ;; *) P=/chat/completions ;; esac
    fresh
    serve "sse:$(dirname "$N")/chat-streams/text.sse"
    pic submit job 'what is C' > /dev/null
    pic run --model "$m" --api-url "$URL$P" > /dev/null 2>&1 || :
    [ -e "$T/log/1.req" ] || fail "$m: no request was made"
    ! grep -q 'googleSearch\|openrouter:web_search\|"type":"web_search' "$T/log/1.req" || fail "$m: a server tool was declared"
    grep -q '"name":"web_search"' "$T/log/1.req" || fail "$m: the function was not declared"
done
unset BRAVE_API_KEY
printf 'PASS: providers with no native search get the function\n'

# A crash after the reply is journaled does not search again: the search is in the journal, and the
# request that resumes the conversation carries it, one request and not two for the same question.
if [ "$FAULTS" = yes ]; then
    fresh
    serve "sse:$N/anthropic_tool.sse" "sse:$(dirname "$N")/streams/text.sse"
    pic submit job 'what is C' > /dev/null
    rc=0
    env PIC_CRASH_AT=after-result:1 "$PIC" --db "$DB" --workspace "$WS" run --model anthropic/test-model --api-url "$URL/messages" > /dev/null 2>&1 || rc=$?
    [ "$rc" = 77 ] || fail "crash: expected the crash hook, got exit $rc"
    [ "$(ls "$T/log" | wc -l | tr -d ' ')" = 1 ] || fail "crash: more than one request before the crash"
    pic run --model anthropic/test-model --api-url "$URL/messages" > /dev/null 2>&1 || fail "crash: recovery failed"
    [ "$(ls "$T/log" | wc -l | tr -d ' ')" = 2 ] || fail "crash: $(ls "$T/log" | wc -l) requests, wanted 2 (the search was asked again)"
    grep -q '"encrypted_content":"ENC1"' "$T/log/2.req" || fail "crash: the journaled search was not sent back"
    printf 'PASS: a crash after the reply does not search again\n'
fi

# A change mid-conversation: when the request that follows does not declare the provider's search
# (a mode that asks or refuses, webSearch brave, offline), the search blocks of earlier replies go
# back as plain text, not as server-tool blocks with no server tool declared beside a function of
# the same name. Each case: a first turn with the search, a change, a second turn.
export BRAVE_API_KEY=brave-test-key
switch_turn() { # switch_turn MODEL PATH SPEC1 SPEC2 CHANGE: the second request is $T/log/2.req
    model=$1 path=$2 spec1=$3 spec2=$4 change=$5
    API_PATH=$path ask "$model" "sse:$spec1" "sse:$spec2"
    case $change in
    mode:*) pic --permission-mode "${change#mode:}" submit job2 'and more' --session latest > /dev/null ;;
    *) pic submit job2 'and more' --session latest > /dev/null ;;
    esac
    case $change in
    brave) "$PIC" settings webSearch brave > /dev/null ;;
    offline) "$PIC" settings offline true > /dev/null ;;
    esac
    pic run --model "$model" --api-url "$URL$path" > /dev/null 2>&1 || fail "$model $change: the second request failed"
    "$PIC" settings --unset webSearch > /dev/null
    "$PIC" settings --unset offline > /dev/null
}
for change in mode:ask-all mode:read-only brave offline; do
    switch_turn anthropic/test-model /messages "$N/anthropic.sse" "$(dirname "$N")/streams/text.sse" "$change"
    ! grep -q 'server_tool_use\|web_search_tool_result\|encrypted_content\|"citations"' "$T/log/2.req" || fail "anthropic $change: search blocks were replayed: $(grep -o ".\{80\}server_tool_use.\{80\}" "$T/log/2.req" | head -2)"
    grep -q 'Searched the web for: c language' "$T/log/2.req" || fail "anthropic $change: the query is not in the history"
    grep -q 'https://example.org/c' "$T/log/2.req" || fail "anthropic $change: the sources are not in the history"
    switch_turn openai/test-model /responses "$N/responses.sse" "$(dirname "$N")/responses-streams/reasoning_text.sse" "$change"
    ! grep -q '"type":"web_search_call"\|ENC-RS-W' "$T/log/2.req" || fail "openai $change: the search call or its reasoning item was replayed alone"
    grep -q "C is a language\." "$T/log/2.req" || fail "openai $change: the answer is missing"
done
# A switch of model: the other provider gets the neutral form, which carries the search as text.
ask anthropic/test-model "sse:$N/anthropic.sse" "sse:$(dirname "$N")/chat-streams/text.sse"
pic submit job2 'and more' --session latest > /dev/null
pic run --model openrouter/test/model --api-url "$URL/chat/completions" > /dev/null 2>&1 || fail "model switch: the second request failed"
! grep -q 'server_tool_use\|web_search_tool_result\|encrypted_content' "$T/log/2.req" || fail "model switch: search blocks were sent to another provider"
grep -q 'Searched the web for: c language' "$T/log/2.req" || fail "model switch: the query is not in the history"
unset BRAVE_API_KEY
printf 'PASS: a change of mode, setting or offline sends past searches as text\n'

if [ "$FAULTS" = yes ]; then
    # Reasoning, a search, then a function call, and the next request no longer declares the
    # search: the turn goes back in the form a model switch uses (no reasoning, no item ids), with
    # the query as text, so the function call does not lose the reasoning item it needs.
    fresh
    serve "sse:$N/responses_tool.sse" "sse:$(dirname "$N")/responses-streams/reasoning_text.sse"
    pic submit job 'what is C' > /dev/null
    rc=0
    env PIC_CRASH_AT=after-result:1 "$PIC" --db "$DB" --workspace "$WS" run --model openai/test-model --api-url "$URL/responses" > /dev/null 2>&1 || rc=$?
    [ "$rc" = 77 ] || fail "demote: expected the crash hook, got exit $rc"
    "$PIC" settings webSearch brave > /dev/null
    pic run --model openai/test-model --api-url "$URL/responses" > /dev/null 2>&1 || fail "demote: recovery failed"
    "$PIC" settings --unset webSearch > /dev/null
    ! grep -q 'ENC-RS-W\|"id":"fc_1"\|"id":"rs_w1"\|web_search_call' "$T/log/2.req" || fail "demote: reasoning or item ids were sent: $(grep -o 'ENC-RS-W\|"id":"fc_1"\|web_search_call' "$T/log/2.req" | head -3)"
    CALL=$(grep -o '"type":"function_call","call_id":"[^"]*"' "$T/log/2.req" | head -1 | sed 's/.*"call_id":"//; s/"$//')
    [ -n "$CALL" ] || fail "demote: the function call is missing"
    grep -q "\"type\":\"function_call_output\",\"call_id\":\"$CALL\"" "$T/log/2.req" || fail "demote: the result does not carry the call's id ($CALL)"
    grep -q 'Searched the web for: c language' "$T/log/2.req" || fail "demote: the query is not in the history"
    printf 'PASS: a demoted Responses turn is sent as a model switch sends it\n'
fi

# The control filter is for the provider's web text: a tool call's arguments and the model's own
# marks come back as they were sent.
fresh
serve "sse:$N/anthropic_crlf.sse" "sse:$(dirname "$N")/streams/text.sse"
pic submit job 'what is C' > /dev/null
pic run --model anthropic/test-model --api-url "$URL/messages" > /dev/null 2>&1 || fail "crlf: run failed"
BODY=$("$(dirname "$SERVER")/sqlite3" "$DB" "SELECT group_concat(body, char(10)) FROM pic_entry WHERE body LIKE '%toolCall%'")
printf '%s\n' "$BODY" | grep -qF 'c\r\nd' || fail "crlf: the tool call's arguments were changed: $BODY"
printf '%s\n' "$BODY" | LC_ALL=C grep -q "$(printf '\342\200\217')" || fail "crlf: the model's own mark was removed"
printf 'PASS: the filter leaves tool arguments and the model text alone\n'
