Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: the Codex app's titles, descriptions and summaries go to the magpie model picked, not ChatGPT (atom_Ray on X)
yetone0d2a10116044
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex fd541dd89..3335b395c 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -43,7 +43,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini alone. A request goes to `<base>/publishers/google/models/<model>:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) || Bedrock Mantle | A request on chat completions or Responses to an [Amazon Bedrock Mantle provider](providers-accounts.md#responsibilities-and-sources-of-truth) goes to the prefix that serves its model (`mantleRoutes`, `provider.MantleBase` in `forwardOnce`): `/openai/v1` for OpenAI's closed GPTs and xAI's Grok, `/v1` for the rest. A model Mantle refuses there with "model `x` isn't supported on this route" (a maker the rule doesn't know yet) is asked once more at the other prefix, and when it is taken there that prefix is remembered for the model in `unfit` (`mantleRouteKey`) until the gateway restarts. A model refused at both gets the first refusal and nothing is remembered (`mantleReroute`). Messages go to `/anthropic` alone. | [`mantle.go`](../../internal/gateway/mantle.go), [`gateway.go`](../../internal/gateway/gateway.go) |-## Codex titles, descriptions and predictions+## Codex titles, descriptions, summaries and predictionsCodex's title and description requests are independent hidden turns. Thesettings `CodexTitles` and `CodexDescriptions` select their models separately;@@ -52,7 +52,19 @@ paths wrap plain model text in the object Codex requested. Titles use`{"title": ...}`; descriptions use `{"description": ...}` with nonempty textand no invented maximum length. Title Off mode does not disable descriptions.-`codexTitlesTo`, `codexDescriptionsTo`, `codexTitle` and `codexDescription` in+The Codex app asks for titles, descriptions and one-line thread summaries+(`thread_summary`, after each message) on a model of its own (`gpt-6-luna`),+whatever the conversation is on. With one of magpie's models picked beside+Codex's ChatGPT sign-in, an unset setting sends these to the model picked+(`codexSideTo`, from `agent.CodexSideModel`: Codex's config `model`, when it+is magpie's and magpie is not Codex's provider), so a conversation on a+third-party model spends none of the ChatGPT account's allowance (atom_Ray on+X). On Codex's own model they still go to ChatGPT. Summaries use+`{"summary": ...}`, with any other string the schema requires+(`compactSummary`) filled and cut to its length (`summaryJSON`).++`codexTitlesTo`, `codexDescriptionsTo`, `codexSummariesTo`, `codexTitle`,+`codexDescription` and `codexSummary` in[`codex_titles.go`](../../internal/gateway/codex_titles.go) own this selectionand response wrapping. Both the Responses API and Codex backend entrypointsuse it. Usage and Routing retain the original purpose; unusable descriptiondiff --git a/internal/agent/agent.go b/internal/agent/agent.goindex b26d475f2..1151cfebc 100644--- a/internal/agent/agent.go+++ b/internal/agent/agent.go@@ -181,6 +181,12 @@ type Agent struct {// its sign-in only as it opens, sends nothing on it till it is opened// again (MasterYi on Discord).AppOut func() bool+ // SideModel is the model Codex is set to when it is one of magpie's,+ // picked beside its ChatGPT sign-in (by the base URL, magpie not its+ // provider), "" otherwise: the gateway answers the Codex app's hidden+ // side turns (titles, descriptions, summaries), which it asks for on a+ // model of its own, on it rather than on the ChatGPT account.+ SideModel func() string// Routed reports that the agent's config sends whatever model it// names to magpie's gateway (Codex's openai_base_url or magpie as its// provider), so a model's name the gateway takes as a routing groupdiff --git a/internal/agent/codex.go b/internal/agent/codex.goindex 6a08eb0db..0975f7a86 100644--- a/internal/agent/codex.go+++ b/internal/agent/codex.go@@ -1255,6 +1255,12 @@ func codexIn(at place) *Agent {return errors.Join(dropMirrorFailover(), dropBase())},OwnVia: codexOwnViaMagpie,+ SideModel: func() string {+ if m := get("model"); viaBase() && !asProvider() && isMagpie(m) {+ return m+ }+ return ""+ },Sync: func() error {// after the sync, which may have put Codex back beside its// sign-in, and whatever it failed at@@ -1999,6 +2005,17 @@ func CodexOwnOnly() bool {return true}+// CodexSideModel is the model this machine's Codex is set to when it is+// one of magpie's, picked beside its ChatGPT sign-in (SideModel), for the+// gateway to answer the Codex app's side turns on (gateway.CodexSideModel).+func CodexSideModel() string {+ home, err := os.UserHomeDir()+ if err != nil {+ return ""+ }+ return codex(home).SideModel()+}+// codexChatGPT reports whether Codex is signed in to a ChatGPT account:// its built-in provider then runs and asks for the model list at// openai_base_url. Signed in with an API key alone, it asks for none.diff --git a/internal/agent/codex_side_test.go b/internal/agent/codex_side_test.gonew file mode 100644index 000000000..01af457ca--- /dev/null+++ b/internal/agent/codex_side_test.go@@ -0,0 +1,40 @@+package agent++import (+ "os"+ "path/filepath"+ "testing"+)++// SideModel is the model of magpie's Codex is on beside its ChatGPT+// sign-in, which the gateway answers the Codex app's titles, descriptions+// and summaries on (atom_Ray on X): none on one of Codex's own models, and+// none with magpie Codex's provider, where those requests reach magpie's+// own API on the model Codex asks for.+func TestCodexSideModel(t *testing.T) {+ home, _ := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"gpt-a\"\n")+ os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"),+ []byte(`{"models":[{"slug":"gpt-a","display_name":"A","priority":1}]}`), 0o644)+ cx := codex(home)+ if got := cx.SideModel(); got != "" {+ t.Fatalf("not connected: %q", got)+ }+ if ok, err := cx.Join(); err != nil || !ok {+ t.Fatalf("join: %v %v", ok, err)+ }+ if got := cx.SideModel(); got != "" {+ t.Fatalf("joined on Codex's own model: %q", got)+ }+ if err := cx.Fields[0].Set("fake/m1"); err != nil {+ t.Fatal(err)+ }+ if got := cx.SideModel(); got != "fake/m1" {+ t.Fatalf("a magpie model beside the sign-in: %q", got)+ }+ if err := cx.Field("login").Set("api"); err != nil {+ t.Fatal(err)+ }+ if got := cx.SideModel(); got != "" {+ t.Fatalf("magpie Codex's provider: %q", got)+ }+}diff --git a/internal/cli/main.go b/internal/cli/main.goindex 785ae3c04..2b4d66552 100644--- a/internal/cli/main.go+++ b/internal/cli/main.go@@ -293,6 +293,10 @@ func run(args []string) error {// a Codex that reaches magpie for account failover alone is handed// only its own models (#1385)gateway.CodexOwnOnly = agent.CodexOwnOnly+ // the Codex app's titles, descriptions and summaries, which it asks+ // for on a model of its own, on the model of magpie's picked beside+ // its ChatGPT sign-in rather than on that account (atom_Ray on X)+ gateway.CodexSideModel = agent.CodexSideModel// the setup kept the same on every computer, by whichever servesgateway.WhileServing = append(gateway.WhileServing, davsync.Run)// and dsh's patch lists, which dsh reads live: a route left behind bydiff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.goindex facca7118..bf0a19e7e 100644--- a/internal/gateway/codex_backend.go+++ b/internal/gateway/codex_backend.go@@ -112,6 +112,10 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {s.codexDescription(w, r, body, to)return}+ if to := codexSummariesTo(r.Header, body, false); to != "" {+ s.codexSummary(w, r, body, to)+ return+ }if to := codexPredictionsTo(r.Header, body, false); to != "" {s.codexPrediction(w, r, body, to)returndiff --git a/internal/gateway/codex_side_test.go b/internal/gateway/codex_side_test.gonew file mode 100644index 000000000..f654d59c2--- /dev/null+++ b/internal/gateway/codex_side_test.go@@ -0,0 +1,152 @@+package gateway++import (+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/provider"+ "github.com/yetone/magpie/internal/usage"+)++// codexSideRequest is one of the Codex app's hidden side turns as it sends+// one beside its ChatGPT sign-in: on gpt-6-luna, its own model, whatever+// the conversation is on, with the thread's source in its turn metadata+// and the schema its answer must fill in text.format.+func codexSideRequest(t *testing.T, s *Server, source, schema string) *httptest.ResponseRecorder {+ t.Helper()+ body := `{"model":"gpt-6-luna","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Latest message: fixed the login bug"}]}],` ++ `"text":{"format":{"type":"json_schema","name":"codex_output_schema","strict":true,"schema":` + schema + `}}}`+ rec := httptest.NewRecorder()+ req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body))+ req.Header.Set("Authorization", "Bearer chatgpt-token")+ req.Header.Set("session_id", "side-thread")+ req.Header.Set("x-codex-turn-metadata", `{"thread_source":"`+source+`"}`)+ s.Handler().ServeHTTP(rec, req)+ return rec+}++const (+ sideTitleSchema = `{"type":"object","properties":{"title":{"type":"string","maxLength":36},"description":{"type":"string"}},"required":["title","description"],"additionalProperties":false}`+ sideDescriptionSchema = `{"type":"object","properties":{"description":{"type":"string"}},"required":["description"],"additionalProperties":false}`+ sideSummarySchema = `{"type":"object","properties":{"summary":{"type":"string"},"compactSummary":{"type":"string","maxLength":60}},"required":["summary","compactSummary"],"additionalProperties":false}`+)++// With one of magpie's models picked beside Codex's ChatGPT sign-in, the+// Codex app's titles, descriptions and summaries, which it asks for on+// gpt-6-luna whatever the conversation is on, are written by the model+// picked, not by ChatGPT, so a conversation on a third-party model spends+// none of the ChatGPT account's allowance (atom_Ray on X: an hour took 2%+// of the 5-hour window, and at 0% they failed). Each answer goes back in+// the shape its schema asks for. On Codex's own model (no side model) they+// go to ChatGPT as before, and so does a turn of the conversation.+func TestCodexSideTurnsOnThePickedModel(t *testing.T) {+ f := &fake{t: t, reply: sse(+ `data: {"id":"c1","choices":[{"index":0,"delta":{"content":"Fixed the login bug"}}]}`,+ `data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":30,"completion_tokens":4}}`,+ `data: [DONE]`)}+ setup(t, provider.Chat, f)+ chatgptCalls := 0+ chatgpt(t, func(w http.ResponseWriter, r *http.Request) {+ io.ReadAll(r.Body)+ chatgptCalls+++ w.Header().Set("Content-Type", "text/event-stream")+ io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"{\"summary\":\"From ChatGPT\"}"}]}],"usage":{"input_tokens":9,"output_tokens":2}}}`))+ })+ side := ""+ CodexSideModel = func() string { return side }+ t.Cleanup(func() { CodexSideModel = nil })+ s := New()++ // on Codex's own model: every side turn to ChatGPT, as before+ for _, src := range []string{"thread_title", "thread_description", "thread_summary"} {+ codexSideRequest(t, s, src, sideSummarySchema)+ }+ if chatgptCalls != 3 || f.calls != 0 {+ t.Fatalf("own model: chatgpt %d, magpie model %d", chatgptCalls, f.calls)+ }++ side = "fake/m1"+ for _, c := range []struct{ source, schema, want string }{+ {"thread_title", sideTitleSchema, `{"description":"Fixed the login bug","title":"Fixed the login bug"}`},+ {"thread_description", sideDescriptionSchema, `{"description":"Fixed the login bug"}`},+ {"thread_summary", sideSummarySchema, `{"compactSummary":"Fixed the login bug","summary":"Fixed the login bug"}`},+ } {+ before := f.calls+ rec := codexSideRequest(t, s, c.source, c.schema)+ if text, _ := outputText(t, rec.Body.String()); rec.Code != 200 || text != c.want || f.calls != before+1 || chatgptCalls != 3 {+ t.Fatalf("%s on the picked model: %d %q, magpie model %d, chatgpt %d", c.source, rec.Code, rec.Body.String(), f.calls, chatgptCalls)+ }+ var sent struct {+ Model string `json:"model"`+ }+ json.Unmarshal(f.got, &sent)+ if sent.Model != "m1" {+ t.Errorf("%s: the magpie model was asked for %q", c.source, sent.Model)+ }+ }++ // a turn of the conversation on Codex's own model is the user's pick:+ // it goes to ChatGPT, side model or not+ rec := httptest.NewRecorder()+ req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"hi"}`))+ req.Header.Set("Authorization", "Bearer chatgpt-token")+ s.Handler().ServeHTTP(rec, req)+ if chatgptCalls != 4 || f.calls != 3 {+ t.Errorf("a plain turn: chatgpt %d, magpie model %d", chatgptCalls, f.calls)+ }++ var kinds []string+ for _, u := range usage.Load(time.Time{}) {+ kinds = append(kinds, u.Provider+":"+u.Kind)+ }+ want := "openai:thread_title openai:thread_description openai:thread_summary fake:thread_title fake:thread_description fake:thread_summary openai:"+ if got := strings.Join(kinds, " "); got != want {+ t.Errorf("ledger %s\nwant %s", got, want)+ }+}++// A summary on one of magpie's models, with magpie Codex's provider, is+// handed back in the shape its schema asks for too: a model behind the+// Chat API never sees the schema, and the app drops a plain answer.+func TestCodexSummaryOnMagpieProvider(t *testing.T) {+ f := &fake{t: t, reply: sse(+ `data: {"id":"c1","choices":[{"index":0,"delta":{"content":"Summary: \"Ran the tests\""}}]}`,+ `data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":2}}`,+ `data: [DONE]`)}+ setup(t, provider.Chat, f)+ s := New()+ body := `{"model":"fake/m1","stream":true,"input":"Summarize","text":{"format":{"type":"json_schema","schema":{"type":"object","properties":{"summary":{"type":"string"}},"required":["summary"]}}}}`+ rec := httptest.NewRecorder()+ req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))+ req.Header.Set("x-codex-turn-metadata", `{"thread_source":"thread_summary"}`)+ s.Handler().ServeHTTP(rec, req)+ if text, _ := outputText(t, rec.Body.String()); rec.Code != 200 || text != `{"summary":"Ran the tests"}` || f.calls != 1 {+ t.Fatalf("summary: %d %q, calls %d", rec.Code, rec.Body.String(), f.calls)+ }+}++func TestSummaryJSON(t *testing.T) {+ long := `{"type":"object","properties":{"summary":{"type":"string"},"compactSummary":{"type":"string","maxLength":10}},"required":["summary","compactSummary"]}`+ var shape titleShape+ json.Unmarshal([]byte(long), &shape)+ for in, want := range map[string]string{+ "Fixed it": `{"compactSummary":"Fixed it","summary":"Fixed it"}`,+ "Fixed the\nlogin bug": `{"compactSummary":"Fixed the","summary":"Fixed the login bug"}`,+ `{"summary":"A","compactSummary":"B"}`: `{"compactSummary":"B","summary":"A"}`,+ "```json\n{\"summary\":\"Fenced\"}\n```": `{"compactSummary":"Fenced","summary":"Fenced"}`,+ "": "",+ "{broken": "",+ } {+ if got := summaryJSON(in, shape); got != want {+ t.Errorf("summaryJSON(%q) = %s, want %s", in, got, want)+ }+ }+ if got := summaryJSON("Ran the tests", titleShape{}); got != `{"summary":"Ran the tests"}` {+ t.Errorf("no shape: %s", got)+ }+}diff --git a/internal/gateway/codex_titles.go b/internal/gateway/codex_titles.goindex c7174c431..2deebfd0a 100644--- a/internal/gateway/codex_titles.go+++ b/internal/gateway/codex_titles.go@@ -34,9 +34,32 @@ func codexTitlesTo(h http.Header, body []byte, ours bool) string {if to := settings.Load().CodexTitles; to != "" {return to}- if m := modelOf(body); m != "" && (ours || strings.Contains(m, "/")) {+ return codexSideTo(body, ours)+}++// CodexSideModel is the model this machine's Codex is set to when it is+// one of magpie's, picked beside Codex's ChatGPT sign-in, "" otherwise+// (agent.CodexSideModel).+var CodexSideModel func() string++// codexSideTo is the model that answers one of the Codex app's hidden+// side turns (a thread's title, description or one-line summary) when no+// setting names one: the model Codex asked for when it is one of magpie's+// (ours: the request came to magpie's own API, where every model is), "" to+// leave it as Codex sent it. The app asks for these on a model of its own+// (gpt-6-luna) whatever the conversation is on, so with one of magpie's+// models picked beside the ChatGPT sign-in every one of them went to+// ChatGPT and spent its allowance, and failed with it once it was used up+// (atom_Ray on X: an hour on a third-party model took 2% of the 5-hour+// window). Those go to the model picked, as the conversation's turns do.+func codexSideTo(body []byte, ours bool) string {+ m := modelOf(body)+ if m != "" && (ours || strings.Contains(m, "/")) {return m}+ if !ours && CodexSideModel != nil {+ return CodexSideModel()+ }return ""}@@ -53,10 +76,19 @@ func codexDescriptionsTo(h http.Header, body []byte, ours bool) string {}// Codex on a magpie model gets no schema upstream (#743), so an empty// setting still wraps the model it asked for, as titles do.- if m := modelOf(body); m != "" && (ours || strings.Contains(m, "/")) {- return m+ return codexSideTo(body, ours)+}++// codexSummariesTo is where the Codex app's request for a thread's+// one-line activity summary goes (thread_summary, asked after each message+// of a thread): the model codexSideTo names, its answer handed back as the+// {"summary": …} the request's schema asks for; "" leaves it as Codex sent+// it.+func codexSummariesTo(h http.Header, body []byte, ours bool) string {+ if !isSummaryKind(requestCallKind(h, requestSessionMetadata(h, body))) {+ return ""}- return ""+ return codexSideTo(body, ours)}// codexPredictionsTo is where the Codex app's request to predict the@@ -164,16 +196,36 @@ func (s *Server) codexTitle(w http.ResponseWriter, r *http.Request, body []byte,// {"description": ...} its schema asks for; a reply without one fails as a// description, not as a title.func (s *Server) codexDescription(w http.ResponseWriter, r *http.Request, body []byte, to string) {+ s.codexShaped(w, r, body, to, "description", true, descriptionJSON, noDescription)+}++// codexSummary answers a thread_summary request as codexSummariesTo says,+// by that model, its text handed back as the {"summary": …} the request's+// schema asks for (a compactSummary beside it when the schema asks for+// one too).+func (s *Server) codexSummary(w http.ResponseWriter, r *http.Request, body []byte, to string) {+ shape := titleShapeOf(body)+ s.codexShaped(w, r, body, to, "summary", false, func(said string) string { return summaryJSON(said, shape) }, noSummary)+}++// codexShaped answers one of Codex's hidden side turns by the model to,+// its answer handed back as shaped makes it the JSON the turn's schema+// asks for, which a model behind another API never sees; an answer+// shaped finds nothing in fails as missing says. chose: magpie picked the+// model in its settings rather than the caller (magpieChose).+func (s *Server) codexShaped(w http.ResponseWriter, r *http.Request, body []byte, to, what string, chose bool, shaped func(said string) string, missing func(said string) string) {body, _ = codexInput(body, true)rec := &recorder{header: http.Header{}, status: 200}check := func(reply string) string {- if res, err := compactReply([]byte(reply)); err == nil && descriptionJSON(messageText(res)) == "" {- return noDescription(messageText(res))+ if res, err := compactReply([]byte(reply)); err == nil && shaped(messageText(res)) == "" {+ return missing(messageText(res))}return ""}ctx := context.WithValue(r.Context(), titleCheckKey{}, check)- ctx = magpieChose(ctx)+ if chose {+ ctx = magpieChose(ctx)+ }s.serve(rec, r.WithContext(ctx), provider.Responses, withModel(body, to))if rec.status >= 400 {for k, vs := range rec.header {@@ -185,7 +237,7 @@ func (s *Server) codexDescription(w http.ResponseWriter, r *http.Request, body [}res, err := compactReply(rec.body.Bytes())if err != nil {- writeError(w, provider.Responses, 502, "description: "+err.Error())+ writeError(w, provider.Responses, 502, what+": "+err.Error())return}id := res.ID@@ -193,7 +245,7 @@ func (s *Server) codexDescription(w http.ResponseWriter, r *http.Request, body [id = fmt.Sprintf("resp_magpie_%d", time.Now().UnixNano())}var out []any- if d := descriptionJSON(messageText(res)); d != "" {+ if d := shaped(messageText(res)); d != "" {out = append(out, map[string]any{"type": "message", "id": "msg_" + strings.TrimPrefix(id, "resp_"), "role": "assistant", "status": "completed","content": []any{map[string]any{"type": "output_text", "text": d, "annotations": []any{}}}})}@@ -305,6 +357,73 @@ func predictionJSON(said string) (string, bool) {return string(b), true}+func noSummary(said string) string {+ said = strings.Join(strings.Fields(said), " ")+ if said == "" {+ return "summary: the model answered with no text, so Codex got no summary"+ }+ if r := []rune(said); len(r) > 80 {+ said = string(r[:80]) + "…"+ }+ return "summary: no summary in the model's answer, so Codex got none: " + said+}++// summaryJSON is a model's answer to a thread_summary request as Codex+// reads one: {"summary": "…"} on one line, with each other string its+// shape requires (compactSummary) the model's own when its JSON gave one,+// else the summary, cut to the schema's length. "" when it gave none.+func summaryJSON(said string, shape titleShape) string {+ t := strings.TrimSpace(said)+ t = afterThought(t)+ if strings.HasPrefix(t, "```") {+ t = strings.TrimPrefix(t, "```")+ if i := strings.IndexByte(t, '\n'); i >= 0 && !strings.Contains(t[:i], "{") {+ t = t[i+1:]+ }+ t = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(t), "```"))+ }+ fields := map[string]any{}+ if strings.HasPrefix(t, "{") {+ if json.NewDecoder(bytes.NewReader([]byte(t))).Decode(&fields) == nil {+ if v, ok := fields["summary"].(string); ok {+ t = v+ }+ }+ }+ t = strings.Join(strings.Fields(t), " ")+ if low := strings.ToLower(t); strings.HasPrefix(low, "summary:") {+ t = t[len("summary:"):]+ }+ t = strings.TrimSpace(strings.Trim(strings.TrimSpace(t), "\"'`*“”‘’"))+ if t == "" || strings.HasPrefix(t, "{") {+ return ""+ }+ clip := func(name, v string) string {+ if n := shape.Properties[name].MaxLength; n > 0 {+ if r := []rune(v); len(r) > n {+ v = strings.TrimSpace(string(r[:n]))+ }+ }+ return v+ }+ out := map[string]string{"summary": clip("summary", t)}+ for _, name := range shape.Required {+ if _, done := out[name]; done {+ continue+ }+ if ty := shape.Properties[name].Type; ty != "" && ty != "string" {+ continue+ }+ v, _ := fields[name].(string)+ if v = strings.Join(strings.Fields(v), " "); v == "" {+ v = t+ }+ out[name] = clip(name, v)+ }+ b, _ := json.Marshal(out)+ return string(b)+}+func noDescription(said string) string {said = strings.Join(strings.Fields(said), " ")if said == "" {diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex 3bedcde12..8802833d4 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -1498,6 +1498,10 @@ func (s *Server) handle(from provider.Protocol) http.HandlerFunc {s.codexDescription(w, r, body, to)return}+ if to := codexSummariesTo(r.Header, body, true); to != "" {+ s.codexSummary(w, r, body, to)+ return+ }if to := codexPredictionsTo(r.Header, body, true); to != "" {s.codexPrediction(w, r, body, to)returndiff --git a/internal/gateway/session_parent.go b/internal/gateway/session_parent.goindex 470da1b87..bfd4634e1 100644--- a/internal/gateway/session_parent.go+++ b/internal/gateway/session_parent.go@@ -15,6 +15,12 @@ func isDescriptionKind(kind string) bool {return kind == "thread_description"}+// isSummaryKind: the Codex app's one-line summary of a thread's latest+// message, shown under its title (thread_summary)+func isSummaryKind(kind string) bool {+ return kind == "thread_summary"+}+// isPredictionKind: the Codex app's guess at the user's next message,// shown in its composer (composer_predictions, #1970)func isPredictionKind(kind string) bool {