gateway, provider, gui: a provider set to compact natively is asked Codex's compaction_trigger as sent and its sealed compaction goes back unchanged; a checkpoint stays with its writer (#1099)
A new per-provider option, off by default. With it on, Codex's compaction_trigger reaches the provider as Codex sent it, and the provider's encrypted compaction item goes back to Codex unchanged instead of magpie's magpie1: summary. Off, nothing changes. Where it can be on (provider.CarriesCompaction): a provider with a Responses API (Sub2API and other OpenAI relays, a remote magpie), a ChatGPT (codex) account, and the built-in GitHub Copilot on its GPT Responses path. Copilot's Claude models are asked on chat completions, so they still get magpie's summary (CompactsOn). A group compacts natively only when every member does. No silent downgrade: - A turn carrying a sealed compaction goes only to the key or account that wrote it (compactions.json beside affinity.json, 0600, 1024 entries / 30 days). With none left, Codex gets a 400 saying the conversation was compacted natively on <who>, not a summarised or dropped context. - A provider whose request would have to be translated (not relayed) is refused with a 400 instead of losing the item. - The upstream's own refusal goes back to Codex as it came, one call. - base_instructions and Codex's identity are untouched. Turning it on: - GUI: the provider editor's Compaction row, "Codex compacts on this provider" (shown only where the wire can carry it; zh, zh-TW, ja, de). - CLI: magpie provider set <id> compaction=native|magpie. A provider that can't carry it is refused. Run on origin/main00501401a, then rebased onto84f14e555(no file in common) and reran gofmt, vet and go test for gateway, gui, provider, cli, usage and sessions: all ok. Rebased again onto8d2a4a7da(gateway.go and codex_backend.go changed on both sides, merged clean) and reran gofmt, vet (darwin, linux nogui, windows) and go test for gateway, cli, provider and gui: all ok. Last rebased onto7a3fed6bb(only gateway-routing.md shared, merged clean): gofmt, vet on all three OSes, and go test -run for the native compaction, sink, CORS, rebind and origin tests in gateway plus the provider tests: ok. - gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean. - set -o pipefail; go test -timeout 40m ./...: every package ok but internal/provider's TestCopilotSecretToolUsername (copilot_cli_test.go:93 token "", 10.05s), the open load flake #1627; it passes alone -count=5 and this change doesn't touch it. - GUI (node --test, chromium + webkit): the provider-editor files, 946 pass, 0 fail; the new provider-native-compaction.test.cjs runs 5 languages at 1100 and 420 (60 cases). - New Go tests: TestNativeCompactionPassesTheTrigger, ...RefusalGoesBack, ...StaysWithItsWriter, ...Copilot (gateway), TestCarriesCompaction, TestSetNativeCompaction (provider), TestProviderSaveNativeCompaction (gui), TestProviderCompactionPair (cli). Broken by hand, each red, then restored: 1. codexInputAs dropping the trigger even when native: all 4 gateway tests fail. 2. checkpoint filter off: StaysWithItsWriter fails. 3. forced relay off: all 4 gateway tests fail (the web_search tool sends the turn to translation). 4. GUI save sending nativeCompaction false: the GUI test's first case fails. Not tried: any real upstream (Sub2API, ChatGPT, Copilot). Copilot may refuse a compacted history holding web_search items; that refusal would go back to Codex as-is.
This commit is contained in:
@@ -130,6 +130,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models kept out of agents' lists for routing groups (`provider.CodexNativeUnlisted`) are dropped from it too, hidden ones kept: every one when the codex provider is "Only through routing groups" (`Provider.Unlisted`), and those a group that unlists its members names (`Group.Unlists`). A Codex there only for failover keeps them, as it is handed no groups; `spawnChoices` drops the same ones (#1602, `TestCodexModelListUnlistedForGroups`).
|
||||
- Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming Messages request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts<n>__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. Carrying reasoning across APIs (an envelope) isn't done.
|
||||
- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. When a provider answers its summary request 404, or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301).
|
||||
- Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set <id> compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The key or account that answered is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); with the writer gone from the candidates (switched off, resting, removed), magpie answers 400 `checkpointError` naming why, and never sends it to another key, drops it, or summarises it in its place. `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`.
|
||||
- A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set <id> codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`.
|
||||
- Every request to a key+URL provider goes with magpie's User-Agent (`magpie/<Version>`, `userAgentFor` in [`user_agent.go`](../../internal/gateway/user_agent.go)), except a provider set `passUserAgent` (#1851, `magpie provider set <id> user-agent=agent`, the editor's "Send the agent's own User-Agent"): it gets the User-Agent the inbound request carried, unchanged, for a coding plan that serves only the agents it names. One the agent didn't send, and magpie's own (`magpiesOwn`: another magpie's `magpie/…`, `magpie-router/1`, `magpie-vision/1`, `magpie-search/1`, and the image tool's `<client> magpie-image/1`, built from MCP's clientInfo, not a User-Agent), go as magpie; magpie never makes up another client's. `forwardOnce` sets it for chat, Anthropic, Responses, Gemini and count_tokens; embeddings, images and videos (`retrieveFrom`, `sendWith`, `remoteVideoContent`) set it with `stampUA` from the caller the request came with (`caller.ua`, `withCaller`), and before #1851 went with Go's default. Claude Code's and Codex's own headers are copied after, as before, and the user's `header.User-Agent` is put on when the request is signed, so it wins. `provider.PassesUserAgent` refuses it for a signed-in account, a plugin's, and a vendor whose own client magpie goes as (`OwnClient`: OpenCode, Cline, Kilo, another magpie); their signing sets their own. `TestUserAgentPassedOn`, `TestUserAgentAccountUntouched`, `TestUserAgentFor`, `TestPassesUserAgent`, `provider-user-agent.test.cjs`.
|
||||
- A Chat upstream that wants a turn's reasoning back (`chatReplaysReasoning` in [`chat.go`](../../internal/gateway/chat.go): a host or a model, as magpie or the provider names it, with `deepseek` in it, such as OpenCode Go's `deepseek-v4.1-flash`, or Command Code's plugin) gets every assistant tool call with `reasoning_content`, relayed (`withReasoningOnToolTurns` in `passthrough`) or translated (`buildChat`). DeepSeek turns the whole request away ("The `reasoning_content` in the thinking mode must be passed back to the API") when a tool call made since the user's last message has none, which a client sends for a turn it saw no thinking on: another model's, a translated one (#1462). The turn's own thinking goes back as it came; one sent in `reasoning` or `reasoning_details` is copied in; otherwise it goes with a space (`noReasoning`: DeepSeek's Chat API takes an empty one, but a relay that leaves empty fields out would drop it). An assistant message right after a tool result, a reply with no call of its own, gets one too: DeepSeek refuses it the same way (checked 2026-10-12, #1822). A reply to the user, any other model and Mistral (#494) are sent as before.
|
||||
|
||||
@@ -21,6 +21,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Anthropic key header | A provider of the user's own on a third-party Anthropic API is sent its key as both `x-api-key` and `Authorization: Bearer` (`AuthHeaders`); Anthropic's own API, Bedrock, Azure, Vertex and every subscription account have their own and never this choice (`BothAuth` is false). Some services refuse the two together with a 401 (Aloha on Discord: "鉴权 header, x-api-key 和 Authorization 不可以同时存在"), so `Provider.AuthHeader` (`authHeader`: empty for both, `x-api-key` or `bearer`; anything else is read as empty) sends one alone, picked in the editor's Key header row (shown while `bothAuth` is true, or a custom provider's Anthropic URL is a third party's). Left at both, a 401 whose body `catalog.BothAuthRefused` tells as that refusal (it names both headers and says they can't be together, in Chinese or English) is asked once more with x-api-key alone, then Bearer alone (`RetryOneAuth`, in the gateway's `forwardOnce` and the provider test's `probe`; `catalog.fetchOne` for the model list through `listAuth`); the first not answered 401 or 403 is kept with `LearnAuthHeader`, which never changes a pick the user made. A request carrying the user's own `Authorization` or `x-api-key` header is never retried. | [`authheader.go`](../../internal/provider/authheader.go), [`test.go`](../../internal/provider/test.go), [`catalog/authheader.go`](../../internal/catalog/authheader.go), [`catalog/live.go`](../../internal/catalog/live.go) |
|
||||
| GLM Coding Plan key at pay as you go | Zhipu's and Z.ai's presets offer Pay as you go first (`/api/paas/v4`) and the Coding Plan (`/api/coding/paas/v4`, Responses at `/api/v1`); both share `/api/anthropic`, which bills the plan, so a plan's key left at Pay as you go worked in Claude Code and was refused 429 code 1113 "余额不足或无可用资源包" in Codex (@cleverpigo on X). Nothing in the key tells the two apart, so a Chat request to `open.bigmodel.cn` or `api.z.ai` at `/api/paas/v4` refused 1113 is asked once more at `/api/coding/paas/v4` (`RetryZhipuCoding`, in the gateway's `forwardOnce` and the provider test's `probe`). Served there, `LearnZhipuCoding` moves a saved provider with that one key, still at that URL, to the plan's OpenAI URL (and the preset's plan Responses URL when it has none); one with other keys stays and is asked again each time. Refused there too, the 1113 body keeps its code and gets both URLs and what to change in its message (`ZhipuNoBalanceHint`). A pay-as-you-go key with a balance is never answered 1113 and never sent to the plan's endpoint. | [`zhipu_coding.go`](../../internal/provider/zhipu_coding.go), [`test.go`](../../internal/provider/test.go) |
|
||||
| Extra body | `ExtraBody` (`extraBody` in providers.json, the editor's *Extra body*, #1604) is a JSON object whose fields `WithExtraBody` adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's `forwardOnce` and in Test and Detect (`tested`). A field the body has already is kept; a name written `"!name"` replaces it. Values are put in as written, objects whole, not merged. `${sessionId}` in any string, at any depth, becomes the request's session: the agent's session header (`sessionOf`), else the id `conversationID` derives from the first user message (`magpie-` and its hash), so it stays the same through one conversation; Test and Detect send `magpie-test-` and 12 random letters, a new one each time. `model`, `stream` and the conversation (`messages`, `input`, `contents`, `system`, `systemInstruction`, `system_instruction`, `instructions`, `tools`, `ExtraBodyReserved`) are magpie's: Save refuses them with or without `!` (`ExtraBodyOK`), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (`cleanExtraBody`). Not sent with it: `count_tokens`, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests. One object goes to every API; fields for one API alone are not a thing yet. | [`extrabody.go`](../../internal/provider/extrabody.go), [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| Native compaction | `NativeCompaction` (`nativeCompaction` in providers.json, the editor's *Compaction* row, `magpie provider set <id> compaction=native\|magpie`; #1099) has Codex's compaction asked of the provider as Codex sent it and its sealed item returned unchanged. Off by default. Only a provider whose wire carries it can be set so (`CarriesCompaction`: a Responses API, a ChatGPT account, GitHub Copilot; not another agent's sign-in or a plugin's), and `CompactsOn(model)` also needs the model asked on Responses. `SetNativeCompaction`, the CLI and the GUI's save refuse it elsewhere. An account keeps it through `Save`'s picks (`withPicks`), and `AddCopy` carries it. The gateway's half is in [gateway-routing](gateway-routing.md). | [`native_compaction.go`](../../internal/provider/native_compaction.go) |
|
||||
| providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) |
|
||||
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). | [`provider.go`](../../internal/provider/provider.go) |
|
||||
| Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models <id> none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) |
|
||||
|
||||
@@ -38,7 +38,10 @@ const providerUsage = `usage:
|
||||
(a relay that checks they are Codex's own), codex=default fits them;
|
||||
user-agent=agent sends the User-Agent the agent gave (pi, opencode…)
|
||||
in place of magpie's, for a plan that serves only agents it names;
|
||||
user-agent=magpie, the default, sends magpie's
|
||||
user-agent=magpie, the default, sends magpie's;
|
||||
compaction=native asks the provider Codex's own compaction and hands
|
||||
Codex its sealed item as it came (a Responses API, a ChatGPT account,
|
||||
Copilot), compaction=magpie, the default, has magpie summarise
|
||||
magpie provider key <id> <key> change the API key
|
||||
magpie provider icon <id> <file|name> give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon
|
||||
magpie provider fallback <id> <provider/model>… where requests go when it's out of quota or down (none clears)
|
||||
@@ -796,6 +799,9 @@ func showProvider(p provider.Provider) error {
|
||||
}
|
||||
kv("unmasked", "yes"+muted.Render(why))
|
||||
}
|
||||
if p.NativeCompaction {
|
||||
kv("compaction", "native"+muted.Render(" Codex's own, sealed by the key or account that answers it"))
|
||||
}
|
||||
switch {
|
||||
case p.Account != nil:
|
||||
who := p.Account.User
|
||||
@@ -1039,6 +1045,18 @@ func applyPairs(p *provider.Provider, pairs []string) error {
|
||||
return fmt.Errorf("search=yes|no, not %q", v)
|
||||
}
|
||||
p.Searches = v == "yes"
|
||||
case "compaction":
|
||||
// native: Codex's compaction_trigger goes to the provider as
|
||||
// Codex sent it, its sealed compaction back to Codex as it
|
||||
// came (#1099); magpie: magpie's summary, the default
|
||||
switch strings.ToLower(v) {
|
||||
case "native", "yes", "on":
|
||||
p.NativeCompaction = true
|
||||
case "magpie", "default", "no", "off":
|
||||
p.NativeCompaction = false
|
||||
default:
|
||||
return fmt.Errorf("compaction=native|magpie, not %q", v)
|
||||
}
|
||||
case "unmasked":
|
||||
// yes: a model on this computer or the local network gets the
|
||||
// requests as written, unmasked by Settings' redaction (lc on
|
||||
@@ -1094,6 +1112,9 @@ func applyPairs(p *provider.Provider, pairs []string) error {
|
||||
return fmt.Errorf("unknown field %q\n\n%s", k, providerUsage)
|
||||
}
|
||||
}
|
||||
if p.NativeCompaction && !p.CarriesCompaction() {
|
||||
return fmt.Errorf("compaction=native: %s can't carry Codex's own compaction; only a provider with a Responses API (responses=), a ChatGPT account or GitHub Copilot can", p.Name)
|
||||
}
|
||||
if workspace != "" {
|
||||
// Bailian's decision model is asked at the workspace's own host
|
||||
if !strings.Contains(p.Decide, provider.WorkspaceID) {
|
||||
|
||||
@@ -29,3 +29,27 @@ func TestProviderUserAgentPair(t *testing.T) {
|
||||
t.Fatalf("an account turning it off: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// compaction=native has a provider whose wire carries it be asked Codex's
|
||||
// own compaction (#1099), compaction=magpie goes back to magpie's summary,
|
||||
// and a provider without a Responses API is refused it.
|
||||
func TestProviderCompactionPair(t *testing.T) {
|
||||
p := provider.Provider{ID: "relay", Name: "Relay", Responses: "https://relay.example/v1", Key: "k"}
|
||||
if err := applyPairs(&p, []string{"compaction=native"}); err != nil || !p.NativeCompaction {
|
||||
t.Fatalf("native: %v %v", p.NativeCompaction, err)
|
||||
}
|
||||
if err := applyPairs(&p, []string{"compaction=magpie"}); err != nil || p.NativeCompaction {
|
||||
t.Fatalf("magpie: %v %v", p.NativeCompaction, err)
|
||||
}
|
||||
if err := applyPairs(&p, []string{"compaction=sometimes"}); err == nil || !strings.Contains(err.Error(), "native|magpie") {
|
||||
t.Fatalf("a made-up value: %v", err)
|
||||
}
|
||||
c := provider.Provider{ID: "chat", Name: "Chat", Chat: "https://chat.example/v1", Key: "k"}
|
||||
if err := applyPairs(&c, []string{"compaction=native"}); err == nil {
|
||||
t.Fatalf("a chat-only provider took it")
|
||||
}
|
||||
cp := provider.Provider{ID: "copilot", Name: "GitHub Copilot", Responses: "https://api.githubcopilot.com", Account: &provider.Account{Agent: "copilot"}}
|
||||
if err := applyPairs(&cp, []string{"compaction=native"}); err != nil || !cp.NativeCompaction {
|
||||
t.Fatalf("copilot: %v %v", cp.NativeCompaction, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +149,9 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
// a sealed subagent task goes to a ChatGPT account the model
|
||||
// or group has, or is turned away (serve, sealedReader)
|
||||
body, compact := codexInput(body, true)
|
||||
// a provider set to compact natively is asked Codex's own
|
||||
// compaction, and its sealed item goes back as it came (#1099)
|
||||
body, compact := codexInputAs(body, true, s.nativeCompactionFor(model))
|
||||
if compact {
|
||||
s.codexCompact(w, r, body)
|
||||
return
|
||||
@@ -1362,6 +1364,13 @@ func codexListTag() string {
|
||||
// replaces Codex's compaction trigger with a request to summarise the input.
|
||||
// OpenAI's own models keep the trigger for their backend to handle.
|
||||
func codexInput(body []byte, magpieModel bool) (_ []byte, compact bool) {
|
||||
return codexInputAs(body, magpieModel, false)
|
||||
}
|
||||
|
||||
// codexInputAs is codexInput, the trigger kept for a magpie model too
|
||||
// when native says its provider compacts natively (NativeCompaction,
|
||||
// #1099): the summaries magpie made before are still restored.
|
||||
func codexInputAs(body []byte, magpieModel, native bool) (_ []byte, compact bool) {
|
||||
var q map[string]json.RawMessage
|
||||
if json.Unmarshal(body, &q) != nil {
|
||||
return body, false
|
||||
@@ -1386,7 +1395,7 @@ func codexInput(body []byte, magpieModel bool) (_ []byte, compact bool) {
|
||||
out = append(out, userMessage(codexSummaryPrefix+"\n"+string(b)))
|
||||
}
|
||||
case "compaction_trigger":
|
||||
if !magpieModel {
|
||||
if !magpieModel || native {
|
||||
out = append(out, it)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1328,10 +1328,11 @@ func (s *Server) handle(from provider.Protocol) http.HandlerFunc {
|
||||
// Codex compacts remotely, a compaction_trigger here, on a
|
||||
// provider table named "OpenAI" (CC Switch's relay tables,
|
||||
// which magpie points here, #1301): the summary is magpie's to
|
||||
// make, as on CodexPath, and magpie's summaries go back as text
|
||||
// make, as on CodexPath, and magpie's summaries go back as text;
|
||||
// a provider set to compact natively is asked Codex's own (#1099)
|
||||
if bytes.Contains(body, []byte(`"compaction`)) {
|
||||
var compact bool
|
||||
if body, compact = codexInput(body, true); compact {
|
||||
if body, compact = codexInputAs(body, true, s.nativeCompactionFor(modelOf(body))); compact {
|
||||
s.codexCompact(w, r, body)
|
||||
return
|
||||
}
|
||||
@@ -1861,6 +1862,32 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
if sealedTask {
|
||||
cands, pl = s.sealedReaders(cands, pl, sealers)
|
||||
}
|
||||
// a compaction a provider set to compact natively sealed goes only to
|
||||
// the key or account that sealed it, or is refused saying so: never
|
||||
// to another, to be refused, dropped or summarised (#1099). Codex's
|
||||
// trigger goes only where it can be asked as Codex sent it.
|
||||
var checkpoint *checkpointWriter
|
||||
if from == provider.Responses {
|
||||
if cp, ok := checkpointOf(body); ok {
|
||||
checkpoint = &cp
|
||||
var left bool
|
||||
if cands, pl, left = checkpointReaders(cands, pl, cp.Who); !left {
|
||||
call.Status, call.Error = 400, "native compaction sealed elsewhere"
|
||||
writeError(w, from, 400, checkpointError(call.Model, cp))
|
||||
turnedAway()
|
||||
return
|
||||
}
|
||||
}
|
||||
if compactionTriggerIn(body) {
|
||||
var left bool
|
||||
if cands, pl, left = s.compactionCarriers(cands, pl); !left {
|
||||
call.Status, call.Error = 400, "native compaction not carried"
|
||||
writeError(w, from, 400, carrierError(call.Model))
|
||||
turnedAway()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
var accountHeld bool // every candidate was an account or key the calling key may not use
|
||||
if keyHeld || accHeld {
|
||||
who := keyWho
|
||||
@@ -2112,6 +2139,21 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
// and the provider's last answer, saved to disk, took seconds on a busy
|
||||
// disk, and the reply's speed counted them as its own)
|
||||
var ended time.Time
|
||||
// the compaction a provider set to compact natively seals, read on the
|
||||
// way to Codex, and who sealed it remembered once it has answered
|
||||
// (#1099)
|
||||
var sealedBy *candidate
|
||||
if from == provider.Responses && compactionTriggerIn(body) {
|
||||
watch := &compactionWatch{w: w}
|
||||
w = watch
|
||||
defer func() {
|
||||
if sealedBy != nil {
|
||||
if enc := watch.sealed(); enc != "" {
|
||||
wroteCheckpoint(enc, *sealedBy)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
for i := 0; i < len(cands); i++ {
|
||||
c := cands[i]
|
||||
if j := s.laneMate(cands, i, isGroup, gaveWay); j > i {
|
||||
@@ -2585,7 +2627,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
refused(stuck, c.who(), attemptBody, "reasoning")
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
// a compaction sealed where native compaction is on is never
|
||||
// left out: its writer's refusal goes back as it came (#1099)
|
||||
if !ok && checkpoint == nil && !s.compactsNatively(c.p, c.model) {
|
||||
resealed = 2
|
||||
if b, ok = withoutCompaction(body); ok {
|
||||
refused(stuck, c.who(), attemptBody, compactionKinds...)
|
||||
@@ -3060,6 +3104,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
if hit == nil || !hit.Compact {
|
||||
answered(stuck, c, aff.Turn, call.Usage)
|
||||
}
|
||||
if s.compactsNatively(c.p, c.model) {
|
||||
sealedBy = &c
|
||||
}
|
||||
if hit != nil && !hit.Compact {
|
||||
ruleAnswered(ruleAt, call.Usage)
|
||||
}
|
||||
@@ -3252,7 +3299,8 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
|
||||
// (the provider is always streamed on that path) rather than relayed,
|
||||
// except a plugin's on Responses, which is relayed streamed and given
|
||||
// back whole (gathers)
|
||||
relay := slices.Contains(s.usable(p, model), from) && (p.Account == nil || !p.Account.Stream || streamOf(body) || gathers(p, from, body))
|
||||
relayable := slices.Contains(s.usable(p, model), from) && (p.Account == nil || !p.Account.Stream || streamOf(body) || gathers(p, from, body))
|
||||
relay := relayable
|
||||
// a Claude model is asked on Messages whatever API the client spoke,
|
||||
// for the cache breakpoints the translation adds: OpenCode speaks Chat
|
||||
// for every model, and a relay drops cache_control on Chat, so every
|
||||
@@ -3294,6 +3342,13 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
|
||||
if relay && from == provider.Chat && !streamOf(body) && dashScope(p) {
|
||||
relay, ownAPI = false, true
|
||||
}
|
||||
// Codex's compaction trigger, or a compaction sealed where native
|
||||
// compaction is on, goes as it came: a translation would leave it out
|
||||
// (#1099)
|
||||
keep := s.keepsCompaction(from, p, model, body)
|
||||
if keep && relayable {
|
||||
relay, ownAPI = true, false
|
||||
}
|
||||
if relay {
|
||||
call.To = from
|
||||
if status, msg, done := s.passthrough(w, r, p, from, model, body, &call.Usage); done {
|
||||
@@ -3301,6 +3356,10 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
|
||||
}
|
||||
// the model isn't served on the client's own API: speak another
|
||||
}
|
||||
if keep {
|
||||
msg := fmt.Sprintf("%s doesn't serve %s on the Responses API, so Codex's native compaction can't be asked of it", p.Name, model)
|
||||
return writeError(w, from, 400, msg), msg
|
||||
}
|
||||
to := s.usable(p, model)
|
||||
if len(to) == 0 {
|
||||
// every API turned the model away: the one the user picked for it
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
package gateway
|
||||
|
||||
// Native compaction (#1099): a provider the user set to compact natively
|
||||
// (provider.Provider.NativeCompaction) is asked Codex's compaction_trigger
|
||||
// as Codex sent it, and the compaction item it writes back goes to Codex
|
||||
// as it came, sealed (encrypted_content), not as magpie's "magpie1:"
|
||||
// summary. Only the key or account that sealed it can read it again, so
|
||||
// magpie remembers who wrote each one (compactions.json, beside
|
||||
// affinity.json), and a later request carrying it goes only there. When
|
||||
// that one can't be asked — switched off, removed, out of the group —
|
||||
// the request is refused, saying why: the compaction is never sent to
|
||||
// another to be refused, dropped (withoutCompaction), or summarised in its
|
||||
// place, which would lose the conversation's earlier context unasked.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
|
||||
const (
|
||||
// checkpointKeep is how long who sealed a compaction is remembered: a
|
||||
// conversation goes on from its compaction for days.
|
||||
checkpointKeep = 30 * 24 * time.Hour
|
||||
// checkpointsKept is how many compactions, the latest, are kept.
|
||||
checkpointsKept = 1024
|
||||
)
|
||||
|
||||
// compactionTriggerIn says whether a Responses request's input holds
|
||||
// Codex's compaction_trigger.
|
||||
func compactionTriggerIn(body []byte) bool {
|
||||
if !bytes.Contains(body, []byte(`"compaction_trigger"`)) {
|
||||
return false
|
||||
}
|
||||
for _, it := range gjson.GetBytes(body, "input").Array() {
|
||||
if it.Get("type").Str == "compaction_trigger" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// sealedCompactions are the encrypted_content of the compaction items in
|
||||
// a Responses request's input that a vendor sealed: magpie's own
|
||||
// ("magpie1:") are text by the time a request is sent, and aren't.
|
||||
func sealedCompactions(body []byte) []string {
|
||||
if !bytes.Contains(body, []byte(`"compaction`)) {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
for _, it := range gjson.GetBytes(body, "input").Array() {
|
||||
if !slices.Contains(compactionKinds, it.Get("type").Str) {
|
||||
continue
|
||||
}
|
||||
if enc := it.Get("encrypted_content").Str; enc != "" && !strings.HasPrefix(enc, magpieCompaction) {
|
||||
out = append(out, enc)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// carriesCompaction is whether c's provider can be asked Codex's own
|
||||
// compaction for model: its wire carries it, and model is asked on
|
||||
// Responses there.
|
||||
func (s *Server) carriesCompaction(p provider.Provider, model string) bool {
|
||||
return p.CarriesCompaction() && slices.Contains(s.usable(p, model), provider.Responses)
|
||||
}
|
||||
|
||||
// compactsNatively is whether a Codex compaction for model at p goes to it
|
||||
// as Codex sent it (provider.Provider.CompactsOn).
|
||||
func (s *Server) compactsNatively(p provider.Provider, model string) bool {
|
||||
return p.CompactsOn(model) && s.carriesCompaction(p, model)
|
||||
}
|
||||
|
||||
// nativeCompactionFor is whether Codex's compaction_trigger for the model
|
||||
// it asked (a provider's model, or a routing group) goes on as Codex sent
|
||||
// it: every member of a group compacting natively, as any of them may
|
||||
// answer it. A group with one that doesn't keeps magpie's summary, which
|
||||
// any member can read.
|
||||
func (s *Server) nativeCompactionFor(asked string) bool {
|
||||
if _, ms, ok := provider.FindGroup(asked); ok {
|
||||
if len(ms) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, m := range ms {
|
||||
if !s.compactsNatively(m.Provider, m.Model) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
p, model, ok := provider.Resolve(asked)
|
||||
return ok && s.compactsNatively(p, model)
|
||||
}
|
||||
|
||||
// keepsCompaction is whether body goes to p as it is for its compaction:
|
||||
// Codex's trigger, to one that carries it, or a sealed compaction, to one
|
||||
// set to compact natively. A translation would leave either out, so such
|
||||
// a request is relayed.
|
||||
func (s *Server) keepsCompaction(from provider.Protocol, p provider.Provider, model string, body []byte) bool {
|
||||
if from != provider.Responses || !s.carriesCompaction(p, model) {
|
||||
return false
|
||||
}
|
||||
return compactionTriggerIn(body) || p.CompactsOn(model) && len(sealedCompactions(body)) > 0
|
||||
}
|
||||
|
||||
// checkpointWriter is who sealed a compaction: the key or account
|
||||
// (candidate.who), its provider and the model it answered as.
|
||||
type checkpointWriter struct {
|
||||
Who string `json:"who"`
|
||||
Provider string `json:"provider"`
|
||||
Model string `json:"model,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
var checkpoints = struct {
|
||||
sync.Mutex
|
||||
m map[string]checkpointWriter // hex sha256 of encrypted_content → who wrote it
|
||||
// the file as last read or written
|
||||
from string
|
||||
mod time.Time
|
||||
}{m: map[string]checkpointWriter{}}
|
||||
|
||||
var checkpointsSaving sync.Mutex
|
||||
|
||||
func checkpointsPath() string {
|
||||
return filepath.Join(filepath.Dir(provider.Path()), "compactions.json")
|
||||
}
|
||||
|
||||
func checkpointKey(enc string) string {
|
||||
h := sha256.Sum256([]byte(enc))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// checkpointFor is who sealed the compaction enc, read from the file
|
||||
// again when it isn't known here and the file changed since. Called with
|
||||
// checkpoints held.
|
||||
func checkpointFor(enc string) (checkpointWriter, bool) {
|
||||
path := checkpointsPath()
|
||||
if path != checkpoints.from && checkpoints.from != "" {
|
||||
// another home (a test's): what was known is of the other's
|
||||
checkpoints.m = map[string]checkpointWriter{}
|
||||
checkpoints.mod = time.Time{}
|
||||
}
|
||||
k := checkpointKey(enc)
|
||||
if cp, ok := checkpoints.m[k]; ok && time.Since(cp.At) <= checkpointKeep {
|
||||
return cp, true
|
||||
}
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil || path == checkpoints.from && fi.ModTime().Equal(checkpoints.mod) {
|
||||
checkpoints.from = path
|
||||
return checkpointWriter{}, false
|
||||
}
|
||||
checkpoints.from, checkpoints.mod = path, fi.ModTime()
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return checkpointWriter{}, false
|
||||
}
|
||||
var saved map[string]checkpointWriter
|
||||
if decodeJSON(b, &saved) != nil {
|
||||
return checkpointWriter{}, false
|
||||
}
|
||||
for sk, v := range saved {
|
||||
if v.Who == "" || time.Since(v.At) > checkpointKeep {
|
||||
continue
|
||||
}
|
||||
if had, ok := checkpoints.m[sk]; ok && !had.At.Before(v.At) {
|
||||
continue
|
||||
}
|
||||
checkpoints.m[sk] = v
|
||||
}
|
||||
cp, ok := checkpoints.m[k]
|
||||
return cp, ok
|
||||
}
|
||||
|
||||
// checkpointOf is who sealed the latest compaction in a Responses
|
||||
// request's input that magpie knows the writer of.
|
||||
func checkpointOf(body []byte) (checkpointWriter, bool) {
|
||||
encs := sealedCompactions(body)
|
||||
if len(encs) == 0 {
|
||||
return checkpointWriter{}, false
|
||||
}
|
||||
checkpoints.Lock()
|
||||
defer checkpoints.Unlock()
|
||||
for _, enc := range slices.Backward(encs) {
|
||||
if cp, ok := checkpointFor(enc); ok {
|
||||
return cp, true
|
||||
}
|
||||
}
|
||||
return checkpointWriter{}, false
|
||||
}
|
||||
|
||||
// wroteCheckpoint remembers that c sealed the compaction enc.
|
||||
func wroteCheckpoint(enc string, c candidate) {
|
||||
now := time.Now()
|
||||
checkpoints.Lock()
|
||||
checkpointFor(enc) // the file's, read in first so the write keeps them
|
||||
checkpoints.m[checkpointKey(enc)] = checkpointWriter{Who: c.who(), Provider: c.p.ID, Model: c.model, At: now}
|
||||
checkpoints.Unlock()
|
||||
saveCheckpoints()
|
||||
}
|
||||
|
||||
// saveCheckpoints writes the latest compactions' writers to the file,
|
||||
// only for this user to read.
|
||||
func saveCheckpoints() {
|
||||
checkpointsSaving.Lock()
|
||||
defer checkpointsSaving.Unlock()
|
||||
type kept struct {
|
||||
k string
|
||||
v checkpointWriter
|
||||
}
|
||||
var ks []kept
|
||||
checkpoints.Lock()
|
||||
for k, v := range checkpoints.m {
|
||||
if time.Since(v.At) <= checkpointKeep {
|
||||
ks = append(ks, kept{k, v})
|
||||
}
|
||||
}
|
||||
checkpoints.Unlock()
|
||||
slices.SortFunc(ks, func(a, b kept) int { return b.v.At.Compare(a.v.At) })
|
||||
ks = ks[:min(len(ks), checkpointsKept)]
|
||||
out := make(map[string]checkpointWriter, len(ks))
|
||||
for _, k := range ks {
|
||||
out[k.k] = k.v
|
||||
}
|
||||
b, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
path := checkpointsPath()
|
||||
if os.MkdirAll(filepath.Dir(path), 0o700) != nil {
|
||||
return
|
||||
}
|
||||
target, err := edit.Target(path) // a symlink stays, its target written
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
tmp := target + ".magpie-tmp"
|
||||
if os.WriteFile(tmp, b, 0o600) != nil {
|
||||
return
|
||||
}
|
||||
if steady.Rename(tmp, target) != nil {
|
||||
os.Remove(tmp)
|
||||
return
|
||||
}
|
||||
if fi, err := os.Stat(path); err == nil {
|
||||
checkpoints.Lock()
|
||||
// what this magpie wrote isn't read back as another's
|
||||
checkpoints.from, checkpoints.mod = path, fi.ModTime()
|
||||
checkpoints.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// checkpointReaders keeps of cands those of the key or account who, pl's
|
||||
// order with them; left says one is left, if only held or capped.
|
||||
func checkpointReaders(cands []candidate, pl planned, who string) (_ []candidate, _ planned, left bool) {
|
||||
return keepCandidates(cands, pl, func(c candidate) bool { return c.who() == who })
|
||||
}
|
||||
|
||||
// compactionCarriers keeps of cands those that can be asked Codex's own
|
||||
// compaction.
|
||||
func (s *Server) compactionCarriers(cands []candidate, pl planned) (_ []candidate, _ planned, left bool) {
|
||||
return keepCandidates(cands, pl, func(c candidate) bool { return s.carriesCompaction(c.p, c.model) })
|
||||
}
|
||||
|
||||
func keepCandidates(cands []candidate, pl planned, keep func(candidate) bool) ([]candidate, planned, bool) {
|
||||
var kept []candidate
|
||||
var order []Weighed
|
||||
for i, c := range cands {
|
||||
if keep(c) {
|
||||
kept = append(kept, c)
|
||||
if i < len(pl.order) {
|
||||
order = append(order, pl.order[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
cands, pl.order = kept, order
|
||||
pl.held = slices.DeleteFunc(slices.Clone(pl.held), func(c candidate) bool { return !keep(c) })
|
||||
pl.capped = slices.DeleteFunc(slices.Clone(pl.capped), func(c candidate) bool { return !keep(c) })
|
||||
return cands, pl, len(cands) > 0 || len(pl.held) > 0 || len(pl.capped) > 0
|
||||
}
|
||||
|
||||
// checkpointError is what Codex is told when the compaction a request
|
||||
// carries was sealed by a key or account the request can't go to now.
|
||||
func checkpointError(model string, cp checkpointWriter) string {
|
||||
return fmt.Sprintf("This conversation was compacted natively (native compaction is on for %s) by %s, and only that key or account can read the compaction it sealed. The request for %s can't go to it now: it is switched off, removed, or no longer serves %s. magpie doesn't send the compaction to another, which would refuse it, nor drop it or summarise it in its place, which would lose the conversation's earlier context. Switch %s on again for %s to go on with this conversation, or start a new one.",
|
||||
cp.Provider, cp.Who, model, model, cp.Who, model)
|
||||
}
|
||||
|
||||
// carrierError is what Codex is told when its compaction_trigger, asked
|
||||
// of a provider set to compact natively, has nowhere left that carries it.
|
||||
func carrierError(model string) string {
|
||||
return fmt.Sprintf("Codex asked %s for its own compaction (native compaction), and none of the keys or accounts that serve %s now can be asked it on the Responses API. magpie doesn't turn it into a summary of its own unasked. Turn native compaction off for the provider to have magpie summarise the conversation instead.", model, model)
|
||||
}
|
||||
|
||||
// compactionWatch reads, on the way past, the compaction a native
|
||||
// compaction request's reply seals, for wroteCheckpoint.
|
||||
type compactionWatch struct {
|
||||
w http.ResponseWriter
|
||||
buf bytes.Buffer
|
||||
over bool
|
||||
}
|
||||
|
||||
// compactionWatchMax is how much of a reply is read for its compaction.
|
||||
const compactionWatchMax = 64 << 20
|
||||
|
||||
func (c *compactionWatch) Header() http.Header { return c.w.Header() }
|
||||
func (c *compactionWatch) WriteHeader(code int) { c.w.WriteHeader(code) }
|
||||
func (c *compactionWatch) Unwrap() http.ResponseWriter { return c.w }
|
||||
|
||||
func (c *compactionWatch) Write(p []byte) (int, error) {
|
||||
if !c.over {
|
||||
if c.buf.Len()+len(p) > compactionWatchMax {
|
||||
c.over = true
|
||||
c.buf = bytes.Buffer{}
|
||||
} else {
|
||||
c.buf.Write(p)
|
||||
}
|
||||
}
|
||||
return c.w.Write(p)
|
||||
}
|
||||
|
||||
func (c *compactionWatch) Flush() {
|
||||
if f, ok := c.w.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
// sealed is the encrypted_content of the last compaction item the reply
|
||||
// gave: in a stream's output_item.done or response.completed, or a JSON
|
||||
// body's output.
|
||||
func (c *compactionWatch) sealed() string {
|
||||
b := bytes.TrimSpace(c.buf.Bytes())
|
||||
if len(b) == 0 {
|
||||
return ""
|
||||
}
|
||||
found := ""
|
||||
fromItems := func(items []gjson.Result) {
|
||||
for _, it := range items {
|
||||
if slices.Contains(compactionKinds, it.Get("type").Str) {
|
||||
if enc := it.Get("encrypted_content").Str; enc != "" && !strings.HasPrefix(enc, magpieCompaction) {
|
||||
found = enc
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if b[0] == '{' {
|
||||
fromItems(gjson.GetBytes(b, "output").Array())
|
||||
return found
|
||||
}
|
||||
for line := range bytes.SplitSeq(b, []byte("\n")) {
|
||||
data, ok := bytes.CutPrefix(bytes.TrimSpace(line), []byte("data:"))
|
||||
if !ok || !bytes.Contains(data, []byte(`"compaction`)) {
|
||||
continue
|
||||
}
|
||||
ev := gjson.ParseBytes(bytes.TrimSpace(data))
|
||||
if it := ev.Get("item"); it.Exists() {
|
||||
fromItems([]gjson.Result{it})
|
||||
}
|
||||
fromItems(ev.Get("response.output").Array())
|
||||
}
|
||||
return found
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// nativeSealedReply is a Responses stream whose output is one compaction item,
|
||||
// sealed by the vendor as enc.
|
||||
func nativeSealedReply(enc string) string {
|
||||
item := `{"type":"compaction","encrypted_content":"` + enc + `"}`
|
||||
return sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp_c1","status":"in_progress","output":[]}}`,
|
||||
`data: {"type":"response.output_item.done","output_index":0,"item":`+item+`}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_c1","status":"completed","output":[`+item+`],"usage":{"input_tokens":9,"output_tokens":2,"total_tokens":11}}}`)
|
||||
}
|
||||
|
||||
func nativeOn(t *testing.T, id string) {
|
||||
t.Helper()
|
||||
if err := provider.SetNativeCompaction(id, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Codex offers web_search on every turn, which has a turn to a provider
|
||||
// that doesn't search translated: a compaction is relayed all the same
|
||||
const compactTurn = `{"model":"%s","stream":true,"instructions":"You are Codex","tools":[{"type":"web_search"}],"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"fix the bug"}]},{"type":"compaction_trigger"}]}`
|
||||
|
||||
func nativeAsk(t *testing.T, model, body string) (int, string) {
|
||||
t.Helper()
|
||||
return codexPost(t, strings.Replace(body, "%s", model, 1))
|
||||
}
|
||||
|
||||
// #1099: a provider set to compact natively is asked Codex's
|
||||
// compaction_trigger as Codex sent it, and the compaction it seals goes
|
||||
// back to Codex unchanged; the next turn carries it to the same provider
|
||||
// as it is. One not set to keeps magpie's summary (magpie1:).
|
||||
func TestNativeCompactionPassesTheTrigger(t *testing.T) {
|
||||
f := &fake{t: t, reply: nativeSealedReply("gAAAAB-sealed-by-relay")}
|
||||
setup(t, provider.Responses, f)
|
||||
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("a relay's compaction reached OpenAI")
|
||||
w.WriteHeader(400)
|
||||
})
|
||||
|
||||
// off: magpie summarises, the trigger never reaches the relay
|
||||
f.reply = sse(
|
||||
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"SUMMARY"}]}}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_s","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}`)
|
||||
code, body := nativeAsk(t, "fake/m1", compactTurn)
|
||||
if code != 200 || strings.Contains(string(f.got), "compaction_trigger") || !strings.Contains(body, magpieCompaction) {
|
||||
t.Fatalf("off: %d %s\nrelay got %s", code, body, f.got)
|
||||
}
|
||||
|
||||
// on
|
||||
nativeOn(t, "fake")
|
||||
f.reply = nativeSealedReply("gAAAAB-sealed-by-relay")
|
||||
code, body = nativeAsk(t, "fake/m1", compactTurn)
|
||||
if code != 200 {
|
||||
t.Fatalf("on: %d %s", code, body)
|
||||
}
|
||||
if !strings.Contains(string(f.got), `{"type":"compaction_trigger"}`) || strings.Contains(string(f.got), "CONTEXT CHECKPOINT COMPACTION") {
|
||||
t.Errorf("the relay wasn't asked Codex's own compaction: %s", f.got)
|
||||
}
|
||||
if f.path != "/v1/responses" {
|
||||
t.Errorf("asked at %s", f.path)
|
||||
}
|
||||
if !strings.Contains(body, `"encrypted_content":"gAAAAB-sealed-by-relay"`) || strings.Contains(body, magpieCompaction) {
|
||||
t.Errorf("Codex got %s", body)
|
||||
}
|
||||
|
||||
// the next turn takes the sealed compaction to the relay as it is
|
||||
f.reply = sse(`data: {"type":"response.completed","response":{"id":"resp_n","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}`)
|
||||
code, body = codexPost(t, `{"model":"fake/m1","stream":true,"tools":[{"type":"web_search"}],"input":[{"type":"compaction","encrypted_content":"gAAAAB-sealed-by-relay"},{"type":"message","role":"user","content":[{"type":"input_text","text":"go on"}]}]}`)
|
||||
if code != 200 || !strings.Contains(string(f.got), `"encrypted_content":"gAAAAB-sealed-by-relay"`) {
|
||||
t.Errorf("next turn: %d %s\nrelay got %s", code, body, f.got)
|
||||
}
|
||||
}
|
||||
|
||||
// A relay that refuses compaction_trigger has its own error go back to
|
||||
// Codex, not a summary of magpie's in its place.
|
||||
func TestNativeCompactionRefusalGoesBack(t *testing.T) {
|
||||
f := &fake{t: t}
|
||||
f.refuse = func(body []byte) (int, string) {
|
||||
if strings.Contains(string(body), "compaction_trigger") {
|
||||
return 400, `{"error":{"message":"Invalid value: 'compaction_trigger'. Supported values are: 'message', 'reasoning'.","type":"invalid_request_error","param":"input[1].type"}}`
|
||||
}
|
||||
return 0, ""
|
||||
}
|
||||
setup(t, provider.Responses, f)
|
||||
chatgpt(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(400) })
|
||||
nativeOn(t, "fake")
|
||||
code, body := nativeAsk(t, "fake/m1", compactTurn)
|
||||
if code != 400 || !strings.Contains(body, "Invalid value: 'compaction_trigger'") || strings.Contains(body, magpieCompaction) {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
if f.calls != 1 {
|
||||
t.Errorf("asked %d times", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// A compaction one key sealed never goes to another provider, which would
|
||||
// refuse it, nor goes without it: the request is answered an error saying
|
||||
// why. The writer, asked again, still reads it.
|
||||
func TestNativeCompactionStaysWithItsWriter(t *testing.T) {
|
||||
f := &fake{t: t, reply: nativeSealedReply("gAAAAB-sealed-by-a")}
|
||||
setup(t, provider.Responses, f)
|
||||
chatgpt(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(400) })
|
||||
g := &fake{t: t, reply: sse(`data: {"type":"response.completed","response":{"id":"resp_b","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}`)}
|
||||
up := httptest.NewServer(g)
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Key: "k2", Models: []string{"m1"}, Responses: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nativeOn(t, "fake")
|
||||
nativeOn(t, "other")
|
||||
if code, body := nativeAsk(t, "fake/m1", compactTurn); code != 200 || !strings.Contains(body, "gAAAAB-sealed-by-a") {
|
||||
t.Fatalf("compact: %d %s", code, body)
|
||||
}
|
||||
next := `{"model":"%s","stream":true,"input":[{"type":"compaction","encrypted_content":"gAAAAB-sealed-by-a"},{"type":"message","role":"user","content":[{"type":"input_text","text":"go on"}]}]}`
|
||||
code, body := nativeAsk(t, "other/m1", next)
|
||||
if code != 400 || !strings.Contains(body, "compacted natively") || !strings.Contains(body, "fake#") {
|
||||
t.Fatalf("another provider: %d %s", code, body)
|
||||
}
|
||||
if g.calls != 0 {
|
||||
t.Errorf("the other provider was sent it: %s", g.got)
|
||||
}
|
||||
f.reply = g.reply
|
||||
if code, body := nativeAsk(t, "fake/m1", next); code != 200 || !strings.Contains(string(f.got), "gAAAAB-sealed-by-a") {
|
||||
t.Errorf("the writer: %d %s", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
// GitHub Copilot's GPT models answer on Responses, so a Copilot account
|
||||
// set to compact natively is asked Codex's compaction as it was sent; its
|
||||
// Claude models, on chat completions, keep magpie's summary.
|
||||
func TestNativeCompactionCopilot(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var asked []string
|
||||
copilotFake(t, "gho_compact1099", func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
switch r.URL.Path {
|
||||
case "/models":
|
||||
io.WriteString(w, `{"data":[
|
||||
{"id":"gpt-5.3-codex","name":"GPT-5.3-Codex","model_picker_enabled":true,"policy":{"state":"enabled"},"supported_endpoints":["/responses"],"capabilities":{"type":"chat"}},
|
||||
{"id":"claude-sonnet-4.5","name":"Claude Sonnet 4.5","model_picker_enabled":true,"policy":{"state":"enabled"},"supported_endpoints":["/chat/completions"],"capabilities":{"type":"chat"}}]}`)
|
||||
case "/responses":
|
||||
asked = append(asked, "/responses "+string(b))
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, nativeSealedReply("gAAAAB-sealed-by-copilot"))
|
||||
case "/chat/completions":
|
||||
asked = append(asked, "/chat/completions "+string(b))
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, "data: {\"id\":\"c1\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"SUMMARY\"}}]}\n\ndata: {\"id\":\"c1\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":3,\"completion_tokens\":1}}\n\ndata: [DONE]\n\n")
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
})
|
||||
chatgpt(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(400) })
|
||||
p, err := provider.Find("copilot")
|
||||
if err != nil || !p.CarriesCompaction() {
|
||||
t.Fatalf("copilot: %v %+v", err, p)
|
||||
}
|
||||
nativeOn(t, "copilot")
|
||||
if p, _ := provider.Find("copilot"); !p.NativeCompaction {
|
||||
t.Fatal("a Copilot account didn't keep native compaction on")
|
||||
}
|
||||
code, body := nativeAsk(t, "copilot/gpt-5.3-codex", compactTurn)
|
||||
if code != 200 || !strings.Contains(body, `"encrypted_content":"gAAAAB-sealed-by-copilot"`) {
|
||||
t.Fatalf("gpt: %d %s", code, body)
|
||||
}
|
||||
mu.Lock()
|
||||
if len(asked) != 1 || !strings.HasPrefix(asked[0], "/responses ") || !strings.Contains(asked[0], `{"type":"compaction_trigger"}`) {
|
||||
t.Errorf("Copilot was asked %q", asked)
|
||||
}
|
||||
asked = nil
|
||||
mu.Unlock()
|
||||
|
||||
code, body = nativeAsk(t, "copilot/claude-sonnet-4.5", compactTurn)
|
||||
if code != 200 || !strings.Contains(body, magpieCompaction) {
|
||||
t.Fatalf("claude: %d %s", code, body)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
for _, a := range asked {
|
||||
if strings.Contains(a, "compaction_trigger") {
|
||||
t.Errorf("Claude on Copilot was asked the trigger: %s", a)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8391,7 +8391,7 @@ function baseAPIOf(p) {
|
||||
|
||||
// draftOf is a saved provider as its editor's form holds it.
|
||||
function draftOf(p) {
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, unredacted: !!p.unredacted, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, unredacted: !!p.unredacted, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };
|
||||
}
|
||||
|
||||
// duplicateProvider opens the Add form on a copy of p (#268): its URLs,
|
||||
@@ -8542,6 +8542,10 @@ function drawEditor(p, presetID) {
|
||||
// the Key header row, shown while the provider has a third-party
|
||||
// Anthropic API, which is sent its key in both headers by default
|
||||
let showAuth = () => {};
|
||||
// the Compaction row, shown while the provider has a Responses API
|
||||
// (Provider.CarriesCompaction): Codex's own compaction can go only there
|
||||
let showCompaction = () => {};
|
||||
const carriesCompaction = () => !!((draft.responses ?? (isNew && pr ? pr.responses : "")) || "").trim();
|
||||
if (custom) {
|
||||
name = input(draft.name, t("e.g. My Relay"));
|
||||
name.oninput = () => { draft.name = name.value; if (isNew) draft.id = slug(name.value); };
|
||||
@@ -8588,6 +8592,7 @@ function drawEditor(p, presetID) {
|
||||
showSearch();
|
||||
showLocal();
|
||||
showAuth();
|
||||
showCompaction();
|
||||
};
|
||||
queueMicrotask(() => slide(seg, "api"));
|
||||
url = input(draft[apiField[draft.api]], urlHint(draft.api), "url");
|
||||
@@ -8595,7 +8600,7 @@ function drawEditor(p, presetID) {
|
||||
url.oninput = () => {
|
||||
draft[apiField[draft.api]] = url.value;
|
||||
if (carried) { draft[carried.from] = carried.value; carried = null; fillEndpoints(); }
|
||||
showSearch(); showLocal(); showAuth();
|
||||
showSearch(); showLocal(); showAuth(); showCompaction();
|
||||
};
|
||||
const urlWrap = el("div", "stack");
|
||||
urlWrap.append(seg, url);
|
||||
@@ -8650,6 +8655,7 @@ function drawEditor(p, presetID) {
|
||||
ed.append(...field(t("Context window"), contextPicks(p, cx), t("How long a request the models take, told to the agents; empty leaves it to the vendor and models.dev")));
|
||||
ed.append(...outputField());
|
||||
ed.append(...compactField());
|
||||
if (p.carriesCompaction) ed.append(...nativeCompactionField(() => true)[0]);
|
||||
ed.append(...field(t("Fallback"), renderFallback(p), fallbackHint(p)));
|
||||
const proxies = el("div", "stack");
|
||||
proxies.append(proxyPicker());
|
||||
@@ -8695,7 +8701,7 @@ function drawEditor(p, presetID) {
|
||||
const priceRate = priceRateOfDraft();
|
||||
if (priceRate === undefined) return priceRateError(ed);
|
||||
if (priceTypedError(ed)) return;
|
||||
const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), unlisted: draft.unlisted, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, ...routingOfDraft(p) };
|
||||
const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), unlisted: draft.unlisted, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) };
|
||||
saving(saveBtn, t("Saving…"));
|
||||
savePluginOptions(subOf(a.agent)).then(() => providerAction("save", body, t("{name} saved", { name: p.name })), (e) => { doneSaving(saveBtn); editorError(e.message || String(e)); }); };
|
||||
bar.append(cancel, saveBtn);
|
||||
@@ -8711,7 +8717,7 @@ function drawEditor(p, presetID) {
|
||||
if (draft.chat === undefined) { draft.chat = p?.chat || ""; draft.responses = p?.responses || ""; }
|
||||
endpoint = input(draft.chat || draft.responses || "", pr.endpoint, "url");
|
||||
endpoint.classList.add("endpoint");
|
||||
endpoint.oninput = () => { draft.chat = draft.responses = endpoint.value.trim(); refreshEndpoints(); };
|
||||
endpoint.oninput = () => { draft.chat = draft.responses = endpoint.value.trim(); refreshEndpoints(); showCompaction(); };
|
||||
ed.append(...field(t("Endpoint"), endpoint, pr.endpointHint ? t(pr.endpointHint) : ""));
|
||||
}
|
||||
|
||||
@@ -9070,7 +9076,12 @@ function drawEditor(p, presetID) {
|
||||
const cx = input(draft.contexts || "", t("e.g. 128k · or gpt-6=1m, comma separated"));
|
||||
if (!decideOnly(p || pr)) ed.append(...field(t("Context window"), contextPicks(p, cx), t("How long a request the models take, told to the agents; empty leaves it to the vendor and models.dev")));
|
||||
if (!decideOnly(p || pr)) ed.append(...outputField());
|
||||
if (!decideOnly(p || pr)) ed.append(...compactField());
|
||||
if (!decideOnly(p || pr)) {
|
||||
ed.append(...compactField());
|
||||
const [row, refresh] = nativeCompactionField(carriesCompaction);
|
||||
ed.append(...row);
|
||||
showCompaction = refresh;
|
||||
}
|
||||
}
|
||||
if (p && !decideOnly(p)) ed.append(...field(t("Fallback"), renderFallback(p), fallbackHint(p)));
|
||||
else if (custom) {
|
||||
@@ -9140,7 +9151,7 @@ function drawEditor(p, presetID) {
|
||||
const add = (label, key, ph, hint) => {
|
||||
if (apiField[draft.api] === key) return;
|
||||
const i = input(draft[key], ph, "url");
|
||||
i.oninput = () => { draft[key] = i.value; if (carried?.from === key) carried = null; showSearch(); showLocal(); showAuth(); };
|
||||
i.oninput = () => { draft[key] = i.value; if (carried?.from === key) carried = null; showSearch(); showLocal(); showAuth(); showCompaction(); };
|
||||
eps.append(...field(t(label), i, t(hint)));
|
||||
};
|
||||
add("OpenAI URL", "chat", "https://…/v1", "if the vendor also serves chat completions");
|
||||
@@ -9242,6 +9253,7 @@ function drawEditor(p, presetID) {
|
||||
body.pinUpstream = !!draft.pinUpstream;
|
||||
if (twoKeyHeaders()) body.authHeader = draft.authHeader || "";
|
||||
body.unredacted = !!draft.unredacted && onLAN();
|
||||
if (!decideOnly(p || pr)) body.nativeCompaction = !!draft.nativeCompaction && carriesCompaction();
|
||||
body.passUserAgent = !!draft.passUserAgent && uaPassable();
|
||||
const cx = parseContexts(draft.contexts || "");
|
||||
if (cx.error) return editorError(t("Context window: {v} is not a length like 128k or 1m", { v: cx.error }), "warn");
|
||||
@@ -9394,6 +9406,21 @@ function outputField() {
|
||||
return field(t("Max output"), wrap, t("The most a reply may hold, told to the agents as their max tokens and sent as max_tokens on Anthropic's API when the agent names none; empty leaves it to the vendor and models.dev"));
|
||||
}
|
||||
|
||||
// nativeCompactionField is the editor's Compaction (#1099): Codex's own
|
||||
// compaction asked of the provider as Codex sent it, its sealed item given
|
||||
// back as it came, in place of the summary magpie writes. Offered only
|
||||
// where the wire carries it (a Responses API, a ChatGPT account, GitHub
|
||||
// Copilot); show says when, for a custom provider whose URLs are typed.
|
||||
function nativeCompactionField(show) {
|
||||
const [ntk, ncb] = tick(t("Codex compacts on this provider"), !!draft.nativeCompaction);
|
||||
ntk.classList.add("native-compaction");
|
||||
ncb.onchange = () => { draft.nativeCompaction = ncb.checked; };
|
||||
const row = field(t("Compaction"), ntk, t("Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context."));
|
||||
const refresh = () => { for (const e of row) e.style.display = show() ? "" : "none"; };
|
||||
refresh();
|
||||
return [row, refresh];
|
||||
}
|
||||
|
||||
// compactField is the editor's Compact at (#876): where Codex and Claude
|
||||
// Code compact a conversation on its models when their window is longer,
|
||||
// one for all of them and model=size for one, as the window is set. Empty
|
||||
|
||||
@@ -3224,6 +3224,8 @@ const I18N = {
|
||||
"Which header the API key goes in on the Anthropic API. Most services take both; pick one for a service that refuses the two together. magpie also switches to one by itself when a service says so.": "Anthropic API 的 API 密钥放在哪个请求头里。多数服务两个都接受;有的服务不允许两个同时出现,就选其中一个。服务这样提示时,magpie 也会自己改成只发一个。",
|
||||
"Redaction": "脱敏",
|
||||
"Send requests unmasked": "请求不脱敏",
|
||||
"Codex compacts on this provider": "Codex 在此服务商上原生压缩",
|
||||
"Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex 的压缩请求原样交给此服务商,它加密的摘要原样还给 Codex。关闭时由 magpie 写摘要。这样压缩过的对话只能在此服务商和账号上继续:换到别处会报错说明,绝不丢掉上下文发出。",
|
||||
"For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "给运行在这台电脑或局域网里的模型:密钥、个人信息和你设的脱敏词按原样发给它。如果它是本地的中转或代理、会把请求转给供应商,请保持关闭。",
|
||||
"User-Agent": "User-Agent",
|
||||
"Send the agent's own User-Agent": "发送 Agent 自己的 User-Agent",
|
||||
@@ -6753,6 +6755,8 @@ const I18N = {
|
||||
"Which header the API key goes in on the Anthropic API. Most services take both; pick one for a service that refuses the two together. magpie also switches to one by itself when a service says so.": "Anthropic API 的 API 金鑰放在哪個標頭裡。多數服務兩個都接受;有的服務不允許兩個同時出現,就選其中一個。服務這樣提示時,magpie 也會自己改成只送一個。",
|
||||
"Redaction": "脫敏",
|
||||
"Send requests unmasked": "請求不脫敏",
|
||||
"Codex compacts on this provider": "Codex 在此服務商上原生壓縮",
|
||||
"Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex 的壓縮請求原樣交給此服務商,它加密的摘要原樣還給 Codex。關閉時由 magpie 寫摘要。這樣壓縮過的對話只能在此服務商和帳號上繼續:換到別處會報錯說明,絕不丟掉上下文送出。",
|
||||
"For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "給執行在這臺電腦或區域網裡的模型:金鑰、個人資訊和你設的脫敏詞按原樣發給它。如果它是本地的中轉或代理、會把請求轉給供應商,請保持關閉。",
|
||||
"User-Agent": "User-Agent",
|
||||
"Send the agent's own User-Agent": "傳送 Agent 自己的 User-Agent",
|
||||
@@ -10301,6 +10305,8 @@ const I18N = {
|
||||
"Which header the API key goes in on the Anthropic API. Most services take both; pick one for a service that refuses the two together. magpie also switches to one by itself when a service says so.": "Anthropic API で API キーを入れるヘッダー。たいていのサービスは両方を受け付けます。両方が同時にあると拒否するサービスでは、どちらか一方を選んでください。サービスがそう伝えてきたときは、magpie も自動で一方だけに切り替えます。",
|
||||
"Redaction": "マスク",
|
||||
"Send requests unmasked": "リクエストをマスクしない",
|
||||
"Codex compacts on this provider": "Codex のコンパクションをこのプロバイダーで行う",
|
||||
"Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex のコンパクション要求をそのままこのプロバイダーに送り、暗号化された要約をそのまま Codex に返します。オフのときは magpie が要約を書きます。こうしてコンパクションした会話は、このプロバイダーとアカウントでのみ続けられます。他へはエラーで断り、コンテキストを落として送ることはしません。",
|
||||
"For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "このコンピューターかローカルネットワークで動くモデル用:シークレット、個人情報、マスクする語はそのまま送られます。リクエストをベンダーに転送するローカルのリレーやプロキシではオフのままにしてください。",
|
||||
"User-Agent": "User-Agent",
|
||||
"Send the agent's own User-Agent": "エージェント自身の User-Agent を送る",
|
||||
@@ -13859,6 +13865,8 @@ const I18N = {
|
||||
"Which header the API key goes in on the Anthropic API. Most services take both; pick one for a service that refuses the two together. magpie also switches to one by itself when a service says so.": "In welchem Header der API-Schlüssel an die Anthropic-API geht. Die meisten Dienste nehmen beide; wähle einen für einen Dienst, der beide zusammen ablehnt. magpie wechselt auch von selbst zu einem, wenn ein Dienst das meldet.",
|
||||
"Redaction": "Maskierung",
|
||||
"Send requests unmasked": "Anfragen unmaskiert senden",
|
||||
"Codex compacts on this provider": "Codex kompaktiert bei diesem Anbieter",
|
||||
"Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.": "Codex’ Kompaktierung geht so an diesen Anbieter, wie Codex sie sendet, und die versiegelte Zusammenfassung kommt unverändert zu Codex zurück. Aus: magpie schreibt die Zusammenfassung. Ein so kompaktiertes Gespräch geht nur bei diesem Anbieter und Konto weiter: ein anderer wird mit einem Fehler abgelehnt, nie ohne den Kontext angefragt.",
|
||||
"For a model running on this computer or your local network: secrets, personal data and your masked words go to it as written. Leave it off for a local relay or proxy that passes requests on to a vendor.": "Für ein Modell auf diesem Computer oder in Ihrem lokalen Netzwerk: Geheimnisse, persönliche Daten und Ihre maskierten Wörter gehen unverändert an es. Lassen Sie es aus für ein lokales Relay oder einen Proxy, der Anfragen an einen Anbieter weiterreicht.",
|
||||
"User-Agent": "User-Agent",
|
||||
"Send the agent's own User-Agent": "Den eigenen User-Agent des Agenten senden",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// The editor's Compaction row (#1099): a Save that sends nativeCompaction
|
||||
// sets it, one that leaves it out keeps it, and a provider without a
|
||||
// Responses API is refused it. /api/providers says which providers can
|
||||
// carry it, for the editor to offer the row.
|
||||
func TestProviderSaveNativeCompaction(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("USERPROFILE", os.Getenv("HOME"))
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
mux := http.NewServeMux()
|
||||
providerRoutes(mux, nil)
|
||||
post := func(body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(body)))
|
||||
return w
|
||||
}
|
||||
on := func(id string) bool {
|
||||
t.Helper()
|
||||
p, err := provider.Find(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p.NativeCompaction
|
||||
}
|
||||
if w := post(`{"id":"relay","name":"Relay","key":"sk-r","responses":"http://127.0.0.1:1/v1","icon":"generic","new":true,"nativeCompaction":true}`); w.Code != 200 || !on("relay") {
|
||||
t.Fatalf("new, on: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := post(`{"id":"relay","from":"relay","name":"Relay","key":"","responses":"http://127.0.0.1:1/v1","icon":"generic","models":[],"headers":{}}`); w.Code != 200 || !on("relay") {
|
||||
t.Fatalf("a save without it: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := post(`{"id":"relay","from":"relay","name":"Relay","key":"","responses":"http://127.0.0.1:1/v1","icon":"generic","models":[],"headers":{},"nativeCompaction":false}`); w.Code != 200 || on("relay") {
|
||||
t.Fatalf("off: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := post(`{"id":"chat","name":"Chat","key":"sk-c","chat":"http://127.0.0.1:1/v1","icon":"generic","new":true,"nativeCompaction":true}`); w.Code == 200 || !strings.Contains(w.Body.String(), "can't carry") {
|
||||
t.Fatalf("a chat-only provider took it: %d %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil))
|
||||
var got struct {
|
||||
Providers []struct {
|
||||
ID string `json:"id"`
|
||||
CarriesCompaction bool `json:"carriesCompaction"`
|
||||
} `json:"providers"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("%v %s", err, w.Body)
|
||||
}
|
||||
carries := map[string]bool{}
|
||||
for _, p := range got.Providers {
|
||||
carries[p.ID] = p.CarriesCompaction
|
||||
}
|
||||
if !carries["relay"] {
|
||||
t.Errorf("the Responses relay isn't said to carry it: %s", w.Body)
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,11 @@ type providerJSON struct {
|
||||
// on this machine or the local network, set to go unmasked by
|
||||
// Settings' redaction (provider.Unredacted)
|
||||
Unredacted bool `json:"unredacted"`
|
||||
// Codex's compaction asked of it as Codex sent it, its sealed item
|
||||
// back as it came (provider.NativeCompaction, #1099); CarriesCompaction: its
|
||||
// wire can carry it, so the editor offers it
|
||||
NativeCompaction bool `json:"nativeCompaction"`
|
||||
CarriesCompaction bool `json:"carriesCompaction,omitempty"`
|
||||
// requests go with the agent's own User-Agent, not magpie's
|
||||
// (provider.PassUserAgent, #1851); OwnClient: they go as a client of
|
||||
// the vendor's own whatever is set (provider.OwnClient), so the
|
||||
@@ -539,7 +544,7 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON {
|
||||
ID: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Host: p.Host(),
|
||||
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(),
|
||||
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL,
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL,
|
||||
Ready: p.Ready(), Chosen: p.Picks(), Models: []modelJSON{}, Agents: []providerAgent{},
|
||||
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Unlisted: p.Unlisted, NoModels: p.ServesNone(), Off: p.Off, Contexts: p.Contexts,
|
||||
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), PriceRate: p.PriceRate,
|
||||
@@ -1109,6 +1114,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
// quota left goes to the back (provider.Provider.Sink); a
|
||||
// save that leaves it out keeps it
|
||||
Sink *bool `json:"sink"`
|
||||
// NativeCompaction, for save: Codex's compaction asked of it
|
||||
// as Codex sent it (provider.Provider.NativeCompaction); a save
|
||||
// that leaves it out keeps it
|
||||
NativeCompaction *bool `json:"nativeCompaction"`
|
||||
// AuthHeader, for save: which header the key goes in on a
|
||||
// third-party Anthropic API (provider.Provider.AuthHeader); a
|
||||
// save that leaves it out keeps it, one learned too
|
||||
@@ -1167,6 +1176,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if req.Sink != nil {
|
||||
in.Sink = *req.Sink
|
||||
}
|
||||
if req.NativeCompaction != nil {
|
||||
in.NativeCompaction = *req.NativeCompaction
|
||||
}
|
||||
if req.AuthHeader != nil {
|
||||
in.AuthHeader = *req.AuthHeader
|
||||
}
|
||||
@@ -1247,6 +1259,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
pr.Searches = in.Searches
|
||||
pr.PinUpstream = in.PinUpstream
|
||||
pr.Unredacted = in.Unredacted
|
||||
pr.NativeCompaction = in.NativeCompaction
|
||||
pr.PassUserAgent = in.PassUserAgent
|
||||
pr.AuthHeader = in.AuthHeader
|
||||
if in.Name != "" {
|
||||
@@ -1323,6 +1336,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
}
|
||||
in.SecretAccessKey = strings.TrimSpace(in.SecretAccessKey)
|
||||
var old *provider.Provider
|
||||
if req.New && in.NativeCompaction && !in.CarriesCompaction() {
|
||||
fail(rw, fmt.Errorf("%s can't carry Codex's native compaction: only a provider with a Responses API, a ChatGPT account or GitHub Copilot can", cmp.Or(in.Name, in.ID)))
|
||||
return
|
||||
}
|
||||
if req.New {
|
||||
// a second one of a preset, or a name already in use, is
|
||||
// added beside the first under the next free id
|
||||
@@ -1453,6 +1470,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if req.Sink == nil {
|
||||
in.Sink = old.Sink
|
||||
}
|
||||
if req.NativeCompaction == nil {
|
||||
in.NativeCompaction = old.NativeCompaction
|
||||
}
|
||||
if req.AuthHeader == nil {
|
||||
in.AuthHeader = old.AuthHeader
|
||||
}
|
||||
@@ -1490,6 +1510,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if in.Icon == "" && old != nil && in.Preset == "" {
|
||||
in.Icon = old.Icon
|
||||
}
|
||||
// native compaction only where the wire carries it: a
|
||||
// signed-in account is told by the one saved
|
||||
if in.NativeCompaction && !in.CarriesCompaction() && (old == nil || old.Account == nil || !old.CarriesCompaction()) {
|
||||
fail(rw, fmt.Errorf("%s can't carry Codex's native compaction: only a provider with a Responses API, a ChatGPT account or GitHub Copilot can", cmp.Or(in.Name, in.ID)))
|
||||
return
|
||||
}
|
||||
if err := provider.Save(in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// #1099: a provider whose wire carries Codex's own compaction (a Responses
|
||||
// API, a ChatGPT account, GitHub Copilot) can be set to be asked it as
|
||||
// Codex sent it. The editor's Compaction row, "Codex compacts on this
|
||||
// provider", is there for such a provider alone, opens as it was saved, and
|
||||
// Save posts it. A Chat Completions relay and a Claude account have no such
|
||||
// row. In every language, wide and narrow.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const base = {
|
||||
icon: "generic", chat: "", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "m1", name: "M1", on: true }], agents: [], fallback: [], headers: {},
|
||||
key: { set: true, masked: "sk-…1234" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", searches: false, unredacted: false, passUserAgent: false,
|
||||
};
|
||||
const relay = { ...base, id: "relay", name: "Responses Relay", responses: "https://relay.example.com/v1", carriesCompaction: true };
|
||||
const chat = { ...base, id: "chatonly", name: "Chat Relay", chat: "https://chat.example.com/v1" };
|
||||
const account = (id, name, agent, extra) => ({
|
||||
id, name, icon: agent + "-color", chat: "", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "m", name: "M", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
|
||||
account: { agent, agentName: name, user: "me@example.com", plan: "PLUS", logins: [{ user: "me@example.com", plan: "PLUS", active: true, on: true }] },
|
||||
proxy: "", ...extra,
|
||||
});
|
||||
const codex = account("codex", "Codex", "codex", { responses: "https://chatgpt.com/backend-api/codex", carriesCompaction: true, nativeCompaction: true });
|
||||
const claude = account("claude", "Claude Code", "claude", { anthropic: "https://api.anthropic.com" });
|
||||
|
||||
function serve(lang, posts) {
|
||||
const providers = { providers: [relay, chat, codex, claude], presets: [], excluded: [], gateway: { running: true, window: true } };
|
||||
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/providers") return json(providers);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") {
|
||||
posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() });
|
||||
return json(providers);
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const strings = [
|
||||
"Compaction", "Codex compacts on this provider",
|
||||
"Codex's compaction is asked of this provider as Codex sent it, and the summary it seals goes back to Codex unchanged. Off, magpie writes the summary. A conversation compacted this way continues only on this provider and account: another is refused with an error, never sent without the context.",
|
||||
];
|
||||
const words = {
|
||||
en: { tick: "Codex compacts on this provider", save: "Save" },
|
||||
zh: { tick: "Codex 在此服务商上原生压缩", save: "保存" },
|
||||
"zh-TW": { tick: "Codex 在此服務商上原生壓縮", save: "儲存" },
|
||||
ja: { tick: "Codex のコンパクションをこのプロバイダーで行う", save: "保存" },
|
||||
de: { tick: "Codex kompaktiert bei diesem Anbieter", save: "Speichern" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(words)) {
|
||||
for (const width of [1100, 420]) {
|
||||
const w = words[lang];
|
||||
const open = async (t, name) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name}-compaction.png`), fullPage: true });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const posts = [];
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: name }).click();
|
||||
await page.locator(".editor .bar").waitFor();
|
||||
return { page, errors, posts };
|
||||
};
|
||||
const row = (page) => page.locator(".editor label.tick", { hasText: w.tick });
|
||||
const box = (page) => row(page).locator("input");
|
||||
const save = async (page, posts) => {
|
||||
const n = posts.length;
|
||||
await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click();
|
||||
for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50);
|
||||
return posts.at(-1);
|
||||
};
|
||||
|
||||
test(`${engine} ${lang} ${width}: a Responses relay is set to have Codex compact on it, and saved so`, async (t) => {
|
||||
const { page, errors, posts } = await open(t, "Responses Relay");
|
||||
assert.equal(await row(page).isVisible(), true);
|
||||
assert.equal(await box(page).isChecked(), false, "opens off");
|
||||
await box(page).scrollIntoViewIfNeeded();
|
||||
const r = await row(page).boundingBox();
|
||||
assert.ok(r.width > 60 && r.x + r.width <= width, `the row fits: ${JSON.stringify(r)}`);
|
||||
const scroller = () => page.evaluate(() => document.querySelector(".editor")?.closest("[class*=scroll], main")?.scrollTop ?? window.scrollY);
|
||||
const y = await scroller();
|
||||
await box(page).check();
|
||||
assert.equal(await scroller(), y, "the click doesn't scroll");
|
||||
assert.equal(await page.locator(".editor select").count(), 0, "no native select");
|
||||
const saved = await save(page, posts);
|
||||
assert.equal(saved.action, "save");
|
||||
assert.equal(saved.body.id, "relay");
|
||||
assert.equal(saved.body.nativeCompaction, true);
|
||||
if (lang !== "en") {
|
||||
const missing = await page.evaluate(([l, ks]) => ks.filter((k) => !I18N[l][k]), [lang, strings]);
|
||||
assert.deepEqual(missing, [], `every string has its ${lang}`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: a ChatGPT account saved compacting natively opens ticked, and is saved off`, async (t) => {
|
||||
const { page, errors, posts } = await open(t, "Codex");
|
||||
assert.equal(await box(page).isChecked(), true);
|
||||
await box(page).scrollIntoViewIfNeeded();
|
||||
await box(page).uncheck();
|
||||
const saved = await save(page, posts);
|
||||
assert.equal(saved.body.id, "codex");
|
||||
assert.equal(saved.body.nativeCompaction, false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: a Chat Completions relay and a Claude account have no such row`, async (t) => {
|
||||
for (const name of ["Chat Relay", "Claude Code"]) {
|
||||
const { page, errors, posts } = await open(t, name);
|
||||
assert.equal(await row(page).isVisible(), false, name);
|
||||
if (name === "Chat Relay") {
|
||||
const saved = await save(page, posts);
|
||||
assert.notEqual(saved.body.nativeCompaction, true, "never posted on");
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// CarriesCompaction says whether p's wire can carry Codex's own
|
||||
// compaction (NativeCompaction, #1099): a compaction_trigger asked and a
|
||||
// sealed compaction item given back, on the Responses API, as Codex sent
|
||||
// them. A provider of no sign-in with a Responses API does (Sub2API and
|
||||
// other relays of OpenAI's, OpenAI's own, a remote magpie), as do a
|
||||
// ChatGPT account and GitHub Copilot, whose GPT models answer on
|
||||
// Responses. Another signed-in agent's, or a plugin's, is asked in its own
|
||||
// client's format, which has no such item.
|
||||
func (p Provider) CarriesCompaction() bool {
|
||||
if p.Account != nil {
|
||||
return !p.IsPlugin() && (p.Account.Agent == "codex" || p.Account.Agent == "copilot") && p.Base(Responses) != ""
|
||||
}
|
||||
return p.Base(Responses) != ""
|
||||
}
|
||||
|
||||
// CompactsOn says whether a Codex compaction for model at p goes to it as
|
||||
// Codex sent it: the user turned NativeCompaction on, its wire carries
|
||||
// it, and model is asked on Responses there (Copilot's Claude models are
|
||||
// not). The gateway also asks whether the model fits Responses as it has
|
||||
// seen it answer (Server.compactsNatively).
|
||||
func (p Provider) CompactsOn(model string) bool {
|
||||
if !p.NativeCompaction || !p.CarriesCompaction() {
|
||||
return false
|
||||
}
|
||||
apis := p.APIs(model)
|
||||
return apis == nil && !p.NamedOnlyOn(Responses) || slices.Contains(apis, Responses)
|
||||
}
|
||||
|
||||
// SetNativeCompaction turns a provider's native compaction on or off
|
||||
// (Provider.NativeCompaction). One whose wire can't carry it is refused
|
||||
// turning it on.
|
||||
func SetNativeCompaction(id string, on bool) error {
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if on && !p.CarriesCompaction() {
|
||||
return fmt.Errorf("%s can't carry Codex's native compaction: only a provider with a Responses API, a ChatGPT account or GitHub Copilot can", p.Name)
|
||||
}
|
||||
p.NativeCompaction = on
|
||||
return Save(*p)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Codex's own compaction (#1099) is offered only where the wire carries
|
||||
// it: a Responses API, a ChatGPT account, GitHub Copilot. Another agent's
|
||||
// sign-in, a plugin's, and a provider without a Responses API can't be
|
||||
// set to it; a model a provider asks on another API isn't compacted there.
|
||||
func TestCarriesCompaction(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
p Provider
|
||||
want bool
|
||||
}{
|
||||
{"a relay on Responses", Provider{Responses: "https://relay.example/v1"}, true},
|
||||
{"chat completions only", Provider{Chat: "https://relay.example/v1"}, false},
|
||||
{"anthropic only", Provider{Anthropic: "https://relay.example"}, false},
|
||||
{"a ChatGPT account", Provider{Responses: "https://chatgpt.com/backend-api/codex", Account: &Account{Agent: "codex"}}, true},
|
||||
{"GitHub Copilot", Provider{Chat: "https://api.githubcopilot.com", Responses: "https://api.githubcopilot.com", Account: &Account{Agent: "copilot"}}, true},
|
||||
{"another agent's sign-in", Provider{Responses: "https://x.example/v1", Account: &Account{Agent: "workbuddy"}}, false},
|
||||
{"a plugin's", Provider{Responses: "plugin://x", Account: &Account{Agent: "plugin:x"}}, false},
|
||||
} {
|
||||
if got := tt.p.CarriesCompaction(); got != tt.want {
|
||||
t.Errorf("%s: %v, want %v", tt.name, got, tt.want)
|
||||
}
|
||||
}
|
||||
on := Provider{Responses: "https://relay.example/v1", NativeCompaction: true}
|
||||
if !on.CompactsOn("m") {
|
||||
t.Error("a relay set to compact natively doesn't")
|
||||
}
|
||||
on.NativeCompaction = false
|
||||
if on.CompactsOn("m") {
|
||||
t.Error("a relay not set to compacts natively")
|
||||
}
|
||||
chat := Provider{Chat: "https://relay.example/v1", NativeCompaction: true}
|
||||
if chat.CompactsOn("m") {
|
||||
t.Error("a chat-only relay compacts natively")
|
||||
}
|
||||
}
|
||||
|
||||
// The option is saved, refused where the wire can't carry it, turned off
|
||||
// again, and kept by a copy.
|
||||
func TestSetNativeCompaction(t *testing.T) {
|
||||
isolate(t)
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
if err := Save(Provider{ID: "relay", Name: "Relay", Responses: "https://relay.example/v1", Key: "sk-1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Save(Provider{ID: "chat", Name: "Chat", Chat: "https://chat.example/v1", Key: "sk-2"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetNativeCompaction("relay", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p, _ := Find("relay"); !p.NativeCompaction {
|
||||
t.Fatal("not saved")
|
||||
}
|
||||
if err := SetNativeCompaction("chat", true); err == nil || !strings.Contains(err.Error(), "can't carry") {
|
||||
t.Fatalf("a chat-only provider took it: %v", err)
|
||||
}
|
||||
if p, _ := Find("chat"); p.NativeCompaction {
|
||||
t.Fatal("saved on a chat-only provider")
|
||||
}
|
||||
id, err := AddCopy(Provider{Name: "Relay copy", Responses: "https://relay.example/v1", Models: []string{"m"}}, "relay")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, _ := Find(id); !c.NativeCompaction {
|
||||
t.Error("a copy lost it")
|
||||
}
|
||||
if err := SetNativeCompaction("relay", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p, _ := Find("relay"); p.NativeCompaction {
|
||||
t.Fatal("not turned off")
|
||||
}
|
||||
}
|
||||
@@ -227,6 +227,18 @@ type Provider struct {
|
||||
// fitting, which a backend that isn't OpenAI's needs (#350).
|
||||
CodexAsSent bool `json:"codexAsSent,omitempty"`
|
||||
|
||||
// NativeCompaction has Codex's compaction_trigger go to the provider
|
||||
// as Codex sent it, and the compaction the provider writes back go to
|
||||
// Codex as it came (#1099), where magpie otherwise asks the model for
|
||||
// a summary and hands Codex that (its "magpie1:" compaction). Only a
|
||||
// provider whose wire carries it takes it (CarriesCompaction): a
|
||||
// Responses API (Sub2API, a remote magpie), a ChatGPT account, GitHub
|
||||
// Copilot's GPT models. Such a compaction is sealed by the key or
|
||||
// account that wrote it, so its conversation stays there, or is
|
||||
// refused, never sent elsewhere to be dropped. Off, the default,
|
||||
// keeps magpie's summary.
|
||||
NativeCompaction bool `json:"nativeCompaction,omitempty"`
|
||||
|
||||
// PassUserAgent has a request go to the vendor with the User-Agent the
|
||||
// agent that sent it gave (pi, opencode, Claude Code…), in place of
|
||||
// magpie's own (#1851): a coding plan that serves only agents it names
|
||||
@@ -620,6 +632,7 @@ func withPicks(a, pk Provider) Provider {
|
||||
a.Models, a.Unlisted, a.Off, a.Fallback, a.Routing, a.Affinity, a.KeepLogin, a.KeepLoginAs, a.Contexts, a.Family = pk.Models, pk.Unlisted, pk.Off, pk.Fallback, pk.Routing, pk.Affinity, pk.KeepLogin, pk.KeepLoginAs, pk.Contexts, pk.Family
|
||||
a.SwitchOnly = pk.SwitchOnly
|
||||
a.Sink, a.NoModels = pk.Sink, pk.NoModels
|
||||
a.NativeCompaction = pk.NativeCompaction
|
||||
a.Proxy, a.AccountProxies, a.AccountModels = pk.Proxy, pk.AccountProxies, pk.AccountModels
|
||||
a.AccountCaps, a.AccountWindowCaps = pk.AccountCaps, pk.AccountWindowCaps
|
||||
a.AccountNames = pk.AccountNames
|
||||
@@ -740,7 +753,7 @@ func Save(p Provider) error {
|
||||
if p.ID == "kiro" {
|
||||
key = p.Key
|
||||
}
|
||||
p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, PickedFrom: p.PickedFrom, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}
|
||||
p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, PickedFrom: p.PickedFrom, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}
|
||||
} else {
|
||||
p.AccountProxies = keyProxies(p) // a provider of keys proxies each key apart
|
||||
if subscriptionID(p.ID) && !stored(p.ID) {
|
||||
@@ -892,6 +905,7 @@ func AddCopy(p Provider, from string) (string, error) {
|
||||
p.Unlisted = p.Unlisted || src.Unlisted
|
||||
p.Searches = p.Searches || src.Searches
|
||||
p.Unredacted = p.Unredacted || src.Unredacted
|
||||
p.NativeCompaction = p.NativeCompaction || src.NativeCompaction
|
||||
p.PassUserAgent = p.PassUserAgent || src.PassUserAgent
|
||||
if p.Website == "" {
|
||||
p.Website = src.Website
|
||||
|
||||
Reference in New Issue
Block a user