gateway: a relay that searches the web by itself is sent Claude Code's WebSearch as it was sent (#359) (#365)

magpie tells the APIs that search by themselves by their host (api.anthropic.com), so a relay in front of Anthropic's API was given magpie's search instead: the request was parsed and built again, and with no searcher set up in magpie the WebSearch tool was left out altogether. A provider now has Searches (magpie provider set <id> search=yes, or the editor's Web search row for a custom provider): a web search offered on its Anthropic or Responses API goes to it as sent. It counts only on an API the provider has an address for, so a Chat-only one isn't taken as searching, and the editor shows the row only while an Anthropic or Responses URL is filled in. A provider said to search isn't one magpie searches with for other models: that would spend the relay's quota, and a relay serving only Claude Code refuses magpie's own request, which has no metadata.user_id.

TestWebSearchOfARelayThatSearches fails without the change (the request built again, magpie searching with the relay, a Chat-only relay taken as searching); provider-search.test.cjs added (Chromium, WebKit, en/zh), its Chat-only case failing without the row's gate. Checked against real Claude Code 2.1.285 through a sub2api relay in claude_code_only mode: WebSearch returns results with search=yes. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass but for TestPluginProxy, which fails on main (813fdcb) as well here.

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Randy
2026-10-01 11:10:41 +08:00
committed by GitHub
co-authored by Claude
parent 5523eb176a
commit e8315b18ed
9 changed files with 318 additions and 7 deletions
+9 -1
View File
@@ -64,6 +64,11 @@ func searchesItself(p provider.Provider, proto provider.Protocol) bool {
// Grok by its id: moved to its plugin, its account is the plugin's
return (p.Account.Agent == "codex" || p.ID == "grok") && proto == provider.Responses
}
// a relay said to search (#359), on an API it has an address for: one
// with only a Chat address would be sent no search tool at all
if p.Searches && (proto == provider.Anthropic || proto == provider.Responses) && p.Base(proto) != "" {
return true
}
return slices.Contains(searchHosts[proto], provider.HostOf(p.Base(proto)))
}
@@ -89,9 +94,12 @@ func searchAsked(proto provider.Protocol, body []byte) bool {
// searcher is the model magpie searches with: the first of the providers
// that search by themselves, with a small model of theirs, as searching
// needs no more.
// needs no more. A relay said to search is left out: it would spend the
// relay's quota on other models' searches, and one that serves only Claude
// Code refuses magpie's own request, which has no metadata.user_id (#359).
func searcher() (provider.Provider, string, bool) {
rank := func(p provider.Provider) int {
p.Searches = false
switch {
case p.Account != nil && p.Account.Agent == "claude":
return 0
+110
View File
@@ -336,3 +336,113 @@ func TestMovedGrokSearchesItself(t *testing.T) {
t.Error("another plugin's provider searches by itself")
}
}
// A relay in front of Anthropic's API searches as Anthropic does, which
// magpie can't tell from its host (#359). One that serves only Claude Code
// refuses a request without Claude Code's metadata.user_id. Set as
// searching by itself, it is sent Claude Code's WebSearch as it was sent;
// not set, the request built again for it keeps the metadata.
func TestWebSearchOfARelayThatSearches(t *testing.T) {
var mu sync.Mutex
var got []map[string]json.RawMessage
relay := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1/models" {
io.WriteString(w, `{"data":[{"id":"claude-haiku-4-5"}]}`)
return
}
if r.URL.Path != "/v1/messages" {
http.NotFound(w, r)
return
}
b, _ := io.ReadAll(r.Body)
var q map[string]json.RawMessage
json.Unmarshal(b, &q)
mu.Lock()
got = append(got, q)
mu.Unlock()
var md struct {
UserID string `json:"user_id"`
}
if json.Unmarshal(q["metadata"], &md); md.UserID == "" {
w.WriteHeader(http.StatusForbidden)
io.WriteString(w, `{"type":"error","error":{"type":"permission_error","message":"This group is restricted to the official Claude Code client."}}`)
return
}
if string(q["stream"]) == "true" {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"claude-haiku-4-5","content":[],"usage":{"input_tokens":5}}}`,
`event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Go 1.27.1 is out."}}`,
`event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`,
`event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}`,
`event: message_stop`+"\n"+`data: {"type":"message_stop"}`))
return
}
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"m","type":"message","role":"assistant","model":"claude-haiku-4-5","content":[{"type":"text","text":"Go 1.27.1 is out."}],"stop_reason":"end_turn","usage":{"input_tokens":5,"output_tokens":5}}`)
}))
defer relay.Close()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir()) // no signed-in agent searches for it
// Claude Code 2.1.285's WebSearch
body := `{"model":"relay/claude-haiku-4-5","max_tokens":32000,"stream":false,
"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.285.3c7; cc_entrypoint=cli;"},{"type":"text","text":"You are Claude Code, Anthropic's official CLI for Claude."},{"type":"text","text":"You are an assistant for performing a web search tool use"}],
"messages":[{"role":"user","content":"Perform a web search for the query: latest go"}],
"tools":[{"type":"web_search_20250305","name":"web_search","max_uses":8}],
"metadata":{"user_id":"{\"device_id\":\"d\",\"session_id\":\"s\"}"}}`
ask := func() *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
req.Header.Set("User-Agent", "claude-cli/2.1.285 (external, cli)")
req.Header.Set("x-app", "cli")
New().Handler().ServeHTTP(rec, req)
return rec
}
p := provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: relay.URL, Models: []string{"claude-haiku-4-5"}, Searches: true}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
// it searches for Claude Code, not for magpie's other models: it would
// spend the relay's quota, and refuse magpie's request without metadata
if _, err := p.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
if sp, _, ok := searcher(); ok {
t.Fatalf("magpie searches with %s", sp.ID)
}
if rec := ask(); rec.Code != 200 || !strings.Contains(rec.Body.String(), "Go 1.27.1 is out.") {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
var tools []map[string]any
var system []any
json.Unmarshal(got[0]["tools"], &tools)
json.Unmarshal(got[0]["system"], &system)
if len(tools) != 1 || tools[0]["type"] != "web_search_20250305" || tools[0]["max_uses"] != float64(8) || len(system) != 3 {
t.Fatalf("sent %s %s", got[0]["tools"], got[0]["system"])
}
// not said to search, it is given no search of its own: magpie has no
// searcher here, so the request is built again, without the tool
got = nil
p.Searches = false
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
if rec := ask(); rec.Code != 200 || !strings.Contains(rec.Body.String(), "Go 1.27.1 is out.") {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
if !strings.Contains(string(got[0]["metadata"]), `device_id`) || strings.Contains(string(got[0]["tools"]), "web_search") {
t.Fatalf("sent %s %s", got[0]["metadata"], got[0]["tools"])
}
// said to search with only a Chat address, it has no API to search on
chat := provider.Provider{ID: "chatrelay", Chat: relay.URL + "/v1", Searches: true}
for _, proto := range []provider.Protocol{provider.Anthropic, provider.Responses, provider.Chat} {
if searchesItself(chat, proto) {
t.Errorf("a Chat-only relay searches by itself on %s", proto)
}
}
}
+21 -3
View File
@@ -3542,7 +3542,7 @@ const PROTOS = [["chat", "OpenAI", "Chat Completions — most agents"], ["respon
// 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, catalog: p.catalog, key: "", api: p.chat ? "openai" : p.anthropic ? "anthropic" : p.responses ? "responses" : "openai", chosen: p.models.filter((m) => m.on).map((m) => m.id), extra: [], headers: headerRows(p.headers), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), keysUrl: p.keysUrl || "", ...proxyDraft(p) };
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, catalog: p.catalog, key: "", api: p.chat ? "openai" : p.anthropic ? "anthropic" : p.responses ? "responses" : "openai", chosen: p.models.filter((m) => m.on).map((m) => m.id), extra: [], headers: headerRows(p.headers), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), keysUrl: p.keysUrl || "", ...proxyDraft(p) };
}
// duplicateProvider opens the Add form on a copy of p (#268): its URLs,
@@ -3662,6 +3662,9 @@ function drawEditor(p, presetID) {
};
if (p && !p.account && !custom) idField();
let fillEndpoints = () => {};
// the Web search row, shown while there is an API it can search on
const searchable = () => !!((draft.anthropic || "").trim() || (draft.responses || "").trim());
let showSearch = () => {};
if (custom) {
name = input(draft.name, t("e.g. My Relay"));
name.oninput = () => { draft.name = name.value; if (isNew) draft.id = slug(name.value); };
@@ -3692,12 +3695,13 @@ function drawEditor(p, presetID) {
slide(seg, "api");
url.placeholder = v === "anthropic" ? "https://…" : "https://…/v1";
fillEndpoints();
showSearch();
};
seg.append(b);
}
queueMicrotask(() => slide(seg, "api"));
url = input(draft[apiField[draft.api]], draft.api === "anthropic" ? "https://…" : "https://…/v1", "url");
url.oninput = () => { draft[apiField[draft.api]] = url.value; };
url.oninput = () => { draft[apiField[draft.api]] = url.value; showSearch(); };
const urlWrap = el("div", "stack");
urlWrap.append(seg, url);
ed.append(...field("Base URL", urlWrap));
@@ -3816,6 +3820,19 @@ function drawEditor(p, presetID) {
}
ed.append(...field(t("Proxy"), proxyPicker()));
// a relay in front of Anthropic's or OpenAI's API searches the web as
// they do, which magpie can't tell from its host (#359): a client's web
// search goes to it as sent, rather than through magpie's own. Only its
// Anthropic or Responses API can be asked to: a Chat one has no such tool
if (custom) {
const [stk, scb] = tick(t("Searches the web by itself"), !!draft.searches);
scb.onchange = () => { draft.searches = scb.checked; };
const row = field(t("Web search"), stk, t("For a relay in front of Anthropic's or OpenAI's own API: Claude Code's WebSearch and Codex's web_search go to it as they were sent, not through magpie's search. magpie doesn't search with it for other models."));
showSearch = () => { for (const e of row) e.style.display = searchable() ? "" : "none"; };
showSearch();
ed.append(...row);
}
// a vendor that tells the whole account's balance only to a token of its
// own (AiHubMix's system access token), where a key knows just its own
// — or a custom provider's, whose Balance URL may not be named yet: a
@@ -3943,7 +3960,7 @@ function drawEditor(p, presetID) {
const add = (label, key, ph, hint) => {
if (apiField[draft.api] === key) return;
const i = input(draft[key], ph, "url");
i.oninput = () => { draft[key] = i.value; };
i.oninput = () => { draft[key] = i.value; showSearch(); };
eps.append(...field(t(label), i, t(hint)));
};
add("OpenAI URL", "chat", "https://…/v1", "if the vendor also serves chat completions");
@@ -4027,6 +4044,7 @@ function drawEditor(p, presetID) {
if (decides) body.decide = (draft.decide || "").trim();
if (custom) { body.icon = draft.icon || "generic"; body.balanceURL = (draft.balanceURL || "").trim(); body.balancePath = (draft.balancePath || "").trim(); body.modelsURL = (draft.modelsURL || "").trim(); }
if (p) { body.fallback = draft.fallback; body.unlisted = draft.unlisted; }
body.searches = !!draft.searches && searchable();
const cx = parseContexts(draft.contexts || "");
if (cx.error) return editorError(t("Context window: {v} is not a length like 128k or 1m", { v: cx.error }), "warn");
body.contexts = cx.map;
+3
View File
@@ -1641,6 +1641,9 @@ const I18N = {
"Forget": "忘掉",
"Drop the list fetched from the vendor; the models.dev one is used until Refresh": "丢弃从供应商拉取的列表;在重新刷新前使用 models.dev 的列表",
"Only through routing groups": "只通过路由分组使用",
"Web search": "联网搜索",
"Searches the web by itself": "自己能联网搜索",
"For a relay in front of Anthropic's or OpenAI's own API: Claude Code's WebSearch and Codex's web_search go to it as they were sent, not through magpie's search. magpie doesn't search with it for other models.": "适用于转发 Anthropic 或 OpenAI 官方 API 的中转:Claude Code 的 WebSearch、Codex 的 web_search 原样发给它,不经过 magpie 的搜索。magpie 不会用它给其他模型搜索。",
"Its models leave the list agents pick from; the routing groups they are in still use them": "它的模型不出现在 Agent 的可选列表里;所在的路由分组仍会使用它们",
"Agents don't see them: only the routing groups they are in use them.": "Agent 看不到这些模型,只有它们所在的路由分组会用到。",
"Agents see the models picked.": "Agent 看到的是已勾选的模型。",
+4 -1
View File
@@ -50,6 +50,8 @@ type providerJSON struct {
Website string `json:"website"`
KeysURL string `json:"keysUrl"`
Headers map[string]string `json:"headers,omitempty"`
// the vendor searches the web by itself (provider.Searches)
Searches bool `json:"searches"`
// the proxy its requests go through: "" the global one, "direct"
// none, or an address (#237)
Proxy string `json:"proxy"`
@@ -225,7 +227,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, Decide: p.Decide,
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, Headers: p.Headers, BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, Headers: p.Headers, Searches: p.Searches, BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL,
Ready: p.Ready(), Chosen: p.Models, Models: []modelJSON{}, Agents: []providerAgent{},
Fallback: p.Fallback, Routing: p.Routing, Affinity: p.Affinity, Unlisted: p.Unlisted, Off: p.Off, Contexts: p.Contexts,
}
@@ -589,6 +591,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if pr, err := provider.FromPreset(in.Preset); err == nil && in.Chat == "" && in.Responses == "" && in.Anthropic == "" {
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.Searches = in.Searches
if in.Name != "" {
pr.Name = in.Name
}
+9 -1
View File
@@ -543,10 +543,18 @@ turns an account's card to each window and back without moving the page.
Claude Code's windows, naming no family, are as they were. No left-border
accent; English and Chinese, Chromium and WebKit, with `/api/plugins` faked.
`provider-search.test.cjs` checks a custom provider's "Searches the web by
itself" (#359): the editor's Web search row opens as saved, ticked for one
saved as searching, and Save posts `searches` ticked or not. A relay with
only a Chat address has no such row; it comes once an Anthropic URL is
typed under More endpoints and goes with it, and Save then posts
`searches: false`. A signed-in account (Codex) has no such row. Every
string has its Chinese; English and Chinese, Chromium and WebKit.
With Node.js and Playwright available:
```sh
node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs internal/gui/tests/library-loading.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/routing-shape.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs internal/gui/tests/codex-auto-reset.test.cjs internal/gui/tests/routing-auto-reset.test.cjs internal/gui/tests/claude-resets.test.cjs internal/gui/tests/library-toggle-status.test.cjs internal/gui/tests/library-all.test.cjs internal/gui/tests/routing-reroute-title.test.cjs internal/gui/tests/plain-names.test.cjs internal/gui/tests/panel-effort.test.cjs internal/gui/tests/agent-models-all-hidden.test.cjs internal/gui/tests/omp-roles.test.cjs internal/gui/tests/claude-effort.test.cjs internal/gui/tests/remote-magpie.test.cjs internal/gui/tests/qoder-cn-tile.test.cjs internal/gui/tests/provider-levels-scroll.test.cjs internal/gui/tests/signin-paste-codex.test.cjs internal/gui/tests/usage-alert.test.cjs internal/gui/tests/quota-families.test.cjs
node --test internal/gui/tests/menu-scroll.test.cjs internal/gui/tests/click-scroll.test.cjs internal/gui/tests/panel-fold.test.cjs internal/gui/tests/panel-routing.test.cjs internal/gui/tests/gateway-fold.test.cjs internal/gui/tests/routing-kind.test.cjs internal/gui/tests/balance-fix.test.cjs internal/gui/tests/cli-update.test.cjs internal/gui/tests/login-import.test.cjs internal/gui/tests/agy-launch.test.cjs internal/gui/tests/currency.test.cjs internal/gui/tests/usage-ledger.test.cjs internal/gui/tests/update-check.test.cjs internal/gui/tests/omarchy.test.cjs internal/gui/tests/brand.test.cjs internal/gui/tests/library-loading.test.cjs node --test internal/gui/tests/signin-callback.test.cjs internal/gui/tests/routing-steady.test.cjs internal/gui/tests/old-webkit.test.cjs internal/gui/tests/session-terminal.test.cjs internal/gui/tests/text-size.test.cjs internal/gui/tests/zcode-site.test.cjs internal/gui/tests/rail-tip.test.cjs internal/gui/tests/sync-update.test.cjs internal/gui/tests/plugin-signin.test.cjs internal/gui/tests/plugin-market.test.cjs internal/gui/tests/s3-sync.test.cjs internal/gui/tests/routing-wb-refused.test.cjs internal/gui/tests/routing-shape.test.cjs internal/gui/tests/market-have.test.cjs internal/gui/tests/sessions-today.test.cjs internal/gui/tests/routing-side-calls.test.cjs internal/gui/tests/import-all-skills.test.cjs internal/gui/tests/routing-flood.test.cjs internal/gui/tests/routing-busy.test.cjs internal/gui/tests/own-skill.test.cjs internal/gui/tests/routing-manual.test.cjs internal/gui/tests/tray-usages.test.cjs internal/gui/tests/provider-remove.test.cjs internal/gui/tests/signin-link.test.cjs internal/gui/tests/tray-inuse.test.cjs internal/gui/tests/codex-auto-reset.test.cjs internal/gui/tests/routing-auto-reset.test.cjs internal/gui/tests/claude-resets.test.cjs internal/gui/tests/library-toggle-status.test.cjs internal/gui/tests/library-all.test.cjs internal/gui/tests/routing-reroute-title.test.cjs internal/gui/tests/plain-names.test.cjs internal/gui/tests/panel-effort.test.cjs internal/gui/tests/agent-models-all-hidden.test.cjs internal/gui/tests/omp-roles.test.cjs internal/gui/tests/claude-effort.test.cjs internal/gui/tests/remote-magpie.test.cjs internal/gui/tests/qoder-cn-tile.test.cjs internal/gui/tests/provider-levels-scroll.test.cjs internal/gui/tests/signin-paste-codex.test.cjs internal/gui/tests/usage-alert.test.cjs internal/gui/tests/quota-families.test.cjs internal/gui/tests/provider-search.test.cjs
```
If Playwright is installed outside the repository, set `NODE_PATH` to the
+139
View File
@@ -0,0 +1,139 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A custom provider's "Searches the web by itself" (#359): a relay in front
// of Anthropic's or OpenAI's own API, whose web search magpie can't tell
// from its host. The editor has a Web search row with it, opening as it was
// saved; Save posts it, ticked or not. A relay with only a Chat address has
// no API to search on: the row comes once an Anthropic one is typed. A
// signed-in account (Codex here) has no such row: magpie knows how it
// searches. In English and Chinese.
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", icon: "generic", chat: "", responses: "", anthropic: "https://relay.example.com", catalog: "",
models: [{ id: "claude-haiku-4-5", name: "Claude Haiku 4.5", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", searches: false,
};
const searching = { ...relay, id: "searching", name: "Searching", searches: true };
const chatOnly = { ...relay, id: "chatonly", name: "Chat Only", chat: "https://chat.example.com/v1", anthropic: "" };
const codex = {
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "",
models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
account: { agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", logins: [{ user: "me@example.com", plan: "PLUS", active: true, on: true }] },
proxy: "",
};
function serve(lang, posts) {
const providers = { providers: [relay, searching, chatOnly, codex], 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/") && route.request().method() === "POST") {
posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() });
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)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const words = {
en: { tick: "Searches the web by itself", save: "Save", more: "More endpoints", anthropic: "Anthropic URL" },
zh: { tick: "自己能联网搜索", save: "保存", more: "更多端点", anthropic: "Anthropic 地址" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
const w = words[lang];
const open = async (t, name) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${name}-search.png`), fullPage: true });
}
await browser.close();
});
const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posts = [];
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: name }).click();
await page.locator(".editor .bar").waitFor();
return { page, errors, posts };
};
const box = (page) => page.locator(".editor label.tick", { hasText: w.tick }).locator("input");
const save = async (page, posts) => {
const n = posts.length;
await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click();
for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50);
return posts.at(-1);
};
test(`${engine} ${lang}: a relay is said to search by itself, and saved so`, async (t) => {
const { page, errors, posts } = await open(t, "Relay");
assert.equal(await box(page).isChecked(), false, "a relay opens as not searching");
await box(page).scrollIntoViewIfNeeded();
await box(page).check();
const saved = await save(page, posts);
assert.equal(saved.action, "save");
assert.equal(saved.body.id, "relay");
assert.equal(saved.body.searches, true);
const missing = await page.evaluate(() => [
"Web search", "Searches the web by itself",
"For a relay in front of Anthropic's or OpenAI's own API: Claude Code's WebSearch and Codex's web_search go to it as they were sent, not through magpie's search. magpie doesn't search with it for other models.",
].filter((k) => !I18N.zh[k]));
assert.deepEqual(missing, [], "every string has its Chinese");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: one saved as searching opens ticked, and is saved unticked`, async (t) => {
const { page, errors, posts } = await open(t, "Searching");
assert.equal(await box(page).isChecked(), true);
await box(page).scrollIntoViewIfNeeded();
await box(page).uncheck();
const saved = await save(page, posts);
assert.equal(saved.body.id, "searching");
assert.equal(saved.body.searches, false);
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: a Chat-only relay has the row once it has an Anthropic URL`, async (t) => {
const { page, errors, posts } = await open(t, "Chat Only");
const tick = page.locator(".editor label.tick", { hasText: w.tick });
assert.equal(await tick.isVisible(), false, "no row with only a Chat address");
await page.locator(".editor details.more summary", { hasText: w.more }).click();
const url = page.locator(".editor details.more label", { hasText: w.anthropic }).locator("xpath=following-sibling::div[1]//input");
await url.fill("https://relay.example.com");
assert.equal(await tick.isVisible(), true, "the row comes with an Anthropic address");
await box(page).scrollIntoViewIfNeeded();
await box(page).check();
await url.fill("");
assert.equal(await tick.isVisible(), false, "and goes with it");
const saved = await save(page, posts);
assert.equal(saved.body.searches, false, "not saved as searching with nothing to search on");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: a signed-in account has no such row`, async (t) => {
const { page, errors } = await open(t, "Codex");
assert.equal(await page.locator(".editor label.tick", { hasText: w.tick }).count(), 0);
assert.deepEqual(errors, []);
});
}
}
+8
View File
@@ -97,6 +97,13 @@ type Provider struct {
// ignore them: their auth is the agent's own.
Headers map[string]string `json:"headers,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
// magpie can't tell from its host. A request offering one then goes to
// it as the client sent it, rather than given magpie's search (#359).
Searches bool `json:"searches,omitempty"`
// Proxy is the proxy magpie's requests to this provider go through
// (#237: Codex through one, a vendor at home without): "" follows
// the global one (Settings' Proxy, the environment's, the system's),
@@ -427,6 +434,7 @@ func AddCopy(p Provider, from string) (string, error) {
p.Fallback = slices.Clone(src.Fallback)
}
p.Unlisted = p.Unlisted || src.Unlisted
p.Searches = p.Searches || src.Searches
if p.Website == "" {
p.Website = src.Website
}
+15 -1
View File
@@ -29,7 +29,7 @@ const providerUsage = `usage:
magpie provider <id> show one provider and its models
magpie provider add <preset> <key> add a preset vendor e.g. magpie provider add deepseek sk-…
again, it adds another (deepseek-2); k=v pairs too: id, name, header.X-Foo
magpie provider add <name> k=v… add a custom vendor k: url, anthropic, responses, key, models, catalog, icon, header.X-Foo, balance, balance.path, balance.token, models.url
magpie provider add <name> k=v… add a custom vendor k: url, anthropic, responses, key, models, catalog, icon, header.X-Foo, balance, balance.path, balance.token, models.url, search
magpie provider set <id> k=v… change a provider's settings, with the same k=v pairs as add
magpie provider key <id> <key> change the API key
magpie provider icon <id> <file|name> give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon
@@ -48,6 +48,9 @@ const providerUsage = `usage:
groups as office/…, each request sent on in the API the agent spoke)
magpie provider add anthropic sk-… id=anthropic-ws2 name="Anthropic WS2" header.anthropic-workspace-id=wrkspc_…
magpie provider set my-relay models.url=https://relay.example.com/api/models catalog=
magpie provider set my-relay search=yes
(the relay answers Claude Code's WebSearch and Codex's web_search itself:
those go to it as sent, not through magpie's own search)
magpie provider add "My Relay" url=https://relay.example.com/v1 key=sk-… balance=https://relay.example.com/api/usage/token balance.path='$data.total_available / 500000'
magpie provider set my-relay balance.path='(1 - credits.monthlyCredits / 70) %'
magpie provider set my-relay balance=https://relay.example.com/api/user/self balance.path='$data.quota / 500000' balance.token=<access token> header.New-Api-User=<user id>
@@ -561,6 +564,9 @@ func showProvider(p provider.Provider) error {
kv("chat", p.Chat)
kv("responses", p.Responses)
kv("anthropic", p.Anthropic)
if p.Searches {
kv("search", "by itself"+muted.Render(" a client's web search goes to it as sent"))
}
switch {
case p.Account != nil:
who := p.Account.User
@@ -663,6 +669,14 @@ func applyPairs(p *provider.Provider, pairs []string) error {
p.BalanceToken = v
case "models.url":
p.ModelsURL = v
case "search":
// yes: the vendor searches the web by itself, a web search a
// client offers going to it as it was sent (a relay in front of
// Anthropic's or OpenAI's API)
if v != "yes" && v != "no" {
return fmt.Errorf("search=yes|no, not %q", v)
}
p.Searches = v == "yes"
case "context":
if err := setContext(p, "*", v); err != nil {
return err