diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 93a975a80..52d34afae 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -16,7 +16,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). | Part | Responsibility | Source | | --- | --- | --- | | Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. | [`gateway.go`](../../internal/gateway/gateway.go) | -| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | +| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | | Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight` (`weightedFirst`). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `wrrMove`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/provider/routing.go`](../../internal/provider/routing.go) | diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 088cd33c1..505eefaae 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -77,6 +77,21 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) { case r.Method == http.MethodGet && rest == "/models": s.codexModels(w, r) return + case r.Method == http.MethodPost && rest == AlphaSearchPath: + // web.run on a magpie model is searched where the model is + // served, never relayed on Codex's own sign-in; one of Codex's + // own models goes through magpie's accounts when its turns do + // (codexAccounts), else on as it came + model := modelOf(body) + if !strings.Contains(model, "/") { + id, ok := codexAccounts(r, model) + if !ok { + break + } + body = withModel(body, id) + } + s.alphaSearchBody(w, r, body) + return case r.Method == http.MethodPost && (rest == "/responses" || rest == "/responses/compact"): var model string body, model, err = requestModel(body) diff --git a/internal/gateway/codex_search.go b/internal/gateway/codex_search.go new file mode 100644 index 000000000..b2bbe26de --- /dev/null +++ b/internal/gateway/codex_search.go @@ -0,0 +1,231 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "log" + "net/http" + "strings" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// AlphaSearchPath is where Codex's own web search, its web.run tool, goes: +// "alpha/search" under the model provider's base URL, so /v1/alpha/search +// on magpie's provider and CodexPath+"/alpha/search" when Codex is signed in +// to ChatGPT. Codex offers web.run since 0.143 for a provider that sends +// x-openai-actor-authorization, as magpie's does, on a model whose catalog +// entry says use_responses_lite, as a ChatGPT account's do in magpie +// (codexcat copies Codex's own entry). Unanswered, the 404 ended the turn: +// Codex takes any failure of web.run as fatal (anton on Discord). +const AlphaSearchPath = "/alpha/search" + +// alphaSearchRequest is the part of Codex's SearchRequest magpie reads; the +// rest goes on to the ChatGPT backend as it came. +type alphaSearchRequest struct { + Model string `json:"model"` + Commands struct { + SearchQuery []alphaQuery `json:"search_query"` + ImageQuery []alphaQuery `json:"image_query"` + } `json:"commands"` +} + +type alphaQuery struct { + Q string `json:"q"` + Domains []string `json:"domains"` +} + +// alphaSearchReply is Codex's SearchResponse: output is what the model is +// shown as the tool's result. +type alphaSearchReply struct { + EncryptedOutput *string `json:"encrypted_output"` + Output string `json:"output"` +} + +// alphaSearch answers POST /v1/alpha/search. A ChatGPT account's model +// goes to the ChatGPT backend's search, as Codex sends it there itself, +// on the account's sign-in. Any other model's search_query is searched as +// magpie searches for a model that can't (webSearch). What magpie can't +// do is said in the tool's output with a 200, which the model reads; a +// failure status would end the turn. +func (s *Server) alphaSearch(w http.ResponseWriter, r *http.Request) { + body, ok := s.readRequestBody(w, r, provider.Responses, 0) + if !ok { + return + } + s.alphaSearchBody(w, r, body) +} + +func (s *Server) alphaSearchBody(w http.ResponseWriter, r *http.Request, body []byte) { + var q alphaSearchRequest + if err := json.Unmarshal(body, &q); err != nil { + writeError(w, provider.Responses, http.StatusBadRequest, "magpie couldn't read the web search request: "+err.Error()) + return + } + if q.Model == "" { + writeError(w, provider.Responses, http.StatusBadRequest, "the web search request names no model") + return + } + note := "" + if ons, model := chatGPTSearchers(r, q.Model); len(ons) > 0 { + answered, why := s.alphaSearchOn(w, r, withModel(body, model), model, ons) + if answered { + return + } + // a failure would end the turn: magpie searches in its place + log.Printf("web search on ChatGPT for %s: %s", q.Model, why) + note = "ChatGPT's web search failed (" + why + "); magpie searched in its place.\n\n" + } + s.alphaSearchHere(w, r, q, note) +} + +// chatGPTSearchers is the ChatGPT accounts a web search for model may go +// to, the one it is served on first and those resting or with a revoked +// sign-in last, with the model as the backend knows it: none when model +// isn't a ChatGPT account's, or the calling key may use none of them. +func chatGPTSearchers(r *http.Request, model string) ([]provider.Provider, string) { + p, bare, ok := provider.Resolve(model) + if !ok || p.Account == nil || p.Account.Agent != "codex" { + return nil, "" + } + who, keyHeld := keyHolds(r) + if keyHeld && !modelAllowed(who, p, bare) { + return nil, "" + } + var all []provider.Provider + if !p.OwnPaused() { + all = append(all, p) + } + all = append(all, p.AlsoOn()...) + var ready, later []provider.Provider + for _, o := range all { + c := candidate{p: o, model: bare, rest: o.ID} + if !accountAllowed(who, c) { + continue + } + if resting(c) || provider.SignInMarked(o.Account) { + later = append(later, o) + continue + } + ready = append(ready, o) + } + return append(ready, later...), bare +} + +// alphaSearchOn sends the search to the ChatGPT backend on each account in +// turn, the next asked when one is refused, limited or fails, and relays +// the backend's answer as it is. It says whether one answered: when none +// did, nothing is written, and the search is magpie's (alphaSearchHere), +// with why returned. +func (s *Server) alphaSearchOn(w http.ResponseWriter, r *http.Request, body []byte, model string, ons []provider.Provider) (bool, string) { + start := time.Now() + w, body, unmask := redacted(w, body) + defer unmask() + var errs []string + for _, on := range ons { + who := "OpenAI (" + on.Account.User + "): " + ctx := on.Via(r.Context()) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, provider.CodexBase+AlphaSearchPath, bytes.NewReader(body)) + if err != nil { + errs = append(errs, who+err.Error()) + continue + } + for k, vs := range r.Header { + if codexHeader(k) { + req.Header[k] = vs + } + } + req.Header.Set("Content-Type", "application/json") + // a nil body: the search is answered in JSON, not streamed + if err := on.Sign(ctx, req, provider.Responses, nil); err != nil { + errs = append(errs, who+err.Error()) + continue + } + // a sign-in its vendor revoked isn't sent again (#1793) + if why, revoked := provider.RevokedSignIn(on.Account, req); revoked { + errs = append(errs, who+why) + continue + } + res, err := s.client.Do(req) + if err != nil { + if r.Context().Err() != nil { + return true, "" + } + errs = append(errs, who+err.Error()) + continue + } + noteSignIn(ctx, on.Account, req, res) + c := Call{Time: start, From: provider.Responses, To: provider.Responses, Model: model, Provider: on.ID, + Agent: agentOf(r), Kind: "web_search", Status: res.StatusCode} + if res.StatusCode < 200 || res.StatusCode > 299 { + msg, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10)) + res.Body.Close() + errs = append(errs, who+res.Status+": "+strings.TrimSpace(string(msg))) + c.Millis, c.Error = time.Since(start).Milliseconds(), res.Status + s.record(c) + continue + } + for k, vs := range res.Header { + if !hopHeader(k) { + w.Header()[k] = vs + } + } + w.WriteHeader(res.StatusCode) + io.Copy(w, res.Body) + res.Body.Close() + c.Millis = time.Since(start).Milliseconds() + s.record(c) + return true, "" + } + return false, strings.Join(errs, "; ") +} + +// alphaSearchHere answers a search for a model no ChatGPT account serves: +// its search_query and image_query searched as magpie searches for a +// model that can't, the findings the tool's output. Opening, clicking or +// finding in a page is the ChatGPT backend's alone, and said so. +func (s *Server) alphaSearchHere(w http.ResponseWriter, r *http.Request, q alphaSearchRequest, note string) { + var queries []string + for _, x := range append(q.Commands.SearchQuery, q.Commands.ImageQuery...) { + text := strings.TrimSpace(x.Q) + if text == "" { + continue + } + for _, d := range x.Domains { + if d = strings.TrimSpace(d); d != "" { + text += " site:" + d + } + } + queries = append(queries, text) + } + if len(queries) == 0 { + writeJSON(w, http.StatusOK, alphaSearchReply{Output: note + "magpie can only search the web for " + q.Model + ": give web.run a search_query. Opening, clicking or finding in a page goes to the ChatGPT backend, for a ChatGPT account's model in magpie."}) + return + } + ctx := context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, Model: q.Model}) + var said []string + for _, query := range queries { + found, _, err := s.webSearch(ctx, query) + if err != nil { + if r.Context().Err() != nil { + return + } + log.Printf("web search for %s: %v", q.Model, err) + msg := "magpie couldn't search the web for " + query + ": " + err.Error() + if errors.Is(err, errNoSearcher) { + msg += ": add a search API in magpie's Settings → Models → Web search (or magpie search add ), or a provider that can search" + } + said = append(said, msg) + continue + } + if len(queries) > 1 { + found = "Search: " + query + "\n" + found + } + said = append(said, found) + } + writeJSON(w, http.StatusOK, alphaSearchReply{Output: note + strings.Join(said, "\n\n")}) +} diff --git a/internal/gateway/codex_search_test.go b/internal/gateway/codex_search_test.go new file mode 100644 index 000000000..f618164a9 --- /dev/null +++ b/internal/gateway/codex_search_test.go @@ -0,0 +1,189 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// codexSearchBody is the SearchRequest Codex's web.run sends, as its own +// test (codex-api/src/endpoint/search.rs) has it on the wire, on model. +func codexSearchBody(model string) string { + return `{"id":"search-session","model":"` + model + `","input":[{"type":"message","id":"msg_search","role":"user","content":[{"type":"input_text","text":"find this"},{"type":"input_image","image_url":"https://example.com/image.png"}]}],"commands":{"search_query":[{"q":"OpenAI news","recency":7,"domains":["openai.com"]}],"open":[{"ref_id":"https://openai.com","lineno":12}]},"settings":{"user_location":{"type":"approximate","country":"US","city":"San Francisco"},"search_context_size":"low","filters":{"allowed_domains":["openai.com"],"blocked_domains":["example.com"]},"image_settings":{"max_results":4,"caption":true},"allowed_callers":["direct"],"external_web_access":true},"max_output_tokens":2500}` +} + +// codexSearchPost sends a search to path as Codex sends it to magpie's +// provider: its bearer token and actor header from the provider table, +// its turn metadata and originator of its own. +func codexSearchPost(h http.Handler, path, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Authorization", "Bearer magpie") + r.Header.Set("x-openai-actor-authorization", "magpie") + r.Header.Set("x-codex-turn-metadata", `{"turn_id":"t1"}`) + r.Header.Set("originator", "codex_exec") + r.Header.Set("User-Agent", "codex_exec/0.162.1 (Linux 6.8; x86_64)") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +type searchReply struct { + EncryptedOutput *string `json:"encrypted_output"` + Output string `json:"output"` + Results []any `json:"results"` +} + +func readSearchReply(t *testing.T, w *httptest.ResponseRecorder) searchReply { + t.Helper() + var v searchReply + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &v) != nil { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + return v +} + +// Codex's web.run on a ChatGPT account's model in magpie posted to +// /v1/alpha/search and got 404, which ended the turn (anton on Discord). +// It goes to the ChatGPT backend's search as Codex sends it there itself: +// on the account's sign-in, the model as the backend knows it, the rest +// of the request as it came; an account out of its allowance passes it +// to the next, and the backend's answer goes back as it is. +func TestCodexWebRunSearchesOnChatGPTAccount(t *testing.T) { + codexSignedIn(t, "spare@example.com") + var mu sync.Mutex + var paths, tried []string + var heads []http.Header + var bodies []map[string]any + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q map[string]any + json.Unmarshal(b, &q) + mu.Lock() + paths = append(paths, r.URL.Path) + tried = append(tried, r.Header.Get("chatgpt-account-id")) + heads = append(heads, r.Header.Clone()) + bodies = append(bodies, q) + mu.Unlock() + if r.Header.Get("chatgpt-account-id") == "acct-1" { + w.WriteHeader(429) + io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached"}}`) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"encrypted_output":"ciphertext","output":"OpenAI news from acct-2","results":[{"type":"text_result","ref_id":"turn0search0","url":"https://example.com/result"}]}`) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + + h := New().Handler() + for _, path := range []string{"/v1/alpha/search", CodexPath + "/alpha/search"} { + mu.Lock() + paths, tried, heads, bodies = nil, nil, nil, nil + mu.Unlock() + got := readSearchReply(t, codexSearchPost(h, path, codexSearchBody("codex/gpt-5.5"))) + if got.Output != "OpenAI news from acct-2" || got.EncryptedOutput == nil || *got.EncryptedOutput != "ciphertext" || len(got.Results) != 1 { + t.Fatalf("%s: answered %+v", path, got) + } + if strings.Join(tried, ",") != "acct-1,acct-2" { + t.Fatalf("%s: accounts asked %v", path, tried) + } + for i, hd := range heads { + if paths[i] != "/backend-api/codex/alpha/search" { + t.Fatalf("%s: went to %s", path, paths[i]) + } + if a := hd.Get("Authorization"); a == "" || a == "Bearer magpie" || hd.Get("x-openai-actor-authorization") != "" { + t.Fatalf("%s: magpie's own token or actor header went on: %v", path, hd) + } + if hd.Get("x-codex-turn-metadata") != `{"turn_id":"t1"}` || hd.Get("originator") != "codex_cli_rs" || hd.Get("Accept") == "text/event-stream" { + t.Fatalf("%s: headers %v", path, hd) + } + q := bodies[i] + cmds, _ := q["commands"].(map[string]any) + if q["model"] != "gpt-5.5" || q["id"] != "search-session" || cmds["open"] == nil || q["settings"] == nil || q["max_output_tokens"] != float64(2500) { + t.Fatalf("%s: body %v", path, q) + } + } + } +} + +// Every ChatGPT account failing ends no turn: magpie searches in its +// place, and the model is told why. +func TestCodexWebRunChatGPTFailsSearchedByMagpie(t *testing.T) { + codexSignedIn(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, `{"error":"down"}`, 500) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + apis := newSearchAPIs(t) + if err := provider.SetSearchAPI(apis.api("tavily", "tvly-k")); err != nil { + t.Fatal(err) + } + st := settings.Load() + st.Searcher = "off" + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + got := readSearchReply(t, codexSearchPost(New().Handler(), "/v1/alpha/search", codexSearchBody("codex/gpt-5.5"))) + if !strings.Contains(got.Output, "ChatGPT's web search failed") || !strings.Contains(got.Output, "500") || + !strings.Contains(got.Output, "go1.27.1 is the latest release.") { + t.Fatalf("answered %q", got.Output) + } +} + +// web.run on a model no ChatGPT account serves: its search_query is +// searched as magpie searches for a model that can't, its domains kept; +// with nothing to search with, or nothing to search, the model is told +// what to do, never a failure that ends the turn. +func TestCodexWebRunOnOtherModelSearchedByMagpie(t *testing.T) { + fresh(t) + // nothing of it goes to the ChatGPT backend, which a relay would reach + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("reached the ChatGPT backend: %s %s", r.Method, r.URL.Path) + http.Error(w, "no", 500) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + h := New().Handler() + got := readSearchReply(t, codexSearchPost(h, "/v1/alpha/search", codexSearchBody("deepseek/deepseek-v4"))) + if !strings.Contains(got.Output, "Settings → Models → Web search") || got.EncryptedOutput != nil { + t.Fatalf("no searcher: %+v", got) + } + apis := newSearchAPIs(t) + if err := provider.SetSearchAPI(apis.api("tavily", "tvly-k")); err != nil { + t.Fatal(err) + } + got = readSearchReply(t, codexSearchPost(h, "/v1/alpha/search", codexSearchBody("deepseek/deepseek-v4"))) + if !strings.Contains(got.Output, "Go downloads") || !strings.Contains(got.Output, "go1.27.1 is the latest release.") { + t.Fatalf("searched: %+v", got) + } + if strings.Join(apis.asked, "|") != "tavily: OpenAI news site:openai.com" { + t.Fatalf("asked %q", apis.asked) + } + // a magpie model through Codex's ChatGPT path is searched the same + got = readSearchReply(t, codexSearchPost(h, CodexPath+"/alpha/search", codexSearchBody("deepseek/deepseek-v4"))) + if !strings.Contains(got.Output, "go1.27.1") { + t.Fatalf("on %s: %+v", CodexPath, got) + } + got = readSearchReply(t, codexSearchPost(h, "/v1/alpha/search", `{"id":"s","model":"deepseek/deepseek-v4","commands":{"open":[{"ref_id":"https://openai.com"}]}}`)) + if !strings.Contains(got.Output, "search_query") { + t.Fatalf("open alone: %+v", got) + } + if w := codexSearchPost(h, "/v1/alpha/search", `nope`); w.Code != 400 { + t.Fatalf("not JSON: %d %s", w.Code, w.Body.String()) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index f1e64636e..9f7e7d9c0 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -555,6 +555,9 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /v1/messages", keepsSignIn(s.handle(provider.Anthropic))) mux.HandleFunc("POST /messages", keepsSignIn(s.handle(provider.Anthropic))) mux.HandleFunc("POST /v1/systemone", s.serveSystemOne) + // Codex's web.run tool (anton on Discord) + mux.HandleFunc("POST /v1"+AlphaSearchPath, s.alphaSearch) + mux.HandleFunc("POST "+AlphaSearchPath, s.alphaSearch) mux.HandleFunc("POST /v1/messages/count_tokens", keepsSignIn(s.countTokens)) mux.HandleFunc("POST /v1/images/generations", s.images(false)) mux.HandleFunc("POST /images/generations", s.images(false))