gateway: a tool Pi adds in a message of its own joins the request's tools on every route, once by name (#2322, deephbz)

Pi 1.2.0 with supportsMidConvoToolAdditions sends a tool it adds
mid-conversation as {"role":"system","tools":[...]} with no content and
keeps top-level tools as they were. parseChat read only top-level tools
and the Chat relay sent the message on as it came, so the tool could be
called on no route, and the tools-only message became an empty part of
the system text ("</cwd>\n\n\n\nUpdated ...").

liftMessageTools (message_tools.go) moves message tools into the
request's tools. handle does it for every Chat body, before serveAgent,
so the Chat relay, schema fixers, redaction, the prompt shown and
routing all see them; parseChat does it too for a body that never came
through handle. Each tool joins once by name and the first definition
wins (top-level, then the earliest message's), as liftAdditionalTools
and a tool_addition in withoutDeferredTools do. A system or developer
message that carried only tools is left out; one with content keeps
its place without tools. Message order is unchanged: the in-place
system message / inline-tools beta part of #2322 is not in this commit.
6312af989 (#2338, inline-only tool_addition joins tools) is not on
origin/main a1f7b8c13, so this builds on neither; the rule matches it.

Tests, from deephbz's literal Pi 1.2.0 request (last comment on #2322):
TestPiAddedToolReachesEveryRoute (Chat relayed to an OpenAI-compatible
upstream, Messages, Responses, Gemini, Codex), TestPiAddedToolOffered-
ToClaudeCode (the Claude subscription bridge's MCP tools.json, a fake
claude; skipped on Windows), TestMessageToolsFirstDefinitionWins.

Run (sandbox HOME, -tags nogui -p 1):
- go test ./internal/gateway -run 'TestPiAddedTool|TestMessageTools|
  Chat|Messages|AdditionalTools|Lite|Deferred|ExtraBody|Gemini|
  CodexAccessPrograms|Developer|ThinkingEffort|Kimi|DeepSeek|ClaudeRun|
  ClaudeSubscription|Strict|Prompt' -count=1: ok (75.8s)
- broken by hand: liftMessageTools a no-op -> every route subtest, the
  bridge test and FirstDefinitionWins red (tools [lookup_pantry], empty
  system relayed, "\n\n\n\n" in the system text); only handle's lift
  removed -> chat relayed red; only parseChat's lift removed -> the
  bridge test and FirstDefinitionWins red.
- gofmt -l internal/gateway: clean; go vet -tags nogui ./internal/gateway
  for GOOS=darwin, linux, windows: clean.
Not run: other packages, the full suite. Not tried with a real Pi or a
real upstream.

Full suite: SUITE_LINE
This commit is contained in:
yetone
2026-10-15 23:08:04 +08:00
parent 934263f543
commit afb0ff7720
5 changed files with 358 additions and 0 deletions
+1
View File
@@ -136,6 +136,7 @@ recorded as a prediction failure (`noPrediction`).
- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. When a provider answers its summary request 404, or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301). A summary is wanted only whole (`askWhole`, `holdWriter.wantWhole`): its stream is held to its end, not let through at its first words, so a reply cut short (`errEndedShort`), failed halfway (a 429 "Individual quota reached" after some of it) or ended `incomplete` (`endedIncomplete`, `incompleteReply`) fails over to the next candidate like a failure before any of it, and rests the account as that failure would; one that reached its output limit rests nobody. With nobody left, `codexCompact` answers 502 and never hands Codex the words before the cut as the summary (#2274, huangzuomin: Antigravity cutting each summary short). Codex with context_management's experimental mode compacts in the background at every step while the conversation is over its threshold and drops a failed compaction without a word, so a conversation whose summaries keep failing is asked again every few seconds, each paying for the whole history (1169 compactions in 6 hours there). After `compactFailsMost` (3) failed summaries in a row of one conversation (`prompt_cache_key`) on one model, each within `compactHeldFor` (5 minutes) of the last, the next is answered at once with a 400 naming the last failure, which Codex doesn't ask again, and no model is asked until 5 minutes have passed (`compactFails` in [`codex_compact_guard.go`](../../internal/gateway/codex_compact_guard.go)); a summary that comes clears the count, and a sign-in's 401 or 403 isn't counted. `TestCodexCompactCutSummaryFailsOver`, `TestCodexCompactCutSummaryIsNoSummary`, `TestCodexCompactKeepsFailingIsHeld`.
- Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set <id> compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); with the writer gone from the candidates (switched off, resting, removed), magpie answers 400 `checkpointError` naming why, and never sends it to another key, drops it, or summarises it in its place. `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`.
- A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set <id> codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`.
- A tool a Chat request's message carries joins the request's `tools` (`liftMessageTools` in [`message_tools.go`](../../internal/gateway/message_tools.go), #2322). Pi with `supportsMidConvoToolAdditions` gives a tool it adds mid-conversation as `{"role":"system","tools":[…]}` with no content, and keeps top-level `tools` as they were at the start; no Chat API reads tools there, and `parseChat` read only the top-level ones, so the tool could be called on no route. `handle` lifts them for every Chat body before `serveAgent`, so the Chat relay, the schema fixers, redaction (the tool is a tool definition, not message text), the prompt shown and routing all see them; `parseChat` lifts too, for a body that never came through `handle` (the Claude subscription bridge's direct callers). Each tool joins once by name and the first definition wins: a top-level tool keeps its own, then the earliest message's, as `liftAdditionalTools` and a `tool_addition` (`withoutDeferredTools`) do. A system or developer message that carried only tools is left out, so it is neither relayed as an empty system message nor joined into the system text as an empty part; one with content keeps its place without `tools`. Messages stay where they are: the in-place system message the issue also asks for is not this change. `TestPiAddedToolReachesEveryRoute` sends deephbz's Pi 1.2.0 bytes through the Chat relay, Messages, Responses, Gemini and Codex, and `TestPiAddedToolOfferedToClaudeCode` through the Claude subscription bridge.
- Every request to a key+URL provider goes with magpie's User-Agent (`magpie/<Version>`, `userAgentFor` in [`user_agent.go`](../../internal/gateway/user_agent.go)), except a provider set `passUserAgent` (#1851, `magpie provider set <id> user-agent=agent`, the editor's "Send the agent's own User-Agent"): it gets the User-Agent the inbound request carried, unchanged, for a coding plan that serves only the agents it names. One the agent didn't send, and magpie's own (`magpiesOwn`: another magpie's `magpie/…`, `magpie-router/1`, `magpie-vision/1`, `magpie-search/1`, and the image tool's `<client> magpie-image/1`, built from MCP's clientInfo, not a User-Agent), go as magpie; magpie never makes up another client's. `forwardOnce` sets it for chat, Anthropic, Responses, Gemini and count_tokens; embeddings, images and videos (`retrieveFrom`, `sendWith`, `remoteVideoContent`) set it with `stampUA` from the caller the request came with (`caller.ua`, `withCaller`), and before #1851 went with Go's default. Claude Code's and Codex's own headers are copied after, as before, and the user's `header.User-Agent` is put on when the request is signed, so it wins. `provider.PassesUserAgent` refuses it for a signed-in account, a plugin's, and a vendor whose own client magpie goes as (`OwnClient`: OpenCode, Cline, Kilo, another magpie); their signing sets their own. `TestUserAgentPassedOn`, `TestUserAgentAccountUntouched`, `TestUserAgentFor`, `TestPassesUserAgent`, `provider-user-agent.test.cjs`.
- A Chat upstream that wants a turn's reasoning back (`chatReplaysReasoning` in [`chat.go`](../../internal/gateway/chat.go): a host or a model, as magpie or the provider names it, with `deepseek` in it, such as OpenCode Go's `deepseek-v4.1-flash`, or Command Code's plugin) gets every assistant tool call with `reasoning_content`, relayed (`withReasoningOnToolTurns` in `passthrough`) or translated (`buildChat`). DeepSeek turns the whole request away ("The `reasoning_content` in the thinking mode must be passed back to the API") when a tool call made since the user's last message has none, which a client sends for a turn it saw no thinking on: another model's, a translated one (#1462). The turn's own thinking goes back as it came; one sent in `reasoning` or `reasoning_details` is copied in; otherwise it goes with a space (`noReasoning`: DeepSeek's Chat API takes an empty one, but a relay that leaves empty fields out would drop it). An assistant message right after a tool result, a reply with no call of its own, gets one too: DeepSeek refuses it the same way (checked 2026-10-12, #1822). A reply to the user, any other model and Mistral (#494) are sent as before.
- Kimi's Chat API (`isKimi`: the Kimi platform's and a Kimi Code membership's hosts or presets) turns `reasoning_details` in a message away in any shape: an entry with a stream's `index` ("the reasoning_details at position 1 entry 0 must not contain streaming index") and any other entry ("… has an invalid type"), checked against api.kimi.com/coding on 2026-10-12. pi keeps another vendor's thinking there (MiMo's, through Command Code, with `index: 0`), so a conversation routed on to Kimi was refused on every turn (#1765). `passthrough` sends it to Kimi as `reasoning_content` (`reasoningDetailsAsContent`), which Kimi takes; a message with `reasoning_content` of its own keeps that. Another upstream that refuses a thinking field "at position N", as Kimi words it (a relay in front of it), is asked once more the same way and marked (`refusedInMessages`, `withoutMessageReasoning`).
+1
View File
@@ -71,6 +71,7 @@ type cRequest struct {
}
func parseChat(body []byte) (*Request, error) {
body = liftMessageTools(body) // a request handle didn't see (#2322)
var c cRequest
if err := decodeJSON(body, &c); err != nil {
return nil, fmt.Errorf("invalid request: %v", err)
+4
View File
@@ -1344,6 +1344,10 @@ func (s *Server) handle(from provider.Protocol) http.HandlerFunc {
}
if from == provider.Chat {
body = thinkingEffort(body)
// a tool Pi adds during a conversation, in a message of its
// own: in the request's tools for every route, the relay's
// and every check that reads them (#2322)
body = liftMessageTools(body)
}
// Claude Code's headers, for a test asked as Claude Code to ask
// with (provider.TestAs), whatever serves this model: a
+98
View File
@@ -0,0 +1,98 @@
package gateway
import (
"bytes"
"encoding/json"
"github.com/tidwall/gjson"
)
// Pi with supportsMidConvoToolAdditions on gives a tool it adds during a
// conversation in a message of its own, not in the request's tools, which
// it keeps as they were at the start (#2322, Pi 1.2.0):
//
// {"role":"system","tools":[{"type":"function","function":{…}}]}
//
// No Chat Completions API reads tools there (OpenAI turns a system message
// with no content away), and parseChat read only the request's own tools,
// so the model could never call the tool on any route. Such tools join the
// request's tools as Codex's additional_tools do (liftAdditionalTools).
// liftMessageTools is a Chat request with the tools its messages carry
// moved into its own tools, each once by name: a tool the request already
// has, or an earlier message gave, keeps that first definition, as a
// tool_addition's does (withoutDeferredTools). A system or developer
// message that carried only tools is left out, rather than sent on as an
// empty system message; one with content keeps its place without its
// tools. A request with no message tools, or one that doesn't parse, is
// as it came.
func liftMessageTools(body []byte) []byte {
if !bytes.Contains(body, []byte(`"tools"`)) {
return body
}
if len(gjson.GetBytes(body, "messages.#.tools").Array()) == 0 {
return body
}
var v struct {
Messages []json.RawMessage `json:"messages"`
Tools []json.RawMessage `json:"tools"`
}
if json.Unmarshal(body, &v) != nil {
return body
}
have := map[string]bool{}
for _, t := range v.Tools {
have[chatToolKey(gjson.ParseBytes(t))] = true
}
tools := v.Tools
msgs := make([]json.RawMessage, 0, len(v.Messages))
for _, raw := range v.Messages {
m := gjson.ParseBytes(raw)
more := m.Get("tools")
if !more.Exists() {
msgs = append(msgs, raw)
continue
}
for _, t := range more.Array() {
if !t.IsObject() {
continue
}
if k := chatToolKey(t); !have[k] {
have[k] = true
tools = append(tools, json.RawMessage(t.Raw))
}
}
role := m.Get("role").String()
if (role == "system" || role == "developer") && emptyContent(m.Get("content")) {
continue
}
var mm map[string]json.RawMessage
if json.Unmarshal(raw, &mm) != nil {
msgs = append(msgs, raw)
continue
}
delete(mm, "tools")
out, err := marshalPlain(mm)
if err != nil {
return body
}
msgs = append(msgs, out)
}
fields := map[string]any{"messages": msgs}
if len(tools) > 0 {
fields["tools"] = tools
}
return withFields(body, fields)
}
// chatToolKey is a Chat tool's name, a hosted tool's without one by its
// type.
func chatToolKey(t gjson.Result) string {
if n := t.Get("function.name").String(); n != "" {
return n
}
if n := t.Get("name").String(); n != "" {
return n
}
return "#" + t.Get("type").String()
}
+254
View File
@@ -0,0 +1,254 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
)
// piAddedTool is Pi 1.2.0's own Chat request for the turn after an
// extension called pi.setActiveTools([lookup_pantry, lookup_recipe]),
// with supportsMidConvoSystemMessages and supportsMidConvoToolAdditions
// on, as deephbz recorded it (#2322; only the working directory was
// redacted). The added tool is in a system message with no content; the
// request's tools stay as they were at the start.
const piAddedTool = `{
"model": "wire-model",
"messages": [
{"role": "system", "content": "You are a helpful cooking assistant. Help the user find recipes and pantry information.\n\n\n\n<cwd>\n(redacted)\n</cwd>"},
{"role": "user", "content": [{"type": "text", "text": "Please reply READY. Do not call any tools."}]},
{"role": "assistant", "content": "PLAIN_OK"},
{"role": "system", "tools": [{"type": "function", "function": {"name": "lookup_recipe", "description": "Look up the recipe catalogue and return the recipe code.", "parameters": {"type": "object", "properties": {}, "required": [], "additionalProperties": false}}}]},
{"role": "system", "content": "Updated system prompt section \"recipe_catalogue\":\n\n<recipe_catalogue>\nThe recipe catalogue is now available.\n</recipe_catalogue>"},
{"role": "user", "content": [{"type": "text", "text": "Please call lookup_recipe exactly once with {}. Then tell me the recipe code it returned."}]}
],
"stream": true,
"stream_options": {"include_usage": true},
"store": false,
"max_completion_tokens": 1024,
"tools": [{"type": "function", "function": {"name": "lookup_pantry", "description": "Look up the pantry and return its status.", "parameters": {"type": "object", "properties": {}, "required": [], "additionalProperties": false}}}]
}`
// piAsking is piAddedTool asking model.
func piAsking(model string) string {
return strings.Replace(piAddedTool, `"wire-model"`, `"`+model+`"`, 1)
}
var piTools = []string{"lookup_pantry", "lookup_recipe"}
func namesAt(body, path string) []string {
var out []string
for _, n := range gjson.Get(body, path).Array() {
out = append(out, n.String())
}
return out
}
// noEmptySystem fails when a system text magpie sent upstream is empty, or
// when the two system texts were joined around an empty one.
func noEmptySystem(t *testing.T, texts []string) {
t.Helper()
all := strings.Join(texts, "\n")
for _, s := range texts {
if strings.TrimSpace(s) == "" {
t.Errorf("an empty system text was sent: %q", texts)
}
}
if !strings.Contains(all, "</cwd>\n\nUpdated system prompt section") {
t.Errorf("system texts not joined as two: %q", all)
}
}
// The tool Pi adds in a message reaches every route a Chat body takes, once
// beside the request's own: relayed to a Chat API, and translated to
// Messages, Responses, Gemini and Codex's ChatGPT backend. A system message
// that carried only the tool is not sent on as an empty system message.
func TestPiAddedToolReachesEveryRoute(t *testing.T) {
srv, seen := relayOfEvery(t)
for _, c := range []struct {
name, model, path string
p provider.Provider
check func(t *testing.T, body string)
}{
{"chat relayed", "wire-model", "/v1/chat/completions", provider.Provider{Chat: srv.URL + "/v1"}, func(t *testing.T, body string) {
if got := namesAt(body, "tools.#.function.name"); !slices.Equal(got, piTools) {
t.Errorf("tools %v, want %v: %s", got, piTools, body)
}
msgs := gjson.Get(body, "messages").Array()
var roles []string
for _, m := range msgs {
roles = append(roles, m.Get("role").String())
if m.Get("tools").Exists() {
t.Errorf("a message still carries tools: %s", m.Raw)
}
if m.Get("role").String() == "system" && strings.TrimSpace(m.Get("content").String()) == "" {
t.Errorf("an empty system message was relayed: %s", m.Raw)
}
}
// the update stays where Pi put it, as every Chat message does
if want := []string{"system", "user", "assistant", "system", "user"}; !slices.Equal(roles, want) {
t.Errorf("roles %v, want %v", roles, want)
}
if !strings.HasPrefix(msgs[3].Get("content").String(), "Updated system prompt section") {
t.Errorf("the update moved: %s", msgs[3].Raw)
}
}},
{"messages", "claude-opus-5-5", "/v1/messages", provider.Provider{Anthropic: srv.URL}, func(t *testing.T, body string) {
if got := namesAt(body, "tools.#.name"); !slices.Equal(got, piTools) {
t.Errorf("tools %v, want %v: %s", got, piTools, body)
}
sys := gjson.Get(body, "system")
texts := namesAt(body, "system.#.text")
if sys.Type == gjson.String {
texts = []string{sys.String()}
}
noEmptySystem(t, texts)
}},
{"responses", "wire-model", "/v1/responses", provider.Provider{Responses: srv.URL + "/v1"}, func(t *testing.T, body string) {
if got := namesAt(body, "tools.#.name"); !slices.Equal(got, piTools) {
t.Errorf("tools %v, want %v: %s", got, piTools, body)
}
noEmptySystem(t, []string{gjson.Get(body, "instructions").String()})
}},
} {
t.Run(c.name, func(t *testing.T) {
fresh(t)
c.p.ID, c.p.Name, c.p.Key, c.p.Models = "pi", "Pi", "k", []string{c.model}
if err := provider.Save(c.p); err != nil {
t.Fatal(err)
}
seen()
if code, b := post(t, "/v1/chat/completions", piAsking("pi/"+c.model)); code != 200 {
t.Fatalf("%d %s", code, b)
}
paths, bodies := seen()
if len(paths) != 1 || paths[0] != c.path {
t.Fatalf("went to %v, want %s", paths, c.path)
}
c.check(t, bodies[0])
})
}
t.Run("gemini", func(t *testing.T) {
fresh(t)
var got []byte
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"OK"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1,"totalTokenCount":2}}`))
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "gem", Name: "Gem", Key: "AIza-test", Gemini: up.URL + "/v1beta", Models: []string{"gemini-2.5-pro"}}); err != nil {
t.Fatal(err)
}
if code, b := post(t, "/v1/chat/completions", piAsking("gem/gemini-2.5-pro")); code != 200 {
t.Fatalf("%d %s", code, b)
}
body := string(got)
if names := namesAt(body, "tools.#.functionDeclarations.#.name|@flatten"); !slices.Equal(names, piTools) {
t.Errorf("tools %v, want %v: %s", names, piTools, body)
}
noEmptySystem(t, namesAt(body, "systemInstruction.parts.#.text"))
})
t.Run("codex", func(t *testing.T) {
codexSignedIn(t, "spare@example.com")
d := daybreak(t)
if code, b := post(t, "/v1/chat/completions", piAsking("codex/gpt-daybreak-blue-latest")); code != 200 {
t.Fatalf("%d %s", code, b)
}
body := string(d.last(t))
if got := namesAt(body, "tools.#.name"); !slices.Equal(got, piTools) {
t.Errorf("tools %v, want %v: %s", got, piTools, body)
}
// the client's system is the developer message ahead of its turns
noEmptySystem(t, namesAt(body, `input.#(role=="developer")#.content.#.text|@flatten`))
})
}
// Through a Claude subscription, whose Claude Code is offered the client's
// tools by magpie's MCP helper, the added tool is offered too, once.
func TestPiAddedToolOfferedToClaudeCode(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("a shell script stands in for Claude Code")
}
dir := t.TempDir()
// answers with the names in the tools file its MCP config names
script := `#!/bin/sh
for a in "$@"; do
case "$a" in *mcpServers*) tp=$(printf '%s' "$a" | sed 's/.*"\([^"]*tools\.json\)".*/\1/');; esac
done
while read -r line; do
names=$(grep -o '"name":"[^"]*"' "$tp" | sed 's/"name":"//; s/"$//' | tr '\n' ',')
echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-opus-5-5","usage":{"input_tokens":1}}}}'
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"tools '"$names"'"}}}'
echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}}'
echo '{"type":"stream_event","event":{"type":"message_stop"}}'
echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
done
`
testenv.Program(t, filepath.Join(dir, "claude"), script)
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
runsEndWithTest(t, dir)
s := New()
t.Cleanup(s.subscription.abortAll)
p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
body := piAsking("claude-opus-5-5")
rec := httptest.NewRecorder()
var u Usage
if code, msg := s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body)), provider.Chat, p, "claude-opus-5-5", []byte(body), &u); code != 200 {
t.Fatalf("%d %s", code, msg)
}
if !strings.Contains(rec.Body.String(), "tools lookup_pantry,lookup_recipe,") {
t.Errorf("Claude Code was not offered %v once each: %s", piTools, rec.Body)
}
}
// A name already offered keeps its first definition: the request's own,
// then the earliest message's. A system message with content and tools
// keeps its place and words.
func TestMessageToolsFirstDefinitionWins(t *testing.T) {
body := `{"model":"m","messages":[
{"role":"system","content":"base"},
{"role":"user","content":"hi"},
{"role":"system","content":"note","tools":[{"type":"function","function":{"name":"a","description":"again"}},{"type":"function","function":{"name":"b","description":"first b"}}]},
{"role":"developer","tools":[{"type":"function","function":{"name":"b","description":"second b"}}]},
{"role":"user","content":"go"}],
"tools":[{"type":"function","function":{"name":"a","description":"own"}}]}`
req, err := parseChat([]byte(body))
if err != nil {
t.Fatal(err)
}
var got []string
for _, tl := range req.Tools {
got = append(got, tl.Name+":"+tl.Description)
}
if want := []string{"a:own", "b:first b"}; !slices.Equal(got, want) {
t.Errorf("tools %v, want %v", got, want)
}
if req.System != "base\n\nnote" {
t.Errorf("system %q", req.System)
}
lifted := string(liftMessageTools([]byte(body)))
if n := len(gjson.Get(lifted, "messages").Array()); n != 4 {
t.Errorf("%d messages, want 4 (the tools-only one left out): %s", n, lifted)
}
if m := gjson.Get(lifted, "messages.2"); m.Get("content").String() != "note" || m.Get("tools").Exists() {
t.Errorf("the system message with content: %s", m.Raw)
}
// a request without message tools is as it came
plain := `{"model":"m","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"a"}}]}`
if out := string(liftMessageTools([]byte(plain))); out != plain {
t.Errorf("changed: %s", out)
}
}