diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index f73d68bb8..fa1f8d1a2 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -28,7 +28,7 @@ Pi's extensions and packages. | MCP server on/off | `ServerOn` (`POST /api/library/servers/on` with `name` and `on`, `magpie library mcp off|on `) turns a server off for everyone without removing it (swang20201 on X, Docker gateway mode, where a server ticked for no agent is still given to every app at the MCP router's address). Off, it is `Hidden` with its agents kept in `Paused` and `Agents` empty, as a plugin's server hidden from agents is (`PluginServerOn`, [Plugin tools](plugin-tools.md)): no agent's file has it, no project's (`syncProjectMCP` skips it, keeping the project's own agents for it), no subagent names it (`renderSubagent`), the router lists and calls it for nobody, and a process the router held for it ends, since `Hidden` and `Paused` are part of its `hubKey`. Its command, URL, env, headers, sign-in, `DisabledTools` and note stay in library.json. On, the agents in `Paused` get it back (none when it had none, so the router gives it to other apps again), as before it was turned off; giving it agents (`ServerAgents`, the CLI's `mcp agents`) turns it on with those (`save`), while Turn all on (`EveryServerAgents` with every agent) leaves it off. The row's switch sits after its agent chips (`serverSwitch` in plugins/library/client.js); off, the row is dimmed, its chips take no click, and it is health-checked only on a click (`TestServerOnKeepsAndRestores`, `TestLibraryMCPOffOn`, `library-mcp-on.test.cjs`). | [`mcp_on.go`](../../internal/library/mcp_on.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`subagents.go`](../../internal/library/subagents.go) | | MCP router | With `MCPHub` on, `syncMCP` gives each agent that can take it one entry, `magpie`, at the gateway's `/mcp/magpie/hub/`, in place of the servers ticked for it; magpie runs those servers itself, once for every agent. | [MCP router](mcp-router.md), [`mcp_hub.go`](../../internal/library/mcp_hub.go) | | MCP market | `MarketServers` lists the featured servers that match a search, then the MCP Registry's; a search that is an address (a repository, a page, an endpoint, a package; `market_addr.go`) finds the ones at it, and `CustomAt` offers one to fill in by hand when none is. The registry lists no server by a repository's folder, so a GitHub address naming one (`#subdirectory=`, `/tree//…`, `parseRepoAt`) is read first: the folder's `pyproject.toml` names the program, and the README's `"env": {…}` examples the keys, offered as `uvx --from git+https://github.com/o/r#subdirectory=p ` (`fromRepo`, CyberCaius on Discord: volcengine/mcp-server's askecho search). A bare repository is read so only when the registry has nothing at it, and a PyPI page, or a one-word search naming mcp the registry lists nothing by, asks PyPI (`fromPyPI`, `uvx `). Of several README keys none is required, since a README often has the user pick one way to sign in (`envInputs`; `TestMarketServerInRepoFolder`). Only Python projects are read from a folder; a Node one there still gets the blank form. A registry package is started the way its entry says (`launchLine`): its `runtimeArguments` are the runner's options (`uvx -p 3.13`, `npx --package`, docker's mounts) and the program's own words (Serena's `start-mcp-server`), then its `packageArguments`; an executable not named after the package is reached with `uvx --from ` or `npx --package `. The shipped crawl keeps each package's executables (`bins`, from npm's `bin` and the wheel's console scripts); a package with none, several with none standing out (`pickBin`), or a required option magpie can't fill isn't offered. A server installed from the market before, still on the line magpie gave it then, is given the new one on load (`healMarketLines`; fwxkogaia on X, `TestRegistryLaunchLines`, `TestInstalledMarketLineHealed`). | [`market.go`](../../internal/library/market.go), [`market_launch.go`](../../internal/library/market_launch.go), [`market_repo.go`](../../internal/library/market_repo.go) | -| Skills | A skill is a folder with a `SKILL.md`. It goes by the `name` its front matter gives, made fit for a file name (ASCII letters, digits, `_` and `-`); a name that would lose a letter or digit that way (one in another script, `CTF•密码学`) or none goes by its folder's name instead, and a skill at a repository's top by the repository's (`nameFor`, `srcFolder`). A front matter setting `disable-model-invocation: true` marks it "Manual only" in the page, in the library and in the agents' own (`meta.Manual`, `SkillView.Manual`, `FoundSkill.Manual`; sunset3279 on Discord): Claude Code runs such a skill only on the user's `/name`. A front matter that doesn't parse, or a value that isn't a bool, is not known to be, and gets no mark (`TestSkillManualFromFrontMatter`, `skill-manual.test.cjs`). Two skills a probe names alike are listed once (`unhiddenFirst`), so names that fell to `CTF`, `Strix` and nothing listed asdfgh1445/ctf-super-hub's 35 skills as 16 (tnt1223 on Discord, `TestSkillsNamedInAnotherScriptAllListed`). It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree//`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- ` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro gets a link too, to the distro's one copy of the skill, magpie's, in `~/.local/share/magpie/skills` (`Target.Store`, `storeSkill`; cutemmuu on X): the distro can't follow a link to the library's folder on Windows, and a link Windows makes through `\\wsl.localhost` is an empty folder in the distro, which in turn shows Windows its own links as entries it can't read, follow or remove, so the link is made, read and taken away in the distro by wsl.exe (`agent.WSLSymlink`, `WSLReadlink`, `WSLRemoveLink`; `TestWSLLinksLive` and `TestWSLSkillsLinkedLive` on a real distro with `MAGPIE_WSL_TEST_DISTRO`). An edit made through the link is in the distro's copy, which `takeEdits` reads as any copy of magpie's (`TestWSLEditThroughLinkReachesTheLibrary`); a copy no agent there links to or is given any more goes, to the backups when edited (`sweepWSLStores`, `TestWSLStoreSweepKeepsEdits`); a folder there that isn't magpie's is never touched, and each agent it is in the way of says so. The copy isn't put in the distro's `~/.agents/skills`, since every agent there reading that folder would get each skill, ticked for it or not. An agent set to copies gets one of its own, as does one whose skills folder or the store is on a Windows drive (#4502), where the distro's link is one Windows can't read. A copy an agent there was given before is made a link on the next sync, its edit taken first and a losing edit set aside (`wslRelink`, `TestWSLOldCopiesBecomeLinks`). A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), only as far as the caller reads: a link to a folder and an update ask GitHub for that folder's own list (`treeUnder`, git's `ref:path`; the whole list when that fails), the market fetches only the skills whose folder is the one it installs (#2794, sickn33/agentic-awesome-skills' 8,589 skills are 287 MB together), and a fetcher keeps such a part apart from another skill's of the same repository, which would otherwise read as removed (`fetcher.get`, `TestMarketSkillFromAHugeRepository`). GitHub's list is read up to `maxTree` (64 MB; that repository's is 11 MB) and an answer over the cap a caller gives `apiGet`, or one cut off, is an error saying so, never a body cut short for JSON to trip on (ye4241's `TestRepoTreeBigList`, `TestApiGetWholeAnswer`); a list GitHub truncated itself is too big (`TestTruncatedListIsTooBig`). And a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go), [`skill_beside.go`](../../internal/library/skill_beside.go) | +| Skills | A skill is a folder with a `SKILL.md`. It goes by the `name` its front matter gives, made fit for a file name (ASCII letters, digits, `_` and `-`); a name that would lose a letter or digit that way (one in another script, `CTF•密码学`) or none goes by its folder's name instead, and a skill at a repository's top by the repository's (`nameFor`, `srcFolder`). A front matter setting `disable-model-invocation: true` marks it "Manual only" in the page, in the library and in the agents' own (`meta.Manual`, `SkillView.Manual`, `FoundSkill.Manual`; sunset3279 on Discord): Claude Code runs such a skill only on the user's `/name`. A front matter that doesn't parse, or a value that isn't a bool, is not known to be, and gets no mark (`TestSkillManualFromFrontMatter`, `skill-manual.test.cjs`). Two skills a probe names alike are listed once (`unhiddenFirst`), so names that fell to `CTF`, `Strix` and nothing listed asdfgh1445/ctf-super-hub's 35 skills as 16 (tnt1223 on Discord, `TestSkillsNamedInAnotherScriptAllListed`). It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree//`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- ` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro gets a link too, to the distro's one copy of the skill, magpie's, in `~/.local/share/magpie/skills` (`Target.Store`, `storeSkill`; cutemmuu on X): the distro can't follow a link to the library's folder on Windows, and a link Windows makes through `\\wsl.localhost` is an empty folder in the distro, which in turn shows Windows its own links as entries it can't read, follow or remove, so the link is made, read and taken away in the distro by wsl.exe (`agent.WSLSymlink`, `WSLReadlink`, `WSLRemoveLink`; `TestWSLLinksLive` and `TestWSLSkillsLinkedLive` on a real distro with `MAGPIE_WSL_TEST_DISTRO`). An edit made through the link is in the distro's copy, which `takeEdits` reads as any copy of magpie's (`TestWSLEditThroughLinkReachesTheLibrary`); a copy no agent there links to or is given any more goes, to the backups when edited (`sweepWSLStores`, `TestWSLStoreSweepKeepsEdits`); a folder there that isn't magpie's is never touched, and each agent it is in the way of says so. The copy isn't put in the distro's `~/.agents/skills`, since every agent there reading that folder would get each skill, ticked for it or not. An agent set to copies gets one of its own, as does one whose skills folder or the store is on a Windows drive (#4502), where the distro's link is one Windows can't read. A copy an agent there was given before is made a link on the next sync, its edit taken first and a losing edit set aside (`wslRelink`, `TestWSLOldCopiesBecomeLinks`). A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill of the user's own is made with `CreateSkill` (`POST /api/library/skills/create`, Skills > New skill; josephBenchap on X): a name (`checkName`, and not one the library or an agent has, compared without case, nor a folder in the way) and a one-line description of at most 1024 characters make `skills//SKILL.md` with `name` and `description` front matter, listed with no source and given to the agents picked; the page then opens it in the reader (`TestCreateSkill`, `library-new-skill.test.cjs`). A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), only as far as the caller reads: a link to a folder and an update ask GitHub for that folder's own list (`treeUnder`, git's `ref:path`; the whole list when that fails), the market fetches only the skills whose folder is the one it installs (#2794, sickn33/agentic-awesome-skills' 8,589 skills are 287 MB together), and a fetcher keeps such a part apart from another skill's of the same repository, which would otherwise read as removed (`fetcher.get`, `TestMarketSkillFromAHugeRepository`). GitHub's list is read up to `maxTree` (64 MB; that repository's is 11 MB) and an answer over the cap a caller gives `apiGet`, or one cut off, is an error saying so, never a body cut short for JSON to trip on (ye4241's `TestRepoTreeBigList`, `TestApiGetWholeAnswer`); a list GitHub truncated itself is too big (`TestTruncatedListIsTooBig`). And a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go), [`skill_beside.go`](../../internal/library/skill_beside.go) | | Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`), in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills), go first, marked official: `magpie-setup` has an agent set magpie up as the user asks through its commands (providers, accounts, agents, routing groups and rules, gateway keys and limits, models, the library), and `magpie-quota` lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Their commands live in magpie's CLI, so a change to a command either uses gets the skill updated in that repository. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) | | Skills a repository or folder added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). A git repository on another host has no such list: when `git ls-remote` gives its ref a head, `findNewGit` reads the fetch the check shares (`fetcher`), once per head while its finds are kept (`gitLooked`), and offers the skills under `newBase` with the address as the library has it, `.git` and all, so an Add keeps the same `repo@ref`. A folder the user added linked skills from is kept as `folder:` in `SeenSkills` (`offered`, at install), which is also how the library knows which folder to look in again: `findNewFolder` reads it as Add from folder does and offers a skill folder there the library doesn't link, hasn't offered, and has no skill by that name of; a folder that can't be read keeps what was found. `View.CheckFolders` (`addedFromFolders`, which reads no folder) puts Check for updates on the page with only linked skills, and makes `checkDue` true. A check never adds or writes a skill: each is offered, and one the user removed or set aside isn't offered again. A folder added before this kept no `folder:` key and is looked in only once the user adds from it again (refeccd on Discord; `TestCheckSkillsFindsNewInGitRepo`, `TestCheckSkillsFindsNewInFolder`, `skill-new-in-repo.test.cjs`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) | | Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. That checkout is the one git finds (`provider.GitAt` in `gitRepoOf`): an empty `.git` between the skill and its checkout is passed over, as git passes it over, and a `.git` file that names no repository (a worktree left behind) is none (#3675, `TestSkillRepoTraced`). A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in plugins/library/client.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). | [`skill_from.go`](../../internal/library/skill_from.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 5c9ed3a1e..f838096f9 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -23,6 +23,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Anthropic key header | A provider of the user's own on a third-party Anthropic API is sent its key as both `x-api-key` and `Authorization: Bearer` (`AuthHeaders`); Anthropic's own API, Bedrock, Azure, Vertex and every subscription account have their own and never this choice (`BothAuth` is false). Some services refuse the two together with a 401 (Aloha on Discord: "鉴权 header, x-api-key 和 Authorization 不可以同时存在"), so `Provider.AuthHeader` (`authHeader`: empty for both, `x-api-key` or `bearer`; anything else is read as empty) sends one alone, picked in the editor's Key header row (shown while `bothAuth` is true, or a custom provider's Anthropic URL is a third party's). Left at both, a 401 whose body `catalog.BothAuthRefused` tells as that refusal (it names both headers and says they can't be together, in Chinese or English) is asked once more with x-api-key alone, then Bearer alone (`RetryOneAuth`, in the gateway's `forwardOnce` and the provider test's `probe`; `catalog.fetchOne` for the model list through `listAuth`); the first not answered 401 or 403 is kept with `LearnAuthHeader`, which never changes a pick the user made. A request carrying the user's own `Authorization` or `x-api-key` header is never retried. | [`authheader.go`](../../internal/provider/authheader.go), [`test.go`](../../internal/provider/test.go), [`catalog/authheader.go`](../../internal/catalog/authheader.go), [`catalog/live.go`](../../internal/catalog/live.go) | | GLM Coding Plan key at pay as you go | Zhipu's and Z.ai's presets offer Pay as you go first (`/api/paas/v4`) and the Coding Plan (`/api/coding/paas/v4`, Responses at `/api/v1`); both share `/api/anthropic`, which bills the plan, so a plan's key left at Pay as you go worked in Claude Code and was refused 429 code 1113 "余额不足或无可用资源包" in Codex (@cleverpigo on X). Nothing in the key tells the two apart, so a Chat request to `open.bigmodel.cn` or `api.z.ai` at `/api/paas/v4` refused 1113 is asked once more at `/api/coding/paas/v4` (`RetryZhipuCoding`, in the gateway's `forwardOnce` and the provider test's `probe`). Served there, `LearnZhipuCoding` moves a saved provider with that one key, still at that URL, to the plan's OpenAI URL (and the preset's plan Responses URL when it has none); one with other keys stays and is asked again each time. Refused there too, the 1113 body keeps its code and gets both URLs and what to change in its message (`ZhipuNoBalanceHint`). A pay-as-you-go key with a balance is never answered 1113 and never sent to the plan's endpoint. | [`zhipu_coding.go`](../../internal/provider/zhipu_coding.go), [`test.go`](../../internal/provider/test.go) | | A Zen free model on OpenCode Go | OpenCode's two gateways serve different free models: Zen's free tier (`/zen`, asked with the public key `OpenCodeAnonymousKey`) serves its `-free` models and big-pickle, Go (`/zen/go`, a Go key) only a few of its own (beam-free, iceman-contributor-free on 2026-11-02). Go answers a model it doesn't serve 400 "Upstream request failed: Model is unavailable." before it reads the key, so Claude Code asking one of Zen's free models on an OpenCode Go provider failed on every request (51bit.eth on Discord). Such a request, a free model by `OpenCodeFree`, is asked once more at Zen's free tier on the same API (`openCodeGoToZenFree`, `OpenCodeFreeURL`), with the public key and never the user's Go key (`RetryOpenCodeFreeOnZen`, in the gateway's `forwardOnce`); a model that isn't free isn't. Refused there too, or not free, the 400 keeps Go's words and says where the model is served. Not changed: when Go's `/models` refuses the key, the provider lists models.dev's `opencode-go`, which names free models Go doesn't serve (#4900). | [`opencode_go_free.go`](../../internal/provider/opencode_go_free.go) | +| OpenCode Go endpoints | Go's docs name one URL per API under `/inference/go`: `/openai/v1` (chat, Responses), `/anthropic` (Messages), `/google/v1beta` (Gemini, `models/{id}:streamGenerateContent`). The preset gives them (`OpenCodeGoChat`, `OpenCodeGoAnthropic`, `OpenCodeGoGemini`); a provider of the preset saved with the older `/zen/go` or `/inference/go/v1` URLs is moved on load, and one added by hand with a single Go URL gets the rest filled beside it (`openCodeEndpoints`). A URL the user gave another API stays. | [`opencode_endpoints.go`](../../internal/provider/opencode_endpoints.go) | | Zhipu's 200 refusals | Zhipu's and Z.ai's `/api/v1` (the GLM Coding Plan's Responses API, from their Codex pages) and `/api/monitor` answer a refusal 200 in the platform's envelope, `{"code":1000,"msg":"身份验证失败。","success":false}`, where their OpenAI and Anthropic endpoints answer the same key 401 (@xanahopper on X: a refused key tested green on the Responses row only). `ZhipuEnveloped` turns a 2xx JSON body from `open.bigmodel.cn` or `api.z.ai` with `success: false` into `{"error":{"code","message"}}` at the status Zhipu's error-code table gives (1000–1005 → 401, 1113 and 1302–1399 → 429, 1220 → 403, 1210–1229, 1261 and 1301 → 400, anything else → 502), in the provider test's `probe` (endpoint tests, model tests, Detect APIs) and the gateway's `forwardOnce`. A stream, a compressed body, a body over 64 KB and every other host pass as they came. The plan's quota card for a key refused there (1000–1005, or a 401) says ` didn't take this key (): …` with the vendor's API-keys page (`zhipuRefused`), not asked again as a team's key, and the GUI shows it as that (`quotaError`) rather than "Allowance unavailable". | [`zhipu_envelope.go`](../../internal/provider/zhipu_envelope.go), [`planquota.go`](../../internal/provider/planquota.go), [`test.go`](../../internal/provider/test.go) | | Extra body | `ExtraBody` (`extraBody` in providers.json, the editor's *Extra body*, #1604) is a JSON object whose fields `WithExtraBody` adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's `forwardOnce` and in Test and Detect (`tested`). A field the body has already is kept; a name written `"!name"` replaces it. Values are put in as written, objects whole, not merged. `${sessionId}` in any string, at any depth, becomes the request's session: the agent's session header (`sessionOf`), else the id `conversationID` derives from how the conversation opens (`magpie-` and its hash, [Gateway routing](gateway-routing.md#responsibilities-and-sources-of-truth)'s Affinity), so it stays the same through one conversation; Test and Detect send `magpie-test-` and 12 random letters, a new one each time. `${threadId}` is the thread the agent names within that session: Codex's `thread_id` (its turn metadata or `thread-id` header, `threadOf`), which a subagent has of its own while it shares its lead's session; read only when the provider's headers or extraBody name it (`AsksThread`). No other agent names a thread, and there `${threadId}` is the session's id. `${subagentId}` becomes the Claude Code subagent the request is of (`x-claude-code-agent-id`, `subOf`), "" on the conversation's own turns, which never send the header, so `${sessionId}:${subagentId}` keeps one prompt_cache_key per subagent where `${sessionId}` alone carries every subagent's turns on one key (#2937). `model`, `stream` and the conversation (`messages`, `input`, `contents`, `system`, `systemInstruction`, `system_instruction`, `instructions`, `tools`, `ExtraBodyReserved`) are magpie's: Save refuses them with or without `!` (`ExtraBodyOK`), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (`cleanExtraBody`). Not sent with it: `count_tokens`, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests, except a ChatGPT (Codex) account's (magpie-releases#18): its requests are built as Codex CLI's (`codexBody`) and take the fields Codex CLI adds by choice, such as `access_programs` (OpenAI's Daybreak), while `store`, `tool_choice` and `include`, which the backend needs as `codexBody` sets them, can't be set (`codexOwned`). Its extraBody is written into providers.json by hand under the account's entry and kept onto the account by `withPicks`, and kept by a later `Save` (#4738: `Save` dropped it before); the editor has no box for it. A client's own top-level `access_programs` on Responses or Chat is carried to a Responses build as it came (`Request.AccessPrograms`), so a request translated (a Codex account is streamed, so a whole Responses request is made again) keeps it as a relayed one does. It reaches only the upstreams Codex itself sends it to (`keepsAccessPrograms`, #3172, see [gateway routing](gateway-routing.md)); it is taken out before the extraBody merge, so an `access_programs` the user puts in a provider's extraBody still goes. One object goes to every API; fields for one API alone are not a thing yet. A `thinking` budget it puts in on an Anthropic endpoint is fitted to a Claude that thinks only adaptively after the merge, as an agent's is (`adaptiveThinking`, `TestExtraBodyBudgetFittedToAdaptiveModel`). | [`extrabody.go`](../../internal/provider/extrabody.go), [`gateway.go`](../../internal/gateway/gateway.go) | | Headers' conversation ids | `${sessionId}`, `${threadId}` and `${subagentId}` in a value of the provider's `Headers` (Axel Burks on Discord: a gateway in front of several Azure accounts routes one conversation to one account by a session header) are the ids extraBody gets, on every request `Sign` signs: the gateway carries the conversation to it in the request's context (`WithConversation`), on every API and `count_tokens` too. A request that is no turn of a conversation (a model list, a balance, an embedding, image or video, System One's decision model, a search) gets an id of its own, `magpie-` and 12 random letters, new each time (`OwnConversation`); Test and Detect's is their `magpie-test-` id, the same in headers and body. A literal placeholder is never sent. In a header the ids go without control characters (`headerSafe`): an agent's session id with CR or LF in it would split the header, or Go would fail the request. A value with neither placeholder goes as written (`SentHeaders`). | [`conversation.go`](../../internal/provider/conversation.go), [`account.go`](../../internal/provider/account.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codex_resume.go`](../../internal/gateway/codex_resume.go) | @@ -66,7 +67,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A Remote magpie's cards (`GET /v1/magpie/quotas/cards`, `writeCards`) carry the estimate too, for the owner or a key with no limits on what it sees, since the computer reading them has none of the remote's calls to reckon from (linkaww on Discord: a Docker magpie's ChatGPT Pro week showed no whole on the other computer; `TestRemoteMagpieCardsCarryTheirWholes`). A Codex card's estimate counts the calls of a ChatGPT API account (`chatgpt-api`) that is the same ChatGPT account, whose plan limits they share: the tokens of both must name the same `chatgpt_account_id` and `chatgpt_user_id`, never matched by name, so two Team seats of one email stay apart (`SamePlanAccounts` in [`chatgpt_same_plan.go`](../../internal/provider/chatgpt_same_plan.go), jctaoo on Discord, `TestWindowHoldsCountsTheSameChatGPTAccountThroughTheAPI`). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). What it has kept includes its own Remote magpies' cards as it last read them (`passedOnCards`, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (`magpie2/magpie1/codex`, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries `via`, the `catalog.Self` of each magpie it went through, and a reader leaves out one that loops (`catalog.Loops`, as a model's `magpie_via`). A refresh of such a card is passed to the magpie it came from (`quotaCardsRefresh` takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (`KeptQuotaReport`) has a remote's cards the same way. A ChatGPT account's card has an *Image generation* row (`WithImageLane`, [`image_lane.go`](../../internal/provider/image_lane.go), `Lane` `images`, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, and neither `/wham/usage` (`additional_rate_limits` is null) nor the reply headers (`x-codex-primary-*`, `x-codex-secondary-*`) tell it. So the row says *Used up* with the reset time while the image model is resting on that account after a refusal (`ImageRest`, the gateway's `restingUntil`, whose time is the refusal's `resets_at`, #2244) and *Unknown* otherwise, never a share or a count (`TestWithImageLaneOnlyReadCodexCards`, `TestCodexImageRowIsTheRefusalsResetTime`, `codex-image-row.test.cjs`). Not done: the count of images made in the window. Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold `priority` (`provider.CanFast` reads them with `RemoteTiers`; Ultrafast too where they hold `ultrafast`, `UltraOn`), and a fast pick of one goes on with `service_tier` `priority` on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's `speed`, has it turned into the tier the remote offers (`forwardTranslated`), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; `TestRemoteMagpieFastPick`, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | -| Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' `magpie_via` ends with this magpie's own `Self` is kept, by provider id and the address it answered at, in `remote-self.json` (`noteSelf`; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (`SelfLeftOut` in `On`, `SwitchedOff`, `remoteMagpies`): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (`ThroughSelf` in `Resolve` and `ResolveRoute`), not passed through the gateway again. The Providers row says *This magpie* (greyed while left out) and its editor says why, with **Use it anyway** (`KeepSelf`, `provider/keepself`, `SetKeepSelf`), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. `KeepSelf` is this computer's own like `KeepLogin` (`Mirror`, `Restore`, blanked in davsync's `hashes`), since the other computer's copy points at this one, which is not itself (`TestRemoteMagpieThatIsThisOneIsLeftOut`, `TestRemoteSelfRecord`, `remote-self.test.cjs`). Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. The quota cards a Remote passes on follow the same ways (X on 0.1.3678: A → B → C → A told Kiro and Codex by `remote-B/kiro` and `remote-B/remote-C/remote-A/remote-B/remote-C/kiro`, hours apart, to a Remote enabled for one local model): a card's `via` that names any magpie twice is a loop too, so one that came round after this magpie restarted (its old `Self` is no longer this one's) is left out (`catalog.Loops`), and isn't kept in `remoteCardCache` (`keepRemoteCards`). A Remote's cards are shown, and passed on, only for the providers it is enabled for: the first part of the card's provider id must be the first part of an exposed model's id there (`remoteCardWanted`), unknown, so all shown, while its list isn't read. One subscription account's copies (same provider, same `user`) are one card, the newest complete reading, then the shorter way (`oneCardPerAccount`, in `RemoteCards` and `CachedCards`; a key's cards, whose `user` is a name two keys may share, are not merged) (`TestRemoteCardsFollowEnabledModelsAndDedupe`, `TestLoopsOnARepeatedMagpie`). | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`remote_self.go`](../../internal/provider/remote_self.go), [`remote_quotas_scope.go`](../../internal/provider/remote_quotas_scope.go) | +| Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' `magpie_via` ends with this magpie's own `Self` is kept, by provider id and the address it answered at, in `remote-self.json` (`noteSelf`; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (`SelfLeftOut` in `On`, `SwitchedOff`, `remoteMagpies`): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (`ThroughSelf` in `Resolve` and `ResolveRoute`), not passed through the gateway again. The Providers row says *This magpie* (greyed while left out) and its editor says why, with **Use it anyway** (`KeepSelf`, `provider/keepself`, `SetKeepSelf`), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. `KeepSelf` is this computer's own like `KeepLogin` (`Mirror`, `Restore`, blanked in davsync's `hashes`), since the other computer's copy points at this one, which is not itself (`TestRemoteMagpieThatIsThisOneIsLeftOut`, `TestRemoteSelfRecord`, `remote-self.test.cjs`). Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. The quota cards a Remote passes on follow the same ways (X on 0.1.3678: A → B → C → A told Kiro and Codex by `remote-B/kiro` and `remote-B/remote-C/remote-A/remote-B/remote-C/kiro`, hours apart, to a Remote enabled for one local model): a card's `via` that names any magpie twice is a loop too, so one that came round after this magpie restarted (its old `Self` is no longer this one's) is left out (`catalog.Loops`), and isn't kept in `remoteCardCache` (`keepRemoteCards`). A Remote's cards are shown, and passed on, only for the providers it is enabled for: the card's provider id must be the provider path of an exposed model there (its id less the last part, or a parent of it, whole parts only: relay/strata enabled tells relay/strata, never relay/kiro; `remoteCardWanted`, `cardWantedFor`, `TestRemoteCardWantedByWholePath`, 748975219 on X), unknown, so all shown, while its list isn't read. One subscription account's copies (same provider, same `user`) are one card, the newest complete reading, then the shorter way (`oneCardPerAccount`, in `RemoteCards` and `CachedCards`; a key's cards, whose `user` is a name two keys may share, are not merged) (`TestRemoteCardsFollowEnabledModelsAndDedupe`, `TestLoopsOnARepeatedMagpie`). | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`remote_self.go`](../../internal/provider/remote_self.go), [`remote_quotas_scope.go`](../../internal/provider/remote_quotas_scope.go) | | A remote magpie that moved | Computer A's router hands it a new address now and then (luckymanjc on Discord), and B's Remote magpie, saved at the old one, reached nothing. When B can't connect to it at all (a dial error, `unconnected`), its list fetch (`fetch` in [`models.go`](../../internal/provider/models.go)) and the gateway's request (`forward` in [`gateway.go`](../../internal/gateway/gateway.go)) call `SeekMoved` ([`remote_moved.go`](../../internal/provider/remote_moved.go)): every address of the old one's /24 and of up to four of B's own private /24s is dialled at A's port (500ms each, 128 at once, `lanNeighbours`). Whatever takes the connection there may be anyone's (a café's network, A switched off), so it is sent neither the key nor the provider's headers until it proves it holds the key (`proves`): B POSTs a nonce of its own and `RemoteKeyID` (the key's sha256, hex) to `RemoteProvePath` (`/v1/magpie/prove`) with no key and no proxy, and checks with `hmac.Equal` that the answer is `RemoteProof`: HMAC-SHA256 under the key of the nonce and the address B dialled. A answers it ([`remote_prove.go`](../../internal/gateway/remote_prove.go)) for an enabled gateway key of that id (`access.ProveSecret`: constant-time compares over every key, then `Check`) at the address the connection reached it on (`http.LocalAddrContextKey`), so a host passing B's nonce on to A elsewhere hands back a proof for A's address, not its own; 404 for a key it hasn't or has turned off. Only an address that proved is asked `/v1/models` with the key, and the first that lists 200 and whose list this magpie didn't make (`magpie_via`) is saved as the provider's address and asked again. A magpie from before the route, one behind a port forward or NAT (it is reached at another address than its own), or one behind a proxy that needs the provider's headers, is not found, and the user types the new address. A name or a public address is never looked around, an address the user changed meanwhile stands, and a provider is looked for once a minute at most, callers at once sharing the look (`TestRemoteMagpieKeyGoesToNoNeighbour`: an impostor that lists 200 for anything, one with a proof under another key, one with a garbled proof and one relaying to the real magpie are sent no key or header and not saved, and the real one is; `TestRemoteProof`, `TestRemoteMagpieFoundMoved`, `TestRemoteMagpieNotFoundStays`, `TestRemoteMagpieMovedIsFound`, `TestRemoteProveAnswersOnlyTheKeysHolder`). | | A relay's Codex entries | A provider the user added by its address with a Responses URL may list its models in Codex's own shape (`slug`, `supported_reasoning_levels`, `shell_type`, `base_instructions`: `catalog.CodexEntry`), plainly or when asked with Codex's `client_version`, as sub2api does (ctopsc on Discord: GPT-6.1 Terra was handed models.dev's 922000 window where the relay said 272000). `fetchOne` keeps such a row whole (`catalog.Model.Codex`, with its window, max window and inputs read off it), and when the plain list has none it asks the same URL once more with `client_version` (`codexEntries`): only where the list is fetched (add, key change, Refresh), never per Codex poll. The answer only adds entries to models the plain list has; one that fails or can't be read keeps the last list's entries (failed read = unknown), one that answers plainly says there are none. `codexcat.listedEntry` hands Codex the relay's entry as given, `base_instructions` included, with magpie's slug, name, priority and " via magpie" description; the user's window, compaction, levels and image setting still win (levels keep the relay's descriptions). A saved list from before is enriched at its next Refresh. `TestCodexListedEntry`, `TestCodexListedEntryInPlainList`. | [`codex_entries.go`](../../internal/provider/codex_entries.go), [`live.go`](../../internal/catalog/live.go), [`codexcat.go`](../../internal/codexcat/codexcat.go) | | An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 850cacfc0..65a0b2c4a 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -1100,7 +1100,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, log.Printf("claude: a branch of a claude -p run's session goes to a new interactive Claude Code, told the whole conversation") from, req.branch = nil, nil } - if from != nil && from.cut != "" { + if from != nil && (from.cut != "" || len(from.cutCalls) > 0) { // a branch is a copy of the run's session as far as the reply // that made the calls, a session of its own: Claude Code's // interactive mode doesn't take --resume-session-at, and resumes @@ -1111,14 +1111,20 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, if from.cutBefore { cutter, how = cutSessionBefore, "a side request that sends the conversation whole, without the calls its run still waits on, goes on in a branch of that run's session, cut before them" } - sid, err := cutter(from.sessions, from.session, from.cut) + var sid string + var err error + if from.cut == "" { + sid, err = cutSessionBeforeCalls(from.sessions, from.session, from.cutCalls) + } else { + sid, err = cutter(from.sessions, from.session, from.cut) + } if err != nil { log.Printf("claude: a branch of a run's session couldn't be cut (%v); a new Claude Code is told the whole conversation", err) from, req.branch = nil, nil } else { log.Printf("claude: %s (%d messages)", how, len(from.since)) from.mu.Lock() - from.session, from.cut, from.cutBefore, from.gone = sid, "", false, false + from.session, from.cut, from.cutCalls, from.cutBefore, from.gone = sid, "", nil, false, false from.mu.Unlock() } } @@ -2530,6 +2536,9 @@ type savedSession struct { // cutBefore: cut before that line, not after it: the reply's words // stay and its calls go (a side request that dropped them, #6128) cutBefore bool + // cutCalls: the cut is before the line of these tool calls, found by + // their ids, when the line's uuid isn't known yet (#6128). + cutCalls []string // tui: the session was made by Claude Code's interactive mode; a // branch of it is too, where it can be (claudePrint) tui bool @@ -2774,10 +2783,27 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession, } run.mu.Lock() at, seq, said := "", 0, "" + var unread []string // pending calls whose line isn't read yet if pending { + for id, l := range run.lines { + switch { + case l.told != told: + case l.uuid == "": + unread = append(unread, id) + if seq == 0 || l.seq < seq { + seq, said = l.seq, l.told + } + } + } + // A reply is parked on once its calls were streamed; its + // session line may not be read yet, nor on disk (#6128): the + // calls are found in the session by their ids, and a line + // already read is a surer place. + slices.Sort(unread) for _, l := range run.lines { if l.uuid != "" && l.told == told && (at == "" || l.seq < seq) { at, seq, said = l.uuid, l.seq, l.told + unread = nil } } } else { @@ -2790,7 +2816,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession, sid, sessions, prefix := run.sessionID, slices.Clone(run.sessions), run.cachePrefix usable := !run.closed && !run.rewound && run.lean == req.leanPrompt && !run.clientMarks && (run.tui || !wantTUI(req)) run.mu.Unlock() - if at == "" { + if at == "" && len(unread) == 0 { continue } switch { @@ -2804,7 +2830,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession, if pending && found != nil && seq <= foundSeq { continue } - found, foundSeq = &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, cutBefore: pending, tui: run.tui, appended: run.appended, cachePrefix: prefix, gone: true}, seq + found, foundSeq = &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, cutCalls: unread, cutBefore: pending, tui: run.tui, appended: run.appended, cachePrefix: prefix, gone: true}, seq } if !pending { break @@ -3007,6 +3033,47 @@ func cutSessionBefore(dirs []string, sid, uuid string) (string, error) { return cutSessionAt(dirs, sid, uuid, cutBefore) } +// cutSessionBeforeCalls is cutSession as far as the line before the first +// assistant line that calls one of ids, the calls a run's reply made that +// its line uuid isn't known for (#6128). Claude Code writes that line late, +// after its tool ran: asked again until cutWait is over, then, with the +// line not there, the session as it stands is what came before the calls. +func cutSessionBeforeCalls(dirs []string, sid string, ids []string) (string, error) { + if len(ids) == 0 { + return "", errors.New("no session to cut") + } + return cutSessionWhere(dirs, sid, "calls "+strings.Join(ids, ","), func(b []byte, last bool) int { + if end := cutBeforeCalls(b, ids); end >= 0 { + return end + } + if last { + return len(b) + } + return -1 + }) +} + +// cutBeforeCalls is where in a session's lines b the first whole assistant +// line calling one of ids begins, -1 when none is there; a line with no +// newline yet is not whole. +func cutBeforeCalls(b []byte, ids []string) int { + for at := 0; at < len(b); { + nl := bytes.IndexByte(b[at:], '\n') + if nl < 0 { + break + } + line := b[at : at+nl] + start := at + at += nl + 1 + for _, id := range ids { + if bytes.Contains(line, []byte(`"id":"`+id+`"`)) { + return start + } + } + } + return -1 +} + // cutSessionWhere copies session sid as far as the place at finds in its // lines (> 0), asked again until cutWait is over; last is the final ask. // what is what it looks for, as an error says. diff --git a/internal/gateway/claude_subscription_summary_test.go b/internal/gateway/claude_subscription_summary_test.go index b37f3f8b2..65cb0c24c 100644 --- a/internal/gateway/claude_subscription_summary_test.go +++ b/internal/gateway/claude_subscription_summary_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) // recih on X (#6128): Claude Code's AgentSummary sends the sub-agent's @@ -70,3 +71,60 @@ func TestClaudeBranchForSummaryWithoutThePendingCall(t *testing.T) { t.Fatalf("closed run: %v %q", got, why) } } + +// #6128 (recih, v0.1.3757): the run parks on a call it streamed before the +// call's session line is read or written (Claude Code writes it after the +// tool ran), so the line has no uuid. The summary is found by the history +// the call answered, and the branch is cut before the call by its id, +// whether the line is on disk by then or not. +func TestClaudeBranchForSummaryBeforeTheCallLineIsRead(t *testing.T) { + was := cutWait + cutWait = 300 * time.Millisecond + t.Cleanup(func() { cutWait = was }) + dir := t.TempDir() + const sid = "lead-session" + path := filepath.Join(dir, sid+".jsonl") + head := `{"uuid":"u1","sessionId":"` + sid + `","type":"user"}` + "\n" + `{"uuid":"a-words","sessionId":"` + sid + `","type":"assistant"}` + "\n" + if err := os.WriteFile(path, []byte(head), 0o600); err != nil { + t.Fatal(err) + } + user := func(s string) Message { return Message{Role: "user", Parts: []Part{{Kind: Text, Text: s}}} } + words := Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: "I will run the tests."}}} + history := []Message{user("task")} + b := newSubscriptionBridge() + run := &subscriptionRun{sessionID: sid, sessions: []string{dir}, tui: true} + own := "claude\x00u" + run.owner.Store(&own) + run.lines = map[string]callLine{"toolu_1": {seq: 1, told: historyKey(history)}} // parked, no uuid yet + b.runs["r"] = run + req := &Request{Messages: append(append(append([]Message{}, history...), words), user("Describe your progress in 3-5 words."))} + got, why := b.branch(req, own) + if got == nil { + t.Fatalf("no branch while the call's line is unread: %s", why) + } + if !got.cutBefore || len(got.cutCalls) != 1 || got.cutCalls[0] != "toolu_1" { + t.Fatalf("branch = %+v, want cut before the call toolu_1", got) + } + // the line is written while the cut waits for it: the cut is before it + go func() { + time.Sleep(60 * time.Millisecond) + f, _ := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600) + defer f.Close() + f.WriteString(`{"uuid":"a-call","sessionId":"` + sid + `","type":"assistant","message":{"content":[{"type":"tool_use","id":"toolu_1"}]}}` + "\n") + }() + id, err := cutSessionBeforeCalls(got.sessions, got.session, got.cutCalls) + if err != nil { + t.Fatal(err) + } + if s, _ := os.ReadFile(filepath.Join(dir, id+".jsonl")); !strings.Contains(string(s), "a-words") || strings.Contains(string(s), "a-call") { + t.Fatalf("branch keeps %q, want the words and not the call", s) + } + // the line never comes: what is on disk is what came before the call + id, err = cutSessionBeforeCalls(got.sessions, got.session, []string{"toolu_9"}) + if err != nil { + t.Fatal(err) + } + if s, _ := os.ReadFile(filepath.Join(dir, id+".jsonl")); !strings.Contains(string(s), "a-words") { + t.Fatalf("branch keeps %q, want the words", s) + } +} diff --git a/internal/gateway/opencode_gemini_test.go b/internal/gateway/opencode_gemini_test.go index ce98ccaf7..33423c2ae 100644 --- a/internal/gateway/opencode_gemini_test.go +++ b/internal/gateway/opencode_gemini_test.go @@ -63,7 +63,7 @@ func openCodeGeminiServer(t *testing.T, s *Server) func() []openCodeAsk { switch { case r.Method != http.MethodPost: return reply(404, "application/json", `{}`) - case gemini && (strings.HasPrefix(path, "/zen/v1/models/") || strings.HasPrefix(path, "/inference/go/v1/models/")): + case gemini && (strings.HasPrefix(path, "/zen/v1/models/") || strings.HasPrefix(path, "/inference/go/google/v1beta/models/")): return reply(200, "text/event-stream", openCodeGeminiSSE) case strings.Contains(path, ":") || strings.Contains(path, "/models/"): return reply(404, "text/html", `Not Found`) @@ -113,7 +113,7 @@ func TestOpenCodeGoGeminiModelOnGeminiAPI(t *testing.T) { } s := New() took := openCodeGeminiServer(t, s) - const want = "opencode.ai/inference/go/v1/models/gemini-4-argon-contributor:streamGenerateContent?alt=sse" + const want = "opencode.ai/inference/go/google/v1beta/models/gemini-4-argon-contributor:streamGenerateContent?alt=sse" check := func(what string, code int, body string) openCodeAsk { t.Helper() asked := took() diff --git a/internal/gateway/opencode_go_free_test.go b/internal/gateway/opencode_go_free_test.go index 3327b319a..c59d1ba22 100644 --- a/internal/gateway/opencode_go_free_test.go +++ b/internal/gateway/opencode_go_free_test.go @@ -36,7 +36,7 @@ func goFreeServer(t *testing.T, models, serves []string, zenStatus int, zenRefus t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("XDG_CACHE_HOME", t.TempDir()) if err := provider.Save(provider.Provider{ID: "go", Name: "OpenCode Go", Preset: "opencode-go", Key: "sk-go-users-own", - Chat: "https://opencode.ai/zen/go/v1", Responses: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go", + Chat: provider.OpenCodeGoChat, Responses: provider.OpenCodeGoChat, Anthropic: provider.OpenCodeGoAnthropic, Models: models}); err != nil { t.Fatal(err) } @@ -55,7 +55,7 @@ func goFreeServer(t *testing.T, models, serves []string, zenStatus int, zenRefus model = m } } - if strings.HasPrefix(r.URL.Path, "/zen/go/") { + if strings.HasPrefix(r.URL.Path, "/inference/go/") { for _, m := range serves { if m == model { return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/event-stream"}}, @@ -96,8 +96,8 @@ func TestOpenCodeGoFreeModelAskedAtZen(t *testing.T) { } a := asked() // on the API Go was asked on, at Zen's free tier - want := map[string]string{"opencode.ai/zen/go/v1/messages": "opencode.ai/inference/anthropic/v1/messages", - "opencode.ai/zen/go/v1/chat/completions": "opencode.ai/inference/openai/v1/chat/completions"} + want := map[string]string{"opencode.ai/inference/go/anthropic/v1/messages": "opencode.ai/inference/anthropic/v1/messages", + "opencode.ai/inference/go/openai/v1/chat/completions": "opencode.ai/inference/openai/v1/chat/completions"} if len(a) != 2 || want[a[0].url] == "" || a[1].url != want[a[0].url] { t.Fatalf("asked %+v", a) } @@ -114,7 +114,7 @@ func TestOpenCodeGoOwnFreeModelStaysOnGo(t *testing.T) { if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from go") { t.Fatalf("%d %s", rec.Code, rec.Body) } - if a := asked(); len(a) != 1 || !strings.HasPrefix(a[0].url, "opencode.ai/zen/go/") { + if a := asked(); len(a) != 1 || !strings.HasPrefix(a[0].url, "opencode.ai/inference/go/") { t.Fatalf("asked %+v", a) } } @@ -137,7 +137,7 @@ func TestOpenCodeGoUnavailableSaysWhere(t *testing.T) { t.Fatalf("%d %s", rec.Code, body) } for _, a := range asked()[n:] { - if !strings.HasPrefix(a.url, "opencode.ai/zen/go/") { + if !strings.HasPrefix(a.url, "opencode.ai/inference/go/") { t.Fatalf("a paid model asked at %s", a.url) } } diff --git a/internal/gui/app.go b/internal/gui/app.go index 9585239ae..9e93bcde2 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -422,6 +422,7 @@ func Run(version string, showMain bool, link string) error { // a quiet start joins the Dock once started (below): Wails activates // an app that starts in it policy := dockPolicy(settings.Load().Dock && !quiet) + webView2Prepare() h.app = application.New(application.Options{ // Windows and Linux start a new process for a magpie:// link (or a // second launch); it hands its arguments to the running one and quits. @@ -472,7 +473,7 @@ func Run(version string, showMain bool, link string) error { updates.install(false) }, // Wails exits on some webview errors; say why before it does. - ErrorHandler: func(err error) { log.Println("magpie:", err) }, + ErrorHandler: func(err error) { webView2Failed(h.app, err) }, }) // Windows without the WebView2 runtime can make no window: Wails would // exit on the first, with nothing on screen to say why (#1806). The diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 2c9b87b36..c56df6802 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -6680,6 +6680,53 @@ magpie.plugin("library", (ctx) => { }; } + // A skill of the user's own: a name and a description make its SKILL.md + // in the library's folder (josephBenchap on X); it opens in the reader, + // whose path opens it in their editor. + function newSkill() { + const all = skillAgents(); + const d = { name: "", description: "", agents: all.map((a) => a.id) }; + const ed = el("div", "editor lib-editor lib-newskill"); + const head = el("div", "ehead"); + head.append(glyph(GLYPH.skill), el("b", "", t("New skill"))); + ed.append(head); + const err = el("div", "editor-error"); + const name = field2("", t("e.g. my-skill"), (v) => { d.name = v.trim(); }); + name.classList.add("mono"); + ed.append(...field(t("Name"), name, t("Letters, digits, - and _ — what the agents call it"))); + const desc = el("textarea", "lib-text small lib-newskilldesc"); + desc.placeholder = t("e.g. Writes release notes. Use when asked for a changelog."); + desc.spellcheck = false; + desc.rows = 2; + desc.maxLength = 1024; + desc.oninput = () => { d.description = desc.value; }; + desc.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (e.key === "Enter") { e.preventDefault(); modal?.save?.(); } }; + ed.append(...field(t("Description"), desc, t("What it does and when to use it: the agent reads this to decide when to load it"))); + const agentsBox = el("div"); + ed.append(...field(t("Agents"), agentsBox)); + ed.append(err); + const drawAgents = () => agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, all: true })); + drawAgents(); + const bar = el("div", "bar"); + bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal)); + const save = async () => { + err.textContent = ""; + try { + take(await api("library/skills/create", { name: d.name, description: d.description, agents: d.agents })); + report(lib.result, t("{name} is in the library now", { name: d.name })); + render(); + const made = lib.skills.find((x) => x.name === d.name); + if (made) viewSkill(made); else closeLibModal(true); + } catch (e) { err.textContent = e.message; } + }; + bar.append(button(t("Create"), "primary", save)); + ed.append(bar); + const original = JSON.stringify(d); + modal = { save, dirty: () => JSON.stringify(d) !== original }; + openLib(ed); + requestAnimationFrame(() => name.focus()); + } + function installCard() { const card = el("div", "list lib-card lib-install"); const line = el("div", "lib-find"); @@ -6695,7 +6742,9 @@ magpie.plugin("library", (ctx) => { if (probing) go.classList.add("busy"); inp.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") find(); else if (e.key === "Escape" && probe) { probe = null; render(); } }; const g = glyph(GLYPH.search, "lib-mini"); - line.append(g, inp, go); + const mk = button(t("New skill"), "", () => newSkill()); + mk.dataset.lib = "new-skill"; + line.append(g, inp, go, mk); card.append(line); async function find() { const src = inp.value.trim(); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 3fd2963bb..5867fcbd7 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -2,6 +2,10 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "New skill": "新建技能", + "e.g. my-skill": "例如 my-skill", + "e.g. Writes release notes. Use when asked for a changelog.": "例如:撰写发布说明。需要更新日志时使用。", + "What it does and when to use it: the agent reads this to decide when to load it": "它做什么、何时使用:Agent 据此决定何时加载它", "This computer follows the server: what you change here is replaced by the next sync.": "这台电脑跟随服务器:你在这里的改动会被下一次同步替换。", "Sync settings": "同步设置", "Stop picking memories": "不再选择记忆", @@ -975,6 +979,10 @@ magpie.strings({ "{name} read again from its source": "已重新从来源读取 {name}", }, "zh-TW": { + "New skill": "新增技能", + "e.g. my-skill": "例如 my-skill", + "e.g. Writes release notes. Use when asked for a changelog.": "例如:撰寫發佈說明。需要更新日誌時使用。", + "What it does and when to use it: the agent reads this to decide when to load it": "它做什麼、何時使用:Agent 據此決定何時載入它", "This computer follows the server: what you change here is replaced by the next sync.": "這台電腦跟隨伺服器:你在這裡的變更會被下一次同步取代。", "Sync settings": "同步設定", "Stop picking memories": "不再選擇記憶", @@ -1948,6 +1956,10 @@ magpie.strings({ "{name} read again from its source": "已重新從來源讀取 {name}", }, ja: { + "New skill": "新しいスキル", + "e.g. my-skill": "例: my-skill", + "e.g. Writes release notes. Use when asked for a changelog.": "例: リリースノートを書く。変更履歴を求められたときに使う。", + "What it does and when to use it: the agent reads this to decide when to load it": "何をするか、いつ使うか。エージェントはこれを読んで読み込むかを決めます", "This computer follows the server: what you change here is replaced by the next sync.": "このコンピュータはサーバーに従います。ここでの変更は次の同期で置き換えられます。", "Sync settings": "同期の設定", "Stop picking memories": "メモリの選択を終える", @@ -2921,6 +2933,10 @@ magpie.strings({ "{name} read again from its source": "{name} をソースから読み直しました", }, de: { + "New skill": "Neuer Skill", + "e.g. my-skill": "z. B. my-skill", + "e.g. Writes release notes. Use when asked for a changelog.": "z. B. Schreibt Release Notes. Zu verwenden, wenn ein Changelog verlangt wird.", + "What it does and when to use it: the agent reads this to decide when to load it": "Was er tut und wann er gebraucht wird: Der Agent entscheidet danach, ob er ihn lädt", "This computer follows the server: what you change here is replaced by the next sync.": "Dieser Computer folgt dem Server: Änderungen hier werden bei der nächsten Synchronisierung ersetzt.", "Sync settings": "Sync-Einstellungen", "Stop picking memories": "Keine Erinnerungen mehr auswählen", diff --git a/internal/gui/library.go b/internal/gui/library.go index 90de5dcc0..8e19d6c63 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -604,11 +604,13 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { // Agents is named as the page sends it, so that it is this // and not the instructions' own Agents that "agents" fills Agents []string `json:"agents"` - Source string - Paths []string - Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents - Server library.Server - Hook library.Hook // a hook saved (#1790) + // Description is a new skill's (skills/create) + Description string `json:"description"` + Source string + Paths []string + Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents + Server library.Server + Hook library.Hook // a hook saved (#1790) // a subagent saved (#2283) Subagent library.Subagent Agent string // the agent whose own skill is in the library's way @@ -715,6 +717,8 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.RemoveSubagents([]string{in.Name}) case "skills/install": res, err = library.InstallSkills(in.Source, in.Paths, in.Agents) + case "skills/create": + res, err = library.CreateSkill(in.Name, in.Description, in.Agents) case "skills/update": res, err = library.UpdateSkill(in.Name, in.Replace) var gone *library.GoneError diff --git a/internal/gui/pageinline.go b/internal/gui/pageinline.go index c04798b0e..ae17f2ccc 100644 --- a/internal/gui/pageinline.go +++ b/internal/gui/pageinline.go @@ -94,9 +94,10 @@ func inlinePage(html []byte, dir string) (out []byte, hashes []string) { if !ok { return tag } - body = strings.ReplaceAll(body, "" + // the hash covers the exact text between the tags, the newline + // before included + s := "" + hash(strings.TrimSuffix(strings.TrimPrefix(s, "")) if attrDefer.MatchString(attrs) { deferred = append(deferred, s) return "" diff --git a/internal/gui/pluginpage_test.go b/internal/gui/pluginpage_test.go index 4ac5deaa6..95e305fe9 100644 --- a/internal/gui/pluginpage_test.go +++ b/internal/gui/pluginpage_test.go @@ -2,12 +2,15 @@ package gui import ( "context" + "crypto/sha256" + "encoding/base64" "encoding/json" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" + "regexp" "strings" "sync" "testing" @@ -456,6 +459,18 @@ func TestPluginPageWebComesAsOneDocument(t *testing.T) { if n := strings.Count(csp, "'sha256-"); n != 3 || !strings.Contains(csp, "data:") { t.Errorf("hashes of the three scripts: %s", csp) } + // each hash is the sha256 of the exact bytes between the tags, as served + inl := regexp.MustCompile(`(?s)`) + got := inl.FindAllStringSubmatch(body, -1) + if len(got) != 3 { + t.Fatalf("inline scripts: %d in %s", len(got), body) + } + for _, m := range got { + sum := sha256.Sum256([]byte(m[1])) + if h := "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"; !strings.Contains(csp, h) { + t.Errorf("served script %q has hash %s, not in the policy: %s", m[1], h, csp) + } + } // not in a browser (the desktop window): files as they are mux = http.NewServeMux() pluginPageRoutes(mux, false) diff --git a/internal/gui/tests/library-new-skill.test.cjs b/internal/gui/tests/library-new-skill.test.cjs new file mode 100644 index 000000000..83a78e43f --- /dev/null +++ b/internal/gui/tests/library-new-skill.test.cjs @@ -0,0 +1,93 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A skill made in the Library (josephBenchap on X): Skills > New skill takes +// a name and a description and the agents, posts library/skills/create, and +// opens the new skill in the reader. A refusal is said in the dialog and the +// dialog stays. No native select, no sideways scroll. English and Chinese, +// Chromium and WebKit, 1100 and 420px. The API is faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/emo"; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` }); +const lib = (skills) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("codex", "Codex"), agent("claude", "Claude Code")], + instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills, servers: [], +}); + +function server(lang, posts, state) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/library") return route.fulfill({ json: lib(state.skills) }); + if (url.pathname === "/api/library/skills/create") { + const b = req.postDataJSON(); + posts.push(b); + if (b.name === "taken") return route.fulfill({ status: 400, body: "there is a skill called taken already" }); + state.skills = [{ name: b.name, description: b.description, agents: b.agents }]; + return route.fulfill({ json: { ...lib(state.skills), result: { changed: b.agents, problems: [] } } }); + } + if (url.pathname === "/api/library/skill") return route.fulfill({ json: { text: `---\nname: ${url.searchParams.get("name")}\n---\n`, path: `${HOME}/.magpie/library/skills/${url.searchParams.get("name")}/SKILL.md` } }); + if (url.pathname === "/api/library/rtk") return route.fulfill({ json: {} }); + if (url.pathname === "/api/davsync") return route.fulfill({ json: { on: false } }); + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": Library makes a skill of the user's own", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { if (errors.length) console.log(errors); await browser.close(); }); + for (const lang of ["en", "zh"]) { + for (const width of [1100, 420]) { + await t.test(`${lang} ${width}`, async () => { + const ctx = await browser.newContext({ viewport: { width, height: 800 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + const posts = [], state = { skills: [] }; + await page.route("**/*", server(lang, posts, state)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const v = page.locator("#view-library"); + await v.locator("[data-lib=new-skill]").click(); + const dlg = page.locator(".lib-newskill"); + await dlg.waitFor(); + assert.equal(await dlg.locator("select").count(), 0, "native select"); + const sideways = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert(sideways <= 0, `page scrolls sideways by ${sideways}px`); + // a refusal stays in the dialog + await dlg.locator("input").first().fill("taken"); + await dlg.locator("textarea").fill("Does a thing"); + await dlg.locator("button.primary").click(); + await dlg.locator(".editor-error").filter({ hasText: "taken" }).waitFor(); + assert.equal(posts.length, 1); + // one agent unticked, then created + await dlg.locator("input").first().fill("my-skill"); + await dlg.locator(".lib-ag[data-agent=claude]").click(); + await dlg.locator("button.primary").click(); + await page.locator(".lib-reader").waitFor(); + assert.deepEqual(posts[1], { name: "my-skill", description: "Does a thing", agents: ["codex"] }); + await page.locator(".lib-reader .lib-md").filter({ hasText: "my-skill" }).waitFor(); + await ctx.close(); + }); + } + } + }); +} diff --git a/internal/gui/tests/plugin-page-csp-hash.test.cjs b/internal/gui/tests/plugin-page-csp-hash.test.cjs new file mode 100644 index 000000000..58e2e0596 --- /dev/null +++ b/internal/gui/tests/plugin-page-csp-hash.test.cjs @@ -0,0 +1,47 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A plugin page served to a browser comes as one document whose inline +// scripts are allowed by hash (pageinline.go). The hash is of the exact +// bytes between the tags, the newline before included; a hash of +// the body alone blocks the script and leaves the page blank (zhangly1 on X). +// pluginpage_test.go checks the hashes Go sends against the bytes it serves; +// this checks the browsers agree, with no violation, and that a hash of the +// body without the newline would have been blocked. +const assert = require("node:assert/strict"); +const crypto = require("node:crypto"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const tok = "d".repeat(32); +const sha = (s) => `'sha256-${crypto.createHash("sha256").update(s).digest("base64")}'`; +const body = "window.ran = 1;"; + +function serve(hash) { + return async (route) => { + const url = new URL(route.request().url()); + if (url.pathname !== `/_magpie/plugin/${tok}/index.html`) return route.fulfill({ status: 404, body: "" }); + const doc = `

page

`; + return route.fulfill({ headers: { "Content-Type": "text/html", "Content-Security-Policy": `sandbox allow-scripts; default-src 'none'; script-src ${hash}` }, body: doc }); + }; +} + +async function open(browser, hash) { + const p = await browser.newPage(); + p.setDefaultNavigationTimeout(60000); + await p.addInitScript(() => { window.violations = []; document.addEventListener("securitypolicyviolation", (e) => window.violations.push(e.violatedDirective)); }); + await p.route("**/*", serve(hash)); + await p.goto(`http://magpie.test/_magpie/plugin/${tok}/index.html`); + return p; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: a hash of the served bytes runs the page's script`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const ok = await open(browser, sha(body + "\n")); + assert.equal(await ok.evaluate(() => window.ran), 1); + assert.deepEqual(await ok.evaluate(() => window.violations), []); + // the old hash, of the body without the newline served after it + const bad = await open(browser, sha(body)); + assert.equal(await bad.evaluate(() => window.ran), undefined); + }); +} diff --git a/internal/gui/webview2.go b/internal/gui/webview2.go index b59d09ffe..832214849 100644 --- a/internal/gui/webview2.go +++ b/internal/gui/webview2.go @@ -2,8 +2,11 @@ package gui import ( "fmt" + "path/filepath" "slices" + "strconv" "strings" + "time" ) // magpie's windows are WebView2 on Windows, a runtime Windows 10 doesn't @@ -127,3 +130,80 @@ func splitArgs(s string) []string { } return out } + +// WebView2 that does not come up. A magpie started while the one before it +// is still going down finds the profile folder held by the old +// msedgewebview2, and Wails waits a minute for a controller that never +// arrives, then exits (@ljlwlcz on X, 0.1.3688: a restart by a script left +// no window). Two things answer it: the start waits for the folder to be +// free, and a start that still fails is tried again, a few times. + +// webView2TryEnv counts the starts that ended in a WebView2 failure; each +// relaunch passes it on. +const webView2TryEnv = "MAGPIE_WV2_TRY" + +// webView2Tries is how many starts are made before the failure is shown. +const webView2Tries = 3 + +// webView2Folder is the folder WebView2 keeps its profile in: the one magpie +// passes Wails (webViewUserDataPath), else Wails' own default, +// %AppData%\. +func webView2Folder(userDataPath, appData, exe string) string { + if userDataPath != "" { + return userDataPath + } + if appData == "" || exe == "" { + return "" + } + return filepath.Join(appData, filepath.Base(exe)) +} + +// webView2Failure says whether err is the webview not coming up, the +// errors Wails' Embed reports: the controller timeout and the loader's. +func webView2Failure(err error) bool { + if err == nil { + return false + } + m := strings.ToLower(err.Error()) + return strings.Contains(m, "webview2") +} + +// webView2Try is the number of starts already made, from the env value. +func webView2Try(v string) int { + n, err := strconv.Atoi(v) + if err != nil || n < 0 { + return 0 + } + return n +} + +// webView2Backoff is how long a start waits before the n-th try (n >= 1). +func webView2Backoff(n int) time.Duration { + return time.Duration(n) * 2 * time.Second +} + +// awaitWebView2Folder polls free until it says so or max passes, and says +// whether it was free. sleep is a var for tests. +func awaitWebView2Folder(free func() bool, max, step time.Duration, sleep func(time.Duration)) bool { + for waited := time.Duration(0); ; waited += step { + if free() { + return true + } + if waited >= max { + return false + } + sleep(step) + } +} + +// webView2FailedNotice is the box shown when the webview would not start +// after every try: what failed and what to do, in lang (English where it +// has none of its own). +func webView2FailedNotice(lang, reason, version string) (title, body string) { + if strings.HasPrefix(lang, "zh") { + return "magpie 的窗口没能打开", + fmt.Sprintf("WebView2 在 %d 次启动里都没有就绪(运行时 %s)。\r\n\r\n%s\r\n\r\n请结束残留的 msedgewebview2.exe 后重新打开 magpie;也可以用 \"magpie web\" 在浏览器里打开。详情见 magpie 的日志。", webView2Tries, version, reason) + } + return "magpie's window didn't open", + fmt.Sprintf("WebView2 was not ready in %d starts (runtime %s).\r\n\r\n%s\r\n\r\nEnd any leftover msedgewebview2.exe and open magpie again, or use \"magpie web\" in your browser. The details are in magpie's log.", webView2Tries, version, reason) +} diff --git a/internal/gui/webview2_lock_windows_test.go b/internal/gui/webview2_lock_windows_test.go new file mode 100644 index 000000000..a1096f55a --- /dev/null +++ b/internal/gui/webview2_lock_windows_test.go @@ -0,0 +1,35 @@ +//go:build windows && !nogui + +package gui + +import ( + "os" + "path/filepath" + "testing" + + "golang.org/x/sys/windows" +) + +// Chromium holds EBWebView\lockfile without sharing while its browser +// process runs; the start waits on it (@ljlwlcz on X). +func TestWebView2FreeSeesTheHeldLockfile(t *testing.T) { + dir := t.TempDir() + if !webView2Free(dir) { + t.Fatal("no lockfile is free") + } + lock := filepath.Join(dir, "EBWebView", "lockfile") + if err := os.MkdirAll(filepath.Dir(lock), 0o755); err != nil { + t.Fatal(err) + } + h, err := windows.CreateFile(windows.StringToUTF16Ptr(lock), windows.GENERIC_READ|windows.GENERIC_WRITE, 0, nil, windows.CREATE_ALWAYS, windows.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + t.Fatal(err) + } + if webView2Free(dir) { + t.Fatal("a lockfile held without sharing is free") + } + windows.CloseHandle(h) + if !webView2Free(dir) { + t.Fatal("a released lockfile is held") + } +} diff --git a/internal/gui/webview2_other.go b/internal/gui/webview2_other.go index 6fa846572..b888525e0 100644 --- a/internal/gui/webview2_other.go +++ b/internal/gui/webview2_other.go @@ -2,7 +2,17 @@ package gui -import "github.com/wailsapp/wails/v3/pkg/application" +import ( + "log" + + "github.com/wailsapp/wails/v3/pkg/application" +) // webView2Check: only Windows' windows are WebView2. func webView2Check(*application.App) bool { return true } + +// webView2Prepare: only Windows' windows are WebView2. +func webView2Prepare() {} + +// webView2Failed: Wails exits after this on every OS; say why. +func webView2Failed(_ *application.App, err error) { log.Println("magpie:", err) } diff --git a/internal/gui/webview2_test.go b/internal/gui/webview2_test.go index d6a9227d5..dc271d8dd 100644 --- a/internal/gui/webview2_test.go +++ b/internal/gui/webview2_test.go @@ -1,8 +1,10 @@ package gui import ( + "errors" "strings" "testing" + "time" ) // #1806 (ufec): Wails' "WebView2" is "" when its lookup fails, the version @@ -55,3 +57,46 @@ func TestWebView2Notice(t *testing.T) { t.Errorf("pt: %q, want English", title) } } + +func TestWebView2Folder(t *testing.T) { + if got := webView2Folder(`D:\p\webview2`, `C:\A`, `C:\x\magpie.exe`); got != `D:\p\webview2` { + t.Fatal(got) + } + if got := webView2Folder("", "", "magpie.exe"); got != "" { + t.Fatal(got) + } +} + +func TestWebView2Failure(t *testing.T) { + for err, want := range map[error]bool{ + errors.New("timed out after 1m0s waiting for the WebView2 controller; x"): true, + errors.New("error calling Webview2Loader: boom"): true, + errors.New("something else"): false, + nil: false, + } { + if got := webView2Failure(err); got != want { + t.Errorf("%v: %t", err, got) + } + } +} + +func TestWebView2Try(t *testing.T) { + if webView2Try("") != 0 || webView2Try("2") != 2 || webView2Try("-1") != 0 || webView2Try("x") != 0 { + t.Fatal("try") + } +} + +// the start waits for the folder to be let go, and gives up after max +func TestAwaitWebView2Folder(t *testing.T) { + n := 0 + var slept time.Duration + free := func() bool { n++; return n > 3 } + sleep := func(d time.Duration) { slept += d } + if !awaitWebView2Folder(free, time.Second, 100*time.Millisecond, sleep) || slept != 300*time.Millisecond { + t.Fatal(n, slept) + } + slept = 0 + if awaitWebView2Folder(func() bool { return false }, time.Second, 100*time.Millisecond, sleep) || slept != time.Second { + t.Fatal(slept) + } +} diff --git a/internal/gui/webview2_windows.go b/internal/gui/webview2_windows.go index e4dac4bcb..651438c18 100644 --- a/internal/gui/webview2_windows.go +++ b/internal/gui/webview2_windows.go @@ -3,11 +3,18 @@ package gui import ( + "errors" + "fmt" "log" + "os" + "path/filepath" + "time" "unsafe" "github.com/wailsapp/wails/v3/pkg/application" + "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/update" "golang.org/x/sys/windows" ) @@ -50,3 +57,73 @@ func webView2Box(title, body string) int { webView2BoxStyle) return int(r) } + +// webView2Dir is the profile folder WebView2 will use. +func webView2Dir() string { + exe, _ := os.Executable() + return webView2Folder(appdir.WebView(), os.Getenv("AppData"), exe) +} + +// webView2Free says whether no other process holds the profile folder. +// Chromium keeps EBWebView\lockfile open without sharing while its browser +// process runs, so opening it fails with a sharing violation until the +// previous magpie's msedgewebview2 has gone. +func webView2Free(dir string) bool { + if dir == "" { + return true + } + f, err := os.OpenFile(filepath.Join(dir, "EBWebView", "lockfile"), os.O_RDWR, 0) + if err != nil { + return !errors.Is(err, windows.ERROR_SHARING_VIOLATION) && !errors.Is(err, windows.ERROR_ACCESS_DENIED) + } + f.Close() + return true +} + +// webView2Prepare runs before the first window. A start after a failed +// one backs off first; then it waits, up to 30s, for the previous +// process' WebView2 to let go of the profile folder. +func webView2Prepare() { + try := webView2Try(os.Getenv(webView2TryEnv)) + if try > 0 { + log.Printf("magpie: WebView2 start %d of %d, after a failure", try+1, webView2Tries) + time.Sleep(webView2Backoff(try)) + } + dir := webView2Dir() + start := time.Now() + if !awaitWebView2Folder(func() bool { return webView2Free(dir) }, 30*time.Second, 250*time.Millisecond, time.Sleep) { + log.Printf("magpie: WebView2 folder %s is still held by another process after 30s; going on", dir) + } else if d := time.Since(start); d > time.Second { + log.Printf("magpie: waited %s for WebView2 folder %s to be free", d.Round(100*time.Millisecond), dir) + } +} + +// webView2Failed is Wails' ErrorHandler; Wails exits as soon as it +// returns. It logs the error with what is needed to read it, and for a +// WebView2 failure starts magpie again (up to webView2Tries starts), the +// last failure shown in a box with the log's place. +func webView2Failed(app *application.App, err error) { + dir := webView2Dir() + ver := "unknown" + if app != nil { + ver = fmt.Sprint(app.Env.Info().PlatformInfo["WebView2"]) + } + log.Printf("magpie: %v (WebView2 runtime %q, profile folder %s, held by another process: %t)", err, ver, dir, !webView2Free(dir)) + if !webView2Failure(err) { + return + } + try := webView2Try(os.Getenv(webView2TryEnv)) + 1 + if try < webView2Tries { + log.Printf("magpie: starting again (start %d of %d)", try+1, webView2Tries) + if rerr := update.Respawn(fmt.Sprintf("%s=%d", webView2TryEnv, try)); rerr != nil { + log.Println("magpie: starting again:", rerr) + } else { + return + } + } + title, body := webView2FailedNotice(trayLang(settings.Load().Lang, systemLang), err.Error(), ver) + procMessageBoxW.Call(0, + uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(body))), + uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(title))), + mbIconError|mbSetForeground|mbTopmost) +} diff --git a/internal/library/create_skill_test.go b/internal/library/create_skill_test.go new file mode 100644 index 000000000..1e04565d9 --- /dev/null +++ b/internal/library/create_skill_test.go @@ -0,0 +1,44 @@ +package library + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// A skill made in the Library (josephBenchap on X): SKILL.md with valid +// front matter in the library's folder, given to the agents picked, and a +// name that clashes or isn't folder-safe is refused. +func TestCreateSkill(t *testing.T) { + h := sandbox(t) + ok(t)(CreateSkill("my-skill", "Does: a thing\nacross lines", []string{"claude", "codex"})) + b, err := os.ReadFile(filepath.Join(skillDir("my-skill"), "SKILL.md")) + if err != nil { + t.Fatal(err) + } + m := parseMeta(b) + if m.Name != "my-skill" || m.Description != "Does: a thing across lines" { + t.Errorf("front matter: %+v\\n%s", m, b) + } + for _, d := range []string{".claude/skills/my-skill", ".codex/skills/my-skill"} { + if _, err := os.Stat(filepath.Join(h, d, "SKILL.md")); err != nil { + t.Errorf("not given to %s: %v", d, err) + } + } + v, _ := Read(nil) + if len(v.Skills) != 1 || v.Skills[0].Name != "my-skill" { + t.Errorf("listed: %+v", v.Skills) + } + skill(t, filepath.Join(h, ".claude/skills/theirs"), "theirs", "An agent's own") + for _, c := range [][2]string{ + {"My-Skill", "d"}, {"theirs", "d"}, {"../x", "d"}, {"a/b", "d"}, {"", "d"}, {"fine", " "}, {"fine", strings.Repeat("x", 1025)}, + } { + if _, err := CreateSkill(c[0], c[1], nil); err == nil { + t.Errorf("%q / %.10q was taken", c[0], c[1]) + } + } + if _, err := os.Lstat(skillDir("fine")); err == nil { + t.Error("a refused skill left a folder") + } +} diff --git a/internal/library/skills.go b/internal/library/skills.go index dd882ae69..de352a178 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -1731,6 +1731,53 @@ func (l *Library) offered(p *Probe, path string, shown bool) { } } +// CreateSkill makes a skill of the user's own in the library's folder: a +// SKILL.md with a name and description in its front matter, listed with no +// source and given to the agents like any other. The name can't be one the +// library has, one an agent has of its own, or a folder in the way. +func CreateSkill(name, description string, agents []string) (*Result, error) { + name = strings.TrimSpace(name) + if err := checkName("skill", name); err != nil { + return nil, err + } + description = strings.Join(strings.Fields(description), " ") + if description == "" { + return nil, errors.New("a skill needs a description: it is how an agent knows when to load it") + } + if len([]rune(description)) > 1024 { + return nil, errors.New("the description is over 1024 characters") + } + return change(func(l *Library) error { + same := func(n string) bool { return strings.EqualFold(n, name) } + if slices.ContainsFunc(l.Skills, func(s *Skill) bool { return same(s.Name) }) || + slices.ContainsFunc(foundSkills(l), func(f FoundSkill) bool { return same(f.Name) }) { + return fmt.Errorf("there is a skill called %s already", name) + } + dir := skillDir(name) + if _, err := os.Lstat(dir); err == nil { + return fmt.Errorf("the library's folder already has a %s in it (%s)", name, dir) + } else if !errors.Is(err, fs.ErrNotExist) { + return err + } + head, err := yaml.Marshal(meta{Name: name, Description: description}) + if err != nil { + return err + } + text := "---\n" + string(head) + "---\n\n# " + name + "\n\nWrite what the agent should do when this skill is used.\n" + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(text), 0o644); err != nil { + os.RemoveAll(dir) + return err + } + ag := slices.Clone(agents) + slices.Sort(ag) + l.Skills = append(l.Skills, &Skill{Name: name, Agents: slices.Compact(ag)}) + return nil + }) +} + // UpdateSkill fetches a skill from GitHub again, in place: the agents' // links go on pointing at it. One changed here since it was fetched is // an *EditedError unless replace is set, and then the changed version is diff --git a/internal/provider/opencode_endpoints.go b/internal/provider/opencode_endpoints.go index 3e65c6a2d..1c61bcb6e 100644 --- a/internal/provider/opencode_endpoints.go +++ b/internal/provider/opencode_endpoints.go @@ -3,6 +3,7 @@ package provider import ( "cmp" "net/url" + "slices" "strings" ) @@ -20,7 +21,16 @@ func openCodeRoot(base string) (root, catalogID string) { if !openCodeHost(u.Hostname()) { return "", "" } - switch path := strings.TrimSuffix(strings.TrimRight(u.Path, "/"), "/v1"); path { + path := strings.TrimRight(u.Path, "/") + if r, ok := strings.CutSuffix(path, "/google/v1beta"); ok { + path = r + } else { + path = strings.TrimSuffix(path, "/v1") + for _, api := range []string{"/openai", "/anthropic", "/google"} { + path = strings.TrimSuffix(path, api) + } + } + switch path { case "/zen/go", "/inference/go": return u.Scheme + "://" + u.Host + path, "opencode-go" case "/zen", "/inference": @@ -63,15 +73,54 @@ func openCodeGateway(base string) string { // root is: models/{model}:streamGenerateContent is asked under it. Zen's // /zen/v1 relays it to the inference API's Google route, reading the key // from x-goog-api-key; Go's /zen/go/v1 has no such route (404), so Go's -// Gemini models are asked at the inference API's /inference/go/v1, where -// Go's docs give their endpoint (opencode.ai/v2/docs/console/go, #2168). +// Gemini models are asked at the inference API, where Go's docs give +// their endpoint: /inference/go/google/v1beta/models/{model} (since +// November 2026; before it /inference/go/v1, #2168). func openCodeGemini(root string) string { if r, ok := strings.CutSuffix(root, "/zen/go"); ok { - return r + "/inference/go/v1" + return r + "/inference/go/google/v1beta" + } + if strings.HasSuffix(root, "/inference/go") { + return root + "/google/v1beta" } return root + "/v1" } +// openCodeGoSplit is whether a Go URL names its API in the path, the way +// Go's docs give them since November 2026: …/inference/go/openai/v1 (chat +// and Responses), …/inference/go/anthropic (Messages) and +// …/inference/go/google/v1beta (Gemini). +func openCodeGoSplit(u string) bool { + pu, err := url.Parse(strings.TrimSpace(u)) + if err != nil || openCodeGateway(u) != "go" { + return false + } + for _, seg := range strings.Split(pu.Path, "/") { + if seg == "openai" || seg == "anthropic" || seg == "google" { + return true + } + } + return false +} + +// openCodeGoOld are the URLs the OpenCode Go preset gave before Go's docs +// named an endpoint per API; a provider of the preset saved with them is +// moved to where the docs have them (openCodeEndpoints). +var openCodeGoOld = map[string]bool{ + "https://opencode.ai/zen/go/v1": true, + "https://opencode.ai/zen/go": true, + "https://opencode.ai/inference/go/v1": true, + "https://opencode.ai/inference/go": true, +} + +// OpenCodeGo are the URLs Go's docs give each API (opencode.ai/docs/console/go, +// Endpoints). +const ( + OpenCodeGoChat = "https://opencode.ai/inference/go/openai/v1" + OpenCodeGoAnthropic = "https://opencode.ai/inference/go/anthropic" + OpenCodeGoGemini = "https://opencode.ai/inference/go/google/v1beta" +) + // openCodeEndpoints fills in the APIs of OpenCode's gateway a provider at // it was saved without. Zen and Go serve each model on one API of three, // all under one root — chat completions and Responses at /v1, Anthropic's @@ -96,9 +145,31 @@ func (p *Provider) openCodeEndpoints() { if root == "" { return } - p.Chat = cmp.Or(p.Chat, root+"/v1") - p.Responses = cmp.Or(p.Responses, root+"/v1") - p.Anthropic = cmp.Or(p.Anthropic, root) + chat, anthropic := root+"/v1", root + if strings.HasSuffix(root, "/inference/go") && slices.ContainsFunc([]string{p.Chat, p.Responses, p.Anthropic, p.Gemini}, openCodeGoSplit) { + chat, anthropic = root+"/openai/v1", root+"/anthropic" + } + if p.Preset == "opencode-go" { + // the preset's own URLs, saved before Go's docs named one per API + for _, f := range []struct { + have *string + to string + }{{&p.Chat, OpenCodeGoChat}, {&p.Responses, OpenCodeGoChat}, {&p.Anthropic, OpenCodeGoAnthropic}} { + if openCodeGoOld[strings.ToLower(*f.have)] { + *f.have = f.to + } + } + if strings.EqualFold(p.Gemini, "https://opencode.ai/inference/go/v1") { + p.Gemini = OpenCodeGoGemini + } + root, catalogID = openCodeRoot(cmp.Or(p.Chat, p.Responses, p.Anthropic, p.Gemini)) + if strings.HasSuffix(root, "/inference/go") { + chat, anthropic = root+"/openai/v1", root+"/anthropic" + } + } + p.Chat = cmp.Or(p.Chat, chat) + p.Responses = cmp.Or(p.Responses, chat) + p.Anthropic = cmp.Or(p.Anthropic, anthropic) p.Gemini = cmp.Or(p.Gemini, openCodeGemini(root)) p.Catalog = cmp.Or(p.Catalog, catalogID) } diff --git a/internal/provider/opencode_endpoints_test.go b/internal/provider/opencode_endpoints_test.go index da18d4cc4..cbf4167ea 100644 --- a/internal/provider/opencode_endpoints_test.go +++ b/internal/provider/opencode_endpoints_test.go @@ -51,14 +51,21 @@ func TestOpenCodeEndpointsFilledIn(t *testing.T) { apis map[string]Protocol // "" for none named }{ {"go, chat alone", Provider{ID: "opencode-go", Chat: zg + "/v1"}, - zg + "/v1", zg + "/v1", zg, igo + "/v1", "opencode-go", + zg + "/v1", zg + "/v1", zg, igo + "/google/v1beta", "opencode-go", map[string]Protocol{"gpt-6-luna": Responses, "minimax-m2.7": Anthropic, "gemini-4-argon-contributor": Gemini, "glm-5.3": ""}}, {"go, anthropic alone with /v1", Provider{ID: "ocgo", Anthropic: zg + "/v1"}, - zg + "/v1", zg + "/v1", zg, igo + "/v1", "opencode-go", + zg + "/v1", zg + "/v1", zg, igo + "/google/v1beta", "opencode-go", map[string]Protocol{"gpt-6-luna": Responses}}, {"go at the inference API", Provider{ID: "ocgo", Chat: igo + "/v1"}, - igo + "/v1", igo + "/v1", igo, igo + "/v1", "opencode-go", + igo + "/v1", igo + "/v1", igo, igo + "/google/v1beta", "opencode-go", map[string]Protocol{"gemini-4-argon-contributor": Gemini, "glm-5.3": ""}}, + {"go at the per-API URLs the docs give", Provider{ID: "ocgo", Chat: igo + "/openai/v1"}, + igo + "/openai/v1", igo + "/openai/v1", igo + "/anthropic", igo + "/google/v1beta", "opencode-go", + map[string]Protocol{"gemini-4-argon-contributor": Gemini, "gpt-6-luna": Responses}}, + {"go, gemini url alone", Provider{ID: "ocgo", Gemini: igo + "/google/v1beta"}, + igo + "/openai/v1", igo + "/openai/v1", igo + "/anthropic", igo + "/google/v1beta", "opencode-go", nil}, + {"the go preset saved with its old URLs", Provider{ID: "opencode-go", Preset: "opencode-go", Chat: zg + "/v1", Responses: zg + "/v1", Anthropic: zg}, + igo + "/openai/v1", igo + "/openai/v1", igo + "/anthropic", igo + "/google/v1beta", "opencode-go", nil}, {"zen saved with go's catalog", Provider{ID: "opencode-go", Catalog: "opencode-go", Chat: zen + "/v1"}, zen + "/v1", zen + "/v1", zen, zen + "/v1", "opencode-go", map[string]Protocol{"claude-opus-5": Anthropic, "gemini-3-flash": Gemini, "minimax-m2.7": ""}}, diff --git a/internal/provider/presets.go b/internal/provider/presets.go index dc00cea50..17cf4468e 100644 --- a/internal/provider/presets.go +++ b/internal/provider/presets.go @@ -564,7 +564,7 @@ var presets = []PresetDef{ Chat: "https://api.gmi-serving.com/v1", Website: "https://www.gmicloud.ai", KeysURL: "https://console.gmicloud.ai"}, {ID: "opencode-go", Name: "OpenCode Go", Icon: "opencode", Kind: KindRelay, Catalog: "opencode-go", - Chat: "https://opencode.ai/zen/go/v1", Responses: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go", + Chat: OpenCodeGoChat, Responses: OpenCodeGoChat, Anthropic: OpenCodeGoAnthropic, Note: "open coding models, $10/month", Website: "https://opencode.ai/docs/go", KeysURL: "https://opencode.ai/auth"}, // Cline's plan for open models, at the Cline API with a Cline key: the diff --git a/internal/provider/remote_quotas_scope.go b/internal/provider/remote_quotas_scope.go index b0f0e8b3a..7976edda0 100644 --- a/internal/provider/remote_quotas_scope.go +++ b/internal/provider/remote_quotas_scope.go @@ -15,9 +15,10 @@ import ( // the same account at different hours). // // - A card is shown for a Remote only when the Remote is enabled for a -// model of the provider the card is of (remoteCardWanted): the first -// part of the card's id is the first part of those models' ids -// (provider/model, as that remote lists them). +// model of the provider the card is of (remoteCardWanted): the +// card's id is the provider path of one of those models' ids, or a +// parent of it, whole parts only (provider/model, as that remote lists +// them; relay/strata enabled does not tell relay/kiro). // - A card whose way names a magpie twice, or this one and another, is // no card (catalog.Loops): it isn't kept (keepRemoteCards) nor told. // - One account's copies are one card, the newest complete reading @@ -35,18 +36,37 @@ func remoteCardWanted(p Provider) func(id string) bool { if len(ms) == 0 { return func(string) bool { return true } } - heads := map[string]bool{} - for _, m := range ms { - head, _, ok := strings.Cut(m.ID, "/") - if !ok { + ids := make([]string, len(ms)) + for i, m := range ms { + ids[i] = m.ID + } + return cardWantedFor(ids) +} + +// cardWantedFor is remoteCardWanted for the enabled model ids as the remote +// lists them: a model's provider path is its id less the last part +// ("relay/strata/m" is of relay/strata). A card is wanted when its id is +// such a path or one of its parents, whole parts only: relay/strata +// enabled tells relay/strata and relay, never relay/kiro or relay/strat. +// A model with no provider before its name leaves it unknown, so wanted. +func cardWantedFor(ids []string) func(id string) bool { + paths := map[string]bool{} + for _, mid := range ids { + i := strings.LastIndex(mid, "/") + if i <= 0 { return func(string) bool { return true } } - heads[head] = true - } - return func(id string) bool { - head, _, _ := strings.Cut(id, "/") - return heads[head] + path := mid[:i] + for { + paths[path] = true + j := strings.LastIndex(path, "/") + if j < 0 { + break + } + path = path[:j] + } } + return func(id string) bool { return paths[id] } } // withoutLoops is cards less those whose way comes back to this magpie. diff --git a/internal/provider/remote_quotas_test.go b/internal/provider/remote_quotas_test.go index e5710611d..80e617b32 100644 --- a/internal/provider/remote_quotas_test.go +++ b/internal/provider/remote_quotas_test.go @@ -668,3 +668,36 @@ func TestRemoteCardsFollowEnabledModelsAndDedupe(t *testing.T) { } } } + +// @748975219 on X (0.1.3771): with only relay/strata/model enabled, the +// cards of relay/kiro and relay/codex still passed, as only the first part +// of the card's id was compared. +func TestRemoteCardWantedByWholePath(t *testing.T) { + cases := []struct { + name string + ids []string + yes []string + no []string + }{ + {"two levels", []string{"relay/strata/m"}, []string{"relay/strata", "relay"}, []string{"relay/kiro", "relay/codex", "kiro", "relay/strata/x"}}, + {"three levels", []string{"a/b/c/m"}, []string{"a/b/c", "a/b", "a"}, []string{"a/b/d", "a/x", "a/b/c/d", "b"}}, + {"not at a boundary", []string{"relay/kiro/m"}, []string{"relay/kiro"}, []string{"relay/kir", "relay/kiro2", "relay/kiroo", "rel"}}, + {"prefix of the other way", []string{"relay/kir/m"}, []string{"relay/kir"}, []string{"relay/kiro"}}, + {"several", []string{"relay/strata/m", "relay/kiro/n"}, []string{"relay/strata", "relay/kiro"}, []string{"relay/codex"}}, + {"one level", []string{"kiro/m"}, []string{"kiro"}, []string{"codex", "kiro/x"}}, + {"unknown provider", []string{"m"}, []string{"anything", "a/b"}, nil}, + } + for _, c := range cases { + w := cardWantedFor(c.ids) + for _, id := range c.yes { + if !w(id) { + t.Errorf("%s: %v should tell %q", c.name, c.ids, id) + } + } + for _, id := range c.no { + if w(id) { + t.Errorf("%s: %v should not tell %q", c.name, c.ids, id) + } + } + } +} diff --git a/internal/update/blocked.go b/internal/update/blocked.go index 345570bb9..20962d9eb 100644 --- a/internal/update/blocked.go +++ b/internal/update/blocked.go @@ -216,3 +216,16 @@ func ReadBlocked(current string) *Blocked { // ClearBlocked forgets the note: the version started after all. func ClearBlocked() { os.Remove(blockedFile()) } + +// Respawn starts this program again with the arguments it was started +// with and extra (NAME=value) added to its environment, detached. The new +// process waits for this one to exit, as a relaunch does (AwaitPredecessor). +func Respawn(extra ...string) error { + exe, err := os.Executable() + if err != nil { + return err + } + env := append(os.Environ(), "MAGPIE_REPLACES="+strconv.Itoa(os.Getpid())) + _, _, err = launch(exe, os.Args[1:], append(env, extra...)) + return err +}