Merge commit '791604559' into pf/serve
This commit is contained in:
@@ -58,6 +58,7 @@ something else shows up as drift.
|
||||
- The YAML ones go through `yamlKept` and `mergeKept` in [`sync.go`](../../internal/agent/sync.go). Each is tested by a `Test<Agent>KeepsTheUsersSettings`.
|
||||
- Copilot in JetBrains IDEs keeps its Bring Your Own Key providers in the Copilot language server's `byok.json`, shared with Xcode's and Eclipse's Copilot (`copilotJetBrains` in [`copilotjetbrains.go`](../../internal/agent/copilotjetbrains.go)). magpie writes its own three keys there, `magpie-provider-config`, `magpie-api-key` and `magpie-models-config`, in the bytes the server itself writes, and only when they differ; the user's providers and keys stay. A magpie model the user hid in Manage Models (`isRegistered: false`) stays hidden through a sync. A new file is made 0600 in a 0700 folder, as the server makes it.
|
||||
- dsh (DeepSeek Harness) sets one API per llm-pi-ai route, so magpie writes a route per protocol (`dshKinds` in [`dsh.go`](../../internal/agent/dsh.go); 01huadalang on Discord): `magpie` (Chat Completions) for most models, `magpie-responses` (`openai-responses`) for a model served on Responses, `magpie-anthropic` (`anthropic-messages`, the gateway root, `forceAdaptiveThinking` where `AdaptiveThinking`) for one served on Messages, by the model's `APIs` (`dshRouteOf`). A model's `APIs` is the one its provider serves it on best (`Provider.Native`, in `magpieModels`, [`route.go`](../../internal/agent/route.go)), and Pi, omp and droid read it the same way. A routing group has `responses` when every member is best on Responses (`allResponses`, #1594), so its tool-call arguments are relayed as they stream; any other group has none and stays on Chat, a Messages-only group too, as a Claude member's thinking is known by its own model. A route with no models is taken out. An api the user picked for a route in dsh's Models page is kept, and so are keys they added there. The start (`agent-default-model`) names its model's route, and Sync moves a start on one of magpie's routes to the route its model is now on (`dshStartOnItsRoute`), its effort and marks kept. Check asks the route the start names to list its model. A dsh session resumed on a model that has since moved routes asks for the model to be picked again, since dsh finds a model by route and id.
|
||||
- dsh takes a model's listed `maxTokens` as every request's output and reserves it, with 65536 of headroom, out of `contextWindow` before deciding when to compact (compaction-basic's `resolveCompactSpec`: the smaller of 80% of the window and window − maxTokens − 65536). A vendor's reply limit near its window had dsh compact at 41248 of a 500000 group (#2823) or fail with no budget (524288/524288, LoKi on Discord; 131072/65536), so magpie lists it held to a quarter of the window on every route and in the older `llm-deepseek` entry (`dshMaxTokens`), as VS Code and Copilot in JetBrains do. A Max output the user set stays as they set it (`outputOr`), even one that leaves dsh no budget. `TestDshOutputLeavesCompactionRoom`.
|
||||
- DeepSeek Harness Desktop (macOS arm64 and Windows x64; no Linux build) reads the same `$DSH_HOME` or `~/.dsh` as the CLI, as its own profile `profiles/desktop` (`resolveDshHome` and `resolveDesktopPaths` in the app's `lib/main.js`), so it takes magpie's routes with no wiring of its own (#2279, liangjinyuan-sihan). It is found by `/Applications/DeepSeek Harness.app`, by `%LOCALAPPDATA%\Programs\DeepSeek Harness`, or by the folder its current-user installer records under `HKCU\Software\1bf39983-50d0-5fe0-9ef4-cece76f67c5e` (`InstallLocation`), whose Uninstall key gives the version (`registered` in [`desktopapp.go`](../../internal/agent/desktopapp.go)), so a user who picked another folder is found. With the app installed but never opened there is no `~/.dsh`: the row is still listed, and connecting writes `profiles/desktop/cordis.patch.yml` from dsh's own template (`dshProfileTemplate`) with magpie's routes, which the app keeps on its first start, since it writes only the files that are missing. The notice says the app starts on it the first time it opens (`noticeDsh5`). Disconnect before that first start removes the profile magpie made when nothing else is in it (`dshTidyUnopened`); once the app has opened it, the profile stays and only magpie's entries go (`TestDshDesktopNeverOpened`, `TestDshDesktopRegisteredFolder`).
|
||||
- Ante's `catalog.json` keeps user-added fields in `providers.magpie` the same way (`ante` in [`ante.go`](../../internal/agent/ante.go)); its `auth`, `http_headers`, `extra_body` and `stream_idle_timeout_secs` are what a gateway shared on the local network or reached from WSL needs to send a key. Ante starts a session on the `provider` and `model` of `settings.json`, not on what its catalog holds (#1210), so magpie sets that pair and puts back what it found there; a pick the user makes in Ante while magpie is wired is theirs and stands.
|
||||
- AstrBot keeps its providers in `data/cmd_config.json` under its root (`$ASTRBOT_ROOT`, else `~/.astrbot`, the desktop app's, else `~/astrbot`), written with a UTF-8 BOM, which magpie keeps (`astrbot` in [`astrbot.go`](../../internal/agent/astrbot.go)). magpie adds a `magpie` entry to `provider_sources` and one `magpie/<model>` entry per model to `provider`, keeps the user's own entries byte for byte and keeps what the user changes in magpie's (timeout, proxy, enable), and sets the default chat model (`agent_runner.config.model.provider_id`, or `provider_settings.default_provider_id` before the agent runner), putting back what it found there. A pick the user makes while magpie is wired is theirs and stands. The first connect copies the file to `cmd_config.json.before-magpie`. AstrBot reads the file only at start-up and its WebUI writes it back whole on save, so the agent's notice says to restart AstrBot before saving in the WebUI. A Docker install's root is inside its container, which magpie doesn't reach.
|
||||
|
||||
@@ -126,6 +126,7 @@ recorded as a prediction failure (`noPrediction`).
|
||||
- In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models.
|
||||
- A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits <account> off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again.
|
||||
- Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873).
|
||||
- One of Codex's own models on the backend path with no routing to do (`codexAccounts` false: one ChatGPT account, no usage cap, no key holds, nothing pinned) is relayed as Codex sent it, on Codex's own sign-in, its bytes and headers unchanged and its reply streamed as it comes (`codexUpstreamOn` with no account): routing was built for more than one account, and that path also keeps the turn's native compaction with the backend. Before, nothing was asked again on it, so an overload went straight to Codex, which doesn't retry the backend's `server_is_overloaded` itself (夜松云 on Discord). Now a transient overload (`codexBusy`: what `busy` calls busy, a 529, a 503 saying overloaded, the backend's in-stream `response.failed` with `server_is_overloaded` (#1418); never a 429, a usage limit, an edge's drop of the connection (`edgeSaidDrop`) or a reset (`codexReset`)) is asked again of the same account, the same body and headers, up to `lastRetries` times after `retryPause<<n`, as the accounts loop asks its last account, and only before any of the reply has reached Codex. A stream is held for it through a `holdWriter` with its reasoning let through (`thinkingShown`), kept alive past `keepHeldAfter` across the tries (one `keptAlive`), so Codex sees the stream's headers and comments, never a failed try's frames. Nothing rests for an overload. Once the retries are spent, a turn whose codex subscription has fallbacks (`codexFallsBack`; never a compaction) goes on to them (`codexFallBack`: the turn served as `codex/<model>` with the account left out of the candidates, `fallbacksOnly`, and the same keepalive carried in `handedOnKey`); without fallbacks Codex gets the last try's failure as the backend said it. Each try is a `HandedOn` usage record and a try in the trace. A success is relayed as before, with nothing held when no retry or fallback is left (`TestCodexOneAccountOverloadAskedAgain`, `…StreamOverloadAskedAgain`, `…OverloadBounded`, `…OverloadFallsBack`, `…OverloadKeptAlive`, `…RefusalNotAskedAgain` in [`codex_one_account_overload_test.go`](../../internal/gateway/codex_one_account_overload_test.go)).
|
||||
- A subscription account whose sign-in its vendor revoked (`provider.SignInRevoked`: 401 `token_revoked` and the like, #1793) fails as `failAuth`: the next member is asked at once, nothing rests, and the account is marked (`noteSignIn` in [`signin_revoked.go`](../../internal/gateway/signin_revoked.go)). Its later requests aren't sent while it has that credential: `forwardOnce` answers them with a 401 of magpie's own (`revokedReply`), so they too pass on. Compaction on an account of magpie's (`compactOn`) picks a marked one last. A key's provider answering the same words rests as before.
|
||||
- A sub2api key out of its own limit answers 429 `api key 7天限额已用完` (or `日限额`, `5小时限额`) as `rate_limit_exceeded`. It is out of quota (`plannedWords`), not rate limited: it rests till the window it filled renews when its windows as last read say so, else `quotaRest`, and its windows are read again (`staleKeyAllowance`). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (`renewed`, told through `provider.OnRenewed`), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (`restingOf`, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503 `No available accounts`, or a later version's 429 `All available accounts are currently rate-limited`) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows.
|
||||
- A 5xx is a server error, not quota, unless the vendor's own quota code says so (`quotaCodes`: `usage_limit_reached`, `RESOURCE_EXHAUSTED`, Claude Code's `usage limit reached|<unix>`). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota by `usedUpWords` (上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (`usedUpWords`) still apply to a 4xx.
|
||||
|
||||
@@ -349,7 +349,7 @@ covers it in both engines, every language and a narrow window.
|
||||
|
||||
### Shared UI rules
|
||||
|
||||
- Settings → General is laid out as macOS System Settings is (1ooogle on X): a row says its name alone when that says enough (Appearance, Colorblind mode, Language, Text size, the fonts, the tray click, the Codex model rows, Open at login, Show in Dock), and keeps one short line where the setting isn't clear from its name or has a consequence (Long conversations, Lightweight mode, Prevent sleep, Session terminal, Codex subagents). A font row's line shows only while its fonts load or fail; the text size keys are the choices' tooltip, and Colorblind mode's note is its Off/On control's (`#colorblindSegs`). Colorblind mode (`settings.Colorblind`, `data-colorblind="1"` on `:root`, #2073) switches the chart series (`--c1`…`--c7`) in both light and dark themes to an Okabe–Ito palette where adjacent series differ in hue and lightness. On a quota curve each window (`data-series`, its index mod 7, set by `drawQuotaPlot` and `quotaCurve`'s legend only) gets a dash of its own on `path.qc-line`, its legend key shows a sample of that line (`.qc-sample`) for the dot, and the even paces (`line.qc-even`) are dotted; the curve's tooltip says so. The balance curve sets no `data-series` and keeps its solid line, dashed fit and dot. The Context tab's "good" grade, which takes `--c2` as a colour rather than a series, keeps a blue (`--c1`). Language is one menu button showing the language picked, opened in the app's menu (`renderLangPick`). See `settings-general.test.cjs` and `quota-curve.test.cjs`.
|
||||
- Settings → General is laid out as macOS System Settings is (1ooogle on X): a row says its name alone when that says enough (Appearance, Colorblind mode, Language, Text size, the fonts, the tray click, the Codex model rows, Open at login, Show in Dock), and keeps one short line where the setting isn't clear from its name or has a consequence (Long conversations, Lightweight mode, Prevent sleep, Session terminal, Codex subagents). A font row's line shows only while its fonts load or fail; the text size keys are the choices' tooltip, and Colorblind mode's note is its Off/On control's (`#colorblindSegs`). Colorblind mode (`settings.Colorblind`, `data-colorblind="1"` on `:root`, #2073) switches the chart series (`--c1`…`--c7`) in both light and dark themes to an Okabe–Ito palette where adjacent series differ in hue and lightness. On a quota curve each window (`data-series`, its index mod 7, set by `drawQuotaPlot` and `quotaCurve`'s legend only) gets a dash of its own on `path.qc-line`, its legend key shows a sample of that line (`.qc-sample`) for the dot, and the even paces (`line.qc-even`) are dotted; the curve's tooltip says so. The balance curve sets no `data-series` and keeps its solid line, dashed fit and dot. The Context tab's "good" grade, which takes `--c2` as a colour rather than a series, keeps a blue (`--c1`). Language is one menu button showing the language picked, opened in the app's menu (`renderLangPick`). See `settings-general.test.cjs` and `quota-curve.test.cjs`. Open at login reads `autostart.Enabled`, which on macOS 13 and later also asks Background Task Management about magpie's launch agent (`SMAppService.statusForLegacyURL:`, matched by the plist's Label, not its path); a record the user switched off in System Settings › General › Login Items reads as needing allowing, and the row keeps On with one line saying so and a button that opens Login Items (`/api/open` allows that one `x-apple.systempreferences` URL). The status read again when the window comes back to the front clears the line. On macOS 12, in a build without cgo, or when the system can't be asked, the plist alone decides, as before (#2120, `login-allow.test.cjs`, `login_allow_test.go`).
|
||||
- Settings' search-provider picker offers **Off**, saved as `searcher: "off"`. Its help explains API-only search and suppresses provider fallback/own-search hints while off; the search priority row is hidden because no provider competes with the APIs. See [gateway search behavior](gateway-routing.md#turning-provider-search-off), [`renderSearcher`](../../internal/gui/assets/app.js), `TestSettingsSearchProviderOff` and `searcher-pick.test.cjs`.
|
||||
- Settings' search APIs are asked in their listed order: each API's row (with its keys' row) is dragged as one, or moved with Alt+↑/↓, and has a switch that turns it off without removing its key (#2286). See [the search APIs' order](gateway-routing.md#the-search-apis-order-and-one-switched-off), `searchArrange` in [`app.js`](../../internal/gui/assets/app.js) and `search-order.test.cjs`.
|
||||
- Settings' Search APIs add row has a base URL field under the key for every API (#1580): the vendor's own address is its placeholder, picking an API already added fills in its saved URL so a new key alone keeps it, and Add with no key changes only the URL. See [a search API's base URL](gateway-routing.md#a-search-apis-base-url), [`renderSearch`](../../internal/gui/assets/app.js) and `search-api.test.cjs`.
|
||||
|
||||
@@ -28,7 +28,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
|
||||
| Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `<claude dir>/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.<Event>]]` array tables with a `[[hooks.<Event>.hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:<Event>` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) |
|
||||
| Subagents | A `Subagent` (#2283) is a name (lowercase letters, digits and -), a one-line description, a prompt, and the library's skills and MCP servers it uses, given to the agents ticked for it. `syncSubagents` writes it as a file of its own in each agent's user-level folder, in that agent's format (`subagentSpecOf`): Markdown with YAML front matter in `~/.claude/agents` (with `skills` and `mcpServers`), `~/.factory/droids` (with `mcpServers`), `~/.config/opencode/agents` (`mode: subagent`), `~/.gemini/agents`, `~/.qwen/agents`, `~/.grok/agents`, `~/.cursor/agents` and `~/.copilot/agents` (`<name>.agent.md`); a TOML role (`name`, `description`, `developer_instructions`) in `$CODEX_HOME/agents`. Skills and servers are named only where the agent's file can name them, and only those the library has. The page lists, per agent, whether it binds skills and servers (`SubagentAgentView`) and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) |
|
||||
| Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) |
|
||||
| RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off). | [`rtk.go`](../../internal/library/rtk.go) |
|
||||
| RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off). The page's No RTK hook tag gives each agent's own reason and rtk-ai/rtk issue (`rtkNoHookWhy` in plugins/library/client.js: dsh #3847, Grok Build and Grok App #2136), and an agent with no entry gets no link; `TestRTKNoHookIssuesAreEachAgents` fails when the page and `rtkNoHook` cite different issues, or two agents cite the same ones without a reason in `sharedRTKIssues`. | [`rtk.go`](../../internal/library/rtk.go) |
|
||||
|
||||
## Runtime path
|
||||
|
||||
|
||||
+19
-2
@@ -1500,6 +1500,23 @@ func dshLevels(ref string) []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
// dshMaxTokens is the maxTokens magpie lists m with. dsh takes a listed
|
||||
// maxTokens as every request's output and reserves it, with 65536 of
|
||||
// headroom, out of contextWindow before it decides when to compact
|
||||
// (compaction-basic's resolveCompactSpec: the threshold is the smaller of
|
||||
// 80% of the window and window - maxTokens - 65536). A vendor's reply limit
|
||||
// near its window leaves dsh compacting at a sliver of it, or failing to
|
||||
// (#2823): 500000 with 393216 compacted at 41248; 524288 with 524288, and
|
||||
// 131072 with 65536, left it no budget at all. So the vendor's figure is
|
||||
// held to a quarter of the window, as VS Code's and Copilot's are, while a
|
||||
// Max output the user set stays as they set it (outputOr).
|
||||
func dshMaxTokens(m catalog.Model) int {
|
||||
if m.Context <= 0 {
|
||||
return maxTokens(m)
|
||||
}
|
||||
return outputOr(m, min(maxTokens(m), max(1, m.Context/4)))
|
||||
}
|
||||
|
||||
// dshRouteConfig is magpie's first route with every one of models on it.
|
||||
func dshRouteConfig(models []catalog.Model, api, gw string) dshPiRoute {
|
||||
return dshKindConfig(dshKinds[0], models, api, gw)
|
||||
@@ -1518,7 +1535,7 @@ func dshKindConfig(k dshKind, models []catalog.Model, api, gw string) dshPiRoute
|
||||
for _, m := range models {
|
||||
e := dshPiModel{ID: m.ID, Name: m.Name, ContextWindow: m.Context}
|
||||
if m.Output > 0 {
|
||||
e.MaxTokens = maxTokens(m)
|
||||
e.MaxTokens = dshMaxTokens(m)
|
||||
}
|
||||
switch {
|
||||
case m.Images:
|
||||
@@ -1604,7 +1621,7 @@ func dshProviderLines(effort string, models []catalog.Model, gw string) []string
|
||||
lines = append(lines, fmt.Sprintf(" contextWindow: %d", m.Context))
|
||||
}
|
||||
if m.Output > 0 {
|
||||
lines = append(lines, fmt.Sprintf(" maxTokens: %d", maxTokens(m)))
|
||||
lines = append(lines, fmt.Sprintf(" maxTokens: %d", dshMaxTokens(m)))
|
||||
}
|
||||
if m.Images {
|
||||
lines = append(lines, " inputModalities: [text, image]")
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
)
|
||||
|
||||
// dshCompactsAt is where dsh's compaction-basic starts compacting a model
|
||||
// listed with window and maxTokens out, as its resolveCompactSpec works it
|
||||
// out with the default policy (thresholdRatio 0.8, headroomTokens 65536):
|
||||
// 0 when it has no budget and fails instead (#2823).
|
||||
func dshCompactsAt(window, out int) int {
|
||||
pressure := window - out - 65536
|
||||
if window-out <= 0 || pressure <= 0 {
|
||||
return 0
|
||||
}
|
||||
return min(window*8/10, pressure)
|
||||
}
|
||||
|
||||
// TestDshOutputLeavesCompactionRoom: dsh reserves the maxTokens magpie lists
|
||||
// a model with, and 65536 more, out of its window before it compacts. A
|
||||
// vendor's reply limit near the window had dsh compact at 41248 of a 500000
|
||||
// group (#2823) or fail outright on 524288/524288 (LoKi on Discord) and
|
||||
// 131072/65536; it is held to a quarter of the window on every route and in
|
||||
// the older llm-deepseek entry, while a Max output the user set stays.
|
||||
func TestDshOutputLeavesCompactionRoom(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
model catalog.Model
|
||||
want int
|
||||
}{
|
||||
{"full window", catalog.Model{ID: "space-bunny-free", Context: 524288, Output: 524288}, 131072},
|
||||
{"above the window", catalog.Model{ID: "above", Context: 524288, Output: 1048576}, 131072},
|
||||
{"group window under its members' output", catalog.Model{ID: "group/smart-split", Context: 500000, Output: 393216}, 125000},
|
||||
{"half the window", catalog.Model{ID: "k131", Context: 131072, Output: 65536}, 32768},
|
||||
{"within a quarter", catalog.Model{ID: "flash", Context: 1000000, Output: 128000}, 128000},
|
||||
{"user output", catalog.Model{ID: "user", Context: 524288, Output: 393216, OutputSet: true}, 393216},
|
||||
{"user full window", catalog.Model{ID: "user-full", Context: 524288, Output: 524288, OutputSet: true}, 524288},
|
||||
{"unknown window", catalog.Model{ID: "unknown", Output: 128000}, 128000},
|
||||
{"unknown output", catalog.Model{ID: "no-output", Context: 524288}, 0},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
for _, k := range dshKinds {
|
||||
got := dshKindConfig(k, []catalog.Model{tc.model}, "", "http://127.0.0.1:3425").Models[0]
|
||||
if got.MaxTokens != tc.want || got.ContextWindow != tc.model.Context {
|
||||
t.Fatalf("%s: contextWindow %d, maxTokens %d; want %d, %d", k.key, got.ContextWindow, got.MaxTokens, tc.model.Context, tc.want)
|
||||
}
|
||||
}
|
||||
lines := strings.Join(dshProviderLines("high", []catalog.Model{tc.model}, "http://127.0.0.1:3425"), "\n")
|
||||
if tc.want > 0 && !strings.Contains(lines+"\n", fmt.Sprintf("maxTokens: %d\n", tc.want)) {
|
||||
t.Fatalf("llm-deepseek entry, want maxTokens: %d:\n%s", tc.want, lines)
|
||||
}
|
||||
if tc.want == 0 && strings.Contains(lines, "maxTokens") {
|
||||
t.Fatalf("llm-deepseek entry lists a maxTokens for a model of no known output:\n%s", lines)
|
||||
}
|
||||
if tc.model.Context > 0 && !tc.model.OutputSet {
|
||||
if at := dshCompactsAt(tc.model.Context, tc.want); at < tc.model.Context/4 {
|
||||
t.Fatalf("dsh compacts %d/%d at %d tokens", tc.model.Context, tc.want, at)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -197,7 +197,7 @@ func TestDshModelLimits(t *testing.T) {
|
||||
want := ` - id: v/see
|
||||
name: see · V
|
||||
contextWindow: 400000
|
||||
maxTokens: 128000
|
||||
maxTokens: 100000
|
||||
input: [text, image]
|
||||
- id: v/plain
|
||||
name: plain · V
|
||||
|
||||
@@ -139,10 +139,11 @@ func TestCrushModelsCarryMaxTokens(t *testing.T) {
|
||||
// output. ZCode and WorkBuddy cap it at zcodeMaxOutput besides, Crush falls
|
||||
// back to 16384 without a known output, OpenCode is handed no limit without
|
||||
// a window, and AtomCode and Snow CLI, each told a window of its own when
|
||||
// the model's isn't known, are cut to that.
|
||||
// the model's isn't known, are cut to that. dsh is held to a quarter of
|
||||
// a known window (dshMaxTokens, #2823).
|
||||
func TestMaxTokensWithinContextWindow(t *testing.T) {
|
||||
home := syncHome(t)
|
||||
check := func(limit string, want int) {
|
||||
check := func(limit string, want, window int) {
|
||||
t.Helper()
|
||||
os.WriteFile(catalog.CachePath(), []byte(`{"zai":{"models":{"glm-4.6":{"id":"glm-4.6","name":"GLM-4.6","limit":{`+limit+`}}}}}`), 0o644)
|
||||
catalog.Reset()
|
||||
@@ -179,6 +180,12 @@ func TestMaxTokensWithinContextWindow(t *testing.T) {
|
||||
if !strings.Contains(limit, "context") {
|
||||
told = strconv.Itoa(min(want, atomcodeContext))
|
||||
}
|
||||
// dsh reserves maxTokens out of its window before compacting, so a
|
||||
// known window holds it to a quarter (dshMaxTokens, #2823).
|
||||
dshTold := n
|
||||
if strings.Contains(limit, "context") {
|
||||
dshTold = strconv.Itoa(min(want, window/4))
|
||||
}
|
||||
snowTold := n
|
||||
if !strings.Contains(limit, "context") {
|
||||
snowTold = strconv.Itoa(min(want, snowContext))
|
||||
@@ -187,7 +194,7 @@ func TestMaxTokensWithinContextWindow(t *testing.T) {
|
||||
"pi": {string(pi), `"maxTokens":` + n},
|
||||
"cline": {string(cline), `"maxTokens":` + n},
|
||||
"omp": {string(omp), "maxTokens: " + n},
|
||||
"dsh": {string(dshRoute), "maxTokens: " + n},
|
||||
"dsh": {string(dshRoute), "maxTokens: " + dshTold},
|
||||
"droid": {string(droid), `"maxOutputTokens":` + n},
|
||||
"qoder": {string(qoder), `"maxOutputTokens":` + n},
|
||||
"hanako": {string(hanako), `"maxOutput":` + n},
|
||||
@@ -207,10 +214,10 @@ func TestMaxTokensWithinContextWindow(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
check(`"context":128000,"output":384000`, 128000)
|
||||
check(`"output":384000`, 384000)
|
||||
check(`"context":204800,"output":131072`, 131072)
|
||||
check(`"context":64000,"output":384000`, 64000)
|
||||
check(`"context":128000,"output":384000`, 128000, 128000)
|
||||
check(`"output":384000`, 384000, 0)
|
||||
check(`"context":204800,"output":131072`, 131072, 204800)
|
||||
check(`"context":64000,"output":384000`, 64000, 64000)
|
||||
}
|
||||
|
||||
// A provider added after a magpie model was picked reaches the lists agents
|
||||
|
||||
@@ -16,8 +16,37 @@ import (
|
||||
// Arg is what magpie is started with at login: the tray, no window.
|
||||
const Arg = "tray"
|
||||
|
||||
// Enabled reports whether magpie opens at login.
|
||||
func Enabled() bool { return enabled() }
|
||||
// State is whether magpie opens at login, as the system will act on it.
|
||||
type State string
|
||||
|
||||
const (
|
||||
// Off: no record, so nothing opens magpie at login.
|
||||
Off State = "off"
|
||||
// On: the record is there, and nothing the system says holds it back.
|
||||
On State = "on"
|
||||
// NeedsAllowing: the record is there, but the user switched it off in
|
||||
// the system's own settings (on the Mac, System Settings › General ›
|
||||
// Login Items › Allow in the Background), so it opens nothing until
|
||||
// it is allowed there again; writing the record anew doesn't do that.
|
||||
NeedsAllowing State = "allow"
|
||||
)
|
||||
|
||||
// LoginItemsURL opens System Settings' Login Items pane, where a record
|
||||
// that NeedsAllowing is allowed again.
|
||||
const LoginItemsURL = "x-apple.systempreferences:com.apple.LoginItems-Settings.extension"
|
||||
|
||||
// Enabled reports whether magpie opens at login. A system that can't be
|
||||
// asked, or that answers something else, is not taken for a no: the
|
||||
// record's own word stands (On).
|
||||
func Enabled() State {
|
||||
if !enabled() {
|
||||
return Off
|
||||
}
|
||||
if heldBack() {
|
||||
return NeedsAllowing
|
||||
}
|
||||
return On
|
||||
}
|
||||
|
||||
// Set has magpie open at login, or not, as this copy of it.
|
||||
func Set(on bool) error {
|
||||
|
||||
@@ -41,3 +41,6 @@ func disable() error {
|
||||
}
|
||||
|
||||
func refresh() error { return nil }
|
||||
|
||||
// heldBack: nothing here is switched off apart from the record itself
|
||||
func heldBack() bool { return false }
|
||||
|
||||
@@ -25,13 +25,13 @@ func TestBootScript(t *testing.T) {
|
||||
if err := os.Chmod(record(), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Enabled() {
|
||||
if Enabled() != Off {
|
||||
t.Fatal("non-executable script reported as enabled")
|
||||
}
|
||||
if err := enable(exe); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !Enabled() {
|
||||
if Enabled() == Off {
|
||||
t.Fatal("enable did not restore executable permission")
|
||||
}
|
||||
if err := exec.Command("/system/bin/sh", record()).Run(); err != nil {
|
||||
|
||||
@@ -28,6 +28,31 @@ func enabled() bool {
|
||||
return err == nil && ourLabel.Match(b) && program.Match(b)
|
||||
}
|
||||
|
||||
// What ServiceManagement's statusForLegacyURL: says of a launch agent
|
||||
// (SMAppServiceStatus). Background Task Management keeps it, by the
|
||||
// plist's Label, wherever the file is: switched off under Login Items ›
|
||||
// Allow in the Background, it is requiresApproval, and stays so when the
|
||||
// plist is written anew, or removed and written again. launchctl
|
||||
// print-disabled doesn't follow that switch (it went on saying enabled,
|
||||
// macOS 26.2), so it isn't asked.
|
||||
const (
|
||||
smNotRegistered = 0
|
||||
smEnabled = 1
|
||||
smRequiresApproval = 2
|
||||
smNotFound = 3
|
||||
// the system couldn't be asked: before macOS 13, or a build without cgo
|
||||
smUnknown = -1
|
||||
)
|
||||
|
||||
// legacyStatus asks the system about the launch agent at path. A var for
|
||||
// the tests; a build without cgo can't ask.
|
||||
var legacyStatus = func(path string) int { return smUnknown }
|
||||
|
||||
// heldBack: the system says the user switched the launch agent off. Only
|
||||
// requiresApproval says so; not registered yet, not found, or no answer
|
||||
// leave the record's own word.
|
||||
func heldBack() bool { return legacyStatus(record()) == smRequiresApproval }
|
||||
|
||||
// a launch agent the system loads at the next login: the app itself, run
|
||||
// once, not kept alive — quitting magpie quits it until then
|
||||
func enable(exe string) error {
|
||||
|
||||
@@ -51,7 +51,7 @@ func TestRefreshOlderLaunchAgent(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
if err := Refresh(); err != nil || Enabled() {
|
||||
if err := Refresh(); err != nil || Enabled() != Off {
|
||||
t.Fatalf("Refresh turned Open at login on: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(home, "Library")); !os.IsNotExist(err) {
|
||||
@@ -176,7 +176,7 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
|
||||
if err := Set(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !Enabled() {
|
||||
if Enabled() == Off {
|
||||
t.Fatal("not on after Set(true)")
|
||||
}
|
||||
p := record()
|
||||
@@ -190,13 +190,13 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
|
||||
if err := os.WriteFile(p, head, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Enabled() {
|
||||
if Enabled() != Off {
|
||||
t.Errorf("a launch agent with no ProgramArguments reads as on:\n%s", head)
|
||||
}
|
||||
if err := os.WriteFile(p, nil, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Enabled() {
|
||||
if Enabled() != Off {
|
||||
t.Error("an empty launch agent reads as on")
|
||||
}
|
||||
// a program named as nothing is no program to run either, and launchd
|
||||
@@ -205,7 +205,93 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
|
||||
if err := os.WriteFile(p, []byte(empty), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Enabled() {
|
||||
if Enabled() != Off {
|
||||
t.Errorf("a launch agent with no program reads as on:\n%s", empty)
|
||||
}
|
||||
}
|
||||
|
||||
// Switched off under System Settings › Login Items › Allow in the
|
||||
// Background, the launch agent stays where it was and opens nothing, so
|
||||
// Open at login says it needs allowing, not on (#2120). Only the system's
|
||||
// requiresApproval says that: no answer, or any other, leaves the record's
|
||||
// word, and no record is off whatever the system says.
|
||||
func TestEnabledFollowsTheSystemsSwitch(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
prev := legacyStatus
|
||||
t.Cleanup(func() { legacyStatus = prev })
|
||||
var asked string
|
||||
status := smRequiresApproval
|
||||
legacyStatus = func(p string) int { asked = p; return status }
|
||||
|
||||
if got := Enabled(); got != Off {
|
||||
t.Fatalf("no launch agent reads %q, want off", got)
|
||||
}
|
||||
if err := Set(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := Enabled(); got != NeedsAllowing {
|
||||
t.Fatalf("switched off in System Settings reads %q, want %q", got, NeedsAllowing)
|
||||
}
|
||||
if asked != record() {
|
||||
t.Fatalf("asked the system about %q, not the launch agent %q", asked, record())
|
||||
}
|
||||
for _, s := range []int{smEnabled, smNotRegistered, smNotFound, smUnknown, 7} {
|
||||
status = s
|
||||
if got := Enabled(); got != On {
|
||||
t.Errorf("the system answering %d reads %q, want on", s, got)
|
||||
}
|
||||
}
|
||||
status = smRequiresApproval
|
||||
if err := Set(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := Enabled(); got != Off {
|
||||
t.Fatalf("turned off reads %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The system's switch is kept by the launch agent's label, wherever its
|
||||
// plist is: a test's record under a sandbox home is com.yetone.magpie
|
||||
// too, and the system would answer for the user's own. The tests ask a
|
||||
// stand-in that knows nothing; askSystem is the real question.
|
||||
var askSystem func(string) int
|
||||
|
||||
func keepToTheSandbox() {
|
||||
askSystem = legacyStatus
|
||||
legacyStatus = func(string) int { return smUnknown }
|
||||
}
|
||||
|
||||
// The real question reaches ServiceManagement: a launch agent under a
|
||||
// label Background Task Management has never seen is notFound, and a path
|
||||
// with no file at all is notRegistered. The user's own label is never
|
||||
// asked about.
|
||||
func TestLegacyStatusAsksTheSystem(t *testing.T) {
|
||||
out, err := exec.Command("sw_vers", "-productVersion").Output()
|
||||
if err != nil {
|
||||
t.Skip("no sw_vers")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "com.yetone.magpie-test.plist")
|
||||
b := strings.Replace(string(plist("/usr/bin/true")), "<string>"+label+"</string>", "<string>com.yetone.magpie-test-"+filepath.Base(dir)+"</string>", 1)
|
||||
if err := os.WriteFile(p, []byte(b), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := askSystem(p)
|
||||
if major := strings.SplitN(strings.TrimSpace(string(out)), ".", 2)[0]; major == "11" || major == "12" {
|
||||
if got != smUnknown {
|
||||
t.Fatalf("macOS %s answered %d, want unknown", out, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !cgoBuilt {
|
||||
t.Skip("built without cgo: the system can't be asked")
|
||||
}
|
||||
if got != smNotFound {
|
||||
t.Errorf("a label BTM never saw answered %d, want notFound (%d)", got, smNotFound)
|
||||
}
|
||||
if got := askSystem(filepath.Join(dir, "none.plist")); got != smNotRegistered {
|
||||
t.Errorf("no file answered %d, want notRegistered (%d)", got, smNotRegistered)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,3 +58,6 @@ func disable() error {
|
||||
|
||||
// refresh: nothing an older magpie wrote here needs writing again
|
||||
func refresh() error { return nil }
|
||||
|
||||
// heldBack: nothing here is switched off apart from the record itself
|
||||
func heldBack() bool { return false }
|
||||
|
||||
@@ -21,7 +21,7 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
|
||||
if err := Set(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !Enabled() {
|
||||
if Enabled() == Off {
|
||||
t.Fatal("not on after Set(true)")
|
||||
}
|
||||
p := record()
|
||||
@@ -35,13 +35,13 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
|
||||
if err := os.WriteFile(p, head, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Enabled() {
|
||||
if Enabled() != Off {
|
||||
t.Errorf("a desktop entry with no Exec reads as on:\n%s", head)
|
||||
}
|
||||
if err := os.WriteFile(p, nil, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Enabled() {
|
||||
if Enabled() != Off {
|
||||
t.Error("an empty desktop entry reads as on")
|
||||
}
|
||||
// an Exec key with nothing after it names nothing to run either, and the
|
||||
@@ -49,7 +49,7 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
|
||||
if err := os.WriteFile(p, []byte("[Desktop Entry]\nType=Application\nName=magpie\nExec=\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if Enabled() {
|
||||
if Enabled() != Off {
|
||||
t.Error("a desktop entry with an empty Exec reads as on")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build darwin && cgo
|
||||
|
||||
package autostart
|
||||
|
||||
/*
|
||||
#cgo CFLAGS: -x objective-c -fobjc-arc
|
||||
#cgo LDFLAGS: -framework Foundation -framework ServiceManagement
|
||||
#include <stdlib.h>
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <ServiceManagement/ServiceManagement.h>
|
||||
|
||||
// SMAppService is macOS 13's; before it there is nothing to ask (-1)
|
||||
static long magpieLegacyStatus(const char *path) {
|
||||
if (@available(macOS 13.0, *)) {
|
||||
@autoreleasepool {
|
||||
NSURL *u = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path]];
|
||||
return (long)[SMAppService statusForLegacyURL:u];
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import "unsafe"
|
||||
|
||||
func init() {
|
||||
legacyStatus = func(path string) int {
|
||||
p := C.CString(path)
|
||||
defer C.free(unsafe.Pointer(p))
|
||||
return int(C.magpieLegacyStatus(p))
|
||||
}
|
||||
}
|
||||
@@ -18,13 +18,13 @@ func TestSet(t *testing.T) {
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", home+"/.config")
|
||||
t.Setenv("APPIMAGE", "/opt/my apps/magpie.AppImage")
|
||||
if Enabled() {
|
||||
if Enabled() != Off {
|
||||
t.Fatal("on before it was turned on")
|
||||
}
|
||||
if err := Set(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !Enabled() {
|
||||
if Enabled() == Off {
|
||||
t.Fatal("not on after Set(true)")
|
||||
}
|
||||
path := record()
|
||||
@@ -41,7 +41,7 @@ func TestSet(t *testing.T) {
|
||||
t.Errorf("%s lacks %q:\n%s", path, want, b)
|
||||
}
|
||||
}
|
||||
if err := Set(false); err != nil || Enabled() {
|
||||
if err := Set(false); err != nil || Enabled() != Off {
|
||||
t.Fatalf("still on after Set(false): %v", err)
|
||||
}
|
||||
if err := Set(false); err != nil {
|
||||
|
||||
@@ -117,3 +117,6 @@ func disable() error {
|
||||
|
||||
// refresh: nothing an older magpie wrote here needs writing again
|
||||
func refresh() error { return nil }
|
||||
|
||||
// heldBack: nothing here is switched off apart from the record itself
|
||||
func heldBack() bool { return false }
|
||||
|
||||
@@ -44,13 +44,13 @@ func TestEnabledUnreadableKeyIsNotOff(t *testing.T) {
|
||||
openRunKey = func(registry.Key, string, uint32) (registry.Key, error) {
|
||||
return 0, windows.ERROR_ACCESS_DENIED
|
||||
}
|
||||
if !Enabled() {
|
||||
if Enabled() == Off {
|
||||
t.Fatal("a Run key that cannot be read reads as off")
|
||||
}
|
||||
openRunKey = func(registry.Key, string, uint32) (registry.Key, error) {
|
||||
return 0, registry.ErrNotExist
|
||||
}
|
||||
if Enabled() {
|
||||
if Enabled() != Off {
|
||||
t.Fatal("no Run key reads as on")
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,7 @@ func TestEnabledWithNoMarkerIsOn(t *testing.T) {
|
||||
openApprovedKey = func(registry.Key, string, uint32) (registry.Key, error) {
|
||||
return 0, registry.ErrNotExist
|
||||
}
|
||||
if !Enabled() {
|
||||
if Enabled() == Off {
|
||||
t.Fatal("a Run value with no Startup apps marker reads as off")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
//go:build darwin && cgo
|
||||
|
||||
package autostart
|
||||
|
||||
// cgoBuilt: this build asks ServiceManagement (autostart_sm_darwin.go)
|
||||
const cgoBuilt = true
|
||||
@@ -0,0 +1,6 @@
|
||||
//go:build !darwin
|
||||
|
||||
package autostart
|
||||
|
||||
// keepToTheSandbox: only the Mac's switch is asked of the system
|
||||
func keepToTheSandbox() {}
|
||||
@@ -6,5 +6,9 @@ import (
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// The tests run in a home of their own, never the user's real files.
|
||||
func TestMain(m *testing.M) { testenv.Main(m) }
|
||||
// The tests run in a home of their own, never the user's real files, and
|
||||
// never ask the system about the user's own login item.
|
||||
func TestMain(m *testing.M) {
|
||||
keepToTheSandbox()
|
||||
testenv.Main(m)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
//go:build darwin && !cgo
|
||||
|
||||
package autostart
|
||||
|
||||
// cgoBuilt: this build has no way to ask ServiceManagement
|
||||
const cgoBuilt = false
|
||||
@@ -22,13 +22,17 @@ func autostartCmd(args []string) error {
|
||||
return fmt.Errorf("usage: magpie autostart [on|off]")
|
||||
}
|
||||
}
|
||||
if autostart.Enabled() {
|
||||
switch autostart.Enabled() {
|
||||
case autostart.NeedsAllowing:
|
||||
// the record is there, and Set(true) can't undo the user's switch
|
||||
fmt.Println("magpie is set to open at login, but it is switched off in System Settings › General › Login Items › Allow in the Background: switch it on there")
|
||||
case autostart.On:
|
||||
if runtime.GOOS == "android" {
|
||||
fmt.Println(green.Render("✓"), "magpie starts the gateway at boot (requires Termux:Boot)")
|
||||
} else {
|
||||
fmt.Println(green.Render("✓"), "magpie opens at login, in the tray")
|
||||
}
|
||||
} else {
|
||||
default:
|
||||
fmt.Println("magpie doesn't open at login")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -278,8 +278,11 @@ func installed(f func(manager) error) error {
|
||||
})
|
||||
}
|
||||
|
||||
// autostartEnabled is a var for the tests.
|
||||
var autostartEnabled = autostart.Enabled
|
||||
// autostartEnabled: magpie's own record is there, whether or not the
|
||||
// user has it switched off in System Settings for now, since switching
|
||||
// it back on there opens the app with the service still installed. A
|
||||
// var for the tests.
|
||||
var autostartEnabled = func() bool { return autostart.Enabled() != autostart.Off }
|
||||
|
||||
// self is the program the service runs: this one, by the name on PATH
|
||||
// when that is this same file, so a package manager's link (Homebrew's
|
||||
|
||||
+399
-171
@@ -829,6 +829,7 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri
|
||||
func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest string, body []byte, on *provider.Provider) {
|
||||
start := time.Now()
|
||||
usage.Saw(agentOf(r))
|
||||
w0, body0 := w, body // as they came, for the fallbacks (codexFallBack)
|
||||
if r.Method == http.MethodPost {
|
||||
var unmask func()
|
||||
var err error
|
||||
@@ -852,6 +853,18 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
if r.URL.RawQuery != "" {
|
||||
u += "?" + r.URL.RawQuery
|
||||
}
|
||||
// Codex's turn on its own sign-in, the one account it has, with
|
||||
// nobody else to ask (codexAccounts): an overload of the backend's —
|
||||
// a busy status, or server_is_overloaded on a stream that has said
|
||||
// nothing yet (#1418), which Codex doesn't ask again for — is asked
|
||||
// again of it, as the accounts loop asks its last account, the same
|
||||
// bytes with the same sign-in, and then of the subscription's
|
||||
// fallbacks; nobody rests for it (夜松云 on Discord)
|
||||
overload := r.Method == http.MethodPost && rest == "/responses" && base == provider.CodexBase && on == nil
|
||||
streams := streamOf(body)
|
||||
kept := &keptAlive{proto: provider.Responses, told: start, streams: streams}
|
||||
busyAgain := 0 // times the turn was asked again for an overload
|
||||
var tried []string // what each of those said, for the request log
|
||||
// a turn goes in the Routing view's live trace as the others do, to
|
||||
// the one it can go to: Codex's own sign-in, or its key
|
||||
var tr *Route
|
||||
@@ -904,10 +917,12 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
window = cmp.Or(provider.CodexWindow(user, model), catalog.ContextOf(model))
|
||||
}
|
||||
s.trace.update(tr, func(t *Route) {
|
||||
t.Tries[0].Done, t.Tries[0].Status, t.Tries[0].Millis, t.Tries[0].Error = true, status, ms, msg
|
||||
t.Tries[0].TTFT, t.Tries[0].FirstText = ttft, text
|
||||
// the last try: the turn asked again for an overload has one each
|
||||
try := &t.Tries[len(t.Tries)-1]
|
||||
try.Done, try.Status, try.Millis, try.Error = true, status, time.Since(try.Start).Milliseconds(), msg
|
||||
try.TTFT, try.FirstText = ttft, text
|
||||
t.ReasoningHidden = first.hidesReasoning(provider.Responses)
|
||||
t.Tries[0].ReasoningHidden = t.ReasoningHidden
|
||||
try.ReasoningHidden = t.ReasoningHidden
|
||||
t.Done, t.Status, t.Error, t.Millis, t.Tokens = true, status, msg, ms, tokens
|
||||
if t.TitleLink != nil && isTitleKind(kind) && status < 400 && msg == "" && !titleReply.truncated {
|
||||
link := *t.TitleLink
|
||||
@@ -916,13 +931,13 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
}
|
||||
t.Output, t.Reasoning, t.TTFT, t.FirstText = out, uu.Reasoning, ttft, text
|
||||
flow := first.flowFor(uu.Reasoning)
|
||||
t.Flow, t.Tries[0].Flow = flow, flow
|
||||
t.Flow, try.Flow = flow, flow
|
||||
t.Usage = routeUsage("openai", model, uu)
|
||||
if prompt != nil {
|
||||
t.Prompt = prompt.calibrated(promptCounted(t.Usage), window)
|
||||
}
|
||||
t.Tries[0].Served, t.Tries[0].Swapped = served, swapped(model, served)
|
||||
t.Served, t.Swapped = t.Tries[0].Served, t.Tries[0].Swapped
|
||||
try.Served, try.Swapped = served, swapped(model, served)
|
||||
t.Served, t.Swapped = try.Served, try.Swapped
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -931,188 +946,311 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
resetNote := "" // what spending it did, for the request log
|
||||
resets := 0 // times a large request ChatGPT closed on was asked again (#1628)
|
||||
sent := len(body) // the bytes that went, compressed (provider.CodexCompressed)
|
||||
for tries := 0; ; tries++ {
|
||||
ctx := provider.ViaSignedIn(r.Context(), "codex")
|
||||
if on != nil {
|
||||
ctx = on.Via(r.Context())
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, r.Method, u, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
writeError(w, provider.Responses, 502, err.Error())
|
||||
end(502, err.Error(), 0, 0)
|
||||
began := start // when the try now going began
|
||||
// failWith tells Codex of a failure before any reply: as the stream's
|
||||
// error once it was sent the stream's headers while it waited
|
||||
failWith := func(status int, msg string) {
|
||||
if kept.sent {
|
||||
streamError(w, provider.Responses, status, msg)
|
||||
return
|
||||
}
|
||||
copyHeaders(req.Header, r.Header)
|
||||
if on != nil {
|
||||
// the account's own token and id in place of the sign-in's;
|
||||
// what Codex said it takes back stays as it said it
|
||||
accept := req.Header.Values("Accept")
|
||||
if err := on.Sign(ctx, req, provider.Responses, body); err != nil {
|
||||
msg := "OpenAI (" + on.Account.User + "): " + err.Error()
|
||||
writeError(w, provider.Responses, 502, msg)
|
||||
writeError(w, provider.Responses, status, msg)
|
||||
}
|
||||
// handOn notes a try that failed for an overload, which the turn goes
|
||||
// on from, after wait: in the trace, and as a row handed on, as the
|
||||
// accounts loop notes one
|
||||
handOn := func(status int, msg string, wait time.Duration) {
|
||||
s.trace.update(tr, func(t *Route) {
|
||||
try := &t.Tries[len(t.Tries)-1]
|
||||
try.Done, try.Status, try.Error, try.Fail = true, status, msg, failOther
|
||||
try.Millis, try.Again = time.Since(try.Start).Milliseconds(), wait.Milliseconds()
|
||||
})
|
||||
servedProvider, servedAccount := codexServed(base, r.Header, on)
|
||||
rec := usage.Record{RouteID: tr.ID, Time: began, Agent: agentOf(r), Provider: servedProvider, Host: provider.HostOf(base),
|
||||
ProviderAccount: servedAccount, Model: modelOf(body), Requested: modelOf(body), Effort: effort,
|
||||
Millis: time.Since(began).Milliseconds(), Status: status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header),
|
||||
Kind: kind, Endpoint: r.URL.Path, HandedOn: true}
|
||||
failedWith(&rec, status, msg, "")
|
||||
appendUsage(r, rec)
|
||||
tried = append(tried, fmt.Sprintf("openai: %d %s", status, msg))
|
||||
}
|
||||
// askAgain pauses wait, Codex kept alive meanwhile, for the turn to be
|
||||
// asked again; false when Codex went away in it
|
||||
askAgain := func(status int, msg string, wait time.Duration) bool {
|
||||
handOn(status, msg, wait)
|
||||
busyAgain++
|
||||
if !pauseAlive(r.Context(), w, kept, streams, start, wait) {
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1].Gone = true })
|
||||
end(status, msg, 0, 0)
|
||||
return false
|
||||
}
|
||||
began = time.Now()
|
||||
s.trace.update(tr, func(t *Route) {
|
||||
again := t.Tries[0]
|
||||
t.Tries = append(t.Tries, Try{ID: again.ID, Model: again.Model, Effort: again.Effort, Start: began})
|
||||
})
|
||||
first, titleReply = firstToken{start: start}, capturedBody{}
|
||||
return true
|
||||
}
|
||||
var sniff *usageSniffer
|
||||
var refusal []byte // what OpenAI said, of a request it turned away
|
||||
for {
|
||||
// the try's own, which a stream that failed before its reply ends
|
||||
// (holdWriter.stop)
|
||||
attempt, cancel := context.WithCancel(r.Context())
|
||||
defer cancel()
|
||||
for tries := 0; ; tries++ {
|
||||
ctx := provider.ViaSignedIn(attempt, "codex")
|
||||
if on != nil {
|
||||
ctx = on.Via(attempt)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, r.Method, u, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
failWith(502, err.Error())
|
||||
end(502, err.Error(), 0, 0)
|
||||
return
|
||||
}
|
||||
copyHeaders(req.Header, r.Header)
|
||||
if on != nil {
|
||||
// the account's own token and id in place of the sign-in's;
|
||||
// what Codex said it takes back stays as it said it
|
||||
accept := req.Header.Values("Accept")
|
||||
if err := on.Sign(ctx, req, provider.Responses, body); err != nil {
|
||||
msg := "OpenAI (" + on.Account.User + "): " + err.Error()
|
||||
writeError(w, provider.Responses, 502, msg)
|
||||
end(502, msg, 0, 0)
|
||||
return
|
||||
}
|
||||
// a sign-in its vendor revoked isn't sent again (#1793)
|
||||
if why, ok := provider.RevokedSignIn(on.Account, req); ok {
|
||||
writeError(w, provider.Responses, 401, why)
|
||||
end(401, why, 0, 0)
|
||||
return
|
||||
}
|
||||
req.Header.Del("Accept")
|
||||
for _, v := range accept {
|
||||
req.Header.Add("Accept", v)
|
||||
}
|
||||
}
|
||||
// left to the transport, the reply comes back plain for the usage in it
|
||||
req.Header.Del("Accept-Encoding")
|
||||
// a turn to ChatGPT goes zstd-compressed again, as Codex sent it
|
||||
// before magpie read it (ylorn on X); an API key's goes plain
|
||||
sent = provider.CodexCompressed(req, body)
|
||||
if res, err = s.client.Do(req); err != nil {
|
||||
msg := "OpenAI: " + err.Error()
|
||||
if rest == "/responses" {
|
||||
msg = codexUnreached(modelOf(body), err)
|
||||
}
|
||||
failWith(502, msg)
|
||||
end(502, msg, 0, 0)
|
||||
return
|
||||
}
|
||||
// a sign-in its vendor revoked isn't sent again (#1793)
|
||||
if why, ok := provider.RevokedSignIn(on.Account, req); ok {
|
||||
writeError(w, provider.Responses, 401, why)
|
||||
end(401, why, 0, 0)
|
||||
return
|
||||
if on != nil {
|
||||
// one of magpie's accounts: a revoked sign-in shows on its
|
||||
// row, to sign in again (#1793)
|
||||
noteSignIn(ctx, on.Account, req, res)
|
||||
}
|
||||
req.Header.Del("Accept")
|
||||
for _, v := range accept {
|
||||
req.Header.Add("Accept", v)
|
||||
if !autoReset && rest == "/responses" && base != codexAPIBase && res.StatusCode == http.StatusTooManyRequests {
|
||||
// the account is out of its allowance: one it lets spend its
|
||||
// resets by itself, its week used up, spends one and is asked
|
||||
// again — nobody else is there to ask
|
||||
autoReset = true
|
||||
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
res.Body.Close()
|
||||
res.Body = io.NopCloser(bytes.NewReader(msg))
|
||||
if failure(res.StatusCode, msg) == failQuota {
|
||||
if who, out, ok := s.autoResetSignedIn(r.Context()); ok {
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1].Reset = &AutoReset{Who: who, Text: out.Text()} })
|
||||
resetNote = "openai (" + who + "): used one of its resets by itself (" + out.Text() + ")"
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// left to the transport, the reply comes back plain for the usage in it
|
||||
req.Header.Del("Accept-Encoding")
|
||||
// a turn to ChatGPT goes zstd-compressed again, as Codex sent it
|
||||
// before magpie read it (ylorn on X); an API key's goes plain
|
||||
sent = provider.CodexCompressed(req, body)
|
||||
if res, err = s.client.Do(req); err != nil {
|
||||
msg := "OpenAI: " + err.Error()
|
||||
if rest == "/responses" {
|
||||
msg = codexUnreached(modelOf(body), err)
|
||||
if rest == "/responses" && base != codexAPIBase && edgeMayDrop(res.StatusCode, sent) && resets < lastRetries {
|
||||
// ChatGPT closed the connection before answering a large
|
||||
// request, which often passes (#1628), or its front couldn't
|
||||
// retry one that large (#2034): asked again after a moment,
|
||||
// as the accounts loop asks its last one again
|
||||
head, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10))
|
||||
res.Body.Close()
|
||||
res.Body = io.NopCloser(bytes.NewReader(head))
|
||||
if edgeSaidDrop(res.StatusCode, head) {
|
||||
wait := retryPause << resets
|
||||
resets++
|
||||
select {
|
||||
case <-time.After(wait):
|
||||
continue
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
}
|
||||
}
|
||||
writeError(w, provider.Responses, 502, msg)
|
||||
end(502, msg, 0, 0)
|
||||
return
|
||||
}
|
||||
if on != nil {
|
||||
// one of magpie's accounts: a revoked sign-in shows on its
|
||||
// row, to sign in again (#1793)
|
||||
noteSignIn(ctx, on.Account, req, res)
|
||||
}
|
||||
if !autoReset && rest == "/responses" && base != codexAPIBase && res.StatusCode == http.StatusTooManyRequests {
|
||||
// the account is out of its allowance: one it lets spend its
|
||||
// resets by itself, its week used up, spends one and is asked
|
||||
// again — nobody else is there to ask
|
||||
autoReset = true
|
||||
if overload && busyAgain < lastRetries && res.StatusCode >= 400 {
|
||||
// the backend too busy for the turn, said as its status
|
||||
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
res.Body.Close()
|
||||
res.Body = io.NopCloser(bytes.NewReader(msg))
|
||||
if codexBusy(res.StatusCode, msg) {
|
||||
if wait, ok := passing(res.StatusCode, res.Header, msg, busyAgain); ok {
|
||||
if !askAgain(res.StatusCode, provider.APIError(msg, res.Status), wait) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if rest != "/responses" || tries >= 3 || (res.StatusCode != 400 && res.StatusCode != 404) {
|
||||
break
|
||||
}
|
||||
// an item OpenAI can't take — sealed by another account, or
|
||||
// another vendor's that it looks up and doesn't have — is taken
|
||||
// out and the rest asked again, rather than the conversation
|
||||
// stuck on it for good
|
||||
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
res.Body.Close()
|
||||
res.Body = io.NopCloser(bytes.NewReader(msg))
|
||||
if failure(res.StatusCode, msg) == failQuota {
|
||||
if who, out, ok := s.autoResetSignedIn(r.Context()); ok {
|
||||
s.trace.update(tr, func(t *Route) { t.Tries[0].Reset = &AutoReset{Who: who, Text: out.Text()} })
|
||||
resetNote = "openai (" + who + "): used one of its resets by itself (" + out.Text() + ")"
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if rest == "/responses" && base != codexAPIBase && edgeMayDrop(res.StatusCode, sent) && resets < lastRetries {
|
||||
// ChatGPT closed the connection before answering a large
|
||||
// request, which often passes (#1628), or its front couldn't
|
||||
// retry one that large (#2034): asked again after a moment,
|
||||
// as the accounts loop asks its last one again
|
||||
head, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10))
|
||||
res.Body.Close()
|
||||
res.Body = io.NopCloser(bytes.NewReader(head))
|
||||
if edgeSaidDrop(res.StatusCode, head) {
|
||||
wait := retryPause << resets
|
||||
resets++
|
||||
select {
|
||||
case <-time.After(wait):
|
||||
continue
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
}
|
||||
}
|
||||
if rest != "/responses" || tries >= 3 || (res.StatusCode != 400 && res.StatusCode != 404) {
|
||||
break
|
||||
}
|
||||
// an item OpenAI can't take — sealed by another account, or
|
||||
// another vendor's that it looks up and doesn't have — is taken
|
||||
// out and the rest asked again, rather than the conversation
|
||||
// stuck on it for good
|
||||
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
res.Body.Close()
|
||||
res.Body = io.NopCloser(bytes.NewReader(msg))
|
||||
b, ok := withoutUnreadable(body, msg)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
body = b
|
||||
}
|
||||
if rest == "/responses" {
|
||||
// a web page or nothing at all, served 200, is the 502 it stands
|
||||
// for (#1012)
|
||||
res = notAnAPIReply(res, "OpenAI: ")
|
||||
if base != codexAPIBase {
|
||||
// still closed on after that: Codex is told what may help,
|
||||
// at the 503 it asks again for (#1628)
|
||||
res = codexDropped(res, sent)
|
||||
}
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if base == codexAPIBase && res.StatusCode == http.StatusUnauthorized {
|
||||
// Codex signed in with an API key OpenAI refuses — often one a
|
||||
// relay issued, left in ~/.codex/auth.json — and one of Codex's own
|
||||
// models was picked, which goes out with Codex's own sign-in
|
||||
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
writeError(w, provider.Responses, res.StatusCode, codexKeyRefused(msg))
|
||||
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
|
||||
Provider: "openai", Agent: agentOf(r), Status: res.StatusCode,
|
||||
Millis: time.Since(start).Milliseconds(), Error: res.Status})
|
||||
end(res.StatusCode, res.Status, 0, 0)
|
||||
return
|
||||
}
|
||||
if rest == "/responses" && res.StatusCode >= 400 {
|
||||
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
res.Body = io.NopCloser(bytes.NewReader(msg))
|
||||
if len(bytes.TrimSpace(msg)) == 0 {
|
||||
// a failure with nothing said of it, which Codex shows as
|
||||
// "Unknown error" alone (#409): said where the turn went
|
||||
said := codexFailedEmpty(modelOf(body), res.Status)
|
||||
writeError(w, provider.Responses, res.StatusCode, said)
|
||||
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
|
||||
Provider: "openai", Agent: agentOf(r), Kind: callKind(r.Header), Status: res.StatusCode,
|
||||
Millis: time.Since(start).Milliseconds(), Error: said})
|
||||
end(res.StatusCode, said, 0, 0)
|
||||
return
|
||||
}
|
||||
}
|
||||
for k, vs := range res.Header {
|
||||
if !hopHeader(k) {
|
||||
w.Header()[k] = vs
|
||||
}
|
||||
}
|
||||
modelsEtag(w.Header())
|
||||
w.WriteHeader(res.StatusCode)
|
||||
var sniff *usageSniffer
|
||||
if rest == "/responses" {
|
||||
ct := res.Header.Get("Content-Type")
|
||||
if ct == "" && streamOf(body) { // the ChatGPT backend streams without saying so
|
||||
ct = "text/event-stream"
|
||||
}
|
||||
sniff = newSniffer(provider.Responses, ct)
|
||||
}
|
||||
f, _ := w.(http.Flusher)
|
||||
buf := make([]byte, 32<<10)
|
||||
var refusal []byte // what OpenAI said, of a request it turned away
|
||||
for {
|
||||
n, err := res.Body.Read(buf)
|
||||
if n > 0 {
|
||||
if captureTitle {
|
||||
titleReply.add(buf[:n])
|
||||
}
|
||||
if sniff != nil {
|
||||
sniff.write(buf[:n])
|
||||
first.see(buf[:n])
|
||||
tools.add(buf[:n])
|
||||
}
|
||||
if res.StatusCode >= 400 && len(refusal) < 8<<10 {
|
||||
refusal = append(refusal, buf[:n]...)
|
||||
}
|
||||
if _, werr := w.Write(buf[:n]); werr != nil {
|
||||
b, ok := withoutUnreadable(body, msg)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
if f != nil {
|
||||
f.Flush()
|
||||
body = b
|
||||
}
|
||||
if rest == "/responses" {
|
||||
// a web page or nothing at all, served 200, is the 502 it stands
|
||||
// for (#1012)
|
||||
res = notAnAPIReply(res, "OpenAI: ")
|
||||
if base != codexAPIBase {
|
||||
// still closed on after that: Codex is told what may help,
|
||||
// at the 503 it asks again for (#1628)
|
||||
res = codexDropped(res, sent)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
defer res.Body.Close()
|
||||
if base == codexAPIBase && res.StatusCode == http.StatusUnauthorized {
|
||||
// Codex signed in with an API key OpenAI refuses — often one a
|
||||
// relay issued, left in ~/.codex/auth.json — and one of Codex's own
|
||||
// models was picked, which goes out with Codex's own sign-in
|
||||
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
writeError(w, provider.Responses, res.StatusCode, codexKeyRefused(msg))
|
||||
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
|
||||
Provider: "openai", Agent: agentOf(r), Status: res.StatusCode,
|
||||
Millis: time.Since(start).Milliseconds(), Error: res.Status})
|
||||
end(res.StatusCode, res.Status, 0, 0)
|
||||
return
|
||||
}
|
||||
if rest == "/responses" && res.StatusCode >= 400 {
|
||||
msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
res.Body = io.NopCloser(bytes.NewReader(msg))
|
||||
if overload && codexBusy(res.StatusCode, msg) && s.codexFallsBack(modelOf(body), body) {
|
||||
// still too busy once asked again: the fallbacks answer
|
||||
said := provider.APIError(msg, res.Status)
|
||||
handOn(res.StatusCode, said, 0)
|
||||
end(res.StatusCode, said, 0, 0)
|
||||
s.codexFallBack(w0, r, body0, kept)
|
||||
return
|
||||
}
|
||||
if len(bytes.TrimSpace(msg)) == 0 {
|
||||
// a failure with nothing said of it, which Codex shows as
|
||||
// "Unknown error" alone (#409): said where the turn went
|
||||
said := codexFailedEmpty(modelOf(body), res.Status)
|
||||
failWith(res.StatusCode, said)
|
||||
s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
|
||||
Provider: "openai", Agent: agentOf(r), Kind: callKind(r.Header), Status: res.StatusCode,
|
||||
Millis: time.Since(start).Milliseconds(), Error: said})
|
||||
end(res.StatusCode, said, 0, 0)
|
||||
return
|
||||
}
|
||||
}
|
||||
// a stream that may still be asked again, or whose Codex has the
|
||||
// stream's headers already, goes through a holdWriter: the frames
|
||||
// before a reply held, its reasoning and text let through as they
|
||||
// come, an error before them held for the turn to be asked again
|
||||
out := w
|
||||
var hw *holdWriter
|
||||
if overload && streams && (busyAgain < lastRetries || kept.sent || s.codexFallsBack(modelOf(body), body)) {
|
||||
hw = newHoldWriter(w, true)
|
||||
hw.alive, hw.streams, hw.ctx, hw.stop = kept, true, r.Context(), cancel
|
||||
// reasoning goes to Codex at once, as it always went
|
||||
hw.thinkingShown = true
|
||||
out = hw
|
||||
}
|
||||
for k, vs := range res.Header {
|
||||
if !hopHeader(k) {
|
||||
out.Header()[k] = vs
|
||||
}
|
||||
}
|
||||
if hw != nil && res.StatusCode < 400 && res.Header.Get("Content-Type") == "" {
|
||||
// the ChatGPT backend streams without saying so: held as the
|
||||
// stream it is
|
||||
out.Header().Set("Content-Type", "text/event-stream")
|
||||
}
|
||||
modelsEtag(out.Header())
|
||||
out.WriteHeader(res.StatusCode)
|
||||
stopWatch := func() {}
|
||||
if hw != nil {
|
||||
stopWatch = hw.watch()
|
||||
}
|
||||
if rest == "/responses" {
|
||||
ct := res.Header.Get("Content-Type")
|
||||
if ct == "" && streams { // the ChatGPT backend streams without saying so
|
||||
ct = "text/event-stream"
|
||||
}
|
||||
sniff = newSniffer(provider.Responses, ct)
|
||||
}
|
||||
f, _ := out.(http.Flusher)
|
||||
buf := make([]byte, 32<<10)
|
||||
refusal = nil
|
||||
for {
|
||||
n, err := res.Body.Read(buf)
|
||||
if n > 0 {
|
||||
if captureTitle {
|
||||
titleReply.add(buf[:n])
|
||||
}
|
||||
if sniff != nil {
|
||||
sniff.write(buf[:n])
|
||||
first.see(buf[:n])
|
||||
tools.add(buf[:n])
|
||||
}
|
||||
if res.StatusCode >= 400 && len(refusal) < 8<<10 {
|
||||
refusal = append(refusal, buf[:n]...)
|
||||
}
|
||||
if _, werr := out.Write(buf[:n]); werr != nil {
|
||||
break
|
||||
}
|
||||
if f != nil {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
stopWatch()
|
||||
if hw == nil {
|
||||
break
|
||||
}
|
||||
hw.settle()
|
||||
if hw.mayAskAgain() && hw.failure != 0 && !hw.refused && codexBusy(hw.failure, hw.errBody()) && r.Context().Err() == nil {
|
||||
// the backend too busy for the turn, said on its stream before
|
||||
// any of the reply (#1418)
|
||||
said := "OpenAI: " + string(hw.errBody())
|
||||
if wait, ok := passing(hw.failure, res.Header, hw.errBody(), busyAgain); ok {
|
||||
res.Body.Close()
|
||||
if !askAgain(hw.failure, said, wait) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if s.codexFallsBack(modelOf(body), body) {
|
||||
res.Body.Close()
|
||||
handOn(hw.failure, said, 0)
|
||||
end(hw.failure, said, 0, 0)
|
||||
s.codexFallBack(w0, r, body0, kept)
|
||||
return
|
||||
}
|
||||
}
|
||||
hw.release()
|
||||
break
|
||||
}
|
||||
if sniff == nil {
|
||||
return
|
||||
@@ -1120,6 +1258,11 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
call := Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
|
||||
Provider: "openai", Agent: agentOf(r), Kind: kind, Status: res.StatusCode,
|
||||
Millis: time.Since(start).Milliseconds(), Fallback: resetNote}
|
||||
if len(tried) > 0 {
|
||||
// the overloads it was asked again for, before the one that answered
|
||||
call.Fallback = strings.Join(append(tried, call.Fallback), "; ")
|
||||
call.Fallback = strings.TrimSuffix(call.Fallback, "; ")
|
||||
}
|
||||
call.TTFT, call.FirstText = first.ms()
|
||||
call.ReasoningHidden = first.hidesReasoning(provider.Responses)
|
||||
uu.add(sniff.usage())
|
||||
@@ -1148,6 +1291,91 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
appendUsage(r, rec)
|
||||
}
|
||||
|
||||
// codexBusy says a failure of the ChatGPT backend's, said as a status or
|
||||
// on a stream before any reply, is it too busy for the turn (busy): no
|
||||
// fault of the account's, nor of the request's. Its front closing on the
|
||||
// request is no overload: a large request's has its own retries
|
||||
// (edgeSaidDrop, codexDropped), and a small one's goes to Codex as the
|
||||
// 503 it asks again for (TestCodexResetJudgedByTheBytesSent). A 429 is
|
||||
// the account's allowance or rate, which isn't outwaited in seconds.
|
||||
func codexBusy(status int, msg []byte) bool {
|
||||
if status == http.StatusTooManyRequests || edgeSaidDrop(status, msg) || codexReset(status, msg) {
|
||||
return false
|
||||
}
|
||||
return busy(status, msg)
|
||||
}
|
||||
|
||||
// codexFallsBack says Codex's turn on one of its own models has fallbacks
|
||||
// to go on to (codexFallBack): the Codex subscription's, set in magpie, at
|
||||
// least one of them found. A turn compacting natively is the backend's to
|
||||
// answer, and goes nowhere else.
|
||||
func (s *Server) codexFallsBack(model string, body []byte) bool {
|
||||
if model == "" || strings.Contains(model, "/") || compactionTriggerIn(body) {
|
||||
return false
|
||||
}
|
||||
p, _, ok := provider.Resolve("codex/" + model)
|
||||
if !ok || p.Account == nil || p.Account.Agent != "codex" {
|
||||
return false
|
||||
}
|
||||
for _, id := range p.Fallback {
|
||||
if _, _, ok := provider.Resolve(id); ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// codexFallBack serves Codex's turn on its own sign-in, which the backend
|
||||
// was too busy for however often it was asked again, from the Codex
|
||||
// subscription's fallbacks, as serve goes on to them for a turn through
|
||||
// magpie's accounts; the account itself is not asked again (handedOnOf).
|
||||
// kept is what Codex was sent while it waited: the stream's headers, once
|
||||
// it had them, which the fallback's reply follows.
|
||||
func (s *Server) codexFallBack(w http.ResponseWriter, r *http.Request, body []byte, kept *keptAlive) {
|
||||
id := "codex/" + modelOf(body)
|
||||
body, _ = codexInputAs(withModel(body, id), true, s.nativeCompactionFor(id))
|
||||
s.serve(w, r.WithContext(context.WithValue(r.Context(), handedOnKey{}, kept)), provider.Responses, body)
|
||||
}
|
||||
|
||||
// handedOnKey carries, in a request codexFallBack hands on, what its
|
||||
// agent was sent while it waited.
|
||||
type handedOnKey struct{}
|
||||
|
||||
// handedOnOf is what the agent of a request codexFallBack handed on was
|
||||
// sent while it waited, nil for any other request.
|
||||
func handedOnOf(r *http.Request) *keptAlive {
|
||||
k, _ := r.Context().Value(handedOnKey{}).(*keptAlive)
|
||||
return k
|
||||
}
|
||||
|
||||
// fallbacksOnly is cands without model's own on provider id, pl with
|
||||
// them: a request handed on to the fallbacks (codexFallBack) after the
|
||||
// account was asked as often as it is asked.
|
||||
func fallbacksOnly(cands []candidate, pl planned, id, model string) ([]candidate, planned) {
|
||||
own := func(c candidate) bool { return c.p.ID == id && c.model == model }
|
||||
var kept []candidate
|
||||
var order []Weighed
|
||||
for i, c := range cands {
|
||||
if !own(c) {
|
||||
kept = append(kept, c)
|
||||
order = append(order, pl.order[i])
|
||||
}
|
||||
}
|
||||
cands, pl.order = kept, order
|
||||
pl.held = slices.DeleteFunc(slices.Clone(pl.held), own)
|
||||
pl.capped = slices.DeleteFunc(slices.Clone(pl.capped), own)
|
||||
var unlisted []candidate
|
||||
var unlistedW []Weighed
|
||||
for i, c := range pl.unlisted {
|
||||
if !own(c) {
|
||||
unlisted = append(unlisted, c)
|
||||
unlistedW = append(unlistedW, pl.unlistedW[i])
|
||||
}
|
||||
}
|
||||
pl.unlisted, pl.unlistedW = unlisted, unlistedW
|
||||
return cands, pl
|
||||
}
|
||||
|
||||
// codexServed is who a relay through codexUpstreamOn is recorded as.
|
||||
// Codex's own ChatGPT sign-in is the codex account, and a compaction
|
||||
// signed by another of its accounts (compactOn) is that account, so the
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// overloadedStatus is the ChatGPT backend's overload said as a status.
|
||||
const overloadedStatus = `{"error":{"type":"server_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`
|
||||
|
||||
// codexAnswer is a turn the ChatGPT backend answers, its frames first.
|
||||
var codexAnswer = sse(append(slices.Clone(overloadedLead),
|
||||
`event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"hello"}`,
|
||||
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":9,"output_tokens":2}}}`)...)
|
||||
|
||||
// overloadedBackend stands in for the ChatGPT backend, answering the n-th
|
||||
// request (from 0) with replies[n], the last one after that; it keeps
|
||||
// every request's body and headers. A 200 goes with no Content-Type, as
|
||||
// the backend sends it.
|
||||
type overloadedBackend struct {
|
||||
replies []reply
|
||||
mu sync.Mutex
|
||||
bodies [][]byte
|
||||
heads []http.Header
|
||||
}
|
||||
|
||||
func (o *overloadedBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
o.mu.Lock()
|
||||
i := min(len(o.bodies), len(o.replies)-1)
|
||||
o.bodies = append(o.bodies, b)
|
||||
o.heads = append(o.heads, r.Header.Clone())
|
||||
o.mu.Unlock()
|
||||
x := o.replies[i]
|
||||
if x.ctype != "" {
|
||||
w.Header().Set("Content-Type", x.ctype)
|
||||
} else {
|
||||
w.Header()["Content-Type"] = nil
|
||||
}
|
||||
w.WriteHeader(x.code)
|
||||
io.WriteString(w, x.body)
|
||||
}
|
||||
|
||||
func (o *overloadedBackend) asked() int {
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
return len(o.bodies)
|
||||
}
|
||||
|
||||
// oneCodexAccount is Codex signed in to ChatGPT with its one account and
|
||||
// nothing else on in magpie, the ChatGPT backend o: a turn on one of
|
||||
// Codex's own models is relayed as it came (codexAccounts), nobody else
|
||||
// to ask.
|
||||
func oneCodexAccount(t *testing.T, o *overloadedBackend) {
|
||||
t.Helper()
|
||||
codexSignedIn(t)
|
||||
up := httptest.NewServer(o)
|
||||
t.Cleanup(up.Close)
|
||||
was := provider.CodexBase
|
||||
provider.CodexBase = up.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { provider.CodexBase = was })
|
||||
pause := retryPause
|
||||
retryPause = time.Millisecond
|
||||
t.Cleanup(func() { retryPause = pause })
|
||||
if id, routed := codexAccounts(httptest.NewRequest("POST", CodexPath+"/responses", nil), "gpt-5.5"); routed {
|
||||
t.Fatalf("one account goes through routing as %s", id)
|
||||
}
|
||||
}
|
||||
|
||||
const oneAccountTurn = `{"model":"gpt-5.5","stream":true,"input":"ping"}`
|
||||
|
||||
// noneResting says nothing rests after an overload: no account is at
|
||||
// fault for it.
|
||||
func noneResting(t *testing.T) {
|
||||
t.Helper()
|
||||
restingUntil.Lock()
|
||||
defer restingUntil.Unlock()
|
||||
if len(restingUntil.m) > 0 {
|
||||
t.Fatalf("rested for an overload: %v", restingUntil.m)
|
||||
}
|
||||
}
|
||||
|
||||
// With one ChatGPT account, Codex's own turn the backend says it is too
|
||||
// busy for (529) is asked again of the same account, after the pause the
|
||||
// accounts loop takes, as Codex sent it (夜松云 on Discord): the answer
|
||||
// reaches Codex, nothing of the failure.
|
||||
func TestCodexOneAccountOverloadAskedAgain(t *testing.T) {
|
||||
o := &overloadedBackend{replies: []reply{{529, "application/json", overloadedStatus}, {200, "", codexAnswer}}}
|
||||
oneCodexAccount(t, o)
|
||||
code, body := codexPost(t, oneAccountTurn)
|
||||
if code != 200 || !strings.Contains(body, "hello") || strings.Contains(body, "overloaded") || o.asked() != 2 {
|
||||
t.Fatalf("%d %q, asked %d times", code, body, o.asked())
|
||||
}
|
||||
// the turn goes again as it went: the same bytes, the same sign-in
|
||||
if !bytes.Equal(o.bodies[0], o.bodies[1]) {
|
||||
t.Fatalf("asked again with another body:\n%s\n%s", o.bodies[0], o.bodies[1])
|
||||
}
|
||||
for _, k := range []string{"Authorization", "Chatgpt-Account-Id"} {
|
||||
if o.heads[0].Get(k) == "" || o.heads[0].Get(k) != o.heads[1].Get(k) {
|
||||
t.Fatalf("%s: %q then %q", k, o.heads[0].Get(k), o.heads[1].Get(k))
|
||||
}
|
||||
}
|
||||
noneResting(t)
|
||||
}
|
||||
|
||||
// The ChatGPT backend's overload as it says it on a turn (#1418): a 200,
|
||||
// the frames before a reply, then server_is_overloaded. Codex doesn't ask
|
||||
// again for it; held while it has only those frames, the turn is asked
|
||||
// again, and Codex has the answer and nothing of the failure.
|
||||
func TestCodexOneAccountStreamOverloadAskedAgain(t *testing.T) {
|
||||
failed := reply{200, "", sse(append(slices.Clone(overloadedLead), overloadedFailed)...)}
|
||||
o := &overloadedBackend{replies: []reply{failed, {200, "", codexAnswer}}}
|
||||
oneCodexAccount(t, o)
|
||||
code, body := codexPost(t, oneAccountTurn)
|
||||
if code != 200 || !strings.Contains(body, "hello") || strings.Contains(body, "server_is_overloaded") || o.asked() != 2 {
|
||||
t.Fatalf("%d %q, asked %d times", code, body, o.asked())
|
||||
}
|
||||
// the answer's frames go with it, once
|
||||
if strings.Count(body, "event: response.created") != 1 {
|
||||
t.Fatalf("frames: %q", body)
|
||||
}
|
||||
noneResting(t)
|
||||
}
|
||||
|
||||
// An overload that lasts is asked again as often as the accounts loop
|
||||
// asks its last account (lastRetries), and then Codex has the backend's
|
||||
// own failure, as it had before.
|
||||
func TestCodexOneAccountOverloadBounded(t *testing.T) {
|
||||
for name, failed := range map[string]reply{
|
||||
"status": {529, "application/json", overloadedStatus},
|
||||
"stream": {200, "", sse(append(slices.Clone(overloadedLead), overloadedFailed)...)},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
o := &overloadedBackend{replies: []reply{failed}}
|
||||
oneCodexAccount(t, o)
|
||||
code, body := codexPost(t, oneAccountTurn)
|
||||
if o.asked() != 1+lastRetries || !strings.Contains(body, "server_is_overloaded") {
|
||||
t.Fatalf("%d %q, asked %d times", code, body, o.asked())
|
||||
}
|
||||
if code != failed.code {
|
||||
t.Fatalf("status %d, the backend's %d", code, failed.code)
|
||||
}
|
||||
noneResting(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// With fallbacks set on the Codex subscription, an overload that lasts
|
||||
// goes on to them once the account was asked again, as a turn through
|
||||
// magpie's accounts does; without the account asked any more.
|
||||
func TestCodexOneAccountOverloadFallsBack(t *testing.T) {
|
||||
for name, failed := range map[string]reply{
|
||||
"status": {529, "application/json", overloadedStatus},
|
||||
"stream": {200, "", sse(append(slices.Clone(overloadedLead), overloadedFailed)...)},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
o := &overloadedBackend{replies: []reply{failed}}
|
||||
oneCodexAccount(t, o)
|
||||
fb := &scripted{replies: []reply{{200, "text/event-stream", sse(
|
||||
`event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"from the fallback"}`,
|
||||
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"f1","status":"completed","output":[]}}`)}}}
|
||||
responsesOn(t, "fb", fb)
|
||||
if err := provider.Save(provider.Provider{ID: "codex", Fallback: []string{"fb/m"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, body := codexPost(t, oneAccountTurn)
|
||||
if code != 200 || !strings.Contains(body, "from the fallback") || strings.Contains(body, "server_is_overloaded") {
|
||||
t.Fatalf("%d %q", code, body)
|
||||
}
|
||||
if o.asked() != 1+lastRetries || fb.n != 1 {
|
||||
t.Fatalf("ChatGPT asked %d times, the fallback %d", o.asked(), fb.n)
|
||||
}
|
||||
noneResting(t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A usage limit isn't an overload: with one account it still goes to
|
||||
// Codex as the backend said it, asked once (TestCodexOwnModelOneAccountRelayed),
|
||||
// and so does a refusal of the request.
|
||||
func TestCodexOneAccountRefusalNotAskedAgain(t *testing.T) {
|
||||
o := &overloadedBackend{replies: []reply{{400, "application/json", `{"error":{"type":"invalid_request_error","message":"Unsupported parameter: foo"}}`}}}
|
||||
oneCodexAccount(t, o)
|
||||
code, body := codexPost(t, oneAccountTurn)
|
||||
if code != 400 || !strings.Contains(body, "Unsupported parameter") || o.asked() != 1 {
|
||||
t.Fatalf("%d %q, asked %d times", code, body, o.asked())
|
||||
}
|
||||
}
|
||||
|
||||
// A backend that is slow to say it is overloaded (#1418: 36s after its
|
||||
// frames) has Codex kept alive meanwhile with the stream's headers and
|
||||
// comments, none of the failed tries; what follows goes on in that
|
||||
// stream: the last try's failure as it was said, or the fallback's reply.
|
||||
func TestCodexOneAccountOverloadKeptAlive(t *testing.T) {
|
||||
k, w := keepHeldAfter, watchEvery
|
||||
keepHeldAfter, watchEvery = 20*time.Millisecond, 5*time.Millisecond
|
||||
t.Cleanup(func() { keepHeldAfter, watchEvery = k, w })
|
||||
for _, withFallback := range []bool{false, true} {
|
||||
codexSignedIn(t)
|
||||
slow := &slowFrames{wait: 150 * time.Millisecond, then: func(int) string { return sse(overloadedFailed) }}
|
||||
up := httptest.NewServer(slow)
|
||||
t.Cleanup(up.Close)
|
||||
was := provider.CodexBase
|
||||
provider.CodexBase = up.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { provider.CodexBase = was })
|
||||
pause := retryPause
|
||||
retryPause = time.Millisecond
|
||||
t.Cleanup(func() { retryPause = pause })
|
||||
fb := &scripted{replies: []reply{{200, "text/event-stream", sse(
|
||||
`event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"from the fallback"}`,
|
||||
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"f1","status":"completed","output":[]}}`)}}}
|
||||
if withFallback {
|
||||
responsesOn(t, "fb", fb)
|
||||
if err := provider.Save(provider.Provider{ID: "codex", Fallback: []string{"fb/m"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
code, body := codexPost(t, oneAccountTurn)
|
||||
slow.mu.Lock()
|
||||
asked := slow.n
|
||||
slow.mu.Unlock()
|
||||
if code != 200 || !strings.Contains(body, ": keepalive") || asked != 1+lastRetries {
|
||||
t.Fatalf("fallback %v: %d %q, asked %d times", withFallback, code, body, asked)
|
||||
}
|
||||
if withFallback {
|
||||
if !strings.Contains(body, "from the fallback") || strings.Contains(body, "server_is_overloaded") || fb.n != 1 {
|
||||
t.Fatalf("fallback: %q, asked %d times", body, fb.n)
|
||||
}
|
||||
} else if strings.Count(body, "server_is_overloaded") != 1 || strings.Count(body, "event: response.created") != 1 {
|
||||
// the last try's own failure, once, and none of the others'
|
||||
t.Fatalf("no fallback: %q", body)
|
||||
}
|
||||
noneResting(t)
|
||||
}
|
||||
}
|
||||
@@ -1977,6 +1977,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
}
|
||||
} else {
|
||||
cands, pl = s.plan(p, model, from)
|
||||
if handedOnOf(r) != nil {
|
||||
// Codex's own sign-in, asked as often as it is asked: only
|
||||
// the fallbacks are left (codexFallBack)
|
||||
cands, pl = fallbacksOnly(cands, pl, p.ID, model)
|
||||
}
|
||||
if provider.IsFastPick(agent, p.ID+"/"+model) {
|
||||
// the agent's pick of it is sent in its vendor's fast mode
|
||||
// (#954), as a group's member may be; its fallbacks, other
|
||||
@@ -2278,6 +2283,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
autoReset := resetFirst != nil // a Codex or Claude reset looked at, once a request
|
||||
// what the tries' held streams sent the agent ahead of a reply (#751)
|
||||
kept := &keptAlive{proto: from, told: start}
|
||||
if k := handedOnOf(r); k != nil {
|
||||
// Codex's own sign-in waited for first, with Codex kept alive
|
||||
kept = k
|
||||
}
|
||||
var sentMs int64 // ms from the request to its answering try going to the vendor
|
||||
// of it, magpie's own, the tries that failed first and the wait for a
|
||||
// slot (usage.Record.Own, Retried, Queued: #1532)
|
||||
|
||||
+11
-3
@@ -395,8 +395,11 @@ type settingsJSON struct {
|
||||
// settings, environment, system, off or none
|
||||
ProxyNow string `json:"proxyNow"`
|
||||
ProxySource string `json:"proxySource"`
|
||||
// whether magpie opens at login: the system's record, not a setting
|
||||
Login bool `json:"login"`
|
||||
// whether magpie opens at login: the system's record, not a setting;
|
||||
// LoginAllow, the record is there but the user switched it off in
|
||||
// System Settings › Login Items, which is where it's allowed again
|
||||
Login bool `json:"login"`
|
||||
LoginAllow bool `json:"loginAllow,omitempty"`
|
||||
// the model that describes images when Vision names none, and those
|
||||
// that can be named
|
||||
VisionAuto string `json:"visionAuto,omitempty"`
|
||||
@@ -583,6 +586,10 @@ type searchFailedJSON struct {
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
// loginState is whether magpie opens at login, as the system will act on
|
||||
// it. A var for the tests: the real one asks the user's own system.
|
||||
var loginState = autostart.Enabled
|
||||
|
||||
func settingsState() settingsJSON {
|
||||
s := settingsJSON{Settings: settings.Load(), Version: Version, Dir: tilde(settings.Dir()), Portable: settings.Portable() != "", Gateway: gateway.URL()}
|
||||
s.AddrEnv = os.Getenv("MAGPIE_ADDR")
|
||||
@@ -622,7 +629,8 @@ func settingsState() settingsJSON {
|
||||
s.OTelEnv = true
|
||||
}
|
||||
}
|
||||
s.Login = autostart.Enabled()
|
||||
login := loginState()
|
||||
s.Login, s.LoginAllow = login != autostart.Off, login == autostart.NeedsAllowing
|
||||
if s.LAN {
|
||||
s.LANURLs, s.LANContainer = gateway.LANURLs(), gateway.ContainerAddrs()
|
||||
}
|
||||
|
||||
@@ -3343,6 +3343,8 @@ input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; m
|
||||
.warm-at .warm-rm, .warm-at .warm-add { min-width: 24px; height: 27px; padding: 0 6px; font-size: 14px; line-height: 1; }
|
||||
.row.pref .sub .warn { color: var(--amber); }
|
||||
.row.pref .sub.wraps { white-space: normal; }
|
||||
.row.pref .login-allow-open { font: inherit; color: var(--accent); padding: 0; background: none; border: 0; cursor: pointer; }
|
||||
.row.pref .login-allow-open:hover { text-decoration: underline; }
|
||||
/* the field's clock and picker in the page's own palette */
|
||||
:root[data-theme="dark"] .warm-at input.at { color-scheme: dark; }
|
||||
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .warm-at input.at { color-scheme: dark; } }
|
||||
|
||||
@@ -18794,6 +18794,32 @@ function renderBarIcon() {
|
||||
.catch((e) => { status(t(e.message), "err"); renderBarIcon(); })));
|
||||
}
|
||||
|
||||
// renderLoginAllow: Open at login switched off in System Settings, its
|
||||
// launch agent still there (#2120, Anoninz). On stays picked, as the record
|
||||
// is, and writing it again doesn't undo the user's switch, so the row says
|
||||
// it won't open and opens Login Items, where it is allowed again. Coming
|
||||
// back to the window reads the settings again (load), so the line goes once
|
||||
// it is allowed there.
|
||||
const loginItemsURL = "x-apple.systempreferences:com.apple.LoginItems-Settings.extension";
|
||||
function renderLoginAllow(s) {
|
||||
const who = $("#loginRow .who");
|
||||
let sub = who.querySelector(".login-allow");
|
||||
if (!s.loginAllow) { sub?.remove(); return; }
|
||||
if (!sub) {
|
||||
sub = document.createElement("div");
|
||||
sub.className = "sub wraps login-allow";
|
||||
who.append(sub);
|
||||
}
|
||||
// the row is hidden on a page served to another computer (web), which
|
||||
// has no System Settings to open
|
||||
const open = document.createElement("button");
|
||||
open.type = "button";
|
||||
open.className = "login-allow-open";
|
||||
open.textContent = t("Open Login Items");
|
||||
open.onclick = () => api("open", { url: loginItemsURL }).catch((e) => status(t(e.message), "err"));
|
||||
sub.replaceChildren(t("Switched off in System Settings’ Login Items, so magpie won’t open at login"), " ", open);
|
||||
}
|
||||
|
||||
async function loadSettings() {
|
||||
const since = prefsWrites;
|
||||
if (!web && fontList === null && !fontListError) loadFonts();
|
||||
@@ -19205,6 +19231,7 @@ function renderSettings() {
|
||||
// the system's record, set on its own, not with the other choices
|
||||
$("#loginSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.login ? "on" : "off", (v) =>
|
||||
writingPrefs(api("settings/login", { on: v === "on" })).then((ns) => { prefs = ns; renderSettings(); }).catch((e) => { status(t(e.message), "err"); renderSettings(); })));
|
||||
renderLoginAllow(s);
|
||||
// Codex's and Claude Code's warm-ups and WorkBuddy's check-in, one tab
|
||||
// each over one card, the rows' names not saying the service again.
|
||||
// A ChatGPT account's next window started as soon as the last resets
|
||||
|
||||
@@ -858,6 +858,8 @@ const I18N = {
|
||||
"Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "为输入框猜测你的下一条消息,每次都把整段对话重读一遍;选 Codex 自带时用该会话的模型,经它的 ChatGPT 登录",
|
||||
"Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Codex 的审批设为自动审批时,代你决定是否批准;由 Codex 决定时用 codex-auto-review,没有则用当前对话的模型(低推理)",
|
||||
"Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "在后台把过去的会话整理成 Codex 的记忆;Codex 自带的:整理用 gpt-5.6-terra,总结对话用 gpt-5.6-luna",
|
||||
"Switched off in System Settings’ Login Items, so magpie won’t open at login": "已在系统设置的登录项里关闭,登录时不会打开 magpie",
|
||||
"Open Login Items": "打开登录项",
|
||||
"Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "登录后在菜单栏打开,不弹出窗口。系统设置 › 通用 › 登录项 里,它列在「App后台活动」下,而不是「登录时打开」",
|
||||
"Opens in the tray with no window": "登录后在托盘打开,不弹出窗口",
|
||||
"With window": "跟随窗口",
|
||||
@@ -3510,6 +3512,9 @@ const I18N = {
|
||||
"Unofficial, on GitHub": "非官方插件 · GitHub",
|
||||
"Looking on GitHub": "正在 GitHub 上查找",
|
||||
"Couldn't ask GitHub: {error}": "无法连接 GitHub:{error}",
|
||||
"{n} more on GitHub couldn't be read: {error}": "GitHub 上还有 {n} 个插件没能读取:{error}",
|
||||
"GitHub found {n} repositories, but none of them could be read: {error}": "GitHub 找到了 {n} 个仓库,但一个都没能读取:{error}",
|
||||
"Couldn't ask GitHub, so these are from before: {error}": "无法连接 GitHub,下面是之前获取的列表:{error}",
|
||||
"Kind of plugin": "插件类型",
|
||||
"Installed or not": "是否已安装",
|
||||
"Not installed": "未安装",
|
||||
@@ -4603,6 +4608,8 @@ const I18N = {
|
||||
"Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "為輸入框猜測你的下一則訊息,每次都把整段對話重讀一遍;選 Codex 自帶時用該會話的模型,經它的 ChatGPT 登入",
|
||||
"Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Codex 的審批設為自動審批時,代你決定是否批准;由 Codex 決定時用 codex-auto-review,沒有則用目前對話的模型(低推理)",
|
||||
"Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "在背景把過去的會話整理成 Codex 的記憶;Codex 自帶的:整理用 gpt-5.6-terra,總結對話用 gpt-5.6-luna",
|
||||
"Switched off in System Settings’ Login Items, so magpie won’t open at login": "已在系統設定的登入項目裡關閉,登入時不會開啟 magpie",
|
||||
"Open Login Items": "打開登入項目",
|
||||
"Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "登入後在選單列開啟,不彈出視窗。系統設定 › 一般 › 登入項目 裡,它列在「App背景活動」下,而不是「在登入時打開」",
|
||||
"Opens in the tray with no window": "登入後在系統匣開啟,不彈出視窗",
|
||||
"With window": "跟隨視窗",
|
||||
@@ -7219,6 +7226,9 @@ const I18N = {
|
||||
"Unofficial, on GitHub": "非官方外掛 · GitHub",
|
||||
"Looking on GitHub": "正在 GitHub 上尋找",
|
||||
"Couldn't ask GitHub: {error}": "無法連線 GitHub:{error}",
|
||||
"{n} more on GitHub couldn't be read: {error}": "GitHub 上還有 {n} 個外掛未能讀取:{error}",
|
||||
"GitHub found {n} repositories, but none of them could be read: {error}": "GitHub 找到了 {n} 個儲存庫,但一個都未能讀取:{error}",
|
||||
"Couldn't ask GitHub, so these are from before: {error}": "無法連線 GitHub,以下是先前取得的列表:{error}",
|
||||
"Kind of plugin": "外掛類型",
|
||||
"Installed or not": "是否已安裝",
|
||||
"Not installed": "未安裝",
|
||||
@@ -8320,6 +8330,8 @@ const I18N = {
|
||||
"Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "入力欄に次のメッセージを予測し、そのたびに会話全体を読み直します。Codex 自身ならスレッドのモデルで、その ChatGPT サインインで送られます",
|
||||
"Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Codex の承認が自動レビューのとき、あなたの代わりに承認を判断します。Codex に任せると codex-auto-review、なければ会話のモデル(低い推論)",
|
||||
"Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "過去のスレッドを Codex のメモリにバックグラウンドでまとめます。Codex の初期設定:整理は gpt-5.6-terra、スレッドの要約は gpt-5.6-luna",
|
||||
"Switched off in System Settings’ Login Items, so magpie won’t open at login": "システム設定のログイン項目でオフになっているため、ログイン時に magpie は開きません",
|
||||
"Open Login Items": "ログイン項目を開く",
|
||||
"Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "ログイン後、ウィンドウなしでメニューバーに開きます。システム設定 › 一般 › ログイン項目では「ログイン時に開く」ではなく「アプリのバックグラウンドでのアクティビティ」に表示されます",
|
||||
"Opens in the tray with no window": "ログイン後、ウィンドウなしでトレイに開きます",
|
||||
"With window": "ウィンドウと連動",
|
||||
@@ -10950,6 +10962,9 @@ const I18N = {
|
||||
"Unofficial, on GitHub": "非公式 · GitHub",
|
||||
"Looking on GitHub": "GitHub を検索中",
|
||||
"Couldn't ask GitHub: {error}": "GitHub に接続できませんでした:{error}",
|
||||
"{n} more on GitHub couldn't be read: {error}": "GitHub 上のほか {n} 件を読み込めませんでした:{error}",
|
||||
"GitHub found {n} repositories, but none of them could be read: {error}": "GitHub で {n} 件のリポジトリが見つかりましたが、どれも読み込めませんでした:{error}",
|
||||
"Couldn't ask GitHub, so these are from before: {error}": "GitHub に接続できないため、以前の一覧を表示しています:{error}",
|
||||
"Kind of plugin": "プラグインの種類",
|
||||
"Installed or not": "インストール済みかどうか",
|
||||
"Not installed": "未インストール",
|
||||
@@ -12051,6 +12066,8 @@ const I18N = {
|
||||
"Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "Errät Ihre nächste Nachricht fürs Eingabefeld und liest dafür jedes Mal das ganze Gespräch neu; bei „Eigene von Codex“ mit dem Modell des Threads über seine ChatGPT-Anmeldung",
|
||||
"Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Entscheidet eine Freigabe an Ihrer Stelle, wenn Codex’ Freigaben auf Auto-Review stehen; „Wie Codex es wählt“ ist codex-auto-review, sonst das Modell des Gesprächs mit wenig Reasoning",
|
||||
"Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "Schreibt im Hintergrund Codex’ Erinnerungen an frühere Threads; Codex’ eigenes: gpt-5.6-terra, Threads zusammengefasst mit gpt-5.6-luna",
|
||||
"Switched off in System Settings’ Login Items, so magpie won’t open at login": "In den Systemeinstellungen unter „Anmeldeobjekte“ ausgeschaltet, daher öffnet sich magpie bei der Anmeldung nicht",
|
||||
"Open Login Items": "Anmeldeobjekte öffnen",
|
||||
"Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "Öffnet sich in der Menüleiste, ohne Fenster. Systemeinstellungen › Allgemein › Anmeldeobjekte führt es unter „App-Hintergrundaktivitäten“, nicht unter „Bei der Anmeldung öffnen“",
|
||||
"Opens in the tray with no window": "Öffnet sich im Infobereich, ohne Fenster",
|
||||
"With window": "Mit Fenster",
|
||||
@@ -14694,6 +14711,9 @@ const I18N = {
|
||||
"Unofficial, on GitHub": "Inoffiziell, auf GitHub",
|
||||
"Looking on GitHub": "Suche auf GitHub",
|
||||
"Couldn't ask GitHub: {error}": "GitHub nicht erreichbar: {error}",
|
||||
"{n} more on GitHub couldn't be read: {error}": "{n} weitere auf GitHub konnten nicht gelesen werden: {error}",
|
||||
"GitHub found {n} repositories, but none of them could be read: {error}": "GitHub hat {n} Repositories gefunden, aber keines konnte gelesen werden: {error}",
|
||||
"Couldn't ask GitHub, so these are from before: {error}": "GitHub nicht erreichbar, dies ist die Liste von zuvor: {error}",
|
||||
"Kind of plugin": "Art des Plugins",
|
||||
"Installed or not": "Installiert oder nicht",
|
||||
"Not installed": "Nicht installiert",
|
||||
|
||||
@@ -50,6 +50,10 @@
|
||||
.pm-ghbar .segs { flex: none; max-width: 100%; }
|
||||
.pm-ghfind { width: min(240px, 100%); }
|
||||
.pm-ghnone { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 22px 12px; border-radius: 12px; border: 1px dashed var(--line); font-size: 12px; color: var(--muted); text-align: center; }
|
||||
/* what GitHub couldn't give, over the cards it could: a quiet line, its
|
||||
reason wrapping anywhere (a URL in it is one long word) */
|
||||
.pm-ghwarn { display: flex; align-items: baseline; flex-wrap: wrap; gap: 2px 10px; font-size: 12px; color: var(--muted); }
|
||||
.pm-ghwarn > span, .pm-ghnone > span { overflow-wrap: anywhere; }
|
||||
|
||||
.pm-logo { flex: none; width: 36px; height: 36px; border-radius: 10px; display: grid; place-items: center; background: var(--pill); color: var(--fg-2); }
|
||||
.pm-logo .ic { width: 20px; height: 20px; }
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
let mine = null; // /api/plugins: what's installed
|
||||
let listings = null; // /api/plugins/listings: the plugins suggested
|
||||
let tagged = null; // /api/plugins/github: repositories their authors tagged magpie-plugin, as listings
|
||||
let taggedErr = ""; // why they couldn't be asked for, while none were had
|
||||
let taggedErr = ""; // why the list isn't GitHub's whole answer: it couldn't be asked, or...
|
||||
let taggedMissing = 0; // ...this many repositories it named couldn't be read
|
||||
let topic = "magpie-plugin";
|
||||
const npm = {}; // /api/plugins/npm: package → what npm says of it
|
||||
const heads = {}; // /api/plugins/git: a git plugin's spec → the commit its repository is at
|
||||
@@ -170,14 +171,22 @@
|
||||
summary: r.description ? { en: r.description } : undefined,
|
||||
npm: { version: r.version || "", publisher: r.owner, repository: r.url, license: r.license, weekly: 0 },
|
||||
});
|
||||
async function loadTagged() {
|
||||
// A failed ask is said, with why, whether or not a list was had before:
|
||||
// an empty list was read as there being no unofficial plugins (till on
|
||||
// Discord: GitHub unreachable from their desktop, the section gone).
|
||||
// A list had before stands through a failed ask that brings none.
|
||||
// again: Try again, which has magpie ask GitHub at once.
|
||||
async function loadTagged(again) {
|
||||
try {
|
||||
const r = await api("plugins/github");
|
||||
tagged = (r.repos || []).map(ghListing);
|
||||
taggedErr = "";
|
||||
const r = await api("plugins/github" + (again ? "?again=1" : ""));
|
||||
const got = (r.repos || []).map(ghListing);
|
||||
if (!(r.error && !got.length && tagged?.length)) tagged = got;
|
||||
taggedErr = r.error || "";
|
||||
taggedMissing = r.missing || 0;
|
||||
if (r.topic) topic = r.topic;
|
||||
} catch (e) {
|
||||
if (!tagged) taggedErr = e.message || String(e);
|
||||
taggedErr = e.message || String(e);
|
||||
taggedMissing = 0;
|
||||
tagged = tagged || [];
|
||||
}
|
||||
}
|
||||
@@ -644,6 +653,10 @@
|
||||
replaceKeeping(ghSec, [ghHead, skeleton(3)]);
|
||||
return ghSec;
|
||||
}
|
||||
// why the list isn't GitHub's whole answer; kept: cards are shown
|
||||
const ghWhy = (kept) => taggedMissing
|
||||
? t(kept ? "{n} more on GitHub couldn't be read: {error}" : "GitHub found {n} repositories, but none of them could be read: {error}", { n: taggedMissing, error: taggedErr })
|
||||
: t(kept ? "Couldn't ask GitHub, so these are from before: {error}" : "Couldn't ask GitHub: {error}", { error: taggedErr });
|
||||
// and one GitHub couldn't be asked of says so, with another go
|
||||
function ghFailed() {
|
||||
ghHead.replaceChildren(...ghTitle());
|
||||
@@ -654,13 +667,28 @@
|
||||
again.onclick = () => {
|
||||
tagged = null;
|
||||
taggedErr = "";
|
||||
taggedMissing = 0;
|
||||
drawBody();
|
||||
loadTagged().then(drawBody);
|
||||
loadTagged(true).then(drawBody);
|
||||
};
|
||||
box.append(el("span", "", t("Couldn't ask GitHub: {error}", { error: taggedErr })), again);
|
||||
box.append(el("span", "", ghWhy(false)), again);
|
||||
replaceKeeping(ghSec, [ghHead, box]);
|
||||
return ghSec;
|
||||
}
|
||||
// the cards GitHub could give, and a line saying what it couldn't, with
|
||||
// another go that keeps them until it answers
|
||||
function ghNote() {
|
||||
const note = el("div", "pm-ghwarn");
|
||||
note.setAttribute("role", "status");
|
||||
const again = el("button", "text", t("Try again"));
|
||||
again.type = "button";
|
||||
again.onclick = () => {
|
||||
again.disabled = true;
|
||||
loadTagged(true).then(drawBody);
|
||||
};
|
||||
note.append(el("span", "", ghWhy(true)), again);
|
||||
return note;
|
||||
}
|
||||
function ghSection(list) {
|
||||
ghList = list;
|
||||
ghHead.replaceChildren(...ghTitle());
|
||||
@@ -677,9 +705,10 @@
|
||||
return ghSec;
|
||||
}
|
||||
function drawGh() {
|
||||
const head = taggedErr ? [ghHead, ghNote()] : [ghHead];
|
||||
if ((tagged || []).length <= 6) {
|
||||
ghGrid.replaceChildren(...ghList.map(card));
|
||||
replaceKeeping(ghSec, [ghHead, ghGrid]);
|
||||
replaceKeeping(ghSec, [...head, ghGrid]);
|
||||
return;
|
||||
}
|
||||
// the kinds there are, in the market's order, each with how many the
|
||||
@@ -724,7 +753,7 @@
|
||||
const shown = found.filter((l) => (!ghKind || kindOf(l) === ghKind) && (!ghHave || have(l) === (ghHave === "have")));
|
||||
if (shown.length) {
|
||||
ghGrid.replaceChildren(...shown.map(card));
|
||||
replaceKeeping(ghSec, [ghHead, ghBar, ghGrid]);
|
||||
replaceKeeping(ghSec, [...head, ghBar, ghGrid]);
|
||||
return;
|
||||
}
|
||||
const none = el("div", "pm-ghnone");
|
||||
@@ -732,7 +761,7 @@
|
||||
all.type = "button";
|
||||
all.onclick = () => { ghKind = ""; ghHave = ""; ghQuery = ""; drawGh(); ghQ.focus(); };
|
||||
none.append(el("span", "", t("No plugin on GitHub matches")), all);
|
||||
replaceKeeping(ghSec, [ghHead, ghBar, none]);
|
||||
replaceKeeping(ghSec, [...head, ghBar, none]);
|
||||
}
|
||||
|
||||
// the head and its search field are made once and drawn again in
|
||||
@@ -886,7 +915,7 @@
|
||||
if (pgs.length) out.push(section(t("Pages"), t("pages of their own in magpie's window, each shut off from the rest and reading only what it lists"), pgs));
|
||||
if (gh.length) out.push(ghSection(gh));
|
||||
else if (!tagged) out.push(ghWaiting());
|
||||
else if (taggedErr) out.push(ghFailed());
|
||||
else if (taggedErr && !tagged.length) out.push(ghFailed());
|
||||
out.push(manual());
|
||||
replaceKeeping(body, out);
|
||||
return;
|
||||
@@ -894,6 +923,7 @@
|
||||
if (ls.length) out.push(section(t("Suggested"), "", ls));
|
||||
if (gh.length) out.push(ghSection(gh));
|
||||
else if (!tagged) out.push(ghWaiting());
|
||||
else if (taggedErr && !tagged.length) out.push(ghFailed());
|
||||
const known = new Set([...listings.map((l) => l.package), ...(tagged || []).map((l) => l.github.package).filter(Boolean)]);
|
||||
const box = el("section", "pm-sec");
|
||||
const h = el("div", "pm-sechead");
|
||||
|
||||
@@ -947,8 +947,8 @@ magpie.plugin("library", (ctx) => {
|
||||
if (a.on && !rtk.path) row.append(tag(t("RTK missing"), "warn", t("{agent}'s hook calls rtk, which isn't installed, so its shell commands fail. Install RTK, or switch this off.", { agent: a.name })));
|
||||
// …or one that is, off the PATH the agent gets
|
||||
else if (a.on && rtk.offPath) row.append(tag(t("Not on PATH"), "warn", t("{agent}'s hook runs rtk by name and can't find it, so RTK does nothing for it. Put RTK on PATH above.", { agent: a.name })));
|
||||
// an agent RTK has no hook for (DeepSeek Harness): listed, with why
|
||||
if (a.noHook) row.append(tag(t("No RTK hook"), "warn", t("RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).", { agent: a.name })));
|
||||
// an agent RTK has no hook for (rtkNoHook in rtk.go): listed, with its own why
|
||||
if (a.noHook) row.append(tag(t("No RTK hook"), "warn", rtkNoHookWhy(a)));
|
||||
// RTK before 0.51 installs Antigravity's hook only per project
|
||||
else if (a.blocked && a.id === "agy") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.51 or newer: older ones install it only per project. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name })));
|
||||
else if (a.blocked && a.id !== "opencode") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.50 or newer: older ones only add @RTK.md to AGENTS.md, which rewrites no command. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name })));
|
||||
@@ -965,6 +965,20 @@ magpie.plugin("library", (ctx) => {
|
||||
if (!rows.length) list.append(el("div", "lib-none", t("None of your agents is one RTK has a hook for.")));
|
||||
body.append(list);
|
||||
}
|
||||
// Why RTK has no hook for an agent: each agent's own reason and its own
|
||||
// rtk-ai/rtk issue, never another agent's (新v学员 on Discord: Grok Build's
|
||||
// said DeepSeek Harness's hooks can't rewrite and linked dsh's issue).
|
||||
// Keyed as rtkNoHook in rtk.go; TestRTKNoHookIssuesAreEachAgents holds the
|
||||
// two together. An agent with no entry gets no reason and no link.
|
||||
function rtkNoHookWhy(a) {
|
||||
const agent = a.name;
|
||||
switch (a.id) {
|
||||
case "dsh": return t("RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).", { agent });
|
||||
case "grok": return t("RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).", { agent });
|
||||
case "grok-app": return t("RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).", { agent });
|
||||
default: return t("RTK can't be given to {agent} yet: RTK has no hook for it.", { agent });
|
||||
}
|
||||
}
|
||||
async function setRTK(a, on) {
|
||||
rtkBusy.add(a.id);
|
||||
render();
|
||||
|
||||
@@ -170,6 +170,9 @@ magpie.strings({
|
||||
"OpenCode 2 needs RTK 0.52 or newer: older ones write a plugin for OpenCode 1, which OpenCode 2 refuses to load. Update RTK (brew upgrade rtk, or its installer again), then switch it on.": "OpenCode 2 需要 RTK 0.52 或更高版本:旧版写的是 OpenCode 1 的插件,OpenCode 2 拒绝加载。请先更新 RTK(brew upgrade rtk,或重新运行其安装脚本)再打开。",
|
||||
"No RTK hook": "RTK 暂不支持",
|
||||
"RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).": "暂时无法给 {agent} 接入 RTK:RTK 的做法是在 agent 执行 shell 命令前把命令改写掉,而 {agent} 的 hook 只能放行或拦截命令,不能改写;RTK 的安装程序也还没有它的选项(github.com/rtk-ai/rtk/issues/3847)。",
|
||||
"RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "暂时无法给 {agent} 接入 RTK:RTK 的安装程序还没有 Grok Build 的选项(github.com/rtk-ai/rtk/issues/2136)。",
|
||||
"RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "暂时无法给 {agent} 接入 RTK:{agent} 运行的是 Grok Build,而 RTK 的安装程序还没有 Grok Build 的选项(github.com/rtk-ai/rtk/issues/2136)。",
|
||||
"RTK can't be given to {agent} yet: RTK has no hook for it.": "暂时无法给 {agent} 接入 RTK:RTK 还没有它的 hook。",
|
||||
"Get RTK": "获取 RTK",
|
||||
"restart an agent after switching it": "切换后需重启对应 Agent",
|
||||
"{agent} runs its commands through RTK": "{agent} 的命令经过 RTK",
|
||||
@@ -777,6 +780,9 @@ magpie.strings({
|
||||
"OpenCode 2 needs RTK 0.52 or newer: older ones write a plugin for OpenCode 1, which OpenCode 2 refuses to load. Update RTK (brew upgrade rtk, or its installer again), then switch it on.": "OpenCode 2 需要 RTK 0.52 或更高版本:舊版寫的是 OpenCode 1 的外掛,OpenCode 2 拒絕載入。請先更新 RTK(brew upgrade rtk,或重新執行其安裝指令碼)再開啟。",
|
||||
"No RTK hook": "RTK 暫不支援",
|
||||
"RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).": "暫時無法給 {agent} 接入 RTK:RTK 的做法是在 agent 執行 shell 命令前把命令改寫掉,而 {agent} 的 hook 只能放行或攔截命令,不能改寫;RTK 的安裝程式也還沒有它的選項(github.com/rtk-ai/rtk/issues/3847)。",
|
||||
"RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "暫時無法給 {agent} 接入 RTK:RTK 的安裝程式還沒有 Grok Build 的選項(github.com/rtk-ai/rtk/issues/2136)。",
|
||||
"RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "暫時無法給 {agent} 接入 RTK:{agent} 執行的是 Grok Build,而 RTK 的安裝程式還沒有 Grok Build 的選項(github.com/rtk-ai/rtk/issues/2136)。",
|
||||
"RTK can't be given to {agent} yet: RTK has no hook for it.": "暫時無法給 {agent} 接入 RTK:RTK 還沒有它的 hook。",
|
||||
"Get RTK": "取得 RTK",
|
||||
"restart an agent after switching it": "切換後需重啟對應 Agent",
|
||||
"{agent} runs its commands through RTK": "{agent} 的命令經過 RTK",
|
||||
@@ -1379,6 +1385,9 @@ magpie.strings({
|
||||
"OpenCode 2 needs RTK 0.52 or newer: older ones write a plugin for OpenCode 1, which OpenCode 2 refuses to load. Update RTK (brew upgrade rtk, or its installer again), then switch it on.": "OpenCode 2 には RTK 0.52 以降が必要です。古いバージョンは OpenCode 1 向けのプラグインを書き込み、OpenCode 2 はその読み込みを拒否します。RTK を更新(brew upgrade rtk、またはインストーラを再実行)してからオンにしてください。",
|
||||
"No RTK hook": "RTK 未対応",
|
||||
"RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).": "{agent} にはまだ RTK を使えません。RTK はエージェントが実行しようとするシェルコマンドを書き換えて動きますが、{agent} のフックはコマンドを許可・拒否できるだけで書き換えられません。RTK のインストーラーにもそのためのオプションはありません(github.com/rtk-ai/rtk/issues/3847)。",
|
||||
"RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "{agent} にはまだ RTK を使えません。RTK のインストーラーに Grok Build のオプションがありません(github.com/rtk-ai/rtk/issues/2136)。",
|
||||
"RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "{agent} にはまだ RTK を使えません。{agent} は Grok Build を実行しますが、RTK のインストーラーに Grok Build のオプションがありません(github.com/rtk-ai/rtk/issues/2136)。",
|
||||
"RTK can't be given to {agent} yet: RTK has no hook for it.": "{agent} にはまだ RTK を使えません。RTK にはそのフックがありません。",
|
||||
"Get RTK": "RTK を入手",
|
||||
"restart an agent after switching it": "切り替え後はエージェントを再起動してください",
|
||||
"{agent} runs its commands through RTK": "{agent} のコマンドは RTK を通ります",
|
||||
@@ -1984,6 +1993,9 @@ magpie.strings({
|
||||
"OpenCode 2 needs RTK 0.52 or newer: older ones write a plugin for OpenCode 1, which OpenCode 2 refuses to load. Update RTK (brew upgrade rtk, or its installer again), then switch it on.": "OpenCode 2 benötigt RTK 0.52 oder neuer: Ältere Versionen schreiben eine Erweiterung für OpenCode 1, die OpenCode 2 nicht lädt. Aktualisieren Sie RTK (brew upgrade rtk oder erneut über den Installer) und schalten Sie es dann ein.",
|
||||
"No RTK hook": "Kein RTK-Hook",
|
||||
"RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).": "RTK lässt sich {agent} noch nicht geben: RTK schreibt den Shell-Befehl um, den ein Agent gleich ausführt, und die Hooks von {agent} können einen Befehl nur erlauben oder ablehnen, nicht ändern. Auch der Installer von RTK hat keine Option dafür (github.com/rtk-ai/rtk/issues/3847).",
|
||||
"RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "RTK lässt sich {agent} noch nicht geben: Der Installer von RTK hat keine Option für Grok Build (github.com/rtk-ai/rtk/issues/2136).",
|
||||
"RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "RTK lässt sich {agent} noch nicht geben: {agent} führt Grok Build aus, und der Installer von RTK hat keine Option für Grok Build (github.com/rtk-ai/rtk/issues/2136).",
|
||||
"RTK can't be given to {agent} yet: RTK has no hook for it.": "RTK lässt sich {agent} noch nicht geben: RTK hat keinen Hook dafür.",
|
||||
"Get RTK": "RTK holen",
|
||||
"restart an agent after switching it": "Agenten nach dem Umschalten neu starten",
|
||||
"{agent} runs its commands through RTK": "{agent} führt seine Befehle über RTK aus",
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/autostart"
|
||||
)
|
||||
|
||||
// Open at login switched off in System Settings, its launch agent still
|
||||
// there, reads as needing to be allowed, not as on (#2120, Anoninz): the
|
||||
// row says so and opens Login Items, the one System Settings pane the page
|
||||
// may open.
|
||||
func TestLoginNeedsAllowing(t *testing.T) {
|
||||
sandboxHome(t)
|
||||
prev := loginState
|
||||
t.Cleanup(func() { loginState = prev })
|
||||
for _, c := range []struct {
|
||||
st autostart.State
|
||||
login, allow bool
|
||||
}{{autostart.Off, false, false}, {autostart.On, true, false}, {autostart.NeedsAllowing, true, true}} {
|
||||
loginState = func() autostart.State { return c.st }
|
||||
s := settingsState()
|
||||
if s.Login != c.login || s.LoginAllow != c.allow {
|
||||
t.Errorf("%s: login %v, loginAllow %v; want %v, %v", c.st, s.Login, s.LoginAllow, c.login, c.allow)
|
||||
}
|
||||
b, _ := json.Marshal(s)
|
||||
if got := strings.Contains(string(b), `"loginAllow":true`); got != c.allow {
|
||||
t.Errorf("%s: loginAllow in the JSON is %v: %s", c.st, got, b)
|
||||
}
|
||||
}
|
||||
|
||||
w := &importWindows{}
|
||||
mux := http.NewServeMux()
|
||||
providerRoutes(mux, w)
|
||||
for _, link := range []string{autostart.LoginItemsURL, "x-apple.systempreferences:com.apple.preference.security?Privacy_FilesAndFolders", "x-apple.systempreferences:"} {
|
||||
w.opened = ""
|
||||
body, _ := json.Marshal(map[string]string{"url": link})
|
||||
mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", "/api/open", strings.NewReader(string(body))))
|
||||
if want := link == autostart.LoginItemsURL; (w.opened == link) != want {
|
||||
t.Errorf("%s: opened %q", link, w.opened)
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-2
@@ -3,6 +3,7 @@ package gui
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
@@ -495,9 +496,15 @@ func pluginRoutes(mux *http.ServeMux, w Windows) {
|
||||
// repositories on GitHub tagged magpie-plugin: nobody's list, shown
|
||||
// apart as not reviewed, installed from the repository
|
||||
mux.HandleFunc("GET /api/plugins/github", func(rw http.ResponseWriter, r *http.Request) {
|
||||
// Try again asks GitHub at once when the list standing isn't its
|
||||
// whole answer
|
||||
if r.URL.Query().Get("again") != "" {
|
||||
plugin.TaggedAskAgain()
|
||||
}
|
||||
got, err := plugin.TaggedRepos(r.Context())
|
||||
// each one's own picture as the page can show it, kept here as an
|
||||
// installed plugin's is (a data URI isn't sent on to the page)
|
||||
repos := append([]plugin.Tagged(nil), plugin.TaggedRepos(r.Context())...)
|
||||
repos := append([]plugin.Tagged(nil), got...)
|
||||
said := make([]string, len(repos))
|
||||
for i := range repos {
|
||||
said[i] = repos[i].Icon
|
||||
@@ -505,7 +512,17 @@ func pluginRoutes(mux *http.ServeMux, w Windows) {
|
||||
for i, ic := range provider.RepoIcons(said, 3*time.Second) {
|
||||
repos[i].Icon = ic
|
||||
}
|
||||
writeJSON(rw, map[string]any{"repos": repos, "topic": plugin.Topic})
|
||||
out := map[string]any{"repos": repos, "topic": plugin.Topic}
|
||||
// why the list isn't GitHub's whole answer: the page says so with
|
||||
// Try again, rather than the section reading as there being none
|
||||
if err != nil {
|
||||
out["error"] = err.Error()
|
||||
var m *plugin.TaggedMissing
|
||||
if errors.As(err, &m) {
|
||||
out["error"], out["missing"] = m.Why.Error(), m.Missing
|
||||
}
|
||||
}
|
||||
writeJSON(rw, out)
|
||||
})
|
||||
// the commit each installed git plugin's repository is at now (asked
|
||||
// at most every ten minutes), by spec; one that didn't answer is left
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/autostart"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
@@ -2276,7 +2277,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
mux.HandleFunc("POST /api/open", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ URL string }
|
||||
_ = json.NewDecoder(r.Body).Decode(&in)
|
||||
if strings.HasPrefix(in.URL, "https://") || strings.HasPrefix(in.URL, "http://") || strings.HasPrefix(in.URL, agent.CindyScheme) || strings.HasPrefix(in.URL, agent.LodyScheme) {
|
||||
// and System Settings' Login Items, where Open at login is allowed
|
||||
// again: that one pane, not System Settings' scheme at large
|
||||
if strings.HasPrefix(in.URL, "https://") || strings.HasPrefix(in.URL, "http://") || strings.HasPrefix(in.URL, agent.CindyScheme) || strings.HasPrefix(in.URL, agent.LodyScheme) || in.URL == autostart.LoginItemsURL {
|
||||
// Open again on a sign-in says why it didn't open (#2043)
|
||||
if err := w.OpenURL(in.URL); err != nil {
|
||||
fail(rw, err)
|
||||
|
||||
@@ -2348,8 +2348,9 @@ node --test internal/gui/tests/ledger-protocol.test.cjs
|
||||
|
||||
`library-rtk-nohook.test.cjs` checks that an agent RTK has no hook for
|
||||
(DeepSeek Harness) is listed in Library › RTK with a No RTK hook tag saying
|
||||
why, and that its switch can't be turned on, while Pi's can. English and
|
||||
Chinese, Chromium and WebKit.
|
||||
why, and that its switch can't be turned on, while Pi's can. Grok Build's
|
||||
tag gives its own reason and rtk-ai/rtk#2136, never dsh's #3847. English
|
||||
and Chinese, Chromium and WebKit.
|
||||
|
||||
```sh
|
||||
node --test internal/gui/tests/library-rtk-nohook.test.cjs
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
// --agent dsh), and the RTK tab left it out, as if magpie hadn't seen it.
|
||||
// It is listed now, tagged No RTK hook with why, and its switch can't be
|
||||
// turned on; in English and Chinese. No backend: the API is faked here.
|
||||
// Discord (新v学员): Grok Build's tag said DeepSeek Harness's reason and
|
||||
// linked dsh's rtk-ai/rtk#3847. Each agent's tag says its own reason now:
|
||||
// Grok Build's cites rtk-ai/rtk#2136, the request for Grok Build, and says
|
||||
// nothing about its hooks.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
@@ -15,7 +19,7 @@ const HOME = "/Users/aimer";
|
||||
const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });
|
||||
const lib = () => ({
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [agent("pi", "Pi"), agent("dsh", "DeepSeek Harness")],
|
||||
agents: [agent("pi", "Pi"), agent("dsh", "DeepSeek Harness"), agent("grok", "Grok Build")],
|
||||
instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [],
|
||||
});
|
||||
const rtkView = () => ({
|
||||
@@ -23,6 +27,7 @@ const rtkView = () => ({
|
||||
agents: [
|
||||
{ id: "pi", name: "Pi", icon: "", on: false },
|
||||
{ id: "dsh", name: "DeepSeek Harness", icon: "", on: false, noHook: true, blocked: "RTK has no hook for DeepSeek Harness yet" },
|
||||
{ id: "grok", name: "Grok Build", icon: "", on: false, noHook: true, blocked: "RTK has no hook for Grok Build yet" },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -49,8 +54,8 @@ function server(lang, calls) {
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { tag: "No RTK hook", why: "DeepSeek Harness's hooks can only allow or deny a command, not change it" },
|
||||
zh: { tag: "RTK 暂不支持", why: "DeepSeek Harness 的 hook 只能放行或拦截命令,不能改写" },
|
||||
en: { tag: "No RTK hook", why: "DeepSeek Harness's hooks can only allow or deny a command, not change it", grok: "RTK's installer has no option for Grok Build" },
|
||||
zh: { tag: "RTK 暂不支持", why: "DeepSeek Harness 的 hook 只能放行或拦截命令,不能改写", grok: "RTK 的安装程序还没有 Grok Build 的选项" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
@@ -79,6 +84,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
const tag = row("DeepSeek Harness").locator(".lib-tag");
|
||||
assert.deepEqual(await tag.allTextContents(), [w.tag]);
|
||||
assert((await tag.getAttribute("title")).includes(w.why), await tag.getAttribute("title"));
|
||||
assert((await tag.getAttribute("title")).includes("rtk-ai/rtk/issues/3847"));
|
||||
// Grok Build's tag is its own: its issue, not dsh's, and nothing
|
||||
// said about its hooks
|
||||
const gtag = row("Grok Build").locator(".lib-tag");
|
||||
assert.deepEqual(await gtag.allTextContents(), [w.tag]);
|
||||
const gwhy = await gtag.getAttribute("title");
|
||||
assert(gwhy.includes(w.grok) && gwhy.includes("rtk-ai/rtk/issues/2136"), gwhy);
|
||||
assert(!gwhy.includes("3847") && !gwhy.includes("DeepSeek") && !gwhy.includes("hook"), gwhy);
|
||||
assert.equal(await row("Grok Build").locator(".lib-switch").isDisabled(), true);
|
||||
const sw = row("DeepSeek Harness").locator(".lib-switch");
|
||||
assert.equal(await sw.isDisabled(), true);
|
||||
// Pi has a hook: nothing to say, and it can be switched on
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Anoninz on #2120: magpie's Open at login said On while the Mac's own
|
||||
// switch for it, in System Settings › General › Login Items, was off, so
|
||||
// magpie never opened at login. Settings now says whether the system will
|
||||
// open it: in every language, at 1000px and 440px, in both engines, on a Mac,
|
||||
// with the API faked:
|
||||
// - a record the system holds switched off shows On with one line under it
|
||||
// saying so, and a button that asks magpie to open Login Items (the exact
|
||||
// x-apple.systempreferences URL, through /api/open);
|
||||
// - the window coming back to the front reads the state again: switched
|
||||
// back on there, the line goes;
|
||||
// - a page served to another computer (web) has no System Settings to
|
||||
// open, and no Open at login row at all.
|
||||
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 { watchSettingsReads, settingsDrawn } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const loginItems = "x-apple.systempreferences:com.apple.LoginItems-Settings.extension";
|
||||
const line = {
|
||||
en: "Switched off in System Settings’ Login Items, so magpie won’t open at login",
|
||||
zh: "已在系统设置的登录项里关闭,登录时不会打开 magpie",
|
||||
"zh-TW": "已在系統設定的登入項目裡關閉,登入時不會開啟 magpie",
|
||||
ja: "システム設定のログイン項目でオフになっているため、ログイン時に magpie は開きません",
|
||||
de: "In den Systemeinstellungen unter „Anmeldeobjekte“ ausgeschaltet, daher öffnet sich magpie bei der Anmeldung nicht",
|
||||
};
|
||||
const button = { en: "Open Login Items", zh: "打开登录项", "zh-TW": "打開登入項目", ja: "ログイン項目を開く", de: "Anmeldeobjekte öffnen" };
|
||||
|
||||
function serve(lang, web, st, opened) {
|
||||
const settings = () => ({ lang, theme: "light", searchVendors: [], searchAPIs: [], ...st });
|
||||
return async (r) => {
|
||||
const url = new URL(r.request().url());
|
||||
const json = (data, status = 200) => r.fulfill({ status, json: data });
|
||||
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` });
|
||||
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: settings() });
|
||||
if (url.pathname === "/api/settings") return json(settings());
|
||||
if (url.pathname === "/api/open") {
|
||||
opened.push(JSON.parse(r.request().postData()).url);
|
||||
return json({});
|
||||
}
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
|
||||
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
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 r.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) for (const width of [1000, 440]) for (const web of [false, true]) {
|
||||
test(`${engine} ${lang} ${width}px${web ? " web" : ""}: Open at login says when the Mac's own switch for it is off`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 760 } })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.addInitScript(() => Object.defineProperty(navigator, "platform", { get: () => "MacIntel" }));
|
||||
const st = { login: true, loginAllow: true }, opened = [];
|
||||
await page.route("**/*", serve(lang, web, st, opened));
|
||||
await watchSettingsReads(page);
|
||||
await page.goto("http://magpie.test/?view=settings&tab=general");
|
||||
await settingsDrawn(page);
|
||||
const sub = page.locator("#loginRow .login-allow");
|
||||
if (web) {
|
||||
await page.locator("#loginRow").waitFor({ state: "hidden" });
|
||||
await page.locator("#langPick span").waitFor();
|
||||
assert.equal(await page.locator("#loginRow").isHidden(), true, "a page served to another computer offers Open at login");
|
||||
assert.deepEqual(errors, []);
|
||||
return;
|
||||
}
|
||||
await sub.waitFor();
|
||||
|
||||
const seen = await page.evaluate(() => {
|
||||
const row = document.querySelector("#loginRow"), s = row.querySelector(".login-allow"), r = row.getBoundingClientRect();
|
||||
return {
|
||||
text: s.firstChild.textContent,
|
||||
inside: [...s.getClientRects()].every((x) => x.left >= r.left - 0.5 && x.right <= r.right + 0.5),
|
||||
stripe: parseFloat(getComputedStyle(row).borderLeftWidth) > 1,
|
||||
sideways: document.documentElement.scrollWidth > innerWidth,
|
||||
selects: document.querySelectorAll("#setPage-general select").length,
|
||||
};
|
||||
});
|
||||
assert.equal(seen.text, line[lang]);
|
||||
assert.ok(seen.inside, "the line runs out of its row");
|
||||
assert.equal(seen.stripe, false, "the row has a stripe down its left");
|
||||
assert.equal(seen.sideways, false, "the page scrolls sideways");
|
||||
assert.equal(seen.selects, 0, "no native <select>");
|
||||
|
||||
const open = page.locator("#loginRow .login-allow-open");
|
||||
assert.equal(await open.innerText(), button[lang]);
|
||||
assert.equal(await open.evaluate((b) => b.tagName), "BUTTON");
|
||||
// scrolled to as a reader would, with the wheel, once the page has come
|
||||
// in (it comes in animated: a place read mid-way isn't where it rests)
|
||||
await page.evaluate(() => Promise.all(document.getAnimations().map((a) => a.finished.catch(() => {}))));
|
||||
let b = await open.boundingBox();
|
||||
for (let i = 0; i < 40 && b.y + b.height > page.viewportSize().height; i++) {
|
||||
await page.mouse.move(width / 2, 300);
|
||||
await page.mouse.wheel(0, 200);
|
||||
await page.waitForTimeout(50);
|
||||
b = await open.boundingBox();
|
||||
}
|
||||
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
|
||||
for (let i = 0; i < 50 && !opened.length; i++) await page.waitForTimeout(50);
|
||||
assert.deepEqual(opened, [loginItems]);
|
||||
|
||||
// switched back on in System Settings, then back to magpie: the line goes
|
||||
st.loginAllow = false;
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("focus")));
|
||||
await sub.waitFor({ state: "detached" });
|
||||
assert.equal(await page.locator("#loginRow .sub").filter({ visible: true }).count(), 0, "Open at login says its name alone again");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,12 @@
|
||||
// place, before the field, with its head, a word that it is looking and
|
||||
// cards still to come; let go, its cards come in where those were and the
|
||||
// word goes. A search while it waits shows the same. When the ask fails,
|
||||
// the section says so with Try again, which asks again. English, Chinese,
|
||||
// the section says so with Try again, which asks again. magpie answering
|
||||
// with an error beside the list (GitHub unreachable from the reader's
|
||||
// desktop: till on Discord, where the section just wasn't there) is said
|
||||
// too: with no list, in the section's place with why and Try again, which
|
||||
// has magpie ask GitHub at once (?again=1); with the cards it could give,
|
||||
// a line over them saying how many more couldn't be read, and why. English, Chinese,
|
||||
// Japanese and German, wide and 440px, in Chromium and WebKit; nothing
|
||||
// scrolls on a click. MAGPIE_WAIT_ASSETS names an older assets directory,
|
||||
// to see this fail on the code before it.
|
||||
@@ -28,8 +33,9 @@ const LISTINGS = [
|
||||
];
|
||||
|
||||
// gh: how /api/plugins/github answers each time it is asked, in turn: a
|
||||
// promise held until let go, or "fail"
|
||||
function server(lang, gh) {
|
||||
// promise held until let go, "fail", or { json } as magpie's answer;
|
||||
// urls: each ask's URL
|
||||
function server(lang, gh, urls = []) {
|
||||
let asked = 0;
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
@@ -43,6 +49,8 @@ function server(lang, gh) {
|
||||
if (url.pathname === "/api/plugins/listings") return json({ listings: LISTINGS });
|
||||
if (url.pathname === "/api/plugins/github") {
|
||||
const next = gh[asked++] ?? gh.at(-1);
|
||||
urls.push(url.pathname + url.search);
|
||||
if (next?.json) return json(next.json);
|
||||
if (next === "fail") return route.fulfill({ status: 502, contentType: "text/plain", body: "GitHub didn't answer" });
|
||||
await next;
|
||||
return json({ repos: REPOS, topic: "magpie-plugin" }).catch(() => {});
|
||||
@@ -57,10 +65,10 @@ function server(lang, gh) {
|
||||
}
|
||||
|
||||
const L = {
|
||||
en: { section: "Unofficial, on GitHub", look: "Looking on GitHub", failed: /Couldn't ask GitHub/, again: "Try again" },
|
||||
zh: { section: "非官方插件 · GitHub", look: "正在 GitHub 上查找", failed: /无法连接 GitHub/, again: "重试" },
|
||||
ja: { section: "非公式 · GitHub", look: "GitHub を検索中", failed: /GitHub に接続できませんでした/, again: "再試行" },
|
||||
de: { section: "Inoffiziell, auf GitHub", look: "Suche auf GitHub", failed: /GitHub nicht erreichbar/, again: "Erneut versuchen" },
|
||||
en: { section: "Unofficial, on GitHub", look: "Looking on GitHub", failed: /Couldn't ask GitHub/, again: "Try again", none: /GitHub found 12 repositories, but none of them could be read/, more: /12 more on GitHub couldn't be read/ },
|
||||
zh: { section: "非官方插件 · GitHub", look: "正在 GitHub 上查找", failed: /无法连接 GitHub/, again: "重试", none: /GitHub 找到了 12 个仓库,但一个都没能读取/, more: /GitHub 上还有 12 个插件没能读取/ },
|
||||
ja: { section: "非公式 · GitHub", look: "GitHub を検索中", failed: /GitHub に接続できませんでした/, again: "再試行", none: /GitHub で 12 件のリポジトリが見つかりましたが/, more: /GitHub 上のほか 12 件を読み込めませんでした/ },
|
||||
de: { section: "Inoffiziell, auf GitHub", look: "Suche auf GitHub", failed: /GitHub nicht erreichbar/, again: "Erneut versuchen", none: /GitHub hat 12 Repositories gefunden/, more: /12 weitere auf GitHub konnten nicht gelesen werden/ },
|
||||
};
|
||||
|
||||
const shot = async (loc, name) => {
|
||||
@@ -78,13 +86,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
for (const width of [980, 440]) {
|
||||
await t.test(lang + " " + width, async () => {
|
||||
const w = L[lang];
|
||||
const open = async (gh) => {
|
||||
const open = async (gh, urls) => {
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 860 } });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, gh));
|
||||
await page.route("**/*", server(lang, gh, urls));
|
||||
await page.addInitScript(() => { try { localStorage.setItem("magpie.pluginTab", "discover"); } catch {} });
|
||||
await page.goto("http://magpie.test/?view=plugins");
|
||||
const view = page.locator("#view-plugins");
|
||||
@@ -152,6 +160,72 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await f.sec.locator(".pm-card:not(.ghost)").first().waitFor();
|
||||
assert.equal(await f.sec.locator(".pm-ghnone").count(), 0);
|
||||
assert.deepEqual(f.errors, []);
|
||||
|
||||
// magpie answers, but GitHub couldn't give it the list: said in
|
||||
// the section's place with why, never the section gone
|
||||
const why = 'http://raw.githubusercontent.com/a/b/main/package.json: Get "https://raw.githubusercontent.com/a/b/main/package.json": dial tcp: i/o timeout';
|
||||
const urls = [];
|
||||
const later = held();
|
||||
const e = await open([{ json: { repos: [], topic: "magpie-plugin", error: why, missing: 12 } }, later], urls);
|
||||
t.after(() => e.ctx.close());
|
||||
await e.sec.locator(".pm-ghnone").waitFor();
|
||||
const said = await e.sec.locator(".pm-ghnone").innerText();
|
||||
assert.match(said, w.none);
|
||||
assert.ok(said.includes("i/o timeout"), said);
|
||||
// its reason wraps: nothing spills at this width
|
||||
assert.ok(await e.sec.evaluate((s) => s.scrollWidth <= s.clientWidth + 1), "the reason fits");
|
||||
await shot(e.sec, `unread-${engine}-${lang}-${width}`);
|
||||
// the search field's results say it too
|
||||
const eq = e.view.locator(".pm-head .pm-find input");
|
||||
await eq.fill("claude");
|
||||
await e.sec.locator(".pm-ghnone").waitFor();
|
||||
await eq.fill("");
|
||||
await e.sec.locator(".pm-ghnone").waitFor();
|
||||
// Try again has magpie ask GitHub at once (wheeled into sight
|
||||
// first, clear of the window's footer, as a reader would)
|
||||
const eAgain = e.sec.getByRole("button", { name: w.again });
|
||||
await e.page.mouse.move(width / 2, 300);
|
||||
for (let i = 0; i < 4; i++) await e.page.mouse.wheel(0, 400);
|
||||
await eAgain.click();
|
||||
await e.sec.locator(".pm-ghlook").waitFor();
|
||||
later.go();
|
||||
await e.sec.locator(".pm-card:not(.ghost)").first().waitFor();
|
||||
assert.deepEqual(urls, ["/api/plugins/github", "/api/plugins/github?again=1"]);
|
||||
assert.equal(await e.sec.locator(".pm-ghwarn, .pm-ghnone").count(), 0);
|
||||
assert.deepEqual(e.errors, []);
|
||||
|
||||
// some came, some couldn't be read: the cards, and a line over
|
||||
// them saying so with Try again, which keeps the cards meanwhile
|
||||
const urls2 = [];
|
||||
const later2 = held();
|
||||
const m = await open([{ json: { repos: REPOS, topic: "magpie-plugin", error: why, missing: 12 } }, later2], urls2);
|
||||
t.after(() => m.ctx.close());
|
||||
await m.sec.locator(".pm-ghwarn").waitFor();
|
||||
assert.match(await m.sec.locator(".pm-ghwarn").innerText(), w.more);
|
||||
assert.equal(await m.sec.locator(".pm-card:not(.ghost)").count(), 2);
|
||||
assert.ok(await m.sec.evaluate((s) => s.scrollWidth <= s.clientWidth + 1), "the line fits");
|
||||
await shot(m.sec, `partial-${engine}-${lang}-${width}`);
|
||||
const mAgain = m.sec.locator(".pm-ghwarn").getByRole("button", { name: w.again });
|
||||
await m.page.mouse.move(width / 2, 300);
|
||||
for (let i = 0; i < 4; i++) await m.page.mouse.wheel(0, 400);
|
||||
await mAgain.click();
|
||||
assert.equal(await m.sec.locator(".pm-card:not(.ghost)").count(), 2, "cards kept while asking");
|
||||
later2.go();
|
||||
await m.sec.locator(".pm-ghwarn").waitFor({ state: "detached" });
|
||||
assert.equal(await m.sec.locator(".pm-card:not(.ghost)").count(), 2);
|
||||
assert.deepEqual(urls2, ["/api/plugins/github", "/api/plugins/github?again=1"]);
|
||||
assert.deepEqual(m.errors, []);
|
||||
|
||||
// a failed ask after a list was had: the list stands, and the
|
||||
// line says it is from before
|
||||
const k = await open([{ json: { repos: REPOS, topic: "magpie-plugin" } }, { json: { repos: [], topic: "magpie-plugin", error: "GitHub's search: 403 rate limit" } }]);
|
||||
t.after(() => k.ctx.close());
|
||||
await k.sec.locator(".pm-card:not(.ghost)").first().waitFor();
|
||||
await k.page.evaluate(() => window.loadPlugins());
|
||||
await k.sec.locator(".pm-ghwarn").waitFor();
|
||||
assert.match(await k.sec.locator(".pm-ghwarn").innerText(), /403 rate limit/);
|
||||
assert.equal(await k.sec.locator(".pm-card:not(.ghost)").count(), 2);
|
||||
assert.deepEqual(k.errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,11 +227,13 @@ var rtkSpecs = map[string]rtkSpec{
|
||||
var rtkNoHook = map[string]string{
|
||||
"dsh": "RTK has no hook for DeepSeek Harness yet: RTK works by rewriting the shell command an agent is about to run, and dsh's hooks can only allow or deny a command, not change it; rtk init has no --agent dsh either (github.com/rtk-ai/rtk/issues/3847)",
|
||||
// rtk init's agents are claude, cursor, codex, copilot, gemini,
|
||||
// opencode and the rest of rtkSpecs. There is no grok or grok-app,
|
||||
// so a hook written here would have nowhere to go, for Grok Build no
|
||||
// more than for the App that runs it.
|
||||
"grok": "RTK has no hook for Grok Build yet: rtk init has no Grok agent, so it cannot rewrite the shell commands Grok Build runs",
|
||||
"grok-app": "RTK has no hook for Grok App yet: rtk init has no Grok or Grok App agent, so it cannot rewrite the shell commands Grok App runs",
|
||||
// opencode and the rest of rtkSpecs (src/hooks/init in rtk 1.0.1).
|
||||
// There is no grok or grok-app, so a hook written here would have
|
||||
// nowhere to go, for Grok Build no more than for the App that runs it.
|
||||
// rtk-ai/rtk#2136 asks for Grok Build, and Grok App runs Grok Build,
|
||||
// so the two share it on purpose (sharedRTKIssues in the test).
|
||||
"grok": "RTK has no hook for Grok Build yet: rtk init has no Grok agent, so it cannot rewrite the shell commands Grok Build runs (github.com/rtk-ai/rtk/issues/2136)",
|
||||
"grok-app": "RTK has no hook for Grok App yet: rtk init has no Grok or Grok App agent, so it cannot rewrite the shell commands Grok App runs (github.com/rtk-ai/rtk/issues/2136)",
|
||||
}
|
||||
|
||||
func opencodePlugin(a *agent.Agent) string {
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// sharedRTKIssues are the agents that cite the same rtk-ai/rtk issues on
|
||||
// purpose, each with why. Any other two agents citing the same list is a
|
||||
// reason copied from one agent onto another.
|
||||
var sharedRTKIssues = map[[2]string]string{
|
||||
// Grok App runs Grok Build, and rtk-ai/rtk#2136 asks for Grok Build.
|
||||
{"grok", "grok-app"}: "Grok App runs Grok Build",
|
||||
}
|
||||
|
||||
var rtkIssueRe = regexp.MustCompile(`github\.com/([\w.-]+/[\w.-]+)/issues/(\d+)`)
|
||||
|
||||
func rtkIssues(s string) []string {
|
||||
var out []string
|
||||
for _, m := range rtkIssueRe.FindAllStringSubmatch(s, -1) {
|
||||
out = append(out, m[1]+"#"+m[2])
|
||||
}
|
||||
sort.Strings(out)
|
||||
return slices.Compact(out)
|
||||
}
|
||||
|
||||
// The RTK tab's no-hook tag says each agent's own reason and cites its
|
||||
// own issues (新v学员 on Discord: Grok Build's tag said DeepSeek Harness's
|
||||
// hooks can't rewrite a command and linked dsh's rtk-ai/rtk#3847, since
|
||||
// every agent got dsh's text). The page's reasons (rtkNoHookWhy in
|
||||
// plugins/library/client.js) cover every agent in rtkNoHook and cite the
|
||||
// same issues as rtk.go's, two agents share an issue list only when
|
||||
// sharedRTKIssues says why, and the fallback for an agent with no entry
|
||||
// cites nothing.
|
||||
func TestRTKNoHookIssuesAreEachAgents(t *testing.T) {
|
||||
src, err := os.ReadFile(filepath.Join("..", "gui", "assets", "plugins", "library", "client.js"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := string(src)
|
||||
start := strings.Index(s, "function rtkNoHookWhy(")
|
||||
if start < 0 {
|
||||
t.Fatal("client.js has no rtkNoHookWhy: the no-hook tag isn't per agent")
|
||||
}
|
||||
end := strings.Index(s[start:], "\n }\n")
|
||||
if end < 0 {
|
||||
t.Fatal("rtkNoHookWhy has no end")
|
||||
}
|
||||
body := s[start : start+end]
|
||||
page := map[string]string{}
|
||||
fallback, hasFallback := "", false
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
if m := regexp.MustCompile(`^\s*case "([\w-]+)": return (.*)$`).FindStringSubmatch(line); m != nil {
|
||||
page[m[1]] = m[2]
|
||||
} else if m := regexp.MustCompile(`^\s*default: return (.*)$`).FindStringSubmatch(line); m != nil {
|
||||
fallback, hasFallback = m[1], true
|
||||
}
|
||||
}
|
||||
if !hasFallback {
|
||||
t.Error("rtkNoHookWhy has no default reason")
|
||||
}
|
||||
if got := rtkIssues(fallback); len(got) > 0 {
|
||||
t.Errorf("the reason for an agent with no entry cites %v", got)
|
||||
}
|
||||
|
||||
ids := make([]string, 0, len(rtkNoHook))
|
||||
for id := range rtkNoHook {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
for _, id := range ids {
|
||||
why, ok := page[id]
|
||||
if !ok {
|
||||
t.Errorf("%s is in rtkNoHook but the page has no reason for it", id)
|
||||
continue
|
||||
}
|
||||
if g, p := rtkIssues(rtkNoHook[id]), rtkIssues(why); !slices.Equal(g, p) {
|
||||
t.Errorf("%s cites %v in rtk.go and %v on the page", id, g, p)
|
||||
}
|
||||
}
|
||||
for id := range page {
|
||||
if _, ok := rtkNoHook[id]; !ok {
|
||||
t.Errorf("the page has a reason for %s, which rtkNoHook doesn't list", id)
|
||||
}
|
||||
}
|
||||
|
||||
for _, src := range []map[string]string{rtkNoHook, page} {
|
||||
for i, a := range ids {
|
||||
for _, b := range ids[i+1:] {
|
||||
ia, ib := rtkIssues(src[a]), rtkIssues(src[b])
|
||||
if len(ia) == 0 || !slices.Equal(ia, ib) {
|
||||
continue
|
||||
}
|
||||
if _, ok := sharedRTKIssues[[2]string{a, b}]; !ok {
|
||||
t.Errorf("%s and %s both cite %v: one's reason was copied onto the other", a, b, ia)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// a deliberate share that no longer holds is dropped from the list
|
||||
for pair := range sharedRTKIssues {
|
||||
if ia := rtkIssues(rtkNoHook[pair[0]]); len(ia) == 0 || !slices.Equal(ia, rtkIssues(rtkNoHook[pair[1]])) {
|
||||
t.Errorf("sharedRTKIssues lists %v, which don't share an issue list", pair)
|
||||
}
|
||||
}
|
||||
}
|
||||
+95
-28
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
@@ -78,6 +79,10 @@ var (
|
||||
taggedMu sync.Mutex
|
||||
taggedL []Tagged
|
||||
taggedAt time.Time
|
||||
// taggedWhy is why taggedL isn't GitHub's whole answer: the search
|
||||
// failed (taggedL is what it said before), or repositories it named
|
||||
// couldn't be read. nil when it is.
|
||||
taggedWhy error
|
||||
// owner/repo@pushed → what its package.json and npm made of it, nil
|
||||
// when it was left out
|
||||
readMu sync.Mutex
|
||||
@@ -96,6 +101,20 @@ func taggedOnDisk() []Tagged {
|
||||
return l
|
||||
}
|
||||
|
||||
// TaggedMissing is the error TaggedRepos gives when GitHub's search
|
||||
// answered but repositories it named couldn't be read: Missing of them
|
||||
// aren't in the list, for Why.
|
||||
type TaggedMissing struct {
|
||||
Missing int
|
||||
Why error
|
||||
}
|
||||
|
||||
func (e *TaggedMissing) Error() string {
|
||||
return fmt.Sprintf("%d repositories tagged %s couldn't be read from GitHub: %v", e.Missing, Topic, e.Why)
|
||||
}
|
||||
|
||||
func (e *TaggedMissing) Unwrap() error { return e.Why }
|
||||
|
||||
// TaggedRepos are the repositories tagged with Topic, the most starred
|
||||
// first: GitHub asked at most every ten minutes (its search lets 10 a minute
|
||||
// through without a token), else what it said last, kept on disk. Archived
|
||||
@@ -104,22 +123,29 @@ func taggedOnDisk() []Tagged {
|
||||
// couldn't install either. A repository whose package.json didn't come in
|
||||
// time is as the list had it last, and the list is asked again in
|
||||
// taggedRetry. MAGPIE_PLUGIN_MARKET=off keeps to none.
|
||||
func TaggedRepos(ctx context.Context) []Tagged {
|
||||
//
|
||||
// The error says the list isn't GitHub's whole answer, and why: the search
|
||||
// failed (the list is what GitHub said before, empty when it never
|
||||
// answered), or, a *TaggedMissing, repositories it named couldn't be read.
|
||||
// An empty list is never a failed read passed off as there being none
|
||||
// (till on Discord: GitHub unreachable from their desktop, and the
|
||||
// section just wasn't there).
|
||||
func TaggedRepos(ctx context.Context) ([]Tagged, error) {
|
||||
taggedMu.Lock()
|
||||
defer taggedMu.Unlock()
|
||||
if taggedL != nil && time.Since(taggedAt) < taggedTTL {
|
||||
return taggedL
|
||||
return taggedL, taggedWhy
|
||||
}
|
||||
if os.Getenv("MAGPIE_PLUGIN_MARKET") == "off" {
|
||||
return []Tagged{}
|
||||
return []Tagged{}, nil
|
||||
}
|
||||
// a magpie started again within the ten minutes: what GitHub said then,
|
||||
// without the wait of asking (a package.json read for each)
|
||||
if taggedL == nil {
|
||||
if fi, err := os.Stat(taggedCache()); err == nil && time.Since(fi.ModTime()) < taggedTTL {
|
||||
if l := taggedOnDisk(); l != nil {
|
||||
taggedL, taggedAt = l, fi.ModTime()
|
||||
return l
|
||||
taggedL, taggedAt, taggedWhy = l, fi.ModTime(), nil
|
||||
return l, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,33 +153,49 @@ func TaggedRepos(ctx context.Context) []Tagged {
|
||||
if last == nil {
|
||||
last = taggedOnDisk()
|
||||
}
|
||||
if l, whole, err := askTagged(ctx, last); err == nil {
|
||||
taggedL, taggedAt = l, time.Now()
|
||||
if l, whole, missing, err := askTagged(ctx, last); err == nil {
|
||||
taggedL, taggedAt, taggedWhy = l, time.Now(), nil
|
||||
if !whole {
|
||||
taggedAt = time.Now().Add(-taggedTTL + taggedRetry)
|
||||
}
|
||||
if missing != nil {
|
||||
taggedWhy = missing
|
||||
}
|
||||
if b, err := json.Marshal(l); err == nil {
|
||||
_ = os.MkdirAll(filepath.Dir(taggedCache()), 0o755)
|
||||
_ = os.WriteFile(taggedCache(), b, 0o644)
|
||||
// a magpie started again meanwhile asks again too
|
||||
_ = os.Chtimes(taggedCache(), taggedAt, taggedAt)
|
||||
}
|
||||
return l
|
||||
return l, taggedWhy
|
||||
} else {
|
||||
// GitHub didn't answer: what it said last, asked again in a
|
||||
// minute, and why it is that
|
||||
l := last
|
||||
if l == nil {
|
||||
l = []Tagged{}
|
||||
}
|
||||
taggedL, taggedAt, taggedWhy = l, time.Now().Add(-taggedTTL+time.Minute), err
|
||||
return l, err
|
||||
}
|
||||
// GitHub didn't answer: what it said last, asked again in a minute
|
||||
l := last
|
||||
if l == nil {
|
||||
l = []Tagged{}
|
||||
}
|
||||
|
||||
// TaggedAskAgain has the next TaggedRepos ask GitHub at once, when what
|
||||
// stands now isn't its whole answer: the Plugins page's Try again. A list
|
||||
// GitHub gave whole stands its ten minutes all the same.
|
||||
func TaggedAskAgain() {
|
||||
taggedMu.Lock()
|
||||
defer taggedMu.Unlock()
|
||||
if taggedWhy != nil {
|
||||
taggedAt = time.Time{}
|
||||
}
|
||||
taggedL, taggedAt = l, time.Now().Add(-taggedTTL+time.Minute)
|
||||
return l
|
||||
}
|
||||
|
||||
// askTagged asks GitHub's search, and reads each repository it names
|
||||
// that wasn't read at its last push. whole is false when a repository was
|
||||
// left out for want of an answer in taggedWait: it is then as last had
|
||||
// it, if it had it.
|
||||
func askTagged(ctx context.Context, last []Tagged) (l []Tagged, whole bool, err error) {
|
||||
// it, if it had it, and missing counts those last didn't have.
|
||||
func askTagged(ctx context.Context, last []Tagged) (l []Tagged, whole bool, missing *TaggedMissing, err error) {
|
||||
c, cancel := context.WithTimeout(ctx, taggedWait)
|
||||
defer cancel()
|
||||
type item struct {
|
||||
@@ -182,14 +224,14 @@ func askTagged(ctx context.Context, last []Tagged) (l []Tagged, whole bool, err
|
||||
"per_page": {strconv.Itoa(taggedPage)}, "page": {strconv.Itoa(page)}}
|
||||
b, err := fetchJSON(c, githubAPI+"/search/repositories?"+v.Encode(), 4<<20)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
return nil, false, nil, err
|
||||
}
|
||||
var p struct {
|
||||
Total int `json:"total_count"`
|
||||
Items []item `json:"items"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &p); err != nil {
|
||||
return nil, false, err
|
||||
return nil, false, nil, err
|
||||
}
|
||||
for _, it := range p.Items {
|
||||
// a repository starred between two pages can show on both
|
||||
@@ -211,8 +253,9 @@ func askTagged(ctx context.Context, last []Tagged) (l []Tagged, whole bool, err
|
||||
r.URL, r.Owner, r.OwnerAvatar, r.Description, r.Stars, r.License, r.Pushed = t.URL, t.Owner, t.OwnerAvatar, t.Description, t.Stars, t.License, t.Pushed
|
||||
return r
|
||||
}
|
||||
var mu sync.Mutex // out, keep, done; late once the page stops waiting
|
||||
var mu sync.Mutex // out, keep, done, why; late once the page stops waiting
|
||||
late := false
|
||||
var why error // a read GitHub or npm didn't answer, the last one
|
||||
out := make([]Tagged, len(r.Items))
|
||||
keep := make([]bool, len(r.Items))
|
||||
done := make([]bool, len(r.Items))
|
||||
@@ -255,7 +298,7 @@ func askTagged(ctx context.Context, last []Tagged) (l []Tagged, whole bool, err
|
||||
defer func() { <-sem }()
|
||||
pc, cancel := context.WithTimeout(bg, taggedEach)
|
||||
defer cancel()
|
||||
got, ok, read := readTagged(pc, t, branch)
|
||||
got, ok, read, rerr := readTagged(pc, t, branch)
|
||||
if read {
|
||||
readMu.Lock()
|
||||
if ok {
|
||||
@@ -270,6 +313,9 @@ func askTagged(ctx context.Context, last []Tagged) (l []Tagged, whole bool, err
|
||||
out[i], keep[i] = got, ok
|
||||
// a package.json GitHub didn't answer for: not known
|
||||
done[i] = ok || read
|
||||
if !done[i] && rerr != nil {
|
||||
why = rerr
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
}(i, t, it.DefaultBranch)
|
||||
@@ -292,6 +338,7 @@ func askTagged(ctx context.Context, last []Tagged) (l []Tagged, whole bool, err
|
||||
}
|
||||
readMu.Unlock()
|
||||
l, whole = []Tagged{}, true
|
||||
gone := 0
|
||||
for i := range out {
|
||||
switch {
|
||||
case keep[i]:
|
||||
@@ -300,23 +347,37 @@ func askTagged(ctx context.Context, last []Tagged) (l []Tagged, whole bool, err
|
||||
whole = false
|
||||
if was, ok := before[strings.ToLower(asked[i].Repo)]; ok {
|
||||
l = append(l, fresh(was, asked[i]))
|
||||
} else {
|
||||
gone++
|
||||
}
|
||||
}
|
||||
}
|
||||
return l, whole, nil
|
||||
if gone > 0 {
|
||||
mu.Lock()
|
||||
w := why
|
||||
mu.Unlock()
|
||||
if w == nil {
|
||||
w = fmt.Errorf("no answer in %s", taggedWait)
|
||||
}
|
||||
missing = &TaggedMissing{Missing: gone, Why: w}
|
||||
}
|
||||
return l, whole, missing, nil
|
||||
}
|
||||
|
||||
// readTagged reads a tagged repository's package.json (on branch), and
|
||||
// npm's copy of the package it names: t as it is installed, whether it is
|
||||
// kept, and whether that is known (GitHub or npm not answering is not,
|
||||
// and it is read again next time).
|
||||
func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool) {
|
||||
// and it is read again next time), with the read that didn't answer.
|
||||
func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool, error) {
|
||||
if branch == "" {
|
||||
branch = "HEAD"
|
||||
}
|
||||
pb, err := fetchJSON(pc, githubRaw+"/"+t.Repo+"/"+url.PathEscape(branch)+"/package.json", 2<<20)
|
||||
if err != nil {
|
||||
return t, false, errors.Is(err, errNotFound)
|
||||
if errors.Is(err, errNotFound) {
|
||||
return t, false, true, nil
|
||||
}
|
||||
return t, false, false, err
|
||||
}
|
||||
var pj struct {
|
||||
Name string `json:"name"`
|
||||
@@ -333,7 +394,7 @@ func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool
|
||||
} `json:"magpie"`
|
||||
}
|
||||
if json.Unmarshal(pb, &pj) != nil || !pkgName.MatchString(pj.Name) {
|
||||
return t, false, true
|
||||
return t, false, true, nil
|
||||
}
|
||||
t.Package, t.Version = pj.Name, pj.Version
|
||||
// a picture, as host.js's iconOf takes one: magpie checks and
|
||||
@@ -354,6 +415,10 @@ func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool
|
||||
// built only to publish), so it is installed from npm
|
||||
b, err := fetchJSON(pc, npmRegistry+"/"+npmPath(pj.Name)+"/latest", 1<<20)
|
||||
known := err == nil || errors.Is(err, errNotFound)
|
||||
var unknown error
|
||||
if !known {
|
||||
unknown = err
|
||||
}
|
||||
// npmNames is whether npm's copy names what it loads (main,
|
||||
// exports); one that names nothing loads an index file
|
||||
npmNames := false
|
||||
@@ -387,12 +452,14 @@ func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool
|
||||
if path.Ext(entry) != "" {
|
||||
_, err := fetchJSON(pc, githubRaw+"/"+t.Repo+"/"+url.PathEscape(branch)+"/"+strings.TrimPrefix(path.Clean("/"+entry), "/"), 1)
|
||||
if errors.Is(err, errNotFound) {
|
||||
return t, false, known
|
||||
return t, false, known, unknown
|
||||
}
|
||||
if err != nil {
|
||||
known, unknown = false, err
|
||||
}
|
||||
known = known && err == nil
|
||||
}
|
||||
}
|
||||
return t, true, known
|
||||
return t, true, known, unknown
|
||||
}
|
||||
|
||||
// pkgEntry is the file importing a package loads, as Bun resolves it: its
|
||||
|
||||
@@ -3,6 +3,7 @@ package plugin
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
@@ -142,6 +143,11 @@ func fakeGitHub(t *testing.T, up *atomic.Bool, asked *atomic.Int32) {
|
||||
// Every page of the search is read: with a page short of what is tagged,
|
||||
// the list is the same as from one page, in GitHub's order (HoGee_xxl on X:
|
||||
// 59 tagged, and the 9 past GitHub's first page of 50 never showed).
|
||||
func taggedList(ctx context.Context) []Tagged {
|
||||
l, _ := TaggedRepos(ctx)
|
||||
return l
|
||||
}
|
||||
|
||||
func TestTaggedReposEveryPage(t *testing.T) {
|
||||
var up atomic.Bool
|
||||
var asked atomic.Int32
|
||||
@@ -152,7 +158,7 @@ func TestTaggedReposEveryPage(t *testing.T) {
|
||||
t.Cleanup(func() { taggedPage = was })
|
||||
|
||||
var repos []string
|
||||
for _, x := range TaggedRepos(context.Background()) {
|
||||
for _, x := range taggedList(context.Background()) {
|
||||
repos = append(repos, x.Repo)
|
||||
}
|
||||
want := "rynfar/meridian griffinmartin/opencode-claude-auth slkiser/opencode-quota someone/word-guard someone/agent-aider someone/page-glance someone/flaky-entry"
|
||||
@@ -172,7 +178,7 @@ func TestTaggedRepos(t *testing.T) {
|
||||
fakeGitHub(t, &up, &asked)
|
||||
ctx := context.Background()
|
||||
|
||||
l := TaggedRepos(ctx)
|
||||
l := taggedList(ctx)
|
||||
var repos []string
|
||||
for _, x := range l {
|
||||
repos = append(repos, x.Repo)
|
||||
@@ -231,7 +237,7 @@ func TestTaggedRepos(t *testing.T) {
|
||||
t.Fatalf("%s isn't a spec Add installs from git", x.Spec)
|
||||
}
|
||||
|
||||
TaggedRepos(ctx)
|
||||
taggedList(ctx)
|
||||
if n := asked.Load(); n != 1 {
|
||||
t.Fatalf("asked %d times in ten minutes", n)
|
||||
}
|
||||
@@ -243,7 +249,7 @@ func TestTaggedRepos(t *testing.T) {
|
||||
taggedAt = time.Now().Add(-taggedTTL - time.Second)
|
||||
taggedMu.Unlock()
|
||||
before := reads.Load()
|
||||
if l := TaggedRepos(ctx); len(l) != 7 || asked.Load() != 2 {
|
||||
if l := taggedList(ctx); len(l) != 7 || asked.Load() != 2 {
|
||||
t.Fatalf("ten minutes on: asked %d times, %d repos", asked.Load(), len(l))
|
||||
}
|
||||
if n := reads.Load() - before; n != 3 {
|
||||
@@ -258,7 +264,7 @@ func TestTaggedRepos(t *testing.T) {
|
||||
if err := os.Chtimes(taggedCache(), time.Now(), time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if l := TaggedRepos(ctx); len(l) != 7 || asked.Load() != 1 {
|
||||
if l := taggedList(ctx); len(l) != 7 || asked.Load() != 1 {
|
||||
t.Fatalf("restarted: asked %d times, %d repos", asked.Load(), len(l))
|
||||
}
|
||||
|
||||
@@ -269,17 +275,36 @@ func TestTaggedRepos(t *testing.T) {
|
||||
}
|
||||
up.Store(false)
|
||||
forget()
|
||||
if l := TaggedRepos(ctx); len(l) != 7 || l[1].Package != "opencode-claude-auth" || asked.Load() != 1 {
|
||||
t.Fatalf("down: %+v", l)
|
||||
// what GitHub said before, and that it couldn't be asked now
|
||||
if l, err := TaggedRepos(ctx); len(l) != 7 || l[1].Package != "opencode-claude-auth" || asked.Load() != 1 || err == nil || !strings.Contains(err.Error(), "503") {
|
||||
t.Fatalf("down: %v %+v", err, l)
|
||||
}
|
||||
// the minute it is held, still said
|
||||
if _, err := TaggedRepos(ctx); err == nil {
|
||||
t.Fatal("down, held: no error")
|
||||
}
|
||||
|
||||
// nothing ever kept, GitHub down: none, not an error
|
||||
// nothing ever kept, GitHub down: none, and an error, never none
|
||||
// passed off as GitHub's answer (till on Discord: the section just
|
||||
// wasn't there)
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
taggedMu.Lock()
|
||||
taggedL = nil
|
||||
taggedMu.Unlock()
|
||||
if l := TaggedRepos(ctx); l == nil || len(l) != 0 {
|
||||
t.Fatalf("down, nothing kept: %#v", l)
|
||||
if l, err := TaggedRepos(ctx); l == nil || len(l) != 0 || err == nil {
|
||||
t.Fatalf("down, nothing kept: %v %#v", err, l)
|
||||
}
|
||||
// Try again asks GitHub at once, up again: its answer, no error
|
||||
up.Store(true)
|
||||
TaggedAskAgain()
|
||||
if l, err := TaggedRepos(ctx); len(l) != 7 || err != nil {
|
||||
t.Fatalf("again: %v, %d repos", err, len(l))
|
||||
}
|
||||
// a whole answer stands its ten minutes: Try again doesn't ask
|
||||
before = asked.Load()
|
||||
TaggedAskAgain()
|
||||
if _, err := TaggedRepos(ctx); err != nil || asked.Load() != before {
|
||||
t.Fatalf("again on a whole answer: %v, asked %d", err, asked.Load()-before)
|
||||
}
|
||||
|
||||
// off: GitHub never asked
|
||||
@@ -289,7 +314,7 @@ func TestTaggedRepos(t *testing.T) {
|
||||
taggedL = nil
|
||||
taggedMu.Unlock()
|
||||
before = asked.Load()
|
||||
if l := TaggedRepos(ctx); len(l) != 0 || asked.Load() != before {
|
||||
if l := taggedList(ctx); len(l) != 0 || asked.Load() != before {
|
||||
t.Fatalf("off: %+v", l)
|
||||
}
|
||||
}
|
||||
@@ -304,7 +329,7 @@ func TestTaggedReposSlowRead(t *testing.T) {
|
||||
up.Store(true)
|
||||
fakeGitHub(t, &up, &asked)
|
||||
ctx := context.Background()
|
||||
if l := TaggedRepos(ctx); len(l) != 7 {
|
||||
if l := taggedList(ctx); len(l) != 7 {
|
||||
t.Fatalf("%d repos", len(l))
|
||||
}
|
||||
|
||||
@@ -336,7 +361,7 @@ func TestTaggedReposSlowRead(t *testing.T) {
|
||||
return nil
|
||||
}
|
||||
cutAsked := time.Now()
|
||||
l := TaggedRepos(ctx)
|
||||
l := taggedList(ctx)
|
||||
cutDone := time.Now()
|
||||
if x := has(l, "someone/word-guard"); len(l) != 7 || x == nil || x.Kind != "middleware" {
|
||||
t.Fatalf("slow package.json: %d repos, word-guard %+v", len(l), x)
|
||||
@@ -388,13 +413,13 @@ func TestTaggedReposSlowRead(t *testing.T) {
|
||||
taggedMu.Lock()
|
||||
taggedAt = time.Now().Add(-taggedTTL + taggedRetry)
|
||||
taggedMu.Unlock()
|
||||
TaggedRepos(ctx)
|
||||
taggedList(ctx)
|
||||
if n := asked.Load(); n != 2 {
|
||||
t.Fatalf("asked again at once: %d", n)
|
||||
}
|
||||
time.Sleep(taggedRetry + 100*time.Millisecond)
|
||||
before := reads.Load()
|
||||
l = TaggedRepos(ctx)
|
||||
l = taggedList(ctx)
|
||||
if n := asked.Load(); n != 3 {
|
||||
t.Fatalf("a list cut short kept: asked %d times", n)
|
||||
}
|
||||
@@ -454,3 +479,44 @@ func TestPkgEntry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GitHub's search answers but raw.githubusercontent.com doesn't (blocked
|
||||
// on the reader's line, as it is in places where api.github.com isn't),
|
||||
// and nothing was kept: the list is empty, and the error says how many
|
||||
// couldn't be read and why, not that none are tagged (till on Discord:
|
||||
// on their desktop the section wasn't there, on their server it had many).
|
||||
// One read before is kept and isn't counted.
|
||||
func TestTaggedReposUnreadable(t *testing.T) {
|
||||
var up atomic.Bool
|
||||
var asked atomic.Int32
|
||||
up.Store(true)
|
||||
fakeGitHub(t, &up, &asked)
|
||||
ctx := context.Background()
|
||||
rawWas := githubRaw
|
||||
githubRaw = "http://127.0.0.1:1/raw" // nothing listens: refused at once
|
||||
t.Cleanup(func() { githubRaw = rawWas })
|
||||
l, err := TaggedRepos(ctx)
|
||||
var m *TaggedMissing
|
||||
if len(l) != 0 || !errors.As(err, &m) || m.Missing != 12 || !strings.Contains(m.Why.Error(), "127.0.0.1:1") {
|
||||
t.Fatalf("raw unreachable: %v (%+v), %d repos", err, m, len(l))
|
||||
}
|
||||
// Try again, raw back: the list, no error
|
||||
githubRaw = rawWas
|
||||
TaggedAskAgain()
|
||||
if l, err := TaggedRepos(ctx); len(l) != 7 || err != nil {
|
||||
t.Fatalf("again: %v, %d repos", err, len(l))
|
||||
}
|
||||
// asked again, raw gone again: the seven read before are as they were,
|
||||
// and only what was never read counts as missing
|
||||
taggedMu.Lock()
|
||||
taggedAt = time.Time{}
|
||||
taggedMu.Unlock()
|
||||
readMu.Lock()
|
||||
clear(readRepo)
|
||||
readMu.Unlock()
|
||||
githubRaw = "http://127.0.0.1:1/raw"
|
||||
l, err = TaggedRepos(ctx)
|
||||
if len(l) != 7 || !errors.As(err, &m) || m.Missing != 5 {
|
||||
t.Fatalf("raw gone, seven kept: %v (%+v), %d repos", err, m, len(l))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +72,24 @@ func antigravityNameEffort(name string) (string, string) {
|
||||
return strings.TrimSpace(name[:open]), level
|
||||
}
|
||||
|
||||
// antigravityNameSpells is whether a name, without the level in brackets,
|
||||
// is the id's family written out: "Gemini 3.5 Flash Lite" spells
|
||||
// gemini-3.5-flash-lite, "Gemini 3.7 Flash (Low)" gemini-3.7-flash-low;
|
||||
// "Gemini 3.5 Flash Lite" doesn't spell gemini-2.5-flash.
|
||||
func antigravityNameSpells(name, id string) bool {
|
||||
n, _ := antigravityNameEffort(name)
|
||||
n = strings.Join(strings.Fields(n), "-")
|
||||
return n != "" && strings.EqualFold(n, EffortFamily(id))
|
||||
}
|
||||
|
||||
// antigravityEnumNames is whether Antigravity's enum for a model names that
|
||||
// id itself (MODEL_GOOGLE_GEMINI_2_5_FLASH is gemini-2.5-flash); the
|
||||
// models it names for themselves have placeholders (MODEL_PLACEHOLDER_M198).
|
||||
func antigravityEnumNames(enum, id string) bool {
|
||||
e, ok := strings.CutPrefix(enum, "MODEL_GOOGLE_")
|
||||
return ok && e != "" && strings.EqualFold(e, strings.NewReplacer("-", "_", ".", "_").Replace(id))
|
||||
}
|
||||
|
||||
// antigravityFamily is one family of Antigravity's ids.
|
||||
type antigravityFamily struct {
|
||||
id string
|
||||
|
||||
+22
-14
@@ -927,7 +927,7 @@ func (g googleAccount) modelInfo(ctx context.Context) ([]googleModelInfo, error)
|
||||
var res struct {
|
||||
Models map[string]struct {
|
||||
DisplayName string `json:"displayName"`
|
||||
TagDescription string `json:"tagDescription"`
|
||||
Model string `json:"model"` // its enum: MODEL_GOOGLE_GEMINI_2_5_FLASH, MODEL_PLACEHOLDER_M198
|
||||
Disabled bool `json:"disabled"`
|
||||
MaxTokens int `json:"maxTokens"`
|
||||
MaxOutputTokens int `json:"maxOutputTokens"`
|
||||
@@ -1001,25 +1001,33 @@ func (g googleAccount) modelInfo(ctx context.Context) ([]googleModelInfo, error)
|
||||
out = append(out, mi)
|
||||
}
|
||||
// Antigravity lists a model it moved its users off under the name
|
||||
// of the one it moved them to, and tags it with that one's id:
|
||||
// gemini-2.5-flash and gemini-2.5-flash-lite came as "Gemini 3.5
|
||||
// Flash Lite", tagged gemini-3.5-flash-lite, beside
|
||||
// gemini-3.5-flash-lite itself, while each id is still answered by
|
||||
// its own model (modelVersion gemini-2.5-flash), so the editor
|
||||
// of the one it moved them to: gemini-2.5-flash and
|
||||
// gemini-2.5-flash-lite come as "Gemini 3.5 Flash Lite", beside
|
||||
// gemini-3.5-flash-lite itself, while each id is still answered
|
||||
// by its own model (modelVersion gemini-2.5-flash), so the editor
|
||||
// had three chips of one name and the first two weren't it
|
||||
// (#1918, kchen0x). Such a model is named for its own id; a
|
||||
// level of the model its tag names (gemini-3.7-flash-low) keeps
|
||||
// the name it was given.
|
||||
owners := map[string]int{}
|
||||
// (#1918, kchen0x). b68377dae told them by tagDescription, which
|
||||
// then named the model moved to; Google has since left it empty
|
||||
// or made it a notice ("GPT-OSS will be removed…"), and the chips
|
||||
// came back (新v学员 on Discord, 10-20). Such a model is named for
|
||||
// its own id when its enum names that id (MODEL_GOOGLE_GEMINI_2_5_
|
||||
// FLASH, where the models Antigravity names truly are
|
||||
// MODEL_PLACEHOLDER_M…), or when another family's model of that
|
||||
// name is the one its name spells. Levels of one model
|
||||
// (gemini-3.7-flash, -low) keep the name they share.
|
||||
spelled := map[string]bool{}
|
||||
for _, mi := range out {
|
||||
owners[mi.Name]++
|
||||
if antigravityNameSpells(mi.Name, mi.ID) {
|
||||
spelled[mi.Name] = true
|
||||
}
|
||||
}
|
||||
for i, mi := range out {
|
||||
tag := res.Models[mi.ID].TagDescription
|
||||
if mi.Name == "" || owners[mi.Name] < 2 || tag == "" || EffortFamily(tag) == EffortFamily(mi.ID) {
|
||||
if mi.Name == "" || antigravityNameSpells(mi.Name, mi.ID) {
|
||||
continue
|
||||
}
|
||||
out[i].Name = catalog.NameOf(mi.ID) // "" is named later, by its id at the least
|
||||
if spelled[mi.Name] || antigravityEnumNames(res.Models[mi.ID].Model, mi.ID) {
|
||||
out[i].Name = catalog.NameOf(mi.ID) // "" is named later, by its id at the least
|
||||
}
|
||||
}
|
||||
rank := map[string]int{}
|
||||
for _, s := range res.AgentModelSorts {
|
||||
|
||||
@@ -732,3 +732,92 @@ func TestAntigravityRetiredModelNamedForItself(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Antigravity's list as it came on 2026-10-20 (testdata, fetchAvailableModels
|
||||
// on a free-tier account, MIME types and experiments left out): the
|
||||
// retired gemini-2.5-flash and gemini-2.5-flash-lite are still "Gemini 3.5
|
||||
// Flash Lite", but with no tagDescription, so naming them by their tag
|
||||
// left two chips of that name in 新v学员's editor (Discord, 10-20). Each
|
||||
// is named for its own id with gemini-3.5-flash-lite in the list, and
|
||||
// without it (an account Antigravity doesn't give it), where only their
|
||||
// enums, MODEL_GOOGLE_GEMINI_2_5_FLASH…, say what they are, and with their
|
||||
// enums placeholders, where only gemini-3.5-flash-lite's id spelling the
|
||||
// name does; no two models read the same, and the names Antigravity gives
|
||||
// the rest stay.
|
||||
func TestAntigravityRetiredModelNamedWithoutTag(t *testing.T) {
|
||||
raw, err := os.ReadFile("testdata/antigravity-models-2026-10-20.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
withLite, noEnums bool
|
||||
}{{"as listed", true, false}, {"no gemini-3.5-flash-lite", false, false}, {"placeholder enums", true, true}} {
|
||||
withLite := c.withLite
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
var list map[string]any
|
||||
if err := json.Unmarshal(raw, &list); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
models := list["models"].(map[string]any)
|
||||
if !withLite {
|
||||
delete(models, "gemini-3.5-flash-lite")
|
||||
}
|
||||
if c.noEnums {
|
||||
for _, id := range []string{"gemini-2.5-flash", "gemini-2.5-flash-lite"} {
|
||||
models[id].(map[string]any)["model"] = "MODEL_PLACEHOLDER_M" + id
|
||||
}
|
||||
}
|
||||
body, _ := json.Marshal(list)
|
||||
f := &fakeGoogle{
|
||||
load: `{"allowedTiers":[{"id":"free-tier","name":"Antigravity","isDefault":true}]}`,
|
||||
onboard: `{"done":true,"response":{"cloudaicompanionProject":"ag-proj"}}`,
|
||||
models: string(body),
|
||||
}
|
||||
googleSandbox(t, f)
|
||||
auth := googleAuth{AccessToken: "tok", RefreshToken: "rt-ag", Expiry: time.Now().Add(time.Hour).UnixMilli()}
|
||||
if err := addGoogleLogin("antigravity", "ag@example.com", "", auth); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
acct := googleLogins("antigravity")[0].acct
|
||||
ms, err := acct.models(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names, seen := map[string]string{}, map[string]string{}
|
||||
for _, m := range collapseAntigravityModels(catalog.Decorate(ms, nil)) {
|
||||
names[m.ID] = m.Name
|
||||
if other, ok := seen[m.Name]; ok {
|
||||
t.Errorf("%s and %s both read %q", other, m.ID, m.Name)
|
||||
}
|
||||
seen[m.Name] = m.ID
|
||||
}
|
||||
for _, id := range []string{"gemini-2.5-flash", "gemini-2.5-flash-lite"} {
|
||||
if n := names[id]; n == "" || strings.Contains(n, "3.5") {
|
||||
t.Errorf("%s is named %q, not for itself", id, n)
|
||||
}
|
||||
}
|
||||
want := map[string]string{
|
||||
"gemini-3-flash": "Gemini 3 Flash",
|
||||
"gemini-3-flash-agent": "Gemini 3.5 Flash (High)",
|
||||
"gemini-3.1-flash-lite": "Gemini 3.1 Flash Lite",
|
||||
"gemini-3.1-flash-image": "Gemini 3.1 Flash Image",
|
||||
"gpt-oss-120b-medium": "GPT-OSS 120B (Medium)",
|
||||
"gemini-3.8-flash": "Gemini 3.8 Flash",
|
||||
}
|
||||
if withLite {
|
||||
want["gemini-3.5-flash-lite"] = "Gemini 3.5 Flash Lite"
|
||||
}
|
||||
for id, w := range want {
|
||||
if names[id] != w {
|
||||
t.Errorf("%s is named %q, want %q", id, names[id], w)
|
||||
}
|
||||
}
|
||||
for _, w := range acct.quota(context.Background(), "").Windows {
|
||||
if strings.HasPrefix(w.Model, "gemini-2.5") && strings.Contains(w.Name, "3.5") {
|
||||
t.Errorf("Usage's window for %s is named %q", w.Model, w.Name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
{
|
||||
"models": {
|
||||
"gemini-3-flash": {
|
||||
"displayName": "Gemini 3 Flash",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": -1,
|
||||
"minThinkingBudget": 128,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65536,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M18",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true
|
||||
},
|
||||
"tab_flash_lite_preview": {
|
||||
"maxTokens": 16384,
|
||||
"maxOutputTokens": 4096,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M19",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsCumulativeContext": true,
|
||||
"supportsEstimateTokenCounter": true,
|
||||
"toolFormatterType": "TOOL_FORMATTER_TYPE_XML",
|
||||
"requiresLeadInGeneration": true
|
||||
},
|
||||
"gemini-3.8-flash-high": {
|
||||
"displayName": "Gemini 3.8 Flash (High)",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": -1,
|
||||
"minThinkingBudget": 32,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65536,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M318",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true
|
||||
},
|
||||
"claude-sonnet-4-6": {
|
||||
"displayName": "Claude Sonnet 4.6 (Thinking)",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": 1024,
|
||||
"recommended": true,
|
||||
"maxTokens": 250000,
|
||||
"maxOutputTokens": 64000,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M35",
|
||||
"apiProvider": "API_PROVIDER_ANTHROPIC_VERTEX",
|
||||
"modelProvider": "MODEL_PROVIDER_ANTHROPIC",
|
||||
"tagTitle": "Notice",
|
||||
"tagDescription": "Sonnet 5.5 is now available on paid Pro and Ultra plans. Third-party model access will no longer be available on your current plan starting on November 2, 2026.",
|
||||
"vertexModelId": "claude-sonnet-4-6@default"
|
||||
},
|
||||
"gemini-3-flash-agent": {
|
||||
"displayName": "Gemini 3.5 Flash (High)",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": -1,
|
||||
"minThinkingBudget": 32,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65536,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M84",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true
|
||||
},
|
||||
"gemini-3.5-flash-lite": {
|
||||
"displayName": "Gemini 3.5 Flash Lite",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"minThinkingBudget": 128,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65535,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M198",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true,
|
||||
"thinkingLevel": 1
|
||||
},
|
||||
"gemini-3.5-flash-extra-low": {
|
||||
"displayName": "Gemini 3.5 Flash (Low)",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": 1000,
|
||||
"minThinkingBudget": 32,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65536,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M187",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true
|
||||
},
|
||||
"gemini-3.1-flash-image": {
|
||||
"displayName": "Gemini 3.1 Flash Image",
|
||||
"supportsImages": true,
|
||||
"maxTokens": 65536,
|
||||
"maxOutputTokens": 65536,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M21",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE"
|
||||
},
|
||||
"gpt-oss-120b-medium": {
|
||||
"displayName": "GPT-OSS 120B (Medium)",
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": 8192,
|
||||
"recommended": true,
|
||||
"maxTokens": 131072,
|
||||
"maxOutputTokens": 32768,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_OPENAI_GPT_OSS_120B_MEDIUM",
|
||||
"apiProvider": "API_PROVIDER_OPENAI_VERTEX",
|
||||
"modelProvider": "MODEL_PROVIDER_OPENAI",
|
||||
"tagTitle": "Notice",
|
||||
"tagDescription": "GPT-OSS will be removed from Antigravity on November 2, 2026.",
|
||||
"vertexModelId": "openai/gpt-oss-120b-maas"
|
||||
},
|
||||
"gemini-2.5-pro": {
|
||||
"displayName": "Gemini 2.5 Pro",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": 1024,
|
||||
"minThinkingBudget": 128,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65535,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_GOOGLE_GEMINI_2_5_PRO",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"requiresImageOutputOutsideFunctionResponses": true
|
||||
},
|
||||
"gemini-3.5-flash-low": {
|
||||
"displayName": "Gemini 3.5 Flash (Medium)",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": 4000,
|
||||
"minThinkingBudget": 32,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65536,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M20",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true
|
||||
},
|
||||
"gemini-3.1-flash-lite": {
|
||||
"displayName": "Gemini 3.1 Flash Lite",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"minThinkingBudget": 128,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65535,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M50",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true,
|
||||
"thinkingLevel": 1
|
||||
},
|
||||
"gemini-3.8-flash-tiered": {
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": -1,
|
||||
"minThinkingBudget": 32,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65536,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M322",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true
|
||||
},
|
||||
"claude-opus-4-6-thinking": {
|
||||
"displayName": "Claude Opus 4.6 (Thinking)",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": 1024,
|
||||
"recommended": true,
|
||||
"maxTokens": 250000,
|
||||
"maxOutputTokens": 64000,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M26",
|
||||
"apiProvider": "API_PROVIDER_ANTHROPIC_VERTEX",
|
||||
"modelProvider": "MODEL_PROVIDER_ANTHROPIC",
|
||||
"tagTitle": "Notice",
|
||||
"tagDescription": "Opus 5.5 is now available on paid Pro and Ultra plans. Third-party model access will no longer be available on your current plan starting on November 2, 2026.",
|
||||
"vertexModelId": "claude-opus-4-6@default"
|
||||
},
|
||||
"gemini-2.5-flash-thinking": {
|
||||
"displayName": "Gemini 3.5 Flash Lite",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"minThinkingBudget": 128,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65535,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true,
|
||||
"thinkingLevel": 1
|
||||
},
|
||||
"gemini-2.5-flash-lite": {
|
||||
"displayName": "Gemini 3.5 Flash Lite",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"minThinkingBudget": 128,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65535,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true,
|
||||
"thinkingLevel": 1
|
||||
},
|
||||
"chat_23310": {
|
||||
"maxTokens": 32768,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1
|
||||
},
|
||||
"model": "MODEL_CHAT_23310",
|
||||
"apiProvider": "API_PROVIDER_INTERNAL",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsCumulativeContext": true,
|
||||
"supportsEstimateTokenCounter": true,
|
||||
"isInternal": true,
|
||||
"promptTemplaterType": "PROMPT_TEMPLATER_TYPE_CHATML",
|
||||
"toolFormatterType": "TOOL_FORMATTER_TYPE_XML",
|
||||
"requiresLeadInGeneration": true
|
||||
},
|
||||
"gemini-3.8-flash-low": {
|
||||
"displayName": "Gemini 3.8 Flash (Low)",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": 1000,
|
||||
"minThinkingBudget": 32,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65536,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M320",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true
|
||||
},
|
||||
"tab_jump_flash_lite_preview": {
|
||||
"maxTokens": 16384,
|
||||
"maxOutputTokens": 4096,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M28",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsCumulativeContext": true,
|
||||
"tabJumpPrintLineRange": true,
|
||||
"supportsEstimateTokenCounter": true,
|
||||
"addCursorToFindReplaceTarget": true,
|
||||
"toolFormatterType": "TOOL_FORMATTER_TYPE_XML",
|
||||
"requiresLeadInGeneration": true,
|
||||
"requiresNoXmlToolExamples": true
|
||||
},
|
||||
"gemini-3.8-flash-medium": {
|
||||
"displayName": "Gemini 3.8 Flash (Medium)",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"thinkingBudget": 4000,
|
||||
"minThinkingBudget": 32,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65536,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_PLACEHOLDER_M319",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true
|
||||
},
|
||||
"chat_20706": {
|
||||
"maxTokens": 16384,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1
|
||||
},
|
||||
"model": "MODEL_CHAT_20706",
|
||||
"apiProvider": "API_PROVIDER_INTERNAL",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsCumulativeContext": true,
|
||||
"tabJumpPrintLineRange": true,
|
||||
"supportsEstimateTokenCounter": true,
|
||||
"isInternal": true,
|
||||
"addCursorToFindReplaceTarget": true,
|
||||
"promptTemplaterType": "PROMPT_TEMPLATER_TYPE_CHATML",
|
||||
"toolFormatterType": "TOOL_FORMATTER_TYPE_XML",
|
||||
"requiresLeadInGeneration": true
|
||||
},
|
||||
"gemini-2.5-flash": {
|
||||
"displayName": "Gemini 3.5 Flash Lite",
|
||||
"supportsImages": true,
|
||||
"supportsThinking": true,
|
||||
"minThinkingBudget": 128,
|
||||
"recommended": true,
|
||||
"maxTokens": 1048576,
|
||||
"maxOutputTokens": 65535,
|
||||
"quotaInfo": {
|
||||
"remainingFraction": 1,
|
||||
"resetTime": "2026-10-26T17:10:26Z"
|
||||
},
|
||||
"model": "MODEL_GOOGLE_GEMINI_2_5_FLASH",
|
||||
"apiProvider": "API_PROVIDER_GOOGLE_GEMINI",
|
||||
"modelProvider": "MODEL_PROVIDER_GOOGLE",
|
||||
"supportsVideo": true,
|
||||
"thinkingLevel": 1
|
||||
}
|
||||
},
|
||||
"defaultAgentModelId": "gemini-3.8-flash-high",
|
||||
"agentModelSorts": [
|
||||
{
|
||||
"displayName": "Recommended",
|
||||
"groups": [
|
||||
{
|
||||
"modelIds": [
|
||||
"gemini-3.8-flash-high",
|
||||
"gemini-3.8-flash-medium",
|
||||
"gemini-3.8-flash-low",
|
||||
"claude-sonnet-4-6",
|
||||
"claude-opus-4-6-thinking",
|
||||
"gpt-oss-120b-medium"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"tieredModelIds": {
|
||||
"flashLite": [
|
||||
"gemini-3.5-flash-lite"
|
||||
],
|
||||
"flash": [
|
||||
"gemini-3.8-flash-tiered"
|
||||
],
|
||||
"pro": [
|
||||
"gemini-3.8-flash-tiered"
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user