search: a ChatGPT account searches for another model by the backend's own search (lucy_85908)
A third-party model in Codex (DeepSeek, MiniMax, ...) had its web searches made by asking gpt-6-luna on the Codex account to search through /responses. A ChatGPT account now searches by the ChatGPT backend's /alpha/search, the request Codex's web.run sends by itself with no model turn (codex-rs ext/web-search): one search_query, the account's small model in "model", allowed_callers ["direct"], and external_web_access from the client's web_search tool (#5018: Codex's "cached" sends false; live by default). The output's pages are read by their 80-dash rule and ref_id; the private-use citation marks are dropped. Measured on a real Plus account (2026-11-03, token not refreshed): 151 alpha/search calls left the 5h window at the same percent, ~1.5-2.2s each; 51 searches by gpt-6-luna took 0% -> 1% of it, 7-15s each, ~9-17k tokens in (40 of them: 414,585 in, 10,313 out). The backend answered the same for any "model" (deepseek-v4 too) and any max_output_tokens. - Automatic (and searchInTurn) picks the backend's search for a ChatGPT account; Settings > Web search offers "<id>/@search" as "its web search". "<id>" and "<id>/<model>" saved before still search by that model, so a user's pick is unchanged. - When the backend's search fails, the account's small model searches (codexSearchBy). - Codex web.run's own search for a non-ChatGPT model (alphaSearchHere) and a Responses request's web_search tool pass their mode on. Run at this head (rebased on origin/main), on mote: - go test ./internal/gateway/... ./internal/gui/ ./internal/agent/ -timeout 45m: gateway and agent ok; gui red only on TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 on mote). After the rebase: the gateway's search tests again ok. - searcher-pick.test.cjs: 22/22, chromium + webkit, en/zh (+ the label is in zh, zh-TW, ja, de). - gofmt -l clean; GOOS=linux go vet gateway, provider; GOOS=windows go vet gateway, gui. - Whole GUI suite on the Linux box (wsl-run): not finished when pushed; its reds so far are WebKit pages this doesn't touch (add-provider, API key palette, Routing headers, click-scroll, Codex resets). Broken by hand, each red: the Automatic switch (TestCodexSearchesWith ItsCheapModel, TestChatGPTAccountSearchesByItsWebSearch), the responses.go mode (TestResponsesWebSearchModeKept), the body's mode, the fallback, and the picker option (searcher-pick). Not tried: a real search through magpie in a sandbox (the request shape was tried by hand against the backend); an account out of its allowance (does alpha/search still answer?); the model fallback still searches live when Codex asked cached. Suggested by lucy_85908 on Discord.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -33,6 +33,10 @@ type alphaSearchRequest struct {
|
||||
SearchQuery []alphaQuery `json:"search_query"`
|
||||
ImageQuery []alphaQuery `json:"image_query"`
|
||||
} `json:"commands"`
|
||||
Settings struct {
|
||||
// Codex's web_search mode: false "cached", true "live"
|
||||
ExternalWebAccess json.RawMessage `json:"external_web_access"`
|
||||
} `json:"settings"`
|
||||
}
|
||||
|
||||
type alphaQuery struct {
|
||||
@@ -222,7 +226,7 @@ func (s *Server) alphaSearchHere(w http.ResponseWriter, r *http.Request, q alpha
|
||||
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})
|
||||
ctx := withWebAccess(context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, Model: q.Model}), q.Settings.ExternalWebAccess)
|
||||
var said []string
|
||||
for _, query := range queries {
|
||||
found, _, err := s.webSearch(ctx, query)
|
||||
|
||||
@@ -257,7 +257,12 @@ type Request struct {
|
||||
ThinkOff bool
|
||||
Parallel *bool // parallel tool calls allowed
|
||||
WebSearch bool // the client offered its provider's own web search
|
||||
Fast bool // the client asked for priority processing: service_tier priority (Codex's Fast mode)
|
||||
// WebAccess is the external_web_access of the client's web_search
|
||||
// tool, as it sent it: Codex's web_search mode (false for "cached",
|
||||
// true for "live"), which magpie's own search for a model that can't
|
||||
// is made in (withWebAccess, #5018)
|
||||
WebAccess json.RawMessage
|
||||
Fast bool // the client asked for priority processing: service_tier priority (Codex's Fast mode)
|
||||
// Ultrafast is Codex's Ultrafast (service_tier "ultrafast"), which a
|
||||
// ChatGPT account on a plan with it offers on its models; Fast is set
|
||||
// with it, so where there is no Ultrafast the request goes fast
|
||||
|
||||
@@ -77,6 +77,9 @@ type rTool struct {
|
||||
Tools []rTool `json:"tools,omitempty"` // a namespace's
|
||||
Execution string `json:"execution,omitempty"`
|
||||
Format *rFormat `json:"format,omitempty"` // a custom tool's
|
||||
// ExternalWebAccess is a web_search tool's mode: false is Codex's
|
||||
// "cached", true its "live"
|
||||
ExternalWebAccess json.RawMessage `json:"external_web_access,omitempty"`
|
||||
}
|
||||
|
||||
// rFormat is what a custom (freeform) tool's input is: "text", or a
|
||||
@@ -523,6 +526,9 @@ func readResponsesFor(body []byte, facts, keepInstructions bool) (*Request, erro
|
||||
for i, t := range append(q.Tools, found...) {
|
||||
if strings.HasPrefix(t.Type, "web_search") {
|
||||
r.WebSearch = true
|
||||
if len(t.ExternalWebAccess) > 0 {
|
||||
r.WebAccess = t.ExternalWebAccess
|
||||
}
|
||||
}
|
||||
switch t.Type {
|
||||
case "function":
|
||||
|
||||
@@ -395,6 +395,10 @@ func autoSearcherReady() (provider.Provider, string, bool, bool) {
|
||||
if m == "" || top >= 0 && (bestReady && !ready || ready == bestReady && r >= top) {
|
||||
continue
|
||||
}
|
||||
if codexSearches(p) {
|
||||
// by the backend's search, which spends no model's tokens
|
||||
m = codexSearchModel
|
||||
}
|
||||
best, model, top, bestReady = p, m, r, ready
|
||||
}
|
||||
return best, model, bestReady, top >= 0
|
||||
@@ -438,6 +442,9 @@ func namedSearcher(v string) (*provider.Provider, string, string) {
|
||||
case provider.KimiCodeSearch(p) != "":
|
||||
// it searches with no model
|
||||
return &p, "", ""
|
||||
case model == codexSearchModel && codexSearches(p):
|
||||
// by the ChatGPT backend's search
|
||||
return &p, codexSearchModel, ""
|
||||
}
|
||||
if model != "" && slices.ContainsFunc(searcherModels(p), func(m catalog.Model) bool { return m.ID == model }) && searchableModel(p, model) {
|
||||
return &p, model, ""
|
||||
@@ -474,7 +481,7 @@ func Searchers() []SearcherChoice {
|
||||
if len(ms) == 0 {
|
||||
continue
|
||||
}
|
||||
out = append(out, SearcherChoice{Provider: p, Small: searcherModel(p), Models: ms, rank: r, ManualOnly: manualOnly, Own: googleAccount(p) || geminiKeySearches(p)})
|
||||
out = append(out, SearcherChoice{Provider: p, Small: searcherModel(p), Models: ms, rank: r, ManualOnly: manualOnly, Own: googleAccount(p) || geminiKeySearches(p), Search: codexSearches(p)})
|
||||
}
|
||||
slices.SortStableFunc(out, func(a, b SearcherChoice) int { return cmp.Compare(a.rank, b.rank) })
|
||||
return out
|
||||
@@ -512,6 +519,10 @@ type SearcherChoice struct {
|
||||
// Own is a Google sign-in or an AI Studio key, whose Gemini searches
|
||||
// for the provider's own models first, whoever is named (ownSearcher)
|
||||
Own bool
|
||||
// Search is a ChatGPT account, which searches by the ChatGPT backend's
|
||||
// search besides its models ("<provider>/@search", codexSearchModel):
|
||||
// magpie's own pick, and what it asks when another fails
|
||||
Search bool
|
||||
}
|
||||
|
||||
// RelaysSaidToSearch are the providers on that are said to search by
|
||||
@@ -902,6 +913,15 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit,
|
||||
return said, hits, err
|
||||
}
|
||||
|
||||
// turnModel is what c searches with when magpie picks it: a ChatGPT
|
||||
// account by the backend's search, another by its small model.
|
||||
func turnModel(c SearcherChoice) string {
|
||||
if c.Search {
|
||||
return codexSearchModel
|
||||
}
|
||||
return c.Small
|
||||
}
|
||||
|
||||
// searchPick is a searcher a search was asked of.
|
||||
type searchPick struct{ id, model string }
|
||||
|
||||
@@ -916,7 +936,7 @@ func (s *Server) searchInTurn(ctx context.Context, query string, tried []searchP
|
||||
if c.ManualOnly || c.Small == "" {
|
||||
continue
|
||||
}
|
||||
if searcherSpent(c.Provider, c.Small) != nil {
|
||||
if searcherSpent(c.Provider, turnModel(c)) != nil {
|
||||
spent = append(spent, c)
|
||||
} else {
|
||||
turn = append(turn, c)
|
||||
@@ -929,13 +949,14 @@ func (s *Server) searchInTurn(ctx context.Context, query string, tried []searchP
|
||||
if slices.ContainsFunc(tried, func(t searchPick) bool { return t.id == c.Provider.ID }) {
|
||||
continue
|
||||
}
|
||||
tried = append(tried, searchPick{c.Provider.ID, c.Small})
|
||||
next := searcherSpent(c.Provider, c.Small)
|
||||
m := turnModel(c)
|
||||
tried = append(tried, searchPick{c.Provider.ID, m})
|
||||
next := searcherSpent(c.Provider, m)
|
||||
if next == nil {
|
||||
var said string
|
||||
var hits []Hit
|
||||
if said, hits, next = s.searchWith(ctx, c.Provider, c.Small, query, searchEffort(c.Provider, c.Small)); next == nil {
|
||||
return said, hits, searcherOf(c.Provider, c.Small), nil
|
||||
if said, hits, next = s.searchBy(ctx, c.Provider, m, query, searchEffort(c.Provider, m)); next == nil {
|
||||
return said, hits, searcherOf(c.Provider, m), nil
|
||||
}
|
||||
}
|
||||
err = errors.Join(err, next)
|
||||
@@ -1021,9 +1042,10 @@ func SearcherFailed() (SearchFailure, bool) {
|
||||
|
||||
// searcherSpent is why a searcher's model isn't asked: every account or
|
||||
// key of it is out of its allowance (spentModel). nil when it has
|
||||
// allowance, or searches with no model (a Kimi Code plan's service).
|
||||
// allowance, or searches with no model (a Kimi Code plan's service, a
|
||||
// ChatGPT account by the backend's search).
|
||||
func searcherSpent(p provider.Provider, model string) error {
|
||||
if model == "" || provider.KimiCodeSearch(p) != "" {
|
||||
if model == "" || model == codexSearchModel || provider.KimiCodeSearch(p) != "" {
|
||||
return nil
|
||||
}
|
||||
back, spent := spentModel(p, model, provider.Anthropic, time.Now())
|
||||
@@ -1263,7 +1285,7 @@ func textCallRound(tools []Tool, ask round) round {
|
||||
// reply. The first round's failure is a status, as another provider may
|
||||
// take over.
|
||||
func (s *Server) searchReply(w http.ResponseWriter, r *http.Request, from provider.Protocol, name string, req *Request, usage *Usage, ask round) (int, string) {
|
||||
ctx, cancel := context.WithCancel(context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, Model: unprefixed(req.Model)}))
|
||||
ctx, cancel := context.WithCancel(withWebAccess(context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, Model: unprefixed(req.Model)}), req.WebAccess))
|
||||
defer cancel()
|
||||
q := *req
|
||||
q.WebSearch = false
|
||||
|
||||
@@ -66,9 +66,10 @@ func Searcher() string {
|
||||
}
|
||||
|
||||
// searcherName is a searcher by its provider and model; a Kimi Code plan,
|
||||
// which searches with no model, by its name.
|
||||
// which searches with no model, and a ChatGPT account by the backend's
|
||||
// search, by its name.
|
||||
func searcherName(p provider.Provider, model string) string {
|
||||
if model == "" {
|
||||
if model == "" || model == codexSearchModel {
|
||||
return p.Name
|
||||
}
|
||||
if e, ok := provider.ServedEntryOf(p.ID + "/" + model); ok && e.Name != "" {
|
||||
@@ -94,7 +95,7 @@ func AutoSearcher() string {
|
||||
// searches with no model (a Kimi Code plan's search service).
|
||||
func NamedSearchModel() string {
|
||||
p, m, why := chosenSearcher()
|
||||
if p == nil || why != "" || m == "" {
|
||||
if p == nil || why != "" || m == "" || m == codexSearchModel {
|
||||
return ""
|
||||
}
|
||||
return p.ID + "/" + m
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A ChatGPT account searches the web for a model that can't by the ChatGPT
|
||||
// backend's own search, the one Codex's web.run tool runs (AlphaSearchPath),
|
||||
// not by a model of the account asked to search: the search is answered by
|
||||
// itself, with no model turn, as Codex asks it (codex-rs ext/web-search,
|
||||
// tool.rs: a SearchRequest, the response's output given to the model as the
|
||||
// tool's result). On a real Plus account (2026-11-03) 151 such searches
|
||||
// left the 5-hour window where it was, each answered in about 2s, while 51
|
||||
// searches by gpt-6-luna through /responses (about 9k tokens in each) took
|
||||
// 1% of it, each in 7-15s (lucy_85908 on Discord). The account's model
|
||||
// searches only when the backend's search fails, or when Settings names a
|
||||
// model of it.
|
||||
|
||||
// codexSearchModel is the "model" a ChatGPT account searches with when it
|
||||
// searches by the backend's search: "<provider>/@search" in Settings'
|
||||
// Searcher. No model id starts with "@".
|
||||
const codexSearchModel = "@search"
|
||||
|
||||
// codexSearchBudget is the max_output_tokens Codex sends with a search: the
|
||||
// truncation budget of its models' tool output (10,000 tokens). The backend
|
||||
// answered the same whatever it was (1,000 to 10,000 tried).
|
||||
const codexSearchBudget = 10000
|
||||
|
||||
// codexSearches is whether p searches by the ChatGPT backend's search: a
|
||||
// ChatGPT account (Codex's sign-in).
|
||||
func codexSearches(p provider.Provider) bool {
|
||||
return p.Account != nil && p.Account.Agent == "codex"
|
||||
}
|
||||
|
||||
// webAccessKey holds the client's web search mode, as Codex sends it in
|
||||
// external_web_access: false for "cached", true for "live", an object for
|
||||
// "indexed".
|
||||
type webAccessKey struct{}
|
||||
|
||||
// withWebAccess is ctx whose searches are made in the mode v says, as the
|
||||
// client sent it; none sent leaves ctx as it is.
|
||||
func withWebAccess(ctx context.Context, v json.RawMessage) context.Context {
|
||||
if len(bytes.TrimSpace(v)) == 0 || string(bytes.TrimSpace(v)) == "null" {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, webAccessKey{}, v)
|
||||
}
|
||||
|
||||
// webAccess is the external_web_access a search with ctx is sent with: the
|
||||
// client's (#5018: Codex's web_search = "cached" was dropped, and every
|
||||
// search went live), else true, a live search, as Codex's "live" sends.
|
||||
func webAccess(ctx context.Context) json.RawMessage {
|
||||
if v, ok := ctx.Value(webAccessKey{}).(json.RawMessage); ok {
|
||||
return v
|
||||
}
|
||||
return json.RawMessage("true")
|
||||
}
|
||||
|
||||
// codexSearchReply is the ChatGPT backend's SearchResponse: output is what
|
||||
// Codex shows the model, results the pages it names.
|
||||
type codexSearchReply struct {
|
||||
Output *string `json:"output"`
|
||||
Results []struct {
|
||||
RefID string `json:"ref_id"`
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Snippet string `json:"snippet"`
|
||||
} `json:"results"`
|
||||
}
|
||||
|
||||
// codexSearchRule is the line between the pages of a search's output.
|
||||
var codexSearchRule = "\n" + strings.Repeat("-", 80) + "\n"
|
||||
|
||||
// codexSearchBy searches with a ChatGPT account: by the backend's search,
|
||||
// then, when it fails, by the account's small model.
|
||||
func (s *Server) codexSearchBy(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) {
|
||||
start := time.Now()
|
||||
said, hits, err := s.codexSearch(ctx, p, query)
|
||||
logOwnSearch(ctx, p, provider.CodexBase, query, start, len(hits), err)
|
||||
if err == nil || ctx.Err() != nil {
|
||||
return said, hits, err
|
||||
}
|
||||
m := searcherModel(p)
|
||||
if m == "" {
|
||||
return "", nil, err
|
||||
}
|
||||
log.Printf("web search on ChatGPT (%s) failed, searching with %s: %v", p.Name, m, err)
|
||||
said, hits, next := s.searchWith(ctx, p, m, query, searchEffort(p, m))
|
||||
if next != nil {
|
||||
return "", nil, errors.Join(err, next)
|
||||
}
|
||||
return said, hits, nil
|
||||
}
|
||||
|
||||
// codexSearch asks the ChatGPT backend's search, as Codex's web.run does.
|
||||
func (s *Server) codexSearch(ctx context.Context, p provider.Provider, query string) (string, []Hit, error) {
|
||||
ctx, cancel := context.WithTimeout(s.metered(p.Via(ctx), p, ""), searchTimeout/2)
|
||||
defer cancel()
|
||||
q, err := maskedQuery(ctx, query, &p)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
// the model a search names is the turn's in Codex; the backend answers
|
||||
// the same whichever it is, so the account's own small model
|
||||
model := searcherModel(p)
|
||||
if model == "" {
|
||||
model = "gpt-5"
|
||||
}
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"id": newUUID(),
|
||||
"model": model,
|
||||
"commands": map[string]any{"search_query": []map[string]any{{"q": q}}},
|
||||
"settings": map[string]any{
|
||||
"allowed_callers": []string{"direct"},
|
||||
"external_web_access": webAccess(ctx),
|
||||
},
|
||||
"max_output_tokens": codexSearchBudget,
|
||||
})
|
||||
who := p.Name + ": "
|
||||
r, err := http.NewRequestWithContext(ctx, http.MethodPost, provider.CodexBase+AlphaSearchPath, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
// a nil body: the search is answered in JSON, not streamed
|
||||
if err := p.Sign(ctx, r, provider.Responses, nil); err != nil {
|
||||
return "", nil, errors.New(who + err.Error())
|
||||
}
|
||||
if why, revoked := provider.RevokedSignIn(p.Account, r); revoked {
|
||||
return "", nil, errors.New(who + why)
|
||||
}
|
||||
res, err := s.client.Do(r)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return "", nil, fmt.Errorf("%sno answer in time", who)
|
||||
}
|
||||
return "", nil, fmt.Errorf("%s%w", who, err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
noteSignIn(ctx, p.Account, r, res)
|
||||
b, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20))
|
||||
if res.StatusCode >= 300 {
|
||||
err := errors.New(who + provider.APIError(b, res.Status))
|
||||
if res.StatusCode == http.StatusTooManyRequests {
|
||||
err = cantServe{err}
|
||||
}
|
||||
return "", nil, err
|
||||
}
|
||||
var out codexSearchReply
|
||||
if err := json.Unmarshal(b, &out); err != nil || out.Output == nil {
|
||||
return "", nil, fmt.Errorf("%sunexpected reply: %s", who, provider.APIError(b, res.Status))
|
||||
}
|
||||
pages := codexPages(*out.Output, out)
|
||||
if len(pages) == 0 {
|
||||
return "", nil, fmt.Errorf("%s%w", who, errFoundNothing)
|
||||
}
|
||||
said, hits := pagesSaid(pages)
|
||||
return said, hits, nil
|
||||
}
|
||||
|
||||
// codexPages are the pages a search's output names, in its order: each
|
||||
// is "Title (URL)", then a line opening with its citation mark (the
|
||||
// private-use "\ue200cite\ue202turn0search0\ue201") and "[wordlim: N]",
|
||||
// then what the page says, and a rule of 80 dashes before the next. The
|
||||
// results name each page's title and address by its ref_id, which the
|
||||
// mark carries.
|
||||
func codexPages(output string, out codexSearchReply) []foundPage {
|
||||
type result struct{ title, url, snippet string }
|
||||
byRef := map[string]result{}
|
||||
for _, x := range out.Results {
|
||||
if x.RefID != "" && x.URL != "" {
|
||||
byRef[x.RefID] = result{x.Title, x.URL, x.Snippet}
|
||||
}
|
||||
}
|
||||
var pages []foundPage
|
||||
for _, block := range strings.Split(output, codexSearchRule) {
|
||||
head, rest, _ := strings.Cut(strings.TrimSpace(block), "\n")
|
||||
title, link := head, ""
|
||||
if i := strings.LastIndex(head, " ("); i >= 0 && strings.HasSuffix(head, ")") {
|
||||
title, link = head[:i], head[i+2:len(head)-1]
|
||||
}
|
||||
ref := ""
|
||||
if i := strings.Index(rest, "\ue202"); i >= 0 {
|
||||
if j := strings.Index(rest[i:], "\ue201"); j >= 0 {
|
||||
ref = rest[i+len("\ue202") : i+j]
|
||||
rest = rest[i+j+len("\ue201"):]
|
||||
}
|
||||
}
|
||||
rest = strings.TrimSpace(rest)
|
||||
if strings.HasPrefix(rest, "[wordlim:") {
|
||||
if _, after, ok := strings.Cut(rest, "]"); ok {
|
||||
rest = after
|
||||
}
|
||||
}
|
||||
text := rest
|
||||
if r, ok := byRef[ref]; ok {
|
||||
title, link = cmp.Or(strings.TrimSpace(r.title), title), r.url
|
||||
if strings.TrimSpace(text) == "" {
|
||||
text = r.snippet
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(link, "http://") && !strings.HasPrefix(link, "https://") {
|
||||
continue
|
||||
}
|
||||
title = searchPlain(title)
|
||||
if title == "" {
|
||||
title = link
|
||||
}
|
||||
pages = append(pages, foundPage{Title: title, URL: link, Text: clipText(searchPlain(strings.Map(dropPrivateUse, text)), pageText)})
|
||||
if len(pages) == searchHits {
|
||||
break
|
||||
}
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
// dropPrivateUse leaves out the private-use characters OpenAI marks
|
||||
// citations with.
|
||||
func dropPrivateUse(r rune) rune {
|
||||
if r >= 0xe000 && r <= 0xf8ff {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}
|
||||
@@ -22,12 +22,14 @@ func TestCodexSearchesWithItsCheapModel(t *testing.T) {
|
||||
if err := catalog.SaveLive("codex", provider.CodexBase, list); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// magpie's own pick searches by the backend's search (search_codex.go);
|
||||
// the cheap model is what it falls back on, and what "codex" names
|
||||
pick := func() (string, string) {
|
||||
p, m, ok := searcher()
|
||||
if !ok {
|
||||
t.Fatal("no searcher with a Codex account signed in")
|
||||
if !ok || m != codexSearchModel {
|
||||
t.Fatalf("searcher = %s/%s %v, want codex by its web search", p.ID, m, ok)
|
||||
}
|
||||
return p.ID, m
|
||||
return p.ID, searcherModel(p)
|
||||
}
|
||||
|
||||
// no catalog: by the name
|
||||
@@ -61,7 +63,7 @@ func TestCodexSearchesWithItsCheapModel(t *testing.T) {
|
||||
if err := settings.Save(st); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if id, m := pick(); id != "codex" || m != "gpt-6.1-sol" {
|
||||
t.Fatalf("searcher = %s/%s, want the one Settings names, codex/gpt-6.1-sol", id, m)
|
||||
if p, m, _ := searcher(); p.ID != "codex" || m != "gpt-6.1-sol" {
|
||||
t.Fatalf("searcher = %s/%s, want the one Settings names, codex/gpt-6.1-sol", p.ID, m)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// fakeChatGPT stands in for the ChatGPT backend: its search answers with
|
||||
// the reply a real Plus account got for "Go 1.26" on 2026-11-03 (three of
|
||||
// its 34 pages), /responses as a model that searched.
|
||||
type fakeChatGPT struct {
|
||||
mu sync.Mutex
|
||||
paths []string
|
||||
bodies []map[string]any
|
||||
searchFails bool
|
||||
}
|
||||
|
||||
func newFakeChatGPT(t *testing.T) *fakeChatGPT {
|
||||
t.Helper()
|
||||
reply, err := os.ReadFile("testdata/codex_alpha_search.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := &fakeChatGPT{}
|
||||
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)
|
||||
f.mu.Lock()
|
||||
f.paths = append(f.paths, r.URL.Path)
|
||||
f.bodies = append(f.bodies, q)
|
||||
fails := f.searchFails
|
||||
f.mu.Unlock()
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/alpha/search"):
|
||||
if fails {
|
||||
http.Error(w, `{"error":{"message":"upstream down"}}`, 502)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(reply)
|
||||
case strings.HasSuffix(r.URL.Path, "/responses"):
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(`data: {"type":"response.created","response":{"id":"r1","model":"gpt-6-luna"}}`,
|
||||
`data: {"type":"response.output_item.done","item":{"type":"web_search_call","status":"completed","action":{"type":"search","query":"Go 1.26","sources":[{"type":"url","url":"https://go.dev/doc/go1.26"}]}}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"Go 1.26 was released on 10 February 2026."}`,
|
||||
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9000,"output_tokens":20}}}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
was := provider.CodexBase
|
||||
provider.CodexBase = up.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { provider.CodexBase = was })
|
||||
if err := catalog.SaveLive("codex", provider.CodexBase, []catalog.Model{{ID: "gpt-6.1-sol"}, {ID: "gpt-6-luna"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeChatGPT) asked() ([]string, []map[string]any) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
paths, bodies := slices.Clone(f.paths), slices.Clone(f.bodies)
|
||||
f.paths, f.bodies = nil, nil
|
||||
return paths, bodies
|
||||
}
|
||||
|
||||
// A ChatGPT account searches for a model that can't (DeepSeek, MiniMax,
|
||||
// … in Codex) by the ChatGPT backend's own search, the one Codex's web.run
|
||||
// asks, not by asking gpt-6-luna to search: lucy_85908 on Discord. 151
|
||||
// such searches on a real Plus account left its 5-hour window where it
|
||||
// was, while 51 by gpt-6-luna took 1% of it. The search is made in the
|
||||
// client's mode (#5018: Codex's web_search = "cached" sends
|
||||
// external_web_access false), live when none is said.
|
||||
func TestChatGPTAccountSearchesByItsWebSearch(t *testing.T) {
|
||||
codexSignedIn(t)
|
||||
f := newFakeChatGPT(t)
|
||||
s := New()
|
||||
|
||||
if p, m, ok := searcher(); !ok || p.ID != "codex" || m != codexSearchModel {
|
||||
t.Fatalf("searcher = %s/%s %v, want codex by its web search", p.ID, m, ok)
|
||||
}
|
||||
if got := AutoSearcher(); !strings.HasPrefix(got, "Codex") || strings.Contains(got, "@search") {
|
||||
t.Fatalf("AutoSearcher = %q", got)
|
||||
}
|
||||
said, hits, err := s.webSearch(context.Background(), "Go 1.26")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths, bodies := f.asked()
|
||||
if !slices.Equal(paths, []string{"/backend-api/codex/alpha/search"}) {
|
||||
t.Fatalf("asked %v, want the backend's search alone, no model", paths)
|
||||
}
|
||||
q := bodies[0]
|
||||
cmds, _ := q["commands"].(map[string]any)
|
||||
sq, _ := cmds["search_query"].([]any)
|
||||
set, _ := q["settings"].(map[string]any)
|
||||
if len(sq) != 1 || sq[0].(map[string]any)["q"] != "Go 1.26" || q["model"] != "gpt-6-luna" || q["id"] == "" ||
|
||||
set["external_web_access"] != true || !slices.Equal(set["allowed_callers"].([]any), []any{"direct"}) {
|
||||
t.Fatalf("body %v", q)
|
||||
}
|
||||
if strings.Contains(string(mustJSON(q)), "magpie") {
|
||||
t.Fatalf("magpie's own words went to the vendor: %v", q)
|
||||
}
|
||||
urls := []string{}
|
||||
for _, h := range hits {
|
||||
urls = append(urls, h.URL)
|
||||
}
|
||||
if !slices.Equal(urls, []string{"https://golang.google.cn/blog/go1.26", "https://golang-org.appspot.com/go.dev/blog/go1.26", "https://go.dev/doc/devel/release"}) {
|
||||
t.Fatalf("hits %v", urls)
|
||||
}
|
||||
if !strings.Contains(said, "Green Tea garbage collector") || !strings.Contains(said, "go1.27.2") ||
|
||||
strings.ContainsAny(said, "") || strings.Contains(said, "wordlim") || strings.Contains(said, "-----") {
|
||||
t.Fatalf("said %q", said)
|
||||
}
|
||||
|
||||
// Codex's cached web search: the search is cached too
|
||||
if _, _, err := s.webSearch(withWebAccess(context.Background(), json.RawMessage("false")), "Go 1.26"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, bodies := f.asked(); bodies[0]["settings"].(map[string]any)["external_web_access"] != false {
|
||||
t.Fatalf("cached went as %v", bodies[0]["settings"])
|
||||
}
|
||||
|
||||
// the backend's search failing: the account's small model searches
|
||||
f.mu.Lock()
|
||||
f.searchFails = true
|
||||
f.mu.Unlock()
|
||||
said, _, err = s.webSearch(context.Background(), "Go 1.26")
|
||||
if err != nil || !strings.Contains(said, "10 February 2026") {
|
||||
t.Fatalf("fallback: %q %v", said, err)
|
||||
}
|
||||
paths, bodies = f.asked()
|
||||
if len(paths) != 2 || !strings.HasSuffix(paths[0], "/alpha/search") || !strings.HasSuffix(paths[1], "/responses") || bodies[1]["model"] != "gpt-6-luna" {
|
||||
t.Fatalf("fallback asked %v %v", paths, bodies)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.searchFails = false
|
||||
f.mu.Unlock()
|
||||
|
||||
// named in Settings: its web search, its small model, a model of it
|
||||
for _, c := range []struct{ named, path, model string }{
|
||||
{"codex/@search", "/alpha/search", ""},
|
||||
{"codex", "/responses", "gpt-6-luna"},
|
||||
{"codex/gpt-6.1-sol", "/responses", "gpt-6.1-sol"},
|
||||
} {
|
||||
st := settings.Load()
|
||||
st.Searcher = c.named
|
||||
if err := settings.Save(st); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := s.webSearch(context.Background(), "Go 1.26"); err != nil {
|
||||
t.Fatalf("%s: %v", c.named, err)
|
||||
}
|
||||
paths, bodies := f.asked()
|
||||
if len(paths) != 1 || !strings.HasSuffix(paths[0], c.path) || c.model != "" && bodies[0]["model"] != c.model {
|
||||
t.Fatalf("%s: asked %v %v", c.named, paths, bodies)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Codex's web_search tool's mode reaches the search magpie makes for a
|
||||
// model that can't (#5018).
|
||||
func TestResponsesWebSearchModeKept(t *testing.T) {
|
||||
for _, c := range []struct{ tool, want string }{
|
||||
{`{"type":"web_search","external_web_access":false}`, "false"},
|
||||
{`{"type":"web_search","external_web_access":true}`, "true"},
|
||||
{`{"type":"web_search"}`, ""},
|
||||
} {
|
||||
r, err := readResponsesFor([]byte(`{"model":"deepseek/deepseek-v4","input":"hi","tools":[`+c.tool+`]}`), false, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !r.WebSearch || string(r.WebAccess) != c.want {
|
||||
t.Fatalf("%s: web search %v, access %q", c.tool, r.WebSearch, r.WebAccess)
|
||||
}
|
||||
want := c.want
|
||||
if want == "" {
|
||||
want = "true"
|
||||
}
|
||||
if got := string(webAccess(withWebAccess(context.Background(), r.WebAccess))); got != want {
|
||||
t.Fatalf("%s: searched with %s", c.tool, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A search's output is read into pages by the marks Codex's own model
|
||||
// reads it by; a page with no address is left out.
|
||||
func TestCodexPagesRead(t *testing.T) {
|
||||
rule := codexSearchRule
|
||||
out := "Go (https://go.dev/)\nciteturn0search0 [wordlim: 200] Crawled: today; Build simple software.\n" + rule +
|
||||
"No address\nciteturn0search9 [wordlim: 200] nothing" + rule +
|
||||
"Bare (https://example.com/a)\njust text"
|
||||
var reply codexSearchReply
|
||||
json.Unmarshal([]byte(`{"results":[{"ref_id":"turn0search0","title":"The Go Programming Language","url":"https://go.dev/"}]}`), &reply)
|
||||
pages := codexPages(out, reply)
|
||||
if len(pages) != 2 || pages[0].Title != "The Go Programming Language" || pages[0].URL != "https://go.dev/" ||
|
||||
!strings.Contains(pages[0].Text, "Build simple software.") || strings.Contains(pages[0].Text, "wordlim") ||
|
||||
pages[1].URL != "https://example.com/a" || pages[1].Text != "just text" {
|
||||
t.Fatalf("%+v", pages)
|
||||
}
|
||||
}
|
||||
@@ -97,11 +97,15 @@ func (s *Server) ownSearch(ctx context.Context, p provider.Provider, query strin
|
||||
}
|
||||
|
||||
// searchBy searches with one searcher: a Kimi Code plan by its search
|
||||
// service, any other by its model.
|
||||
// service, a ChatGPT account named with codexSearchModel by the backend's
|
||||
// search, any other by its model.
|
||||
func (s *Server) searchBy(ctx context.Context, p provider.Provider, model, query, effort string) (string, []Hit, error) {
|
||||
if provider.KimiCodeSearch(p) != "" {
|
||||
return s.kimiSearch(ctx, p, query)
|
||||
}
|
||||
if model == codexSearchModel && codexSearches(p) {
|
||||
return s.codexSearchBy(ctx, p, query)
|
||||
}
|
||||
return s.searchWith(ctx, p, model, query, effort)
|
||||
}
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ func VisionEfforts() []string {
|
||||
// asked to search at: the one picked in Settings fitted to its levels,
|
||||
// or "" to send none.
|
||||
func searchEffort(p provider.Provider, model string) string {
|
||||
if model == "" {
|
||||
if model == "" || model == codexSearchModel {
|
||||
return ""
|
||||
}
|
||||
return sideEffort(p.ID+"/"+model, settings.Load().SearcherEffort)
|
||||
@@ -98,7 +98,7 @@ func SearchEffortNow() string {
|
||||
// SearchEfforts are the levels of the model that searches now: none for
|
||||
// a Kimi Code plan's search service, which has no model.
|
||||
func SearchEfforts() []string {
|
||||
if p, m, ok := searcher(); ok && m != "" {
|
||||
if p, m, ok := searcher(); ok && m != "" && m != codexSearchModel {
|
||||
return ModelEfforts(p.ID + "/" + m)
|
||||
}
|
||||
return nil
|
||||
|
||||
File diff suppressed because one or more lines are too long
+4
-1
@@ -594,6 +594,9 @@ type searchChoiceJSON struct {
|
||||
// Own is a Google sign-in or an AI Studio key, which searches for its
|
||||
// own models first
|
||||
Own bool `json:"own,omitempty"`
|
||||
// Search is a ChatGPT account, which searches by the ChatGPT backend's
|
||||
// search ("<id>/@search") besides its models
|
||||
Search bool `json:"search,omitempty"`
|
||||
}
|
||||
|
||||
type searchVendorJSON struct {
|
||||
@@ -632,7 +635,7 @@ func searchState(s *settingsJSON) {
|
||||
s.SearchChoices = []searchChoiceJSON{}
|
||||
for _, c := range gateway.Searchers() {
|
||||
p := c.Provider
|
||||
j := searchChoiceJSON{ID: p.ID, Name: p.Name, Icon: p.Icon, Small: c.Small, SmallName: names[p.ID+"/"+c.Small], Models: []modelRef{}, Service: c.Service, Own: c.Own}
|
||||
j := searchChoiceJSON{ID: p.ID, Name: p.Name, Icon: p.Icon, Small: c.Small, SmallName: names[p.ID+"/"+c.Small], Models: []modelRef{}, Service: c.Service, Own: c.Own, Search: c.Search}
|
||||
for _, m := range c.Models {
|
||||
id := p.ID + "/" + m.ID
|
||||
j.Models = append(j.Models, modelRef{ID: id, Name: cmp.Or(names[id], m.Name, m.ID), Provider: p.ID, PName: p.Name, Icon: p.Icon})
|
||||
|
||||
@@ -321,7 +321,7 @@ function renderSearcher(s, keep, box) {
|
||||
const [pid, ...rest] = id.split("/");
|
||||
const c = choices.find((x) => x.id === pid);
|
||||
if (!c) return id;
|
||||
if (c.service) return `${c.name} · ${t("its web search")}`;
|
||||
if (c.service || (c.search && rest.join("/") === "@search")) return `${c.name} · ${t("its web search")}`;
|
||||
if (!rest.length) return `${c.name} · ${c.smallName || c.small}`;
|
||||
const m = c.models.find((x) => x.id === id);
|
||||
return `${m ? m.name : rest.join("/")} · ${c.name}`;
|
||||
@@ -376,6 +376,9 @@ function renderSearcher(s, keep, box) {
|
||||
options.push({ value: c.id, label: t("its web search"), note: c.name, icon: c.icon, group: c.name });
|
||||
continue;
|
||||
}
|
||||
// a ChatGPT account searches by its own web search, with no model's
|
||||
// tokens spent (lucy_85908 on Discord); its models stay to be picked
|
||||
if (c.search) options.push({ value: `${c.id}/@search`, label: t("its web search"), note: c.name, icon: c.icon, group: c.name });
|
||||
// its small model is offered once (Player on Discord): the model of the
|
||||
// same name below it searched just the same, "<provider>/<small>" being
|
||||
// that model named rather than magpie's pick, so a pick saved so is
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
// one named that magpie can't use (turned off) is said in the row, magpie's pick shown instead;
|
||||
// relays said to search are manual-only, including during fallback; a Kimi Code plan, which
|
||||
// searches by its web search with no model, is offered by itself and said to search for its
|
||||
// own models first. Another setting saved
|
||||
// own models first; a ChatGPT account is offered by its web search ("<id>/@search", no
|
||||
// model's tokens spent, lucy_85908 on Discord) besides its small model and models. Another setting saved
|
||||
// keeps the pick (prefsKeep). No click moves the page. English and Chinese, Chromium and
|
||||
// WebKit, with the API faked. Search help covers costs for every provider and
|
||||
// explains current eligibility without claiming a provider can never search.
|
||||
@@ -36,6 +37,9 @@ const choices = [
|
||||
{ id: "relay", name: "MyRelay", icon: "generic", small: "claude-haiku-4-5", models: [
|
||||
{ id: "relay/claude-haiku-4-5", name: "Claude Haiku 4.5", provider: "relay", providerName: "MyRelay" }] },
|
||||
{ id: "kimi", name: "Kimi Code", icon: "kimi", small: "", models: [], service: true },
|
||||
{ id: "codex", name: "Codex (me@example.com)", icon: "openai", small: "gpt-6-luna", smallName: "GPT-6 Luna", search: true, models: [
|
||||
{ id: "codex/gpt-6-luna", name: "GPT-6 Luna", provider: "codex", providerName: "Codex (me@example.com)" },
|
||||
{ id: "codex/gpt-6.1-sol", name: "GPT-6.1 Sol", provider: "codex", providerName: "Codex (me@example.com)" }] },
|
||||
{ id: "antigravity", name: "Antigravity", icon: "antigravity", small: "gemini-3-flash", own: true, models: [
|
||||
{ id: "antigravity/gemini-3-flash", name: "Gemini 3 Flash", provider: "antigravity", providerName: "Antigravity" }] },
|
||||
];
|
||||
@@ -260,12 +264,25 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const kimi = (await page.locator("#list li:not(.group)").allInnerTexts()).filter((x) => x.includes("Kimi Code"));
|
||||
assert.equal(kimi.length, 1, "the plan is offered once, with no model");
|
||||
assert(kimi[0].includes(w.web));
|
||||
const web = page.locator("#list li:not(.group)", { hasText: w.web });
|
||||
const web = page.locator("#list li:not(.group)", { hasText: w.web }).filter({ hasText: "Kimi Code" });
|
||||
await web.scrollIntoViewIfNeeded();
|
||||
await click(web);
|
||||
await page.waitForFunction((want) => document.querySelector("#searchList button.searcher-pick")?.innerText === want, `Kimi Code · ${w.web}`);
|
||||
assert.equal(posted.at(-1).searcher, "kimi");
|
||||
|
||||
// a ChatGPT account, by its web search: its small model and models
|
||||
// are still offered
|
||||
await click(row.locator("button.searcher-pick"));
|
||||
await page.locator("#pop").waitFor({ state: "visible" });
|
||||
const codex = (await page.locator("#list li:not(.group)").allInnerTexts()).filter((x) => x.includes("Codex (me@example.com)"));
|
||||
assert.equal(codex.filter((x) => x.includes(w.web)).length, 1, codex.join(" | "));
|
||||
assert(codex.some((x) => x.includes("GPT-6 Luna")) && codex.some((x) => x.includes("GPT-6.1 Sol")), codex.join(" | "));
|
||||
const cweb = page.locator("#list li:not(.group)", { hasText: w.web }).filter({ hasText: "Codex (me@example.com)" });
|
||||
await cweb.scrollIntoViewIfNeeded();
|
||||
await click(cweb);
|
||||
await page.waitForFunction((want) => document.querySelector("#searchList button.searcher-pick")?.innerText === want, `Codex (me@example.com) · ${w.web}`);
|
||||
assert.equal(posted.at(-1).searcher, "codex/@search");
|
||||
|
||||
// back to a provider, by its small model
|
||||
await click(row.locator("button.searcher-pick"));
|
||||
await page.locator("#pop").waitFor({ state: "visible" });
|
||||
|
||||
Reference in New Issue
Block a user