provider: a provider's Extra body adds JSON fields to every request's body, ${sessionId} as the session (#1604, Luc-xz)

What: a provider has an Extra body (extraBody in providers.json, a JSON
object, beside Headers; an "Extra body" box in the editor under Headers).
Its fields are added at the top level of every JSON body sent to that
provider, in the gateway's forwardOnce: Messages, Chat, Responses and
Gemini, relayed as they came or translated from another API. Test models
and Detect send them too (provider.tested), so a relay that
refuses a request without them can be tested before a Save.

- A field the request already has is kept; "!name" replaces it.
- ${sessionId}, in any string at any depth, becomes the session id: the
  agent's session header (sessionOf), else the id conversationID derives
  from the first user message (magpie-<hash>), stable through one
  conversation. Test and Detect send magpie-test-<12 random letters>.
- model, stream and the conversation (messages, input, contents, system,
  systemInstruction, system_instruction, instructions, tools) are never
  set from it: Save refuses them (ExtraBodyOK), the editor says why as
  they are typed and holds the Save, and one written by hand into
  providers.json is dropped on read (cleanExtraBody).
- Not sent: count_tokens, embeddings, images, video, the decision model,
  and signed-in accounts' requests. One object goes to every API;
  per-API sections aren't done.
- A save that leaves extraBody out keeps the saved one; {} clears it.

Why: Luc-xz's relay turns Responses requests away without a
prompt_cache_key, and headers alone couldn't add one.

Docs: providers-accounts.md has an Extra body row and its tests.

Run:
- go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui
  -run ExtraBody: pass. The tests are TestExtraBodyResponsesRelayed,
  ChatDerivedSession, Translated (messages→chat, chat→responses),
  Anthropic (count_tokens left alone), Gemini (relayed and from chat),
  TestExtraBodyTested/OK/ReadByHand, TestWithExtraBody and
  TestProviderExtraBodySaved.
- Broken by hand, each FAIL recorded, then restored:
  - WithExtraBody removed from forwardOnce: all 5 gateway tests FAIL.
  - the countsTokens guard dropped: TestExtraBodyAnthropic FAIL.
  - tested() without the extra body: TestExtraBodyTested FAIL.
  - Save's ExtraBodyOK skipped: TestProviderExtraBodySaved FAIL.
  - keep-when-omitted skipped: TestProviderExtraBodySaved FAIL.
- internal/gui/tests/extra-body.test.cjs: en, zh, ja and de, in Chromium
  and WebKit, 8/8 pass. It covers live errors, Save held and focused, Test
  sending the typed object, the 420px fit, Save as an object, and empty
  saving {}.
- Also run: gui-de, gui-ja, gui-zh-tw, i18n-keys, provider-*, providers-*,
  balance-fix, duplicate-pause, editor-short-window, ux-safety and
  vertex-editor.
- gofmt -l clean; go vet -tags nogui for darwin, linux and windows on
  provider, gateway and gui; the full go test ./... after the rebase.

Not tried: a real relay that needs prompt_cache_key; the fixtures are
httptest upstreams.
This commit is contained in:
yetone
2026-10-11 22:41:11 +08:00
parent a2afc18282
commit 863af7abc8
14 changed files with 915 additions and 16 deletions
+3
View File
@@ -18,6 +18,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Part | Responsibility | Source |
| --- | --- | --- |
| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `Affinity`, concurrency and queue limits, `Headers`, `Proxy`, models, and balance settings. `BaseAPI` is the API a custom provider's editor shows its Base URL as: the one the user picked and saved, while it has a URL, so a provider with a chat URL beside its Responses one isn't shown as OpenAI compatible after Responses was picked. Requests go by which URLs are set. A custom provider's `Gemini` URL is the base of Google's Gemini API, or of one that answers as it does (#1346): `GeminiBase` keeps it as the base (…/v1beta added to a bare host, a pasted endpoint or model list cut back), requests go to `models/{model}:streamGenerateContent?alt=sse` under it (`GeminiPath`) signed with `x-goog-api-key` (`AuthHeaders`), and its models are listed by `catalog.FetchGemini` (paged, only those serving generateContent). Factory's sign-in alone keeps its own `/generate` route and token (`FactoryGemini`). `Account` is set only for a subscription and is never saved (`json:"-"`). | [`provider.go`](../../internal/provider/provider.go) |
| Extra body | `ExtraBody` (`extraBody` in providers.json, the editor's *Extra body*, #1604) is a JSON object whose fields `WithExtraBody` adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's `forwardOnce` and in Test and Detect (`tested`). A field the body has already is kept; a name written `"!name"` replaces it. Values are put in as written, objects whole, not merged. `${sessionId}` in any string, at any depth, becomes the request's session: the agent's session header (`sessionOf`), else the id `conversationID` derives from the first user message (`magpie-` and its hash), so it stays the same through one conversation; Test and Detect send `magpie-test-` and 12 random letters, a new one each time. `model`, `stream` and the conversation (`messages`, `input`, `contents`, `system`, `systemInstruction`, `system_instruction`, `instructions`, `tools`, `ExtraBodyReserved`) are magpie's: Save refuses them with or without `!` (`ExtraBodyOK`), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (`cleanExtraBody`). Not sent with it: `count_tokens`, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests. One object goes to every API; fields for one API alone are not a thing yet. | [`extrabody.go`](../../internal/provider/extrabody.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) |
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). | [`provider.go`](../../internal/provider/provider.go) |
| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`). `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) |
@@ -148,6 +149,8 @@ go test -tags nogui ./internal/provider
go test -tags nogui -run 'Vertex' .
go test -tags nogui ./internal/provider ./internal/agent -run 'TestAccountDiscovery'
node --test internal/gui/tests/account-discovery.test.cjs
go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui -run ExtraBody
node --test internal/gui/tests/extra-body.test.cjs
```
The package's tests use a home of their own (`testenv`). Never point them at
+207
View File
@@ -0,0 +1,207 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// withExtraBody gives the saved provider id the extraBody written.
func withExtraBody(t *testing.T, id, extra string) {
t.Helper()
p, err := provider.Find(id)
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal([]byte(extra), &p.ExtraBody); err != nil {
t.Fatal(err)
}
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
}
// postWith is post with the client's own headers.
func postWith(t *testing.T, path, body string, head map[string]string) (int, string) {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", path, strings.NewReader(body))
for k, v := range head {
req.Header.Set(k, v)
}
New().Handler().ServeHTTP(rec, req)
return rec.Code, rec.Body.String()
}
const (
chatReply = "data: {\"id\":\"c1\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"OK\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"
responsesReply = `{"id":"r","object":"response","status":"completed","output":[]}`
)
func anthropicReply() string {
return sse(
`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"m1","usage":{"input_tokens":7}}}`,
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"OK"}}`,
`data: {"type":"content_block_stop","index":0}`,
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`,
`data: {"type":"message_stop"}`)
}
// Luc-xz's relay (#1604) turns a Responses request away without a
// prompt_cache_key: the provider's extraBody adds one, the session's id,
// filling in only what the client didn't send, unless a name is forced.
func TestExtraBodyResponsesRelayed(t *testing.T) {
f := &fake{t: t, reply: responsesReply, ctype: "application/json"}
setup(t, provider.Responses, f)
withExtraBody(t, "fake", `{"prompt_cache_key":"${sessionId}","metadata":{"who":"agent-${sessionId}"},"!service_tier":"flex","model":"other"}`)
code, body := postWith(t, "/v1/responses", `{"model":"m1","input":"hi","service_tier":"auto"}`, map[string]string{"session_id": "sess-42"})
if code != 200 {
t.Fatalf("status %d: %s", code, body)
}
if got := gjson.GetBytes(f.got, "prompt_cache_key").String(); got != "sess-42" {
t.Errorf("prompt_cache_key %q in %s", got, f.got)
}
if got := gjson.GetBytes(f.got, "metadata.who").String(); got != "agent-sess-42" {
t.Errorf("metadata.who %q in %s", got, f.got)
}
if got := gjson.GetBytes(f.got, "service_tier").String(); got != "flex" {
t.Errorf("forced service_tier %q in %s", got, f.got)
}
if got := gjson.GetBytes(f.got, "model").String(); got != "m1" {
t.Errorf("model %q in %s", got, f.got)
}
if gjson.GetBytes(f.got, "input").String() != "hi" {
t.Errorf("input changed: %s", f.got)
}
// the client's own key is kept
code, body = postWith(t, "/v1/responses", `{"model":"m1","input":"hi","prompt_cache_key":"mine"}`, map[string]string{"session_id": "sess-42"})
if code != 200 {
t.Fatalf("status %d: %s", code, body)
}
if got := gjson.GetBytes(f.got, "prompt_cache_key").String(); got != "mine" {
t.Errorf("client's prompt_cache_key replaced by %q", got)
}
}
// Without a session header, ${sessionId} is the id magpie derives from the
// conversation's first user message: never the literal, the same on every
// turn of one conversation, different for another.
func TestExtraBodyChatDerivedSession(t *testing.T) {
f := &fake{t: t, reply: chatReply}
setup(t, provider.Chat, f)
withExtraBody(t, "fake", `{"user":"${sessionId}","temperature":0.5}`)
ask := func(msgs string) string {
t.Helper()
code, body := post(t, "/v1/chat/completions", `{"model":"m1","messages":`+msgs+`}`)
if code != 200 {
t.Fatalf("status %d: %s", code, body)
}
if gjson.GetBytes(f.got, "temperature").Raw != "0.5" {
t.Errorf("temperature in %s", f.got)
}
return gjson.GetBytes(f.got, "user").String()
}
one := ask(`[{"role":"user","content":"first"}]`)
again := ask(`[{"role":"user","content":"first"},{"role":"assistant","content":"OK"},{"role":"user","content":"next"}]`)
other := ask(`[{"role":"user","content":"another"}]`)
if !strings.HasPrefix(one, "magpie-") || one != again || one == other {
t.Errorf("derived ids: %q %q %q", one, again, other)
}
}
// A request magpie translates gets the fields too, on top of the
// translated body: Messages to a Chat provider, Chat to a Responses one.
func TestExtraBodyTranslated(t *testing.T) {
t.Run("messages to chat", func(t *testing.T) {
f := &fake{t: t, reply: chatReply}
setup(t, provider.Chat, f)
withExtraBody(t, "fake", `{"prompt_cache_key":"${sessionId}"}`)
code, body := postWith(t, "/v1/messages", `{"model":"m1","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`, map[string]string{"X-Claude-Code-Session-Id": "cc-1"})
if code != 200 {
t.Fatalf("status %d: %s", code, body)
}
if f.path != "/v1/chat/completions" || gjson.GetBytes(f.got, "prompt_cache_key").String() != "cc-1" {
t.Errorf("%s: %s", f.path, f.got)
}
})
t.Run("chat to responses", func(t *testing.T) {
f := &fake{t: t, reply: sse(`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`)}
setup(t, provider.Responses, f)
withExtraBody(t, "fake", `{"prompt_cache_key":"${sessionId}"}`)
code, body := postWith(t, "/v1/chat/completions", `{"model":"m1","messages":[{"role":"user","content":"hi"}]}`, map[string]string{"x-session-id": "s-9"})
if code != 200 {
t.Fatalf("status %d: %s", code, body)
}
if f.path != "/v1/responses" || gjson.GetBytes(f.got, "prompt_cache_key").String() != "s-9" {
t.Errorf("%s: %s", f.path, f.got)
}
})
}
// An Anthropic provider gets them on Messages, and not on count_tokens,
// which asks for no reply.
func TestExtraBodyAnthropic(t *testing.T) {
f := &fake{t: t, reply: anthropicReply()}
setup(t, provider.Anthropic, f)
withExtraBody(t, "fake", `{"metadata":{"user_id":"${sessionId}"},"!max_tokens":99}`)
code, body := postWith(t, "/v1/messages", `{"model":"m1","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`, map[string]string{"session_id": "a-1"})
if code != 200 {
t.Fatalf("status %d: %s", code, body)
}
if gjson.GetBytes(f.got, "metadata.user_id").String() != "a-1" || gjson.GetBytes(f.got, "max_tokens").Int() != 99 {
t.Errorf("messages body %s", f.got)
}
f.reply, f.ctype = `{"input_tokens":3}`, "application/json"
code, body = postWith(t, "/v1/messages/count_tokens", `{"model":"m1","messages":[{"role":"user","content":"hi"}]}`, map[string]string{"session_id": "a-1"})
if code != 200 {
t.Fatalf("count_tokens %d: %s", code, body)
}
if f.path != "/v1/messages/count_tokens" || gjson.GetBytes(f.got, "metadata").Exists() {
t.Errorf("count_tokens %s: %s", f.path, f.got)
}
}
// A Gemini provider gets them on a Gemini client's relayed request and on
// one translated from Chat.
func TestExtraBodyGemini(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
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)
}
withExtraBody(t, "gem", `{"cachedContent":"cachedContents/${sessionId}","contents":[]}`)
code, body := postWith(t, "/v1beta/models/gem/gemini-2.5-pro:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`, map[string]string{"session_id": "g-1"})
if code != 200 {
t.Fatalf("gemini %d: %s", code, body)
}
if gjson.GetBytes(got, "cachedContent").String() != "cachedContents/g-1" || !strings.Contains(gjson.GetBytes(got, "contents").Raw, "hi") {
t.Errorf("gemini body %s", got)
}
code, body = postWith(t, "/v1/chat/completions", `{"model":"gem/gemini-2.5-pro","messages":[{"role":"user","content":"hi"}]}`, map[string]string{"session_id": "g-2"})
if code != 200 {
t.Fatalf("chat %d: %s", code, body)
}
if gjson.GetBytes(got, "cachedContent").String() != "cachedContents/g-2" {
t.Errorf("chat to gemini body %s", got)
}
}
+13
View File
@@ -3096,6 +3096,12 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
// auto mode's review goes to Claude alone (automode.go)
betas, body = s.serverReview(p, asked, body)
}
if !countsTokens(path) {
// the user's own fields for the provider (#1604), last, so the
// body is as it goes out when they fill in what it lacks, and
// before it is signed
body = p.WithExtraBody(body, cmp.Or(sessionOf(in), conversationID(in, body)))
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.Base(to)+path, bytes.NewReader(body))
if err != nil {
return nil, err
@@ -3201,6 +3207,13 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
return res, nil
}
// countsTokens is a path that only counts a request's tokens (Anthropic's
// count_tokens): no reply is asked, so a provider's extra body fields, for
// asking one, aren't sent there.
func countsTokens(path string) bool {
return strings.Contains(path, "count_tokens")
}
// fromClaudeCode is a request Claude Code sent, by the User-Agent it gives
// (claude-cli/2.1.0 (external, cli)).
func fromClaudeCode(in http.Header) bool {
+8 -4
View File
@@ -2429,7 +2429,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
font-size: 12.5px; outline: none; width: 100%; min-width: 0;
transition: border-color .12s, box-shadow .12s;
}
.editor input:focus, .editor .headers textarea.json:focus, .acc input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); outline: none; }
.editor input:focus, .editor .headers textarea.json:focus, .editor .extra-body textarea.json:focus, .acc input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); outline: none; }
.editor input::placeholder, .acc input::placeholder { color: var(--faint); }
.editor .pair { display: flex; gap: 8px; align-items: center; }
.editor .pair input:first-child { flex: 1; }
@@ -2454,9 +2454,13 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.editor .headers .pair.col .hhead { display: flex; gap: 8px; align-items: center; width: 100%; }
.editor .headers .pair.col .hhead input { flex: 1; min-width: 0; }
.editor .headers .pair.col .side { flex: none; }
.editor .headers textarea.json { width: 100%; box-sizing: border-box; padding: 7px 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); outline: none; font-family: var(--code-font, var(--code)); font-size: 12px; line-height: 1.5; resize: vertical; tab-size: 2; white-space: pre; overflow: auto; transition: border-color .12s, box-shadow .12s; }
:where(html[data-fonts]) .editor .headers textarea.json { font-style: var(--code-style, inherit); font-weight: var(--code-weight, inherit); font-stretch: var(--code-stretch, 100%); }
.editor .headers textarea.json.bad { border-color: var(--danger, #d66); }
.editor .headers textarea.json, .editor .extra-body textarea.json { width: 100%; box-sizing: border-box; padding: 7px 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); outline: none; font-family: var(--code-font, var(--code)); font-size: 12px; line-height: 1.5; resize: vertical; tab-size: 2; white-space: pre; overflow: auto; transition: border-color .12s, box-shadow .12s; }
:where(html[data-fonts]) .editor .headers textarea.json, :where(html[data-fonts]) .editor .extra-body textarea.json { font-style: var(--code-style, inherit); font-weight: var(--code-weight, inherit); font-stretch: var(--code-stretch, 100%); }
.editor .headers textarea.json.bad, .editor .extra-body textarea.json.bad { border-color: var(--danger, #d66); }
/* a provider's extra body fields (#1604): the JSON, and why it can't be saved */
.editor .extra-body { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.editor .extra-body .why { font-size: 12px; line-height: 1.45; color: var(--red); overflow-wrap: anywhere; }
.editor .extra-body .why:empty { display: none; }
.segs { position: relative; display: inline-flex; padding: 2px; border-radius: 7px; background: var(--pill); align-self: flex-start; }
.opt { position: relative; z-index: 1; white-space: nowrap; height: 22px; padding: 0 10px; border-radius: 5px; font-size: 12px; color: var(--muted); transition: color .18s var(--ease), transform .14s var(--ease); }
.opt.on { color: var(--fg); }
+59 -1
View File
@@ -7568,6 +7568,9 @@ function asTyped() {
// credentials typed, as a pasted key is
if (draft.vertex) body.vertex = vertexOfDraft();
if (draft.headers) body.headers = headersOf(draft.headers);
// the extra body typed, when it reads; one that doesn't is the saved one's
const xb = extraBodyOf(draft.extraBody);
if (xb.value) body.extraBody = xb.value;
const proxy = draft.proxyMode === undefined ? null : proxyOfDraft();
if (proxy !== null) body.proxy = proxy;
return body;
@@ -7749,6 +7752,56 @@ function headerEditor(hints = []) {
}
function parses(s) { try { JSON.parse(s); return true; } catch { return false; } }
// A provider's extra body fields (#1604): a JSON object the gateway merges
// into the top of every request's body to the vendor, filling in what the
// body lacks, or replacing it for a name written "!name"; ${sessionId} is
// the conversation's id. The fields magpie sets itself — the model, stream,
// the conversation — are refused, as provider.ExtraBodyReserved refuses
// them on a save. The draft keeps the text as typed; extraBodyOf reads it.
const EXTRA_BODY_RESERVED = ["model", "stream", "messages", "input", "contents", "system", "systemInstruction", "system_instruction", "instructions", "tools"];
function extraBodyText(obj) {
return obj && Object.keys(obj).length ? JSON.stringify(obj, null, 2) : "";
}
// extraBodyOf is the object a save sends ({} for none), or why it can't be
function extraBodyOf(text) {
const s = (text || "").trim();
if (!s) return { value: {} };
let v;
try { v = JSON.parse(s); } catch { return { error: t("not valid JSON") }; }
if (!v || typeof v !== "object" || Array.isArray(v)) return { error: t("write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}") };
const seen = new Set();
for (const k of Object.keys(v)) {
const name = k.trim().replace(/^!/, "").trim();
if (!name) return { error: t("a field needs a name") };
if (EXTRA_BODY_RESERVED.includes(name)) return { error: t("magpie sets {k} itself, so it can't be added", { k: name }) };
if (seen.has(name)) return { error: t("{k} is named twice", { k: name }) };
seen.add(name);
}
return { value: v };
}
function extraBodyEditor() {
const box = el("div", "extra-body");
const ta = el("textarea", "json");
ta.value = draft.extraBody || "";
ta.spellcheck = false;
ta.wrap = "off";
ta.rows = Math.min(12, Math.max(3, ta.value.split("\n").length));
ta.placeholder = "{\n \"prompt_cache_key\": \"${sessionId}\"\n}";
const why = el("div", "why");
why.setAttribute("aria-live", "polite");
const check = () => {
const err = (draft.extraBody || "").trim() ? extraBodyOf(draft.extraBody).error || "" : "";
ta.classList.toggle("bad", !!err);
ta.setAttribute("aria-invalid", err ? "true" : "false");
why.textContent = err;
};
ta.oninput = () => { draft.extraBody = ta.value; check(); };
ta.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") cancelEdit(); };
check();
box.append(ta, why);
return box;
}
// iconPicker: a custom provider's icon — one of the built-in ones, or a
// picture of the user's own, which magpie keeps in ~/.config/magpie/icons.
// A routing group's icon: its providers' icons stacked, the first on top,
@@ -8186,7 +8239,7 @@ function baseAPIOf(p) {
// draftOf is a saved provider as its editor's form holds it.
function draftOf(p) {
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), extra: [], headers: headerRows(p.headers), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, unredacted: !!p.unredacted, pinUpstream: !!p.pinUpstream, balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, unredacted: !!p.unredacted, pinUpstream: !!p.pinUpstream, balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };
}
// duplicateProvider opens the Add form on a copy of p (#268): its URLs,
@@ -8598,6 +8651,8 @@ function drawEditor(p, presetID) {
} else {
ed.append(...field(t("Headers"), headerEditor(pr?.headerHints || []), t("Optional headers sent with every request to {p}, applied after auth.", { p: pr?.name || p?.name })));
}
// and JSON fields of the user's own for each request's body (#1604)
ed.append(...field(t("Extra body"), extraBodyEditor(), t("JSON fields added to the body of every request to the vendor. A field the request has already is kept; write \"!name\" to replace it. ${sessionId} is the conversation's id.")));
const proxies = el("div", "stack");
proxies.append(proxyPicker());
const perKey = keyProxyPicker(p);
@@ -8930,6 +8985,9 @@ function drawEditor(p, presetID) {
// new: an Add never replaces a provider that has the id already
const body = { id: p ? slug(draft.id) || p.id : draft.id, from: p?.id, name: draft.name, preset: draft.preset, key: draft.key || "", chat: draft.chat, responses: draft.responses, anthropic: draft.anthropic, gemini: (draft.gemini || "").trim(), catalog: draft.catalog, models: p ? chosenIds() : draft.extra, headers: headersOf(draft.headers), new: isNew };
if (isNew && draft.copyOf) body.copyOf = draft.copyOf;
const xb = extraBodyOf(draft.extraBody);
if (xb.error) { ed.querySelector(".extra-body textarea")?.focus({ preventScroll: true }); return editorError(t("Extra body: {why}", { why: xb.error }), "warn"); }
body.extraBody = xb.value;
if (decides || custom) body.decide = (custom && draft.api !== "decide" && !p?.decide ? "" : draft.decide || "").trim();
if ((body.decide || "").includes(WORKSPACE)) { ed.querySelector(".workspace-id")?.focus({ preventScroll: true }); return editorError(t("Give the workspace ID your API key belongs to, or pick the Token Plan"), "warn"); }
if (custom) {
+32
View File
@@ -1749,6 +1749,14 @@ const I18N = {
"+ Add header": "+ 添加请求头",
"Add the {h} header; its value is yours to fill in": "添加 {h} 请求头,值由你填写",
"Optional headers sent with every request to {p}, applied after auth.": "随每个发往 {p} 的请求发送的可选请求头,在鉴权之后应用。",
"Extra body": "额外请求体",
"JSON fields added to the body of every request to the vendor. A field the request has already is kept; write \"!name\" to replace it. ${sessionId} is the conversation's id.": "加进发往供应商的每个请求体里的 JSON 字段。请求里已有的字段会保留;写成 \"!name\" 则替换它。${sessionId} 是会话的 ID。",
"not valid JSON": "不是有效的 JSON",
"write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "请写一个 JSON 对象,例如 {\"prompt_cache_key\": \"${sessionId}\"}",
"a field needs a name": "字段需要一个名字",
"magpie sets {k} itself, so it can't be added": "{k} 由 magpie 自己设置,不能添加",
"{k} is named twice": "{k} 出现了两次",
"Extra body: {why}": "额外请求体:{why}",
// a provider's own proxy (#237)
"Global proxy": "全局代理",
"Direct": "直连",
@@ -6060,6 +6068,14 @@ const I18N = {
"+ Add header": "+ 新增請求頭",
"Add the {h} header; its value is yours to fill in": "新增 {h} 請求頭,值由你填寫",
"Optional headers sent with every request to {p}, applied after auth.": "隨每個發往 {p} 的請求傳送的可選請求頭,在鑑權之後應用。",
"Extra body": "額外請求體",
"JSON fields added to the body of every request to the vendor. A field the request has already is kept; write \"!name\" to replace it. ${sessionId} is the conversation's id.": "加進發往供應商的每個請求體裡的 JSON 欄位。請求裡已有的欄位會保留;寫成 \"!name\" 則取代它。${sessionId} 是對話的 ID。",
"not valid JSON": "不是有效的 JSON",
"write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "請寫一個 JSON 物件,例如 {\"prompt_cache_key\": \"${sessionId}\"}",
"a field needs a name": "欄位需要一個名稱",
"magpie sets {k} itself, so it can't be added": "{k} 由 magpie 自己設定,不能加入",
"{k} is named twice": "{k} 出現了兩次",
"Extra body: {why}": "額外請求體:{why}",
"Global proxy": "全域代理",
"Direct": "直連",
"Follows the proxy in Settings": "跟隨設定裡的代理",
@@ -10347,6 +10363,14 @@ const I18N = {
"+ Add header": "+ ヘッダーを追加",
"Add the {h} header; its value is yours to fill in": "{h} ヘッダーを追加します。値は自分で入力してください",
"Optional headers sent with every request to {p}, applied after auth.": "{p} へのすべてのリクエストに付ける任意のヘッダー。認証の後に適用されます。",
"Extra body": "追加ボディ",
"JSON fields added to the body of every request to the vendor. A field the request has already is kept; write \"!name\" to replace it. ${sessionId} is the conversation's id.": "ベンダーへのすべてのリクエストのボディに加える JSON フィールド。リクエストにすでにあるフィールドはそのまま残り、\"!name\" と書くと置き換えます。${sessionId} は会話の ID です。",
"not valid JSON": "有効な JSON ではありません",
"write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "JSON オブジェクトを書いてください(例: {\"prompt_cache_key\": \"${sessionId}\"})",
"a field needs a name": "フィールドには名前が必要です",
"magpie sets {k} itself, so it can't be added": "{k} は magpie が自分で設定するため、追加できません",
"{k} is named twice": "{k} が 2 回指定されています",
"Extra body: {why}": "追加ボディ: {why}",
"Global proxy": "グローバルプロキシ",
"Direct": "直接接続",
"Follows the proxy in Settings": "設定のプロキシに従う",
@@ -14653,6 +14677,14 @@ const I18N = {
"+ Add header": "+ Header hinzufügen",
"Add the {h} header; its value is yours to fill in": "Header {h} hinzufügen; den Wert tragen Sie selbst ein",
"Optional headers sent with every request to {p}, applied after auth.": "Optionale Header, die mit jeder Anfrage an {p} gesendet und nach der Authentifizierung angewendet werden.",
"Extra body": "Zusätzlicher Body",
"JSON fields added to the body of every request to the vendor. A field the request has already is kept; write \"!name\" to replace it. ${sessionId} is the conversation's id.": "JSON-Felder, die dem Body jeder Anfrage an den Anbieter hinzugefügt werden. Ein Feld, das die Anfrage schon hat, bleibt erhalten; schreib \"!name\", um es zu ersetzen. ${sessionId} ist die ID der Unterhaltung.",
"not valid JSON": "kein gültiges JSON",
"write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "schreib ein JSON-Objekt, etwa {\"prompt_cache_key\": \"${sessionId}\"}",
"a field needs a name": "ein Feld braucht einen Namen",
"magpie sets {k} itself, so it can't be added": "{k} setzt magpie selbst, es kann nicht hinzugefügt werden",
"{k} is named twice": "{k} kommt zweimal vor",
"Extra body: {why}": "Zusätzlicher Body: {why}",
"Global proxy": "Globaler Proxy",
"Direct": "Direkt",
"Follows the proxy in Settings": "Folgt dem Proxy aus den Einstellungen",
+83
View File
@@ -0,0 +1,83 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A provider's extra body fields (#1604) are saved from the editor, shown
// back to it, kept by a save that doesn't send them, cleared by {}, and a
// save naming a field magpie sets itself is refused with why.
func TestProviderExtraBodySaved(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", os.Getenv("HOME"))
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
mux := http.NewServeMux()
providerRoutes(mux, nil)
post := func(action, body string) *httptest.ResponseRecorder {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/"+action, strings.NewReader(body)))
return w
}
stored := func() string {
t.Helper()
p, err := provider.Find("relay")
if err != nil {
t.Fatal(err)
}
if p.ExtraBody == nil {
return ""
}
b, _ := json.Marshal(p.ExtraBody)
return string(b)
}
const u = "http://127.0.0.1:1/v1"
if w := post("save", `{"id":"relay","name":"Relay","key":"sk-a","responses":"`+u+`","icon":"generic","new":true,"extraBody":{"prompt_cache_key":"${sessionId}","!service_tier":"flex"}}`); w.Code != 200 {
t.Fatalf("save: %d %s", w.Code, w.Body)
}
if got := stored(); got != `{"!service_tier":"flex","prompt_cache_key":"${sessionId}"}` {
t.Fatalf("stored %s", got)
}
// the editor is given them
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil))
if !strings.Contains(w.Body.String(), `"extraBody":{"!service_tier":"flex","prompt_cache_key":"${sessionId}"}`) {
t.Errorf("not shown: %s", w.Body)
}
// a save without them keeps them
if w := post("save", `{"id":"relay","from":"relay","name":"Relay","responses":"`+u+`","icon":"generic"}`); w.Code != 200 {
t.Fatalf("save: %d %s", w.Code, w.Body)
}
if got := stored(); !strings.Contains(got, "prompt_cache_key") {
t.Fatalf("a save without them lost them: %s", got)
}
// one naming the model, or the conversation, is refused and changes nothing
for _, bad := range []string{`{"model":"x"}`, `{"!messages":[]}`, `{"input":"x"}`} {
w := post("save", `{"id":"relay","from":"relay","name":"Relay","responses":"`+u+`","icon":"generic","extraBody":`+bad+`}`)
if w.Code == 200 || !strings.Contains(w.Body.String(), "can't set") {
t.Errorf("%s: %d %s", bad, w.Code, w.Body)
}
}
if got := stored(); !strings.Contains(got, "prompt_cache_key") {
t.Fatalf("a refused save changed them: %s", got)
}
// {} clears them
if w := post("save", `{"id":"relay","from":"relay","name":"Relay","responses":"`+u+`","icon":"generic","extraBody":{}}`); w.Code != 200 {
t.Fatalf("save: %d %s", w.Code, w.Body)
}
if got := stored(); got != "" {
t.Fatalf("{} left %s", got)
}
}
+24 -6
View File
@@ -5,6 +5,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@@ -73,6 +74,8 @@ type providerJSON struct {
Website string `json:"website"`
KeysURL string `json:"keysUrl"`
Headers map[string]string `json:"headers,omitempty"`
// JSON fields added to each request's body (provider.ExtraBody, #1604)
ExtraBody provider.ExtraBody `json:"extraBody,omitempty"`
// the API the user gave a custom provider's Base URL as (BaseAPI)
BaseAPI string `json:"baseAPI,omitempty"`
// the vendor searches the web by itself (provider.Searches)
@@ -495,7 +498,7 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON {
ID: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Host: p.Host(),
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(),
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL,
Ready: p.Ready(), Chosen: p.Picks(), Models: []modelJSON{}, Agents: []providerAgent{},
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, Unlisted: p.Unlisted, Off: p.Off, Contexts: p.Contexts,
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), PriceRate: p.PriceRate,
@@ -1169,6 +1172,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if pr, err := provider.FromPreset(in.Preset); err == nil && in.Chat == "" && in.Responses == "" && in.Anthropic == "" && in.Gemini == "" {
pr.Key, pr.Models, pr.Fallback, pr.Headers, pr.BalanceToken, pr.Contexts = in.Key, in.Models, in.Fallback, in.Headers, in.BalanceToken, in.Contexts
pr.ZhipuTeam = in.ZhipuTeam
pr.ExtraBody = in.ExtraBody
pr.SecretAccessKey = in.SecretAccessKey
pr.Vertex = in.Vertex
pr.Searches = in.Searches
@@ -1187,6 +1191,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
}
in = pr
}
// fields the body can't be given are refused, not dropped
// unseen (#1604)
if why := provider.ExtraBodyOK(in.ExtraBody); why != "" {
fail(rw, errors.New(why))
return
}
cc, keepCC, err := concurrencyOf(req.MaxConcurrency)
if err != nil {
fail(rw, err)
@@ -1310,6 +1320,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if in.ZhipuTeam == nil && old != nil {
in.ZhipuTeam = old.ZhipuTeam
}
// and its extra body fields: {} clears them
if in.ExtraBody == nil && old != nil {
in.ExtraBody = old.ExtraBody
}
// a Volcengine access key likewise: its ID kept when left
// out, its Secret when sent blank, unless the form dropped it
if req.AccessKeyID == nil && old != nil {
@@ -1995,11 +2009,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
// typed is the saved provider p as the editor's form has it (in), for
// Refresh and Test models before a Save: a key pasted to replace the saved
// one is the one asked with, and the URLs, headers and proxy typed are
// where and how. Nothing is saved. What the form left blank (the key above
// all) is the saved one's; the provider's other keys are kept. A Vertex AI
// provider's project, location, credentials file and service account are
// the ones typed, spelled as a Save keeps them, unless no project is.
// one is the one asked with, and the URLs, headers, extra body and proxy
// typed are where and how. Nothing is saved. What the form left blank (the
// key above all) is the saved one's; the provider's other keys are kept. A
// Vertex AI provider's project, location, credentials file and service
// account are the ones typed, spelled as a Save keeps them, unless no
// project is.
func typed(p, in provider.Provider, proxy *string) provider.Provider {
if k := strings.TrimSpace(in.Key); k != "" && k != p.Key {
p.Key, p.KeyName, p.KeyProtocol, p.KeyWeight = k, "", "", 0
@@ -2018,6 +2033,9 @@ func typed(p, in provider.Provider, proxy *string) provider.Provider {
if in.Headers != nil {
p.Headers = in.Headers
}
if in.ExtraBody != nil {
p.ExtraBody = in.ExtraBody
}
if proxy != nil {
p.Proxy = *proxy
}
+143
View File
@@ -0,0 +1,143 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A provider's Extra body (#1604, Luc-xz: a relay that turns Responses
// requests away without a prompt_cache_key): the editor shows the saved
// JSON, says live why what is typed can't be saved — not JSON, not an
// object, a field magpie sets itself (model, stream, the conversation) —
// and a Save is held until it can; a good one is saved as an object, sent
// with Test before a Save, and an emptied box clears it ({}). It fits a
// narrow window. In English, Chinese, Japanese and German, Chromium and
// WebKit.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const relay = {
id: "relay", name: "Relay", preset: "", icon: "generic", chat: "", responses: "https://relay.example.com/v1", anthropic: "", catalog: "", baseAPI: "responses",
models: [{ id: "gpt-5.1", name: "gpt-5.1", on: true }], agents: [], fallback: [], headers: {},
extraBody: { prompt_cache_key: "${sessionId}" },
key: { set: true, masked: "sk-…one" }, keyList: [{ id: "k1", name: "", masked: "sk-…one", on: true, active: true }],
balanceToken: { takes: false, set: false }, proxy: "",
};
function serve(lang, calls) {
const providers = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname.startsWith("/api/provider/")) {
const body = route.request().postDataJSON();
calls.push([url.pathname.slice(14), body]);
if (url.pathname === "/api/provider/test") return json({ results: (body.test || ["gpt-5.1"]).map((model) => ({ protocol: "responses", ok: true, ms: 9, model })) });
if (url.pathname === "/api/provider/save") return json(providers);
}
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const words = {
en: { label: "Extra body", save: "Save", test: "Test models", model: "magpie sets model itself", object: "write a JSON object", json: "not valid JSON" },
zh: { label: "额外请求体", save: "保存", test: "测试模型", model: "model 由 magpie 自己设置", object: "请写一个 JSON 对象", json: "不是有效的 JSON" },
ja: { label: "追加ボディ", save: "保存", test: "モデルをテスト", model: "model は magpie が自分で設定", object: "JSON オブジェクトを書いてください", json: "有効な JSON ではありません" },
de: { label: "Zusätzlicher Body", save: "Speichern", test: "Modelle testen", model: "model setzt magpie selbst", object: "schreib ein JSON-Objekt", json: "kein gültiges JSON" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
const w = words[lang];
test(`${engine} ${lang}: Extra body is checked as it is typed, saved, tested and cleared`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 900, height: 900 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const calls = [];
await page.route("**/*", serve(lang, calls));
await page.goto("http://magpie.test/?view=providers");
const open = async () => {
await page.locator(".row.provider", { hasText: "Relay" }).click();
const ed = page.locator(".editor");
await ed.locator(".extra-body textarea").waitFor();
return ed;
};
let ed = await open();
const box = ed.locator(".extra-body textarea");
const why = ed.locator(".extra-body .why");
assert.equal(await page.locator(`label[for="${await box.getAttribute("id")}"]`).textContent(), w.label, "labelled");
assert.deepEqual(JSON.parse(await box.inputValue()), { prompt_cache_key: "${sessionId}" }, "the saved JSON is shown");
assert.ok(!(await box.evaluate((e) => e.classList.contains("bad"))));
assert.equal(await why.textContent(), "");
const said = async (text, want) => {
await box.fill(text);
assert.ok(await box.evaluate((e) => e.classList.contains("bad")), `${text} is marked`);
assert.equal(await box.getAttribute("aria-invalid"), "true");
assert.ok((await why.textContent()).includes(want), `${text}: ${await why.textContent()}`);
assert.ok(await why.isVisible());
};
await said(`{"model": "gpt-4o"}`, w.model);
await said(`{"!stream": false}`, "stream");
await said(`{"messages": []}`, "messages");
await said(`[1, 2]`, w.object);
await said(`{"a":`, w.json);
// a Save is held while it can't be saved, and says why
await ed.locator(".bar").getByRole("button", { name: w.save, exact: true }).click();
await page.waitForTimeout(200);
assert.deepEqual(calls.map((c) => c[0]), [], "nothing saved");
assert.ok(await ed.isVisible());
assert.ok(await box.evaluate((e) => e === document.activeElement), "the box is focused");
// a good one: no mark, Test asks with it before a Save
const good = { prompt_cache_key: "${sessionId}", "!service_tier": "flex", metadata: { app: "magpie" } };
await box.fill(JSON.stringify(good, null, 2));
assert.ok(!(await box.evaluate((e) => e.classList.contains("bad"))));
assert.equal(await box.getAttribute("aria-invalid"), "false");
assert.ok(!(await why.isVisible()));
await ed.locator(".mfoot").getByRole("button", { name: w.test, exact: true }).click();
for (let i = 0; i < 60 && !calls.length; i++) await page.waitForTimeout(50);
assert.equal(calls[0][0], "test");
assert.deepEqual(calls[0][1].extraBody, good, "Test asks with the extra body typed");
// the narrow window: the box and its reason stay inside the editor
await page.setViewportSize({ width: 420, height: 900 });
await box.fill(`{"model": "a-model-name-long-enough-to-need-wrapping-in-a-narrow-window-x"}`);
const fits = await page.evaluate(() => {
const ed = document.querySelector(".editor").getBoundingClientRect();
return [...document.querySelectorAll(".extra-body textarea, .extra-body .why")].every((e) => { const r = e.getBoundingClientRect(); return r.left >= ed.left - 0.5 && r.right <= ed.right + 0.5; });
});
assert.ok(fits, "fits a narrow window");
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth), "no sideways scroll");
await page.setViewportSize({ width: 900, height: 900 });
await box.fill(JSON.stringify(good));
await ed.locator(".bar").getByRole("button", { name: w.save, exact: true }).click();
for (let i = 0; i < 60 && !calls.some((c) => c[0] === "save"); i++) await page.waitForTimeout(50);
const saved = calls.find((c) => c[0] === "save");
assert.ok(saved, "saved");
assert.deepEqual(saved[1].extraBody, good, "saved as an object");
// emptied: a Save clears it
calls.length = 0;
await page.locator(".editor").waitFor({ state: "hidden" });
ed = await open();
await ed.locator(".extra-body textarea").fill("");
await ed.locator(".bar").getByRole("button", { name: w.save, exact: true }).click();
for (let i = 0; i < 60 && !calls.some((c) => c[0] === "save"); i++) await page.waitForTimeout(50);
assert.deepEqual(calls.find((c) => c[0] === "save")?.[1].extraBody, {}, "an empty box clears it");
assert.deepEqual(errors, []);
});
}
}
+1 -1
View File
@@ -171,7 +171,7 @@ func (q Provider) detectOne(proto Protocol, m string, wait time.Duration) (Detec
}
return d, func(ctx context.Context) Result {
u, body := tiny(k, proto, UpstreamName(q, m))
return probe(ctx, k, proto, u, k.Prepare([]byte(body)), m, wait)
return probe(ctx, k, proto, u, k.tested(body), m, wait)
}
}
+182
View File
@@ -0,0 +1,182 @@
package provider
// A provider's extraBody (Luc-xz, #1604): JSON fields the user adds to the
// body of every request magpie sends the provider — a relay that turns a
// Responses request away without a prompt_cache_key, say — as Headers adds
// headers. They are merged at the top level of the body as it goes out,
// whichever API it is on (Chat, Responses, Messages, Gemini) and whether it
// was relayed or translated (gateway.forwardOnce):
//
// - A field the body has already — the client's own, or what magpie put
// there for it — is kept: the user's value fills in what is missing.
// - A name written with a "!" before it ("!prompt_cache_key") is forced:
// it replaces the body's own.
// - ${sessionId} in a string value, at any depth, is the conversation's
// id: the session the agent names (its session header), else one
// magpie derives from the conversation's first user message — the same
// for every turn of it. A fixed string would put every session on one
// cache key.
// - The fields that carry the conversation, or that magpie must decide
// for routing and streaming to work (ExtraBodyReserved), can't be set:
// a save naming one is refused, and one written into the file by hand
// is left out.
//
// The editor's Test and Detect send them too, on their own session
// (tested), so a relay that turns a request away without them still
// answers its Test. A request that only counts tokens gets none of them,
// nor one to another API (embeddings, images, video, a decision API's):
// the fields are for asking the model for a reply. Neither does a
// signed-in account's: its body is the agent's own, as its headers are.
import (
"bytes"
"crypto/rand"
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
)
// ExtraBody is a provider's extra body fields, each value as the user
// wrote it, a name that begins with "!" forced.
type ExtraBody map[string]json.RawMessage
// UnmarshalJSON reads an object; anything else written by hand (a string,
// a list) is read as none, rather than failing the whole providers file.
func (e *ExtraBody) UnmarshalJSON(b []byte) error {
var m map[string]json.RawMessage
if json.Unmarshal(b, &m) != nil {
*e = nil
return nil
}
*e = m
return nil
}
// ExtraBodyReserved are the fields extraBody can't set: the model and
// whether to stream, which magpie decides for routing and reads the reply
// by, and the conversation itself — its messages, input or contents, its
// system prompt and instructions, its tools.
var ExtraBodyReserved = []string{"model", "stream", "messages", "input", "contents", "system", "systemInstruction", "system_instruction", "instructions", "tools"}
// SessionPlaceholder is what a string value of extraBody writes for the
// conversation's id.
const SessionPlaceholder = "${sessionId}"
// extraName is a field's name without its "!", and whether it is forced.
func extraName(k string) (string, bool) {
n, forced := strings.CutPrefix(strings.TrimSpace(k), "!")
return strings.TrimSpace(n), forced
}
// ExtraBodyOK says what is wrong with an extraBody, "" when nothing is.
func ExtraBodyOK(e ExtraBody) string {
seen := map[string]bool{}
for _, k := range slices.Sorted(maps.Keys(e)) {
n, _ := extraName(k)
switch {
case n == "":
return "an extra body field needs a name"
case slices.Contains(ExtraBodyReserved, n):
return fmt.Sprintf("extra body can't set %q: magpie sets the model, stream and the conversation itself", n)
case seen[n]:
return fmt.Sprintf("extra body names %q twice", n)
case !json.Valid(e[k]):
return fmt.Sprintf("extra body's %q is not JSON", n)
}
seen[n] = true
}
return ""
}
// cleanExtraBody drops what can't be sent (ExtraBodyOK's faults, for a
// file written by hand), and is nil when nothing is left.
func cleanExtraBody(e ExtraBody) ExtraBody {
out := ExtraBody{}
seen := map[string]bool{}
for _, k := range slices.Sorted(maps.Keys(e)) {
n, forced := extraName(k)
if n == "" || slices.Contains(ExtraBodyReserved, n) || seen[n] || !json.Valid(e[k]) {
continue
}
seen[n] = true
v := bytes.TrimSpace(e[k])
if forced {
out["!"+n] = slices.Clone(v)
} else {
out[n] = slices.Clone(v)
}
}
if len(out) == 0 {
return nil
}
return out
}
// WithExtraBody is body with the provider's extra fields merged in, as the
// package's comment says; session is the conversation's id for
// ${sessionId}. A body that isn't a JSON object goes as it came.
func (p Provider) WithExtraBody(body []byte, session string) []byte {
if len(p.ExtraBody) == 0 || p.Account != nil {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))
dec.UseNumber()
var m map[string]any
if dec.Decode(&m) != nil || m == nil {
return body
}
changed := false
for k, raw := range p.ExtraBody {
n, forced := extraName(k)
if n == "" || slices.Contains(ExtraBodyReserved, n) {
continue
}
if _, has := m[n]; has && !forced {
continue
}
d := json.NewDecoder(bytes.NewReader(raw))
d.UseNumber()
var v any
if d.Decode(&v) != nil {
continue
}
m[n], changed = withSession(v, session), true
}
if !changed {
return body
}
var out bytes.Buffer
enc := json.NewEncoder(&out)
enc.SetEscapeHTML(false) // <, > and & as the agent wrote them
if enc.Encode(m) != nil {
return body
}
return bytes.TrimSuffix(out.Bytes(), []byte("\n"))
}
// withSession is v with ${sessionId} in its strings, at any depth, as
// session.
func withSession(v any, session string) any {
switch x := v.(type) {
case string:
return strings.ReplaceAll(x, SessionPlaceholder, session)
case map[string]any:
for k, e := range x {
x[k] = withSession(e, session)
}
case []any:
for i, e := range x {
x[i] = withSession(e, session)
}
}
return v
}
// tested is a test's or a detection's tiny request body for p as it goes
// out: the extra fields, on a session of the test's own, then what the
// backend adjusts.
func (p Provider) tested(body string) []byte {
return p.Prepare(p.WithExtraBody([]byte(body), "magpie-test-"+strings.ToLower(rand.Text()[:12])))
}
+148
View File
@@ -0,0 +1,148 @@
package provider
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// The editor's Test and Detect ask with the extra fields too, so a relay
// that turns a request away without a prompt_cache_key (#1604) answers
// them, on a session id of the test's own.
func TestExtraBodyTested(t *testing.T) {
detectHome(t)
const model = "gpt-test"
var keys []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method + " " + r.URL.Path {
case "GET /v1/models":
io.WriteString(w, `{"data":[{"id":"`+model+`"}]}`)
case "POST /v1/responses":
var in struct {
Key string `json:"prompt_cache_key"`
}
if json.NewDecoder(r.Body).Decode(&in) != nil || in.Key == "" {
http.Error(w, `{"error":{"message":"prompt_cache_key is required"}}`, http.StatusBadRequest)
return
}
keys = append(keys, in.Key)
io.WriteString(w, `{"object":"response","status":"completed","output":[]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
p := Provider{ID: "relay", Key: "sk-relay", Responses: srv.URL + "/v1", Models: []string{model},
ExtraBody: ExtraBody{"prompt_cache_key": json.RawMessage(`"${sessionId}"`)}}
ctx := context.Background()
if rs := p.Test(ctx); len(rs) != 1 || !rs[0].OK {
t.Fatalf("Test: %+v", rs)
}
if rs := p.TestModels(ctx, []string{model}); len(rs) != 1 || !rs[0].OK {
t.Fatalf("TestModels: %+v", rs)
}
rs, err := p.Detect(ctx, srv.URL, model)
if err != nil || len(rs) != len(detectProtocols) || !rs[1].Result.OK {
t.Fatalf("Detect: %v, %+v", err, rs)
}
if len(keys) != 3 || !strings.HasPrefix(keys[0], "magpie-test-") || keys[0] == keys[1] {
t.Errorf("asked with %q", keys)
}
}
func TestExtraBodyOK(t *testing.T) {
for _, c := range []struct {
in, want string
}{
{`{}`, ""},
{`{"prompt_cache_key":"${sessionId}","!service_tier":"flex","metadata":{"a":[1,2]}}`, ""},
{`{"model":"x"}`, `can't set "model"`},
{`{"!stream":true}`, `can't set "stream"`},
{`{"messages":[]}`, `can't set "messages"`},
{`{"input":"x"}`, `can't set "input"`},
{`{"contents":[]}`, `can't set "contents"`},
{`{"!":1}`, "needs a name"},
{`{"user":"a","!user":"b"}`, `names "user" twice`},
} {
var e ExtraBody
if err := json.Unmarshal([]byte(c.in), &e); err != nil {
t.Fatal(err)
}
got := ExtraBodyOK(e)
if (c.want == "") != (got == "") || !strings.Contains(got, c.want) {
t.Errorf("%s: %q, want %q", c.in, got, c.want)
}
}
if got := ExtraBodyOK(ExtraBody{"a": json.RawMessage(`{`)}); !strings.Contains(got, "not JSON") {
t.Errorf("bad value: %q", got)
}
}
// A providers file written by hand with something other than an object, or
// with fields extraBody can't set, still reads: the rest of it is kept.
func TestExtraBodyReadByHand(t *testing.T) {
var ps []Provider
if err := json.Unmarshal([]byte(`[{"id":"a","extraBody":"oops"},{"id":"b","extraBody":{"model":"x","messages":[],"user":"u"," !tier ":"t"}}]`), &ps); err != nil {
t.Fatal(err)
}
if ps[0].ExtraBody != nil {
t.Errorf("a string read as %v", ps[0].ExtraBody)
}
got := cleanExtraBody(ps[1].ExtraBody)
if len(got) != 2 || string(got["user"]) != `"u"` || string(got["!tier"]) != `"t"` {
t.Errorf("cleaned to %v", got)
}
if cleanExtraBody(ExtraBody{"model": json.RawMessage(`1`)}) != nil {
t.Error("nothing left isn't nil")
}
}
func TestWithExtraBody(t *testing.T) {
p := Provider{ExtraBody: ExtraBody{
"prompt_cache_key": json.RawMessage(`"${sessionId}"`),
"metadata": json.RawMessage(`{"tags":["s-${sessionId}"],"n":1}`),
"!service_tier": json.RawMessage(`"flex"`),
"model": json.RawMessage(`"never"`),
"big": json.RawMessage(`12345678901234567890`),
}}
out := p.WithExtraBody([]byte(`{"model":"m","service_tier":"auto","input":"a<b>&c","prompt_cache_key":"mine"}`), "S1")
var m map[string]any
if err := json.Unmarshal(out, &m); err != nil {
t.Fatalf("%s: %v", out, err)
}
if m["model"] != "m" || m["prompt_cache_key"] != "mine" || m["service_tier"] != "flex" || m["input"] != "a<b>&c" {
t.Errorf("merged %s", out)
}
if !strings.Contains(string(out), `"tags":["s-S1"]`) || !strings.Contains(string(out), `"big":12345678901234567890`) {
t.Errorf("values %s", out)
}
if !strings.Contains(string(out), `"a<b>&c"`) {
t.Errorf("escaped %s", out)
}
out = p.WithExtraBody([]byte(`{"model":"m"}`), "S2")
if !strings.Contains(string(out), `"prompt_cache_key":"S2"`) {
t.Errorf("filled %s", out)
}
// a body that isn't an object goes as it came
for _, b := range []string{`[1]`, `not json`, ``} {
if got := string(p.WithExtraBody([]byte(b), "S")); got != b {
t.Errorf("%q became %q", b, got)
}
}
// a signed-in account's body is the agent's own
acct := p
acct.Account = &Account{}
if got := string(acct.WithExtraBody([]byte(`{"model":"m"}`), "S")); got != `{"model":"m"}` {
t.Errorf("account body %s", got)
}
// none set: the body's bytes as they were
if got := string((Provider{}).WithExtraBody([]byte(`{"b":1, "a":2}`), "S")); got != `{"b":1, "a":2}` {
t.Errorf("unchanged body %s", got)
}
}
+8
View File
@@ -179,6 +179,12 @@ type Provider struct {
// ignore them: their auth is the agent's own.
Headers map[string]string `json:"headers,omitempty"`
// ExtraBody are JSON fields added to the body of every request to the
// vendor (#1604), filling in what the body lacks, or replacing it for a
// name written "!name"; ${sessionId} in a value is the conversation's
// id (extrabody.go). Signed-in agent accounts ignore it, as Headers.
ExtraBody ExtraBody `json:"extraBody,omitempty"`
// Searches says the vendor answers a web search tool offered on its
// Anthropic or Responses API by itself (web_search_20250305,
// web_search): a relay in front of Anthropic's or OpenAI's API, which
@@ -451,6 +457,7 @@ func (p Provider) clone() Provider {
p.Models = slices.Clone(p.Models)
p.PickedFrom = slices.Clone(p.PickedFrom)
p.Headers = maps.Clone(p.Headers)
p.ExtraBody = maps.Clone(p.ExtraBody)
p.AccountProxies = maps.Clone(p.AccountProxies)
p.AccountCaps = maps.Clone(p.AccountCaps)
p.AccountNames = maps.Clone(p.AccountNames)
@@ -1063,6 +1070,7 @@ func normalize(p Provider) Provider {
// a preset's provider keeps its headers too: the preset gives the
// endpoints and catalog, the headers say which workspace or app it is
p.Headers = cleanHeaders(p.Headers)
p.ExtraBody = cleanExtraBody(p.ExtraBody)
if pr := Preset(p.Preset); pr != nil {
if p.Icon == "" {
p.Icon = pr.Icon
+4 -4
View File
@@ -51,7 +51,7 @@ func (p Provider) Test(ctx context.Context) []Result {
return []Result{{Protocol: proto, Model: model, Error: "no key is on for this endpoint"}}
}
url, body := tiny(q, proto, UpstreamName(p, model))
return []Result{probe(ctx, q, proto, url, q.Prepare([]byte(asClient(client, proto, body))), model, testWait)}
return []Result{probe(ctx, q, proto, url, q.tested(asClient(client, proto, body)), model, testWait)}
}
if p.isClaudeAccount() {
return []Result{p.testClaude(ctx, p.testModel(p, Anthropic))}
@@ -68,7 +68,7 @@ func (p Provider) Test(ctx context.Context) []Result {
continue
}
url, body := tiny(q, proto, UpstreamName(p, model))
out = append(out, probe(ctx, q, proto, url, q.Prepare([]byte(body)), model, testWait))
out = append(out, probe(ctx, q, proto, url, q.tested(body), model, testWait))
}
if p.IsRemoteMagpie() {
// The model list already checked its key and named its decisions.
@@ -312,7 +312,7 @@ func (p Provider) testOne(ctx context.Context, model string) Result {
r := probe(ctx, q, proto, url, []byte(body), model, drawWait)
if !r.OK && (r.Status == 404 || r.Status == 405) {
url, body := tiny(q, proto, model)
if c := probe(ctx, q, proto, url, q.Prepare([]byte(body)), model, testWait); c.OK {
if c := probe(ctx, q, proto, url, q.tested(body), model, testWait); c.OK {
return c
}
}
@@ -322,7 +322,7 @@ func (p Provider) testOne(ctx context.Context, model string) Result {
if client != "" {
body = asClient(client, proto, body)
}
return probe(ctx, q, proto, url, q.Prepare([]byte(body)), model, testWait)
return probe(ctx, q, proto, url, q.tested(body), model, testWait)
}
// keyFor is p using the first key on that works with proto: one made for