Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
library: skills install from any git repository, GitLab and a company's own among them (sunset on Discord)
yetone9fd80b2128a2
diff --git a/docs/subsystems/library.md b/docs/subsystems/library.mdindex 93632e6bf..ce474ca27 100644--- a/docs/subsystems/library.md+++ b/docs/subsystems/library.md@@ -20,11 +20,11 @@ agents RTK, a CLI that cuts shell output down before the model reads it.| Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid and Cline. A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away, and what it made is listed in the project's `.gitignore`. | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go) || Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). A set can be kept in a file of the user's own instead of `instruction-sets/` (`InstrSet.File`, 新v学员 on Discord): `~/.agents/AGENTS.md`, which Droid and omp read too. `textPath` reads it, `putText` keeps it aside and writes it but never removes it, removing the set lets go of it, and `linkable` refuses a file magpie writes into (an agent's own instructions, a file with the marker line), the library's own and another set's. The app's `KeepLinked` looks at the file every 30 s and writes a change into the agents (`SyncLinked`). A set's text is read without magpie's part (`setText`), and an agent whose instructions file is, links followed, the file the set on is kept in (`isSetFile`: `instructions.md` linked to `~/.claude/CLAUDE.md`, or both linked to one dotfile) gets no part written into it, and one written before is taken out with every part nested in it: read with its part, each sync wrote the whole file into that part again and it doubled, to gigabytes (#2349, `TestInstructionsSetLinkedToAgentsFile`). `Collect` carries the set's text, not where its file is; `Put` keeps this computer's file for the set and never empties it for a text not carried. Alma's file is `~/.config/alma/USER.md`, which its main chat reads into its system prompt as its owner's profile (0.4.164's `out/main/index.js`; a workspace's `USER.md` is read instead), and whose leading front matter (`name`, `telegram_id`, `discord_id`) is who its bots answer to (#2315, Jie211). The target is a `Profile`: magpie's part goes after the user's, so the front matter stays first, and `ImportInstructions` refuses it, as moving it out would take that front matter out of the file and into every agent's (`TestAlmaInstructionsKeepTheProfile`, `TestAlmaProfileIsNotImported`, `library-alma-profile.test.cjs`). | [`instructions.go`](../../internal/library/instructions.go) || MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/<name>`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/<name>` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:<port>/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) |-| Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. 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`), 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), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go) |+| Skills | A skill is a folder with a `SKILL.md`. 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/<ref>/<path>`, `/-/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 -- <url> <ref>` 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 always gets a copy. 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`), 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) || Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`) go first, marked official: `magpie-quota`, in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills/magpie-quota), lets an agent read `magpie quota --json` and wait with `magpie quota wait`. 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 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}`). | [`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. 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) |-| Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`, or `$XDG_STATE_HOME/skills/.skill-lock.json` when that is set, both read with the XDG one winning) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skills.go`](../../internal/library/skills.go) |+| Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`, or `$XDG_STATE_HOME/skills/.skill-lock.json` when that is set, both read with the XDG one winning) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. A skill from another git repository (`kind: git`) keeps the repository's head commit it was fetched at in `Commit`, and `Hash`. A check runs `git ls-remote` for the ref (`gitRemoteHead`): the same head is current; another one is fetched shallowly, once per repository and ref in a check, and the skill's folder hashed, so a commit that left the skill as it was is current and its head is kept as `Commit` (`checkGitSkill`). Its `*EditedError` and the page's Changed here, Update and the question before replacing a change name that repository, not GitHub (`editedError`, `skill-git-source.test.cjs`). New skills in such a repository (`findNew`), Group again, icons and the market are GitHub's only. | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skills.go`](../../internal/library/skills.go) || Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `<claude dir>/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.<Event>]]` array tables with a `[[hooks.<Event>.hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:<Event>` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) || Subagents | A `Subagent` (#2283) is a name (lowercase letters, digits and -), a one-line description, a prompt, and the library's skills and MCP servers it uses, given to the agents ticked for it. `syncSubagents` writes it as a file of its own in each agent's user-level folder, in that agent's format (`subagentSpecOf`): Markdown with YAML front matter in `~/.claude/agents` (with `skills` and `mcpServers`), `~/.factory/droids` (with `mcpServers`), `~/.config/opencode/agents` (`mode: subagent`), `~/.gemini/agents`, `~/.qwen/agents`, `~/.grok/agents`, `~/.cursor/agents` and `~/.copilot/agents` (`<name>.agent.md`); a TOML role (`name`, `description`, `developer_instructions`) in `$CODEX_HOME/agents`. Skills and servers are named only where the agent's file can name them, and only those the library has. The page lists, per agent, whether it binds skills and servers (`SubagentAgentView`) and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) || Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) |@@ -41,7 +41,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.- magpie takes away only what `Applied` or its mark says it wrote. A folder of the user's with a skill's name is never touched. The user's own fields in an MCP entry are kept.- An edit never silently loses. When an agent's copy of a skill and the library both changed, the newest edit wins, and the losing one is kept with the backups.-- An update from GitHub never silently replaces a skill changed here. It is refused, or skipped in an update of several, until the user says to replace it, and the version replaced goes to the backups.+- An update from GitHub or a git repository never silently replaces a skill changed here. It is refused, or skipped in an update of several, until the user says to replace it, and the version replaced goes to the backups.- A copy's mark establishes that it is unchanged only after its whole folder was scanned. If a subtree or its metadata can't be read, the copy stays in place and the sync reports a `Problem`; it isn't replaced, relinked or removed. A later sync tries again once it can be read. The same scan failure stops replacing a project's or Claude Desktop's copy.- A failure for one agent is a `Problem` in the result. It doesn't stop the others.- An MCP OAuth sign-in canceled or timed out before its callback commits never saves a late token or changes an existing sign-in. The callback's write and the flow's ending share a lock (`flow.keep` in [`mcpauth.go`](../../internal/mcpauth/mcpauth.go)); if the write wins first, it completes and tells the agents before saying done. A cancellation is not a sign-out of credentials already committed.@@ -75,10 +75,10 @@ agents RTK, a CLI that cuts shell output down before the model reads it.## Verification```sh-go test -tags nogui ./internal/library -run 'TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckSaysSignInRanOut|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut'+go test -tags nogui ./internal/library -run 'TestGit|TestInstallFromGitRepo|TestReadLooksAtEachFolderOnce|TestLinkChangedBetweenVisitsShows|TestUnreadablePartIsLookedAtAgain|TestCheckSkillsFindsNewOnes|TestNewBase|TestUpdateKeeps|TestCheckDue|TestCheckSkillsMarksItDone|TestTargets|TestServer|TestImportServer|TestCheck|TestInstructions|TestInstructionsSetLinkedToAgentsFile|TestInstructionSets|TestTakesAlma|TestAlma|TestLinkedSet|TestLinkRefused|TestSkill|TestRemoveFoundSkill|TestInstallSet|TestInstallLists|TestEverySkillAgents|TestEveryServerAgents|TestSomeServersAgents|TestRemoveServers|TestRTK|TestEnvRefs|TestDshRefRoundTrip|TestDshImportKeepsJS|TestAgentMCPFiles|TestCodeBuddyMCPFile|TestZedMCP|TestOwnServerFromElsewhereRunsThisMagpie|TestUsersOwnServerStaysAsItIs|TestCarriedOwnServerIsEachComputersMagpie|TestCarry|TestPageReadDoesntReadUnchangedSkillsAgain|TestJustWrittenSkillIsReadAgain|TestUnreadableSkillIsntRememberedAsDifferent|TestGlanceLeavesOutTheAgentsSkills|TestPluginAgent|TestPluginMCPFormatsAreWritten|TestToolsOff|TestOffList|TestHooks|TestSubagent|TestCheckRenewsMagpiesSignIn|TestCheckSaysSignInRanOut|TestSignInAsTheUsersOwnApp|TestOAuthAppChecked|TestOAuthAppSecretCarried|TestGoneAgentListedToTakeOut'go test -race ./internal/mcpauthgo test -tags nogui ./internal/library-node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs+node --test internal/gui/tests/library-items.test.cjs internal/gui/tests/library-alma-profile.test.cjs internal/gui/tests/library-rtk-gain.test.cjs internal/gui/tests/library-rtk-nohook.test.cjs internal/gui/tests/library-servers-bulk.test.cjs internal/gui/tests/library-pick-remove.test.cjs internal/gui/tests/library-env-refs.test.cjs internal/gui/tests/library-zed-mcp.test.cjs internal/gui/tests/library-workbuddy-trust.test.cjs internal/gui/tests/skill-new-in-repo.test.cjs internal/gui/tests/skill-update-edited.test.cjs internal/gui/tests/skill-git-source.test.cjs internal/gui/tests/remove-found-skill.test.cjs internal/gui/tests/found-skill-pick-remove.test.cjs internal/gui/tests/library-loading.test.cjs internal/gui/tests/library-mcp-tools.test.cjs internal/gui/tests/library-mcp-tool-switch.test.cjs internal/gui/tests/library-hooks.test.cjs internal/gui/tests/library-subagents.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/mcp-signin-health.test.cjs internal/gui/tests/mcp-signin.test.cjs internal/gui/tests/mcp-editor-cancel.test.cjs internal/gui/tests/mcp-oauth-app.test.cjs internal/gui/tests/library-ime-scroll.test.cjs```The package's `TestMain` runs in a home of its own (`testenv`), never thediff --git a/internal/agent/agentenv_test.go b/internal/agent/agentenv_test.goindex 0c6e4e3f5..6c16903c5 100644--- a/internal/agent/agentenv_test.go+++ b/internal/agent/agentenv_test.go@@ -35,6 +35,8 @@ var notAnAgent = map[string]string{"MAGPIE_SITE_ORIGIN": "a site origin magpie's Omarchy theme answers, to try the site locally","MAGPIE_PARTNERS": "where magpie's own partner list is read from (a URL, or off), not a folder","CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "Claude Code's behaviour flag, not an agent's folder",+ "GIT_SSH": "the user's own SSH program for git, which a skill fetched with their git keeps",+ "GIT_SSH_COMMAND": "the same, as a command",}// TestFolderVarsAreListed says every variable the packages that find andiff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.goindex 33d261f04..beee87327 100644--- a/internal/cli/library_cli.go+++ b/internal/cli/library_cli.go@@ -139,7 +139,7 @@ func libraryCmd(args []string) error {if res, err = library.UpdateSkill(rest[1], len(rest) == 3); err == nil {fmt.Println(green.Render("✓"), rest[1], "is up to date")} else if errors.As(err, &edited) {- err = fmt.Errorf("%w\n magpie library skill update %s --replace-edits takes GitHub's in its place, keeping yours with the backups", err, rest[1])+ err = fmt.Errorf("%w\n magpie library skill update %s --replace-edits takes the fetched one in its place, keeping yours with the backups", err, rest[1])}case len(rest) == 1 && rest[0] == "update":res, err = library.UpdateSkills()diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.jsindex b463f05f2..12524fc19 100644--- a/internal/gui/assets/plugins/library/client.js+++ b/internal/gui/assets/plugins/library/client.js@@ -2640,7 +2640,7 @@ magpie.plugin("library", (ctx) => {rh.append(el("span", "label", t("In the library")));const box = el("div", "lib-groups");if (lib.skills.length > 8) rh.append(skillFilter(box, all));- const fresh = lib.skills.filter((s) => s.kind === "github" || s.origin);+ const fresh = lib.skills.filter((s) => s.kind === "github" || s.kind === "git" || s.origin);rh.append(el("span", "grow"));if (lib.skills.length > 1) rh.append(sortBy("libSkills", SKILL_SORTS(), () => { if (box.isConnected) drawSkills(box, all); }));if (lib.skills.length > 1) rh.append(foldAllButton(box, all));@@ -2656,9 +2656,11 @@ magpie.plugin("library", (ctx) => {if (lib.skills.length > 1 && all.length) rh.append(pickButton("skills"), ...everyButtons("skills", all));if (byAgentRows("skills").length) rh.append(byAgentButton("skills"));if (lib.skills.length > 1) rh.append(removeEveryButton("skills"));- if (lib.skills.some((s) => s.kind === "github")) {+ if (lib.skills.some((s) => s.kind === "github" || s.kind === "git")) {const c = button(checking ? t("Checking…") : t("Check for updates"), "lib-updall", () => checkSkills());- c.title = t("Ask GitHub which skills changed since they were installed");+ c.title = lib.skills.some((s) => s.kind === "git")+ ? t("Ask the repositories your skills came from which skills changed since they were installed")+ : t("Ask GitHub which skills changed since they were installed");c.disabled = checking;if (checking) c.classList.add("busy");rh.append(c);@@ -2829,6 +2831,9 @@ magpie.plugin("library", (ctx) => {try { folds = JSON.parse(localStorage.getItem("magpie.libSkillFolds") || "{}") || {}; } catch {}function saveFolds() { try { localStorage.setItem("magpie.libSkillFolds", JSON.stringify(folds)); } catch {} }const repoOf = (u) => (u || "").replace(/^https:\/\/github\.com\//, "").split("/").slice(0, 2).join("/");+ // the repository a skill from another git host (kind "git") came from,+ // as the page names it: its address, without https:// or a folder in it+ const gitRepoOf = (s) => (s.kind === "git" ? (s.source || "").replace(/^https?:\/\//, "").replace(/\/-\/tree\/.*$/, "") : "");// the repository a skill came from, however it came in: magpie traces// one not installed from GitHub too (the skills CLI's lock, the git// checkout it's in), so a repository's skills are one group (White@@ -2934,6 +2939,11 @@ magpie.plugin("library", (ctx) => {const m = /^https:\/\/github\.com\/[^/]+\/[^/]+\/tree\/[^/]+\/(.+)$/.exec(s.source || "");return m ? m[1].split("/").slice(0, -1).join("/") : "";}+ if (s.kind === "git") {+ // GitLab's …/-/tree/<ref>/<path to the folder>/<skill>+ const m = /\/-\/tree\/[^/]+\/(.+)$/.exec(s.source || "");+ return m ? m[1].split("/").slice(0, -1).join("/") : "";+ }if (s.kind === "folder") return tilde((s.source || "").replace(/[\\/][^\\/]+[\\/]?$/, ""));return "";};@@ -2957,7 +2967,7 @@ magpie.plugin("library", (ctx) => {if (g.repo) {// the folder in the repository is known of those installed from it// only: one traced to it goes by its name with the rest- let m = g.skills.every((s) => s.kind === "github") ? split(g.skills, folderIn) : null, mono = true;+ let m = g.skills.every((s) => s.kind === "github" || s.kind === "git") ? split(g.skills, folderIn) : null, mono = true;if (!m) { mono = false; m = byStart(); }if (!m) return null;return [...m].map(([key, skills]) => ({ key, skills, mono, label: label(key, mono) })).sort(order);@@ -4402,7 +4412,7 @@ magpie.plugin("library", (ctx) => {const inp = el("input");inp.type = "text";inp.dataset.lib = "source";- inp.placeholder = t("owner/repo, a GitHub link, or a folder on this computer");+ inp.placeholder = t("owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer");inp.spellcheck = false;inp.autocomplete = "off";inp.value = probe?.source || "";@@ -4442,7 +4452,8 @@ magpie.plugin("library", (ctx) => {const left = (p.found.left || []).map((x) => el("div", "lib-none lib-left", t("{name} is too big to install: {size}, over the {limit} a skill may be", { name: x.path.split("/").pop() || p.found.source, size: Math.round(x.size / 1048576) + " MB", limit: "200 MB" })));if (!c.length) { box.append(...(left.length ? left : [el("div", "lib-none", t("No skills there — a skill is a folder with a SKILL.md in it."))])); return box; }const head = el("div", "lib-probehead");- const src = p.found.kind === "github" ? "github.com/" + p.found.source.replace(/^https?:\/\/github\.com\//, "") : tilde(p.found.source);+ const src = p.found.kind === "github" ? "github.com/" + p.found.source.replace(/^https?:\/\/github\.com\//, "")+ : p.found.kind === "git" ? p.found.source.replace(/^https:\/\//, "") : tilde(p.found.source);head.append(el("span", "note", c.length === 1 ? t("1 skill in {src}", { src }) : t("{n} skills in {src}", { n: c.length, src })));head.append(el("span", "grow"));const fresh = c.filter((x) => !x.have);@@ -4519,7 +4530,9 @@ magpie.plugin("library", (ctx) => {}// changed here since it was fetched from GitHub (#1449): an update asks// before it replaces that- if (s.edited) nm.append(tag(t("Changed here"), "warn lib-edited", t("You changed it since it was fetched from GitHub. Updating asks before it replaces your changes.")));+ if (s.edited) nm.append(tag(t("Changed here"), "warn lib-edited", gitRepoOf(s)+ ? t("You changed it since it was fetched from {repo}. Updating asks before it replaces your changes.", { repo: gitRepoOf(s) })+ : t("You changed it since it was fetched from GitHub. Updating asks before it replaces your changes.")));// a copy in an agent that differs from the library's skill (#896): a// sync makes it againif (s.behind?.length) {@@ -4544,13 +4557,23 @@ magpie.plugin("library", (ctx) => {a.href = s.source;a.onclick = (e) => { e.preventDefault(); e.stopPropagation(); browse(s.source); };src.append(a);+ } else if (s.kind === "git" && /^https?:\/\//.test(s.source)) {+ const a = el("a", "lib-srclink", s.source.replace(/^https:\/\//, ""));+ a.href = s.source;+ a.onclick = (e) => { e.preventDefault(); e.stopPropagation(); browse(s.source); };+ src.append(a);+ } else if (s.kind === "git") {+ // an SSH address (git@host:path) or a file:// one: no page to open+ const a = el("span", "lib-srclink", s.source);+ a.title = s.source;+ src.append(a);} else {src.append(el("span", "", t("linked from")), pathLink(s.source));}who.append(src);}const acts = el("div", "lib-rowacts");- if (s.kind === "github" || s.origin) {+ if (s.kind === "github" || s.kind === "git" || s.origin) {const u = button("", "lib-icon", async (e, b) => {if (s.edited) return confirmUpdateEdited(s);b.classList.add("busy");@@ -4558,8 +4581,10 @@ magpie.plugin("library", (ctx) => {b.classList.remove("busy");});u.append(svg(GLYPH.up, 13, 1.5));- u.title = s.origin ? t("Update from GitHub ({repo}, as CC Switch installed it)", { repo: s.origin.replace(/^https:\/\/github\.com\//, "") }) : t("Update from GitHub");- if (c?.status === "current") u.title += "\n" + t("Up to date with GitHub") + "\n" + checkLine(c);+ const gitRepo = gitRepoOf(s);+ u.title = s.origin ? t("Update from GitHub ({repo}, as CC Switch installed it)", { repo: s.origin.replace(/^https:\/\/github\.com\//, "") })+ : gitRepo ? t("Update from {repo}", { repo: gitRepo }) : t("Update from GitHub");+ if (c?.status === "current") u.title += "\n" + (gitRepo ? t("Up to date with {repo}", { repo: gitRepo }) : t("Up to date with GitHub")) + "\n" + checkLine(c);else if (c?.status === "update") u.title += "\n" + checkLine(c);if (s.edited) u.title += "\n" + t("Changed here: asks before it replaces your changes");acts.append(u);@@ -4580,9 +4605,12 @@ magpie.plugin("library", (ctx) => {function confirmUpdateEdited(s) {const ed = el("div", "editor lib-editor lib-update-edited");const head = el("div", "ehead");- head.append(glyph(GLYPH.up), el("b", "", t("Replace your changes to {name}?", { name: s.name })));+ const repo = gitRepoOf(s);+ head.append(glyph(GLYPH.up), el("b", "", repo ? t("Replace your changes to {name} with the version in {repo}?", { name: s.name, repo }) : t("Replace your changes to {name}?", { name: s.name })));ed.append(head);- ed.append(el("p", "lib-confirm", t("You changed {name} here since it was fetched from GitHub. Updating puts GitHub's version in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).", { name: s.name })));+ ed.append(el("p", "lib-confirm", repo+ ? t("You changed {name} here since it was fetched from {repo}. Updating puts the version there in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).", { name: s.name, repo })+ : t("You changed {name} here since it was fetched from GitHub. Updating puts GitHub's version in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).", { name: s.name })));const bar = el("div", "bar");const go = button(t("Update"), "primary", async () => {go.disabled = true;diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.jsindex bfc39a5c2..20b75f605 100644--- a/internal/gui/assets/plugins/library/i18n.js+++ b/internal/gui/assets/plugins/library/i18n.js@@ -461,7 +461,13 @@ magpie.strings({"Written into {files} of the project, beside what's in them; a file magpie makes is listed in its .gitignore. A server there by the same name that isn't magpie's is left as it is.": "写入项目的 {files},与已有内容并存;magpie 新建的文件会列入 .gitignore。其中非 magpie 写入的同名服务器保持不动。","Claude Code asks before it starts a project's servers; Codex reads .codex/config.toml, and Pi .pi/mcp.json, only in a project you trust.": "Claude Code 启动项目服务器前会先询问;Codex 的 .codex/config.toml 和 Pi 的 .pi/mcp.json 仅在受信任的项目中读取。","{agents} reads no project MCP file magpie knows of.": "{agents} 没有 magpie 已知的项目 MCP 文件。",- "owner/repo, a GitHub link, or a folder on this computer": "owner/repo、GitHub 链接,或本机上的文件夹",+ "owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer": "owner/repo、GitHub 或 GitLab 链接、任意 git 仓库地址,或本机上的文件夹",+ "Ask the repositories your skills came from which skills changed since they were installed": "向技能来源的仓库查询哪些技能在安装后有了改动",+ "Update from {repo}": "从 {repo} 更新",+ "Up to date with {repo}": "与 {repo} 一致",+ "You changed it since it was fetched from {repo}. Updating asks before it replaces your changes.": "从 {repo} 获取后你在本地改动过它。更新前会先询问,不会直接覆盖你的改动。",+ "Replace your changes to {name} with the version in {repo}?": "用 {repo} 中的版本替换你对 {name} 的改动?",+ "You changed {name} here since it was fetched from {repo}. Updating puts the version there in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).": "从 {repo} 获取 {name} 后你在本地改动过它。更新会用那里的版本替换它,你的版本会保存在 magpie 的备份里(资源库顶部的「备份」)。","Find skills": "查找技能","No SKILL.md found there": "那里没有找到 SKILL.md","No skills there — a skill is a folder with a SKILL.md in it.": "那里没有技能 — 技能是一个含 SKILL.md 的文件夹。",@@ -1062,7 +1068,13 @@ magpie.strings({"Written into {files} of the project, beside what's in them; a file magpie makes is listed in its .gitignore. A server there by the same name that isn't magpie's is left as it is.": "寫入專案的 {files},與已有內容並存;magpie 新增的檔案會列入 .gitignore。其中非 magpie 寫入的同名伺服器保持不動。","Claude Code asks before it starts a project's servers; Codex reads .codex/config.toml, and Pi .pi/mcp.json, only in a project you trust.": "Claude Code 啟動專案伺服器前會先詢問;Codex 的 .codex/config.toml 和 Pi 的 .pi/mcp.json 僅在受信任的專案中讀取。","{agents} reads no project MCP file magpie knows of.": "{agents} 沒有 magpie 已知的專案 MCP 檔案。",- "owner/repo, a GitHub link, or a folder on this computer": "owner/repo、GitHub 連結,或本機上的資料夾",+ "owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer": "owner/repo、GitHub 或 GitLab 連結、任何 git 儲存庫位址,或本機上的資料夾",+ "Ask the repositories your skills came from which skills changed since they were installed": "向技能來源的儲存庫查詢哪些技能在安裝後有了改動",+ "Update from {repo}": "從 {repo} 更新",+ "Up to date with {repo}": "與 {repo} 一致",+ "You changed it since it was fetched from {repo}. Updating asks before it replaces your changes.": "從 {repo} 取得後你在本機改動過它。更新前會先詢問,不會直接覆蓋你的改動。",+ "Replace your changes to {name} with the version in {repo}?": "用 {repo} 中的版本取代你對 {name} 的改動?",+ "You changed {name} here since it was fetched from {repo}. Updating puts the version there in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).": "從 {repo} 取得 {name} 後你在本機改動過它。更新會用那裡的版本取代它,你的版本會保存在 magpie 的備份裡(資源庫頂部的「備份」)。","Find skills": "查詢技能","No SKILL.md found there": "那裡沒有找到 SKILL.md","No skills there — a skill is a folder with a SKILL.md in it.": "那裡沒有技能 — 技能是一個含 SKILL.md 的資料夾。",@@ -1658,7 +1670,13 @@ magpie.strings({"Written into {files} of the project, beside what's in them; a file magpie makes is listed in its .gitignore. A server there by the same name that isn't magpie's is left as it is.": "プロジェクトの {files} に、既存の内容と並べて書き込みます。magpie が作成したファイルは .gitignore に記載します。そこにある magpie のものでない同名のサーバーはそのままです。","Claude Code asks before it starts a project's servers; Codex reads .codex/config.toml, and Pi .pi/mcp.json, only in a project you trust.": "Claude Code はプロジェクトのサーバーを起動する前に確認します。Codex は .codex/config.toml を、Pi は .pi/mcp.json を、信頼したプロジェクトでのみ読みます。","{agents} reads no project MCP file magpie knows of.": "{agents} は magpie が把握しているプロジェクトの MCP ファイルを読みません。",- "owner/repo, a GitHub link, or a folder on this computer": "owner/repo、GitHub のリンク、またはこのコンピュータ上のフォルダ",+ "owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer": "owner/repo、GitHub または GitLab のリンク、任意の git リポジトリのアドレス、またはこのコンピュータ上のフォルダ",+ "Ask the repositories your skills came from which skills changed since they were installed": "インストール後に変更されたスキルを、取得元のリポジトリに問い合わせます",+ "Update from {repo}": "{repo} からアップデート",+ "Up to date with {repo}": "{repo} と同じ",+ "You changed it since it was fetched from {repo}. Updating asks before it replaces your changes.": "{repo} から取得した後、ここで変更されています。更新は変更を置き換える前に確認します。",+ "Replace your changes to {name} with the version in {repo}?": "{name} への変更を {repo} の版で置き換えますか?",+ "You changed {name} here since it was fetched from {repo}. Updating puts the version there in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).": "{name} は {repo} から取得した後、ここで変更されています。更新するとそこの版に置き換わります。あなたの版は magpie のバックアップ(ライブラリ上部の「バックアップ」)に残ります。","Find skills": "スキルを探す","No SKILL.md found there": "そこに SKILL.md が見つかりません","No skills there — a skill is a folder with a SKILL.md in it.": "そこにスキルはありません — スキルとは SKILL.md を含むフォルダです。",@@ -2257,7 +2275,13 @@ magpie.strings({"Written into {files} of the project, beside what's in them; a file magpie makes is listed in its .gitignore. A server there by the same name that isn't magpie's is left as it is.": "In {files} des Projekts geschrieben, neben dem vorhandenen Inhalt; eine von magpie erstellte Datei wird in seiner .gitignore eingetragen. Ein gleichnamiger Server dort, der nicht von magpie stammt, bleibt unverändert.","Claude Code asks before it starts a project's servers; Codex reads .codex/config.toml, and Pi .pi/mcp.json, only in a project you trust.": "Claude Code fragt nach, bevor es die Server eines Projekts startet; Codex liest .codex/config.toml und Pi .pi/mcp.json nur in einem Projekt, dem Sie vertrauen.","{agents} reads no project MCP file magpie knows of.": "{agents} liest keine Projekt-MCP-Datei, die magpie kennt.",- "owner/repo, a GitHub link, or a folder on this computer": "owner/repo, ein GitHub-Link oder ein Ordner auf diesem Computer",+ "owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer": "owner/repo, ein GitHub- oder GitLab-Link, die Adresse eines beliebigen Git-Repositorys oder ein Ordner auf diesem Computer",+ "Ask the repositories your skills came from which skills changed since they were installed": "Bei den Repositorys, aus denen die Skills stammen, abfragen, welche sich seit der Installation geändert haben",+ "Update from {repo}": "Von {repo} aktualisieren",+ "Up to date with {repo}": "Auf dem Stand von {repo}",+ "You changed it since it was fetched from {repo}. Updating asks before it replaces your changes.": "Du hast ihn geändert, seit er von {repo} geholt wurde. Ein Update fragt, bevor es deine Änderungen ersetzt.",+ "Replace your changes to {name} with the version in {repo}?": "Deine Änderungen an {name} durch die Version aus {repo} ersetzen?",+ "You changed {name} here since it was fetched from {repo}. Updating puts the version there in its place. Yours is kept in magpie's backups (Backups, at the top of the Library).": "Du hast {name} hier geändert, seit er von {repo} geholt wurde. Das Update setzt die Version von dort an seine Stelle. Deine bleibt in den Backups von magpie (Backups, oben in der Bibliothek).","Find skills": "Skills suchen","No SKILL.md found there": "Dort keine SKILL.md gefunden","No skills there — a skill is a folder with a SKILL.md in it.": "Dort keine Skills – ein Skill ist ein Ordner mit einer SKILL.md darin.",diff --git a/internal/gui/tests/skill-git-source.test.cjs b/internal/gui/tests/skill-git-source.test.cjsnew file mode 100644index 000000000..07551eae4--- /dev/null+++ b/internal/gui/tests/skill-git-source.test.cjs@@ -0,0 +1,124 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// sunset on Discord: skills from GitLab, and from a company's own GitLab.+// The add box says any git repository's address works. A skill from one+// (kind "git") shows where it came from (a link for an https address, the+// address as text for an SSH one), has its own Update naming the+// repository, and Check for updates is offered for it. A probe of one+// names the repository. In English and Chinese, in Chromium and WebKit,+// wide and narrow. No backend: the API is faked here.+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/sunset";+const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills` });+const HTTPS = "https://gitlab.corp.example/team/skills/-/tree/HEAD/skills/pdf";+const SSH = "[email protected]:team/private.git";+const lib = () => ({+ dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,+ agents: [agent("claude", "Claude Code")],+ instructions: { agents: [] }, servers: [], foundServers: [], projects: [], foundSkills: [], newSkills: [],+ checkDue: false,+ skills: [+ { name: "pdf", description: "PDFs", kind: "git", source: HTTPS, agents: ["claude"] },+ { name: "review", description: "Reviews", kind: "git", source: SSH, agents: ["claude"], edited: true },+ ],+});+const probe = { source: "https://gitlab.corp.example/team/skills", kind: "git", candidates: [{ path: "skills/a", name: "a", description: "a", have: false }] };++function server(lang, posts) {+ 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/library") return route.fulfill({ json: lib() });+ if (url.pathname === "/api/library/skills/probe") { posts.push(req.postDataJSON()); return route.fulfill({ json: probe }); }+ if (url.pathname.startsWith("/api/library/skills/")) { posts.push(url.pathname.split("/").pop()); return route.fulfill({ json: { ...lib(), result: { changed: [] } } }); }+ if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });+ 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 });+ };+}++const words = {+ en: { ph: "owner/repo, a GitHub or GitLab link, any git repository's address, or a folder on this computer", upd: "Update from gitlab.corp.example/team/skills", updSSH: "Update from " + SSH, check: "Check for updates", found: "1 skill in gitlab.corp.example/team/skills",+ tip: "You changed it since it was fetched from " + SSH + ". Updating asks before it replaces your changes.", ask: "Replace your changes to review with the version in " + SSH + "?" },+ zh: { ph: "owner/repo、GitHub 或 GitLab 链接、任意 git 仓库地址,或本机上的文件夹", upd: "从 gitlab.corp.example/team/skills 更新", updSSH: "从 " + SSH + " 更新", check: "检查更新", found: null,+ tip: "从 " + SSH + " 获取后你在本地改动过它。更新前会先询问,不会直接覆盖你的改动。", ask: "用 " + SSH + " 中的版本替换你对 review 的改动?" },+};++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(engine + ": a skill from a git repository shows it, updates from it, and the add box says so", async (t) => {+ assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");+ 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 width of [900, 400]) for (const lang of ["en", "zh"]) {+ await t.test(`${lang} at ${width}px`, async () => {+ const w = words[lang], posts = [];+ const ctx = await browser.newContext({ viewport: { width, height: 900 } });+ await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} });+ const page = await ctx.newPage();+ page.setDefaultTimeout(5000);+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", server(lang, posts));+ await page.goto("http://magpie.test/");+ await page.locator('button[data-view="library"]').click();+ const v = page.locator("#view-library");+ const src = v.locator('input[data-lib="source"]');+ await src.waitFor();+ assert.equal(await src.getAttribute("placeholder"), w.ph);++ const row = (name) => v.locator(".lib-skill", { has: page.locator(".name", { hasText: new RegExp("^" + name) }) });+ await row("pdf").waitFor();+ const link = row("pdf").locator("a.lib-srclink");+ assert.equal(await link.getAttribute("href"), HTTPS);+ assert.equal((await link.textContent()).trim(), HTTPS.replace("https://", ""));+ const ssh = row("review").locator(".lib-src .lib-srclink");+ assert.equal(await ssh.evaluate((e) => e.tagName), "SPAN", "an SSH address isn't a link");+ assert.equal((await ssh.textContent()).trim(), SSH);+ assert.equal(await row("pdf").locator(".lib-rowacts button.lib-icon").first().getAttribute("title"), w.upd);+ assert.equal((await row("review").locator(".lib-rowacts button.lib-icon").first().getAttribute("title")).split("\n")[0], w.updSSH);+ const check = v.locator(".row-head button.lib-updall", { hasText: w.check });+ assert.equal(await check.count(), 1, "Check for updates is offered");+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll");++ await row("pdf").locator(".lib-rowacts button.lib-icon").first().click();+ await page.waitForTimeout(200);+ assert.deepEqual(posts, ["update"]);+ // one changed here names the repository it would be replaced from+ assert.equal(await row("review").locator(".lib-tag.lib-edited").getAttribute("title"), w.tip);+ await row("review").locator(".lib-rowacts button.lib-icon").first().click();+ const modal = page.locator(".lib-update-edited");+ await modal.waitFor();+ assert.equal((await modal.locator(".ehead b").textContent()).trim(), w.ask);+ assert.match(await modal.locator(".lib-confirm").textContent(), new RegExp(SSH.replace(/[.]/g, "\\.")));+ assert.deepEqual(posts, ["update"], "asking sends nothing");+ await page.keyboard.press("Escape");+ await modal.waitFor({ state: "detached" });++ await src.fill("https://gitlab.corp.example/team/skills");+ await src.press("Enter");+ const head = v.locator(".lib-probehead .note");+ await head.waitFor();+ assert.equal(posts[1].source, "https://gitlab.corp.example/team/skills");+ if (w.found) assert.equal((await head.textContent()).trim(), w.found);+ else assert.match(await head.textContent(), /gitlab\.corp\.example\/team\/skills/);+ await ctx.close();+ });+ }+ assert.deepEqual(errors, []);+ });+}diff --git a/internal/library/skill_changed.go b/internal/library/skill_changed.goindex 97644323b..0862fb101 100644--- a/internal/library/skill_changed.go+++ b/internal/library/skill_changed.go@@ -21,11 +21,25 @@ import ()// EditedError is an update refused because the skill was changed here-// since it was fetched from GitHub.-type EditedError struct{ Name string }+// since it was fetched from GitHub, or From, the git repository it came+// from.+type EditedError struct{ Name, From string }func (e *EditedError) Error() string {- return fmt.Sprintf("%s was changed here since it was fetched from GitHub; updating it would replace those changes", e.Name)+ from := e.From+ if from == "" {+ from = "GitHub"+ }+ return fmt.Sprintf("%s was changed here since it was fetched from %s; updating it would replace those changes", e.Name, from)+}++// editedError is the refusal of an update of s, naming where it came from.+func editedError(s *Skill) *EditedError {+ e := &EditedError{Name: s.Name}+ if s.Source != nil && s.Source.Kind == "git" {+ e.From = s.Source.Repo+ }+ return e}// edits remembers, for each skill's library folder, its hash as of when@@ -72,7 +86,7 @@ func libraryHash(name string) string {// hash of what it fetched (installed before it did), or the folder can't// be read.func (l *Library) editState(s *Skill, targets []*Target) (edited, known bool) {- if s.Source == nil || s.Source.Kind != "github" || s.Hash == "" {+ if !s.Source.remote() || s.Hash == "" {return false, false}lib := skillDir(s.Name)diff --git a/internal/library/skill_from.go b/internal/library/skill_from.goindex 3a9055da9..83d82c023 100644--- a/internal/library/skill_from.go+++ b/internal/library/skill_from.go@@ -30,6 +30,9 @@ func (tr *tracer) repoOf(s *Skill) string {if s.Source != nil && s.Source.Kind == "github" {return s.Source.Repo}+ if s.Source != nil && s.Source.Kind == "git" {+ return remoteRepo(s.Source.Repo) // host/path, as a checkout of it is+ }if o, ok := ccSwitchOrigin(s); ok {return o.Repo}diff --git a/internal/library/skillcheck.go b/internal/library/skillcheck.goindex 3db9d16d8..ce799af04 100644--- a/internal/library/skillcheck.go+++ b/internal/library/skillcheck.go@@ -97,7 +97,7 @@ const checkEvery = 12 * time.Hour// GitHub for updates: none checked since magpie started, or not for// checkEvery.func checkDue(l *Library) bool {- if !slices.ContainsFunc(l.Skills, func(s *Skill) bool { return s.Source != nil && s.Source.Kind == "github" }) {+ if !slices.ContainsFunc(l.Skills, func(s *Skill) bool { return s.Source.remote() }) {return false}at := checkedAt.Load()@@ -275,7 +275,8 @@ func firstLine(s string) string {// that isn't known yet, by fetching the repository once and comparing the// folder's files with the skill's. A skill GitHub couldn't be asked about// is unknown, and the others are checked all the same; once GitHub limits-// requests, the rest aren't asked about.+// requests, the rest aren't asked about. A skill from another git+// repository is checked with the user's git (checkGitSkill).func CheckSkills() ([]SkillCheck, error) {mu.Lock()l, err := load()@@ -285,8 +286,8 @@ func CheckSkills() ([]SkillCheck, error) {}byRepo := map[string][]*Skill{}for _, s := range l.Skills {- if s.Source != nil && s.Source.Kind == "github" {- byRepo[s.Source.Repo] = append(byRepo[s.Source.Repo], s)+ if s.Source.remote() {+ byRepo[s.Source.Kind+"\x00"+s.Source.Repo] = append(byRepo[s.Source.Kind+"\x00"+s.Source.Repo], s)}}f := &fetcher{}@@ -306,9 +307,16 @@ func CheckSkills() ([]SkillCheck, error) {sem <- struct{}{}defer func() { <-sem }()asked := map[string]*commit{} // a repository's skills in one folder are asked about once+ heads := map[string]string{} // a git repository's refs, asked about oncerefs := []string{}for _, s := range skills {- c, sha, hash := checkSkill(s, f, asked, &limited)+ var c SkillCheck+ var sha, hash string+ if s.Source.Kind == "git" {+ c, sha, hash = checkGitSkill(s, f, heads)+ } else {+ c, sha, hash = checkSkill(s, f, asked, &limited)+ }omu.Lock()out = append(out, c)if sha != "" {@@ -319,8 +327,12 @@ func CheckSkills() ([]SkillCheck, error) {refs = append(refs, s.Source.Ref)}}- // and what the repository has added beside them since+ // and what the repository has added beside them since: GitHub's+ // list of its files says, which another host has no API forfor _, ref := range refs {+ if skills[0].Source.Kind != "github" {+ break+ }if found, ok := findNew(l, skills[0].Source.Repo, ref, f, &limited); ok {newFound.Lock()newFound.m[repoKey(skills[0].Source.Repo, ref)] = found@@ -338,7 +350,9 @@ func CheckSkills() ([]SkillCheck, error) {if l, err := load(); err == nil {for _, s := range l.Skills {k, ok := known[s.Name]- if ok && s.Source != nil && s.Source.Kind == "github" && s.Commit == "" && (s.Hash == "" || s.Hash == k[1]) {+ // a git repository's commit is the whole repository's: a+ // check that found the files the same at a later one keeps that+ if ok && s.Source.remote() && (s.Commit == "" || s.Source.Kind == "git") && (s.Hash == "" || s.Hash == k[1]) {s.Commit, s.Hash = k[0], k[1]}}diff --git a/internal/library/skillgit.go b/internal/library/skillgit.gonew file mode 100644index 000000000..9175b6dca--- /dev/null+++ b/internal/library/skillgit.go@@ -0,0 +1,461 @@+package library++// Skills from any git repository (sunset on Discord): GitLab, a company's+// own GitLab on its intranet, Gitea, a bare repository on this machine.+// magpie can't ask such a host for a tarball or its commits the way it+// asks GitHub, so it runs the user's own git, which signs in to the host+// the way it does for the user (a credential helper, a token, an SSH key+// in the agent). The address is data: it reaches git as an argument after+// "--", never through a shell, and what git can't be told apart from an+// option, or a transport that runs a command, is refused before git runs.++import (+ "context"+ "errors"+ "fmt"+ "net/url"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "strings"+ "sync"+ "time"+ "unicode"++ "github.com/yetone/magpie/internal/proc"+)++// gitPath is where git is, "" when it isn't here; a variable for tests.+var gitPath = func() string { return proc.FindTool("git") }++// gitTimeout is how long one git command may take before it is stopped:+// a host that never answers, or a sign-in no one can see, ends there.+var gitTimeout = 3 * time.Minute++var (+ // remoteHelper is git's <transport>::<address>, which hands the+ // address to a helper program (ext:: runs a command)+ remoteHelper = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.-]*::`)+ // scpLike is git's user@host:path for SSH+ scpLike = regexp.MustCompile(`^(?:([\w.-]+)@)?([\w.-]+):(.+)$`)+ gitRef = regexp.MustCompile(`^[\w./+@-]+$`)+ hexRef = regexp.MustCompile(`^[0-9a-fA-F]{7,40}$`)+)++// gitSchemes are the URL schemes a git source may have. file:// is a+// repository on this machine or a mounted share, which the user named.+var gitSchemes = map[string]bool{"https": true, "http": true, "ssh": true, "git": true, "git+ssh": true, "ssh+git": true, "file": true}++// gitSource reads a git repository out of what the user typed: a URL+// (https://host/group/sub/repo(.git), ssh://, git://, file://), SSH's+// git@host:group/repo.git, or host/group/repo. A GitLab page's+// /-/tree/<ref>/<path> (or /-/blob/…/SKILL.md), and Gitea's+// /src/branch/<ref>/<path>, name a branch and a folder in it; the ref is+// the first part after them, so a branch with a / in its name is read+// as a ref and a folder. ok is false for what isn't meant as one; an+// error is one that is, refused.+func gitSource(s string) (src Source, ok bool, err error) {+ s = strings.TrimSpace(s)+ if s == "" {+ return Source{}, false, nil+ }+ if strings.HasPrefix(s, "-") {+ return Source{}, true, fmt.Errorf("a repository's address can't start with -")+ }+ if remoteHelper.MatchString(s) {+ return Source{}, true, fmt.Errorf("magpie doesn't install from a git address with a transport (%s): give the repository's https or SSH address", s[:strings.Index(s, "::")+2])+ }+ if strings.IndexFunc(s, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) >= 0 {+ return Source{}, false, nil+ }+ repo, rest := s, ""+ for _, sep := range []string{"/-/tree/", "/-/blob/", "/src/branch/", "/src/tag/", "/src/commit/"} {+ if i := strings.Index(s, sep); i > 0 {+ repo, rest = s[:i], s[i+len(sep):]+ break+ }+ }+ repo = strings.TrimSuffix(repo, "/")+ if strings.HasSuffix(repo, "/-") { // https://host/group/repo/-/ alone+ repo = strings.TrimSuffix(repo, "/-")+ }+ if !strings.Contains(repo, "://") {+ // user@host:path, or host.name:path; a Windows drive (C:) is a+ // folder, never a host+ if m := scpLike.FindStringSubmatch(repo); m != nil && len(m[2]) > 1 && (m[1] != "" || strings.Contains(m[2], ".")) {+ if strings.HasPrefix(m[3], "-") || strings.HasPrefix(m[2], "-") {+ return Source{}, true, fmt.Errorf("a repository's address can't start with -")+ }+ } else if first, _, _ := strings.Cut(repo, "/"); strings.Contains(first, ".") && strings.Count(repo, "/") >= 2 {+ repo = "https://" + repo // gitlab.example.com/group/repo+ } else {+ return Source{}, false, nil+ }+ }+ if strings.Contains(repo, "://") {+ u, err := url.Parse(repo)+ if err != nil || u.Scheme == "" {+ return Source{}, false, nil+ }+ if !gitSchemes[strings.ToLower(u.Scheme)] {+ return Source{}, true, fmt.Errorf("magpie doesn't install from a %s:// address: give the repository's https or SSH address", u.Scheme)+ }+ if _, set := u.User.Password(); set {+ // it would be kept in library.json, shown on the page and+ // carried to a backup+ return Source{}, true, fmt.Errorf("leave the password or token out of the address: magpie runs your own git, which signs in with its credential helper or your SSH key")+ }+ if strings.ToLower(u.Scheme) != "file" && (u.Host == "" || strings.HasPrefix(u.Host, "-")) {+ return Source{}, true, fmt.Errorf("%s names no host", repo)+ }+ if strings.Trim(u.Path, "/") == "" {+ return Source{}, true, fmt.Errorf("%s names no repository", repo)+ }+ }+ src = Source{Kind: "git", Repo: repo}+ if rest != "" {+ ref, path, _ := strings.Cut(strings.Trim(rest, "/"), "/")+ if ref != "HEAD" {+ src.Ref = ref+ }+ if q := strings.IndexAny(path, "?#"); q >= 0 {+ path = path[:q]+ }+ src.Path = strings.Trim(strings.TrimSuffix(strings.TrimSuffix(path, "SKILL.md"), "/"), "/")+ if src.Ref != "" && (!gitRef.MatchString(src.Ref) || strings.HasPrefix(src.Ref, "-") || strings.Contains(src.Ref, "..")) {+ return Source{}, true, fmt.Errorf("%q isn't a branch or tag git can fetch", src.Ref)+ }+ if strings.Contains("/"+src.Path+"/", "/../") {+ return Source{}, true, fmt.Errorf("%q isn't a folder in the repository", src.Path)+ }+ }+ return src, true, nil+}++// gitURL is a git source as the user can type it again: the repository,+// and its ref and folder as a GitLab page names them. An https address+// loses its .git there, so it opens the repository's page; GitLab and+// Gitea fetch it without one too.+func gitURL(s *Source) string {+ if s.Ref == "" && s.Path == "" {+ return s.Repo+ }+ ref := s.Ref+ if ref == "" {+ ref = "HEAD"+ }+ u := s.Repo+ if strings.HasPrefix(u, "https://") || strings.HasPrefix(u, "http://") {+ u = strings.TrimSuffix(u, ".git") // the page, not the clone+ }+ u += "/-/tree/" + ref+ if s.Path != "" {+ u += "/" + s.Path+ }+ return u+}++// sameGitRepo is whether two addresses are one repository: by host and+// path, however it is reached (https, SSH, with .git or without).+func sameGitRepo(a, b string) bool {+ if strings.EqualFold(strings.TrimSuffix(a, ".git"), strings.TrimSuffix(b, ".git")) {+ return true+ }+ ra, rb := remoteRepo(a), remoteRepo(b)+ return ra != "" && strings.EqualFold(ra, rb)+}++// gitHeads is the commit each git download is at, by its folder.+var gitHeads = struct {+ sync.Mutex+ m map[string]string+}{m: map[string]string{}}++func gitHeadOf(dir string) string {+ gitHeads.Lock()+ defer gitHeads.Unlock()+ return gitHeads.m[dir]+}++func noteGitHead(dir, sha string) {+ gitHeads.Lock()+ defer gitHeads.Unlock()+ for d := range gitHeads.m {+ if _, err := os.Stat(d); err != nil {+ delete(gitHeads.m, d) // a download removed since+ }+ }+ gitHeads.m[dir] = sha+}++// errNoGit is git missing from this computer.+func errNoGit() error {+ return errors.New("installing from a git repository runs git, and git isn't installed here (or isn't on PATH): install git and try again")+}++// gitEnv is the environment git runs in: the user's, so their credential+// helper, SSH agent and config work, with every question asked on a+// terminal turned off (no one sees it, and it would wait for ever), and+// git's messages in English, as magpie reads them.+func gitEnv(git string) []string {+ env := append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "LC_ALL=C", "LANGUAGE=C")+ if os.Getenv("GIT_SSH_COMMAND") == "" && os.Getenv("GIT_SSH") == "" {+ // ssh asks for a passphrase or a new host's key on the terminal:+ // BatchMode refuses instead. A core.sshCommand of the user's own+ // (a key for the intranet) is kept, which GIT_SSH_COMMAND would+ // override.+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ cmd := proc.CommandContext(ctx, git, "config", "--global", "--get", "core.sshCommand")+ cmd.Env = env+ if out, _ := cmd.Output(); strings.TrimSpace(string(out)) == "" {+ env = append(env, "GIT_SSH_COMMAND=ssh -o BatchMode=yes")+ }+ }+ return env+}++// runGit runs git with args in dir, and gives back its output, or an+// error saying plainly what went wrong for src.+func runGit(ctx context.Context, git string, env []string, dir string, src Source, args ...string) ([]byte, error) {+ cmd := proc.CommandContext(ctx, git, append([]string{"-c", "protocol.ext.allow=never", "-c", "core.symlinks=false"}, args...)...)+ cmd.Dir, cmd.Env = dir, env+ var stderr strings.Builder+ cmd.Stderr = &stderr+ out, err := cmd.Output()+ if err == nil {+ return out, nil+ }+ if ctx.Err() == context.DeadlineExceeded {+ return nil, fmt.Errorf("git took over %s to fetch %s and was stopped", gitTimeout, src.Repo)+ }+ var ee *exec.ExitError+ if !errors.As(err, &ee) {+ return nil, fmt.Errorf("couldn't run git: %w", err)+ }+ return nil, gitError(src, stderr.String())+}++// gitError says what git's message means for the user.+func gitError(src Source, msg string) error {+ low := strings.ToLower(msg)+ said := gitSaid(msg)+ host := gitHost(src.Repo)+ switch {+ case strings.Contains(low, "xcrun: error") || strings.Contains(low, "invalid active developer path") || strings.Contains(low, "no developer tools were found"):+ return errors.New("installing from a git repository runs git, and git isn't installed here: install Apple's command line tools (xcode-select --install) and try again")+ case strings.Contains(low, "host key verification failed"):+ return fmt.Errorf("SSH doesn't know %s's host key yet: connect to it once with ssh or git in a terminal to accept it, then try again (git said: %s)", host, said)+ case strings.Contains(low, "could not read username") || strings.Contains(low, "could not read password") ||+ strings.Contains(low, "terminal prompts disabled") || strings.Contains(low, "authentication failed") ||+ strings.Contains(low, "permission denied") || strings.Contains(low, "access denied") ||+ strings.Contains(low, "the requested url returned error: 401") || strings.Contains(low, "the requested url returned error: 403"):+ return fmt.Errorf("git couldn't sign in to %s. magpie runs your own git, so sign in the way git does there (a credential helper or an SSH key that can read the repository), check `git clone %s` works in a terminal, and try again (git said: %s)", host, src.Repo, said)+ case strings.Contains(low, "couldn't find remote ref") || strings.Contains(low, "unknown revision"):+ return fmt.Errorf("%s has no branch or tag %s", src.Repo, src.Ref)+ case strings.Contains(low, "repository not found") || strings.Contains(low, "does not appear to be a git repository") ||+ strings.Contains(low, "not found") && strings.Contains(low, "repository") || strings.Contains(low, "returned error: 404"):+ return fmt.Errorf("there's no git repository at %s, or it can't be read without signing in (git said: %s)", src.Repo, said)+ case strings.Contains(low, "could not resolve host") || strings.Contains(low, "connection refused") ||+ strings.Contains(low, "connection timed out") || strings.Contains(low, "network is unreachable") || strings.Contains(low, "couldn't connect"):+ return fmt.Errorf("git couldn't reach %s (git said: %s)", host, said)+ }+ return fmt.Errorf("git couldn't fetch %s: %s", src.Repo, said)+}++// gitSaid is git's message, its last few lines, for an error.+func gitSaid(s string) string {+ var keep []string+ for _, l := range strings.Split(strings.TrimSpace(s), "\n") {+ if l = strings.TrimSpace(l); l != "" && !strings.HasPrefix(l, "hint:") {+ keep = append(keep, l)+ }+ }+ if len(keep) > 3 {+ keep = keep[len(keep)-3:]+ }+ out := strings.Join(keep, " / ")+ if r := []rune(out); len(r) > 400 {+ out = string(r[:399]) + "…"+ }+ if out == "" {+ out = "nothing"+ }+ return out+}++// gitHost is the host of a repository's address, for a message.+func gitHost(repo string) string {+ if u, err := url.Parse(repo); err == nil && u.Scheme != "" {+ if u.Host == "" {+ return repo+ }+ return u.Hostname()+ }+ if m := scpLike.FindStringSubmatch(repo); m != nil {+ return m[2]+ }+ return repo+}++// fetchGit fetches the repository's ref (its default branch when "")+// with the user's git, one commit deep, into a new folder, and gives it+// back without its .git: what GitHub's tarball would have. Links are+// checked out as small files holding where they point, as a tarball's+// are left out: never followed out of the folder.+func fetchGit(src Source) (string, error) {+ git := gitPath()+ if git == "" {+ return "", errNoGit()+ }+ ctx, cancel := context.WithTimeout(context.Background(), gitTimeout)+ defer cancel()+ env := gitEnv(git)+ tmp, err := os.MkdirTemp("", skillTemp)+ if err != nil {+ return "", err+ }+ fail := func(err error) (string, error) {+ os.RemoveAll(tmp)+ return "", err+ }+ if _, err := runGit(ctx, git, env, tmp, src, "init", "-q"); err != nil {+ return fail(err)+ }+ ref := src.Ref+ if ref == "" {+ ref = "HEAD"+ }+ if _, err := runGit(ctx, git, env, tmp, src, "fetch", "-q", "--depth", "1", "--no-tags", "--", src.Repo, ref); err != nil {+ // a host that serves git over plain ("dumb") HTTP can't fetch one+ // commit deep: the whole history then+ if !strings.Contains(strings.ToLower(err.Error()), "shallow") {+ return fail(err)+ }+ if _, err := runGit(ctx, git, env, tmp, src, "fetch", "-q", "--no-tags", "--", src.Repo, ref); err != nil {+ return fail(err)+ }+ }+ if _, err := runGit(ctx, git, env, tmp, src, "-c", "advice.detachedHead=false", "checkout", "-q", "FETCH_HEAD"); err != nil {+ return fail(err)+ }+ out, err := runGit(ctx, git, env, tmp, src, "rev-parse", "FETCH_HEAD")+ if err != nil {+ return fail(err)+ }+ if err := os.RemoveAll(filepath.Join(tmp, ".git")); err != nil {+ return fail(err)+ }+ if size := dirSize(tmp); size > maxFetch {+ return fail(fmt.Errorf("%s is %s, over the %s magpie fetches", src.Repo, mb(size), mb(maxFetch)))+ }+ noteGitHead(tmp, strings.TrimSpace(string(out)))+ return tmp, nil+}++func dirSize(dir string) int64 {+ var n int64+ filepath.Walk(dir, func(_ string, fi os.FileInfo, err error) error {+ if err == nil && fi.Mode().IsRegular() {+ n += fi.Size()+ }+ return nil+ })+ return n+}++// gitRemoteHead asks the repository, with git ls-remote, which commit its+// ref (its default branch when "") is at now. A ref that is a commit is+// that commit.+func gitRemoteHead(src Source) (string, error) {+ if hexRef.MatchString(src.Ref) {+ return strings.ToLower(src.Ref), nil+ }+ git := gitPath()+ if git == "" {+ return "", errNoGit()+ }+ ctx, cancel := context.WithTimeout(context.Background(), gitTimeout)+ defer cancel()+ args := []string{"ls-remote", "--", src.Repo}+ if src.Ref == "" {+ args = append(args, "HEAD")+ } else {+ args = append(args, "refs/heads/"+src.Ref, "refs/tags/"+src.Ref, "refs/tags/"+src.Ref+"^{}")+ }+ out, err := runGit(ctx, git, gitEnv(git), os.TempDir(), src, args...)+ if err != nil {+ return "", err+ }+ refs := map[string]string{}+ for _, l := range strings.Split(string(out), "\n") {+ if sha, name, ok := strings.Cut(strings.TrimSpace(l), "\t"); ok {+ refs[name] = sha+ }+ }+ for _, k := range []string{"HEAD", "refs/tags/" + src.Ref + "^{}", "refs/heads/" + src.Ref, "refs/tags/" + src.Ref} {+ if sha := refs[k]; hexRef.MatchString(sha) {+ return sha, nil+ }+ }+ if src.Ref == "" {+ return "", fmt.Errorf("%s names no default branch", src.Repo)+ }+ return "", fmt.Errorf("%s has no branch or tag %s any more", src.Repo, src.Ref)+}++// checkGitSkill checks a skill from a git repository: git ls-remote says+// which commit its ref is at; one the skill was fetched at is current,+// and for another the repository is fetched and the skill's folder+// compared with the library's, since a commit elsewhere in the repository+// doesn't change it. When its files are the repository's, it gives back+// the commit they're at and their hash, for the library to keep.+func checkGitSkill(s *Skill, f *fetcher, asked map[string]string) (SkillCheck, string, string) {+ src := *s.Source+ c := SkillCheck{Name: s.Name, Status: "unknown"}+ head, ok := asked[src.Ref]+ if !ok {+ var err error+ if head, err = gitRemoteHead(src); err != nil {+ c.Error = err.Error()+ return c, "", ""+ }+ asked[src.Ref] = head+ }+ c.Commit = head+ if s.Commit != "" && strings.EqualFold(s.Commit, head) {+ c.Status = "current"+ return c, "", ""+ }+ tmp, err := f.fetch(src)+ if err != nil {+ c.Error = err.Error()+ return c, "", ""+ }+ from := filepath.Join(tmp, filepath.FromSlash(src.Path))+ if _, ok := readMeta(from); !ok {+ c.Error = fmt.Sprintf("%s has no SKILL.md at %s any more", src.Repo, src.Path)+ return c, "", ""+ }+ have := s.Hash+ if have == "" {+ have = hashDir(skillDir(s.Name))+ }+ if theirs := hashDir(from); theirs == "" || theirs != have {+ c.Status = "update"+ return c, "", ""+ }+ c.Status = "current"+ if h := gitHeadOf(tmp); h != "" {+ c.Commit = h+ }+ return c, c.Commit, have+}++// isGit is whether what the user typed is a git repository's address+// magpie fetches from.+func isGit(s string) bool {+ _, ok, err := gitSource(s)+ return ok && err == nil+}diff --git a/internal/library/skillgit_test.go b/internal/library/skillgit_test.gonew file mode 100644index 000000000..1ccb22cc4--- /dev/null+++ b/internal/library/skillgit_test.go@@ -0,0 +1,274 @@+package library++import (+ "errors"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+)++// sunset on Discord: skills from GitLab, and from a company's own GitLab+// on its intranet. What the user types is read as a git repository, with+// a GitLab page's ref and folder; what git would take as an option, or a+// transport that runs a command, is refused.+func TestGitSourceReads(t *testing.T) {+ for _, c := range []struct{ in, repo, ref, path string }{+ {"https://gitlab.com/group/skills", "https://gitlab.com/group/skills", "", ""},+ {"https://gitlab.com/group/skills.git", "https://gitlab.com/group/skills.git", "", ""},+ {"https://git.corp.example/team/sub/deep/skills/", "https://git.corp.example/team/sub/deep/skills", "", ""},+ {"https://git.corp.example/team/sub/skills/-/tree/main/skills/pdf", "https://git.corp.example/team/sub/skills", "main", "skills/pdf"},+ {"https://gitlab.com/g/r/-/tree/HEAD", "https://gitlab.com/g/r", "", ""},+ {"https://gitlab.com/g/r/-/blob/v1.2/skills/pdf/SKILL.md", "https://gitlab.com/g/r", "v1.2", "skills/pdf"},+ {"https://gitea.corp/g/r/src/branch/dev/skills", "https://gitea.corp/g/r", "dev", "skills"},+ {"http://10.0.0.5/g/r.git", "http://10.0.0.5/g/r.git", "", ""},+ {"[email protected]:team/sub/skills.git", "[email protected]:team/sub/skills.git", "", ""},+ {"git@gitlab:team/skills.git", "git@gitlab:team/skills.git", "", ""},+ {"ssh://[email protected]:2222/team/skills.git", "ssh://[email protected]:2222/team/skills.git", "", ""},+ {"file:///srv/git/skills.git", "file:///srv/git/skills.git", "", ""},+ {"gitlab.com/group/skills", "https://gitlab.com/group/skills", "", ""},+ } {+ src, ok, err := gitSource(c.in)+ if !ok || err != nil {+ t.Errorf("%s: ok %v, %v", c.in, ok, err)+ continue+ }+ if src.Kind != "git" || src.Repo != c.repo || src.Ref != c.ref || src.Path != c.path {+ t.Errorf("%s: read as %+v", c.in, src)+ }+ // what the page shows is read back as the same source+ if back, _, err := gitSource(src.String()); err != nil || !sameGitRepo(back.Repo, src.Repo) || back.Ref != src.Ref || back.Path != src.Path {+ t.Errorf("%s: shown as %s, read back as %+v (%v)", c.in, src.String(), back, err)+ }+ }+ for _, in := range []string{"owner/repo", "C:/Users/me/skills", "hello", "", "skills folder"} {+ if _, ok, _ := gitSource(in); ok {+ t.Errorf("%q read as a git repository", in)+ }+ }+ for _, in := range []string{+ "-uhack", "--upload-pack=touch /tmp/x", "ext::sh -c touch% /tmp/x", "file::/tmp/x", "fd::3",+ "https://me:[email protected]/g/r.git", "ftp://host/g/r", "https://gitlab.com/",+ "https://gitlab.com/g/r/-/tree/--upload-pack=x/skills", "https://gitlab.com/g/r/-/tree/main/../../x",+ "git@-oProxyCommand=x:g/r",+ } {+ if _, ok, err := gitSource(in); ok && err == nil {+ t.Errorf("%q isn't refused", in)+ }+ }+}++// gitRepo makes a bare repository with skills in it, and gives its+// file:// address and a function to commit files to it. git runs with no+// system or user config of the machine's (no credential helper, no+// Keychain).+func gitRepo(t *testing.T, files map[string]string) (string, func(map[string]string)) {+ t.Helper()+ git, err := exec.LookPath("git")+ if err != nil {+ t.Skip("git isn't installed")+ }+ old := gitPath+ gitPath = func() string { return git }+ t.Cleanup(func() { gitPath = old })+ t.Setenv("GIT_CONFIG_NOSYSTEM", "1")+ t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(t.TempDir(), "gitconfig"))+ root := t.TempDir()+ bare, work := filepath.Join(root, "skills.git"), filepath.Join(root, "work")+ run := func(dir string, args ...string) {+ t.Helper()+ cmd := exec.Command(git, append([]string{"-c", "user.name=t", "-c", "[email protected]", "-c", "init.defaultBranch=main", "-c", "commit.gpgsign=false"}, args...)...)+ cmd.Dir = dir+ if out, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("git %v: %v\n%s", args, err, out)+ }+ }+ run(root, "init", "-q", "--bare", bare)+ run(root, "init", "-q", work)+ commit := func(files map[string]string) {+ for p, body := range files {+ write(t, filepath.Join(work, filepath.FromSlash(p)), body)+ }+ run(work, "add", "-A")+ run(work, "commit", "-q", "-m", "skills")+ run(work, "push", "-q", bare, "HEAD:refs/heads/main")+ }+ commit(files)+ p := filepath.ToSlash(bare)+ if !strings.HasPrefix(p, "/") {+ p = "/" + p // C:/… on Windows+ }+ return "file://" + p, commit+}++func TestInstallFromGitRepo(t *testing.T) {+ sandbox(t)+ addr, commit := gitRepo(t, map[string]string{+ "skills/pdf/SKILL.md": "---\nname: pdf\ndescription: PDFs\n---\nv1\n",+ "skills/pdf/notes.md": "one",+ "skills/review/SKILL.md": "---\nname: review\ndescription: Reviews\n---\n",+ "README.md": "hi",+ })+ p, err := ProbeSkills(addr)+ if err != nil {+ t.Fatal(err)+ }+ if p.Kind != "git" || len(p.Candidates) != 2 || p.Candidates[0].Path != "skills/pdf" {+ t.Fatalf("probe %+v", p)+ }+ if _, err := InstallSkills(addr, []string{"skills/pdf"}, []string{"claude"}); err != nil {+ t.Fatal(err)+ }+ l, _ := load()+ s := l.skill("pdf")+ if s == nil || s.Source.Kind != "git" || s.Source.Repo != addr || s.Source.Path != "skills/pdf" || s.Hash == "" || len(s.Commit) != 40 {+ t.Fatalf("installed as %+v %+v", s, s.Source)+ }+ if b, err := os.ReadFile(filepath.Join(skillDir("pdf"), "notes.md")); err != nil || string(b) != "one" {+ t.Fatalf("notes.md: %q %v", b, err)+ }+ if _, err := os.Stat(filepath.Join(skillDir("pdf"), ".git")); err == nil {+ t.Fatal("the skill has git's folder")+ }+ installedAt := s.Commit++ // the repository changes the skill: a check says so, an update takes it+ commit(map[string]string{"skills/pdf/notes.md": "two"})+ checks, err := CheckSkills()+ if err != nil {+ t.Fatal(err)+ }+ if len(checks) != 1 || checks[0].Status != "update" {+ t.Fatalf("check %+v", checks)+ }+ if _, err := UpdateSkill("pdf", false); err != nil {+ t.Fatal(err)+ }+ if b, _ := os.ReadFile(filepath.Join(skillDir("pdf"), "notes.md")); string(b) != "two" {+ t.Fatalf("not updated: %q", b)+ }+ l, _ = load()+ updatedAt := l.skill("pdf").Commit+ if len(updatedAt) != 40 || updatedAt == installedAt {+ t.Fatalf("commit after the update %q (was %q)", updatedAt, installedAt)+ }+ if checks, _ := CheckSkills(); len(checks) != 1 || checks[0].Status != "current" {+ t.Fatalf("after the update %+v", checks)+ }++ // a commit elsewhere in the repository leaves the skill current, at it+ commit(map[string]string{"README.md": "changed"})+ if checks, _ := CheckSkills(); len(checks) != 1 || checks[0].Status != "current" || checks[0].Error != "" {+ t.Fatalf("after a commit elsewhere %+v", checks)+ }+ l, _ = load()+ if c := l.skill("pdf").Commit; c == updatedAt || len(c) != 40 {+ t.Fatalf("the commit found the same isn't kept: %q", c)+ }++ // installing it again is had already+ res, err := InstallSkills(addr, []string{"skills/pdf"}, nil)+ if err != nil || len(res.Had) != 1 {+ t.Fatalf("again: %+v %v", res, err)+ }++ // changed here, an update is refused, naming the repository+ write(t, filepath.Join(skillDir("pdf"), "notes.md"), "mine")+ commit(map[string]string{"skills/pdf/notes.md": "three"})+ _, err = UpdateSkill("pdf", false)+ var edited *EditedError+ if !errors.As(err, &edited) || !strings.Contains(err.Error(), "fetched from "+addr) {+ t.Fatalf("an update over a change here: %v", err)+ }+}++// A GitLab page's address of a folder on a branch installs that folder+// from that branch.+func TestGitTreeURLInstallsFolder(t *testing.T) {+ sandbox(t)+ addr, commit := gitRepo(t, map[string]string{"skills/a/SKILL.md": "---\nname: a\ndescription: on main\n---\n"})+ _ = commit+ p, err := ProbeSkills(addr + "/-/tree/main/skills/a")+ if err != nil {+ t.Fatal(err)+ }+ if len(p.Candidates) != 1 || p.Candidates[0].Name != "a" || p.Candidates[0].Path != "skills/a" {+ t.Fatalf("candidates %+v", p.Candidates)+ }+ if _, err := ProbeSkills(addr + "/-/tree/nope/skills/a"); err == nil || !strings.Contains(err.Error(), "no branch or tag nope") {+ t.Fatalf("a missing branch: %v", err)+ }+ if _, err := ProbeSkills(addr + "/-/tree/main/skills/zz"); err == nil || !strings.Contains(err.Error(), "has no folder skills/zz") {+ t.Fatalf("a missing folder: %v", err)+ }+}++// Without git, the probe says git is needed; nothing else is tried.+func TestGitMissingSaysSo(t *testing.T) {+ sandbox(t)+ old := gitPath+ gitPath = func() string { return "" }+ t.Cleanup(func() { gitPath = old })+ _, err := ProbeSkills("https://gitlab.example.com/team/skills.git")+ if err == nil || !strings.Contains(err.Error(), "git isn't installed") {+ t.Fatalf("got %v", err)+ }+}++// A host that wants a sign-in git can't give it: the error says git+// couldn't sign in, and how the user's own git signs in, never waits for+// a password.+func TestGitSignInRefusedSaysSo(t *testing.T) {+ sandbox(t)+ gitRepo(t, map[string]string{"a/SKILL.md": "---\nname: a\n---\n"})+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("WWW-Authenticate", `Basic realm="GitLab"`)+ w.WriteHeader(401)+ }))+ t.Cleanup(srv.Close)+ _, err := ProbeSkills(srv.URL + "/team/private-skills.git")+ if err == nil || !strings.Contains(err.Error(), "git couldn't sign in to 127.0.0.1") {+ t.Fatalf("got %v", err)+ }+}++// What git would read as an option, or a transport that runs a command,+// never reaches git.+func TestGitRefusesOptionsAndTransports(t *testing.T) {+ sandbox(t)+ old := gitPath+ gitPath = func() string { t.Error("git ran"); return "" }+ t.Cleanup(func() { gitPath = old })+ for in, want := range map[string]string{+ "-uhack": "can't start with -",+ "--upload-pack=touch x": "can't start with -",+ "ext::sh -c touch% x": "transport (ext::)",+ "file::/tmp/x": "transport (file::)",+ "https://u:[email protected]/g": "leave the password or token out",+ } {+ if _, err := ProbeSkills(in); err == nil || !strings.Contains(err.Error(), want) {+ t.Errorf("%q: %v", in, err)+ }+ }+}++// git's own words, as it prints them, read as what they mean.+func TestGitErrorsSaid(t *testing.T) {+ src := Source{Kind: "git", Repo: "https://git.corp.example/team/skills.git", Ref: "dev"}+ for msg, want := range map[string]string{+ "fatal: could not read Username for 'https://git.corp.example': terminal prompts disabled\n": "git couldn't sign in to git.corp.example",+ "remote: HTTP Basic: Access denied\nfatal: Authentication failed for 'https://git.corp.example/team/skills.git/'\n": "git couldn't sign in",+ "[email protected]: Permission denied (publickey).\nfatal: Could not read from remote repository.\n": "git couldn't sign in",+ "Host key verification failed.\nfatal: Could not read from remote repository.\n": "host key",+ "fatal: couldn't find remote ref dev\n": "has no branch or tag dev",+ "fatal: unable to access 'https://git.corp.example/team/skills.git/': Could not resolve host: git.corp.example\n": "couldn't reach git.corp.example",+ "xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun\n": "git isn't installed",+ } {+ if err := gitError(src, msg); !strings.Contains(err.Error(), want) {+ t.Errorf("%q said as %q", msg, err)+ }+ }+}diff --git a/internal/library/skills.go b/internal/library/skills.goindex c5a42def5..2a6adc257 100644--- a/internal/library/skills.go+++ b/internal/library/skills.go@@ -34,7 +34,8 @@ type Skill struct {// Hash is of the skill's files as last fetched from GitHub, and Commit// the last commit to have touched its folder there, once a check has// found the two to agree: together they tell whether GitHub has- // changed the skill since.+ // changed the skill since. For one from another git repository,+ // Commit is the commit of the repository it was fetched at.Hash string `json:"hash,omitempty"`Commit string `json:"commit,omitempty"`// From is the repository one not installed from GitHub was found to@@ -43,11 +44,12 @@ type Skill struct {}// Source is where a skill came from: a GitHub repository it can be updated-// from, or a folder on this machine the library links to, so that editing-// the folder is editing the skill.+// from, another git repository (fetched with the user's own git), or a+// folder on this machine the library links to, so that editing the folder+// is editing the skill.type Source struct {- Kind string `json:"kind"` // github | folder- Repo string `json:"repo,omitempty"`+ Kind string `json:"kind"` // github | git | folder+ Repo string `json:"repo,omitempty"` // owner/repo for github, the address git fetches for gitRef string `json:"ref,omitempty"`Path string `json:"path,omitempty"` // in the repositoryDir string `json:"dir,omitempty"` // the folder, for kind folder@@ -60,6 +62,9 @@ func (s *Source) String() string {if s.Kind == "folder" {return s.Dir}+ if s.Kind == "git" {+ return gitURL(s)+ }u := "https://github.com/" + s.Repoif s.Ref != "" || s.Path != "" {ref := s.Ref@@ -747,12 +752,20 @@ var tarballURL = func(repo, ref string) string {return "https://codeload.github.com/" + repo + "/tar.gz/" + url.PathEscape(ref)}-// fetch downloads the repository into a new folder and gives it back. A+// remote is whether a skill's source is a repository it is fetched from+// again to update: GitHub, or another git repository.+func (s *Source) remote() bool { return s != nil && (s.Kind == "github" || s.Kind == "git") }++// fetch downloads the repository into a new folder and gives it back; one+// not on GitHub is fetched with the user's git (fetchGit). A// repository codeload doesn't hand out without a token, a private one, is// asked of GitHub's API with the user's GitHub token (37FlowAI on X): the// API redirects to codeload, and the token, sent to the API's host alone,// isn't carried over to it.func fetch(src Source) (string, error) {+ if src.Kind == "git" {+ return fetchGit(src)+ }c := &http.Client{Timeout: 2 * time.Minute}get := func(u string) (*http.Response, bool, error) {req, _ := http.NewRequest("GET", u, nil)@@ -994,12 +1007,16 @@ func skillsCommand(input string) string {}// ProbeSkills looks for skills at what the user typed: a GitHub repository-// (or a folder in one), a folder on this machine, or a skills CLI command-// for either.+// (or a folder in one), any other git repository (GitLab, one on a+// company's own server; fetched with the user's git), a folder on this+// machine, or a skills CLI command for one of them.func ProbeSkills(input string) (*Probe, error) {input = strings.TrimSpace(skillsCommand(input))if input == "" {- return nil, fmt.Errorf("paste a GitHub link or a folder's path")+ return nil, fmt.Errorf("paste a GitHub or git repository's link or a folder's path")+ }+ if strings.HasPrefix(input, "-") {+ return nil, fmt.Errorf("a repository's address can't start with -")}sweepStaleDownloads()@@ -1011,12 +1028,15 @@ func ProbeSkills(input string) (*Probe, error) {}p.Kind, p.root, p.src = "folder", dir, Source{Kind: "folder", Dir: dir}p.Candidates = candidates(dir, "")- } else if src, ok := githubSource(input); ok {+ } else if src, ok := githubSource(input); ok || isGit(input) {+ if !ok {+ src, _, _ = gitSource(input)+ }tmp, err := fetch(src)if err != nil {return nil, err}- p.Kind, p.root, p.src = "github", tmp, src+ p.Kind, p.root, p.src = src.Kind, tmp, srcif _, err := os.Stat(filepath.Join(tmp, filepath.FromSlash(src.Path))); src.Path != "" && err != nil {os.RemoveAll(tmp)return nil, fmt.Errorf("%s has no folder %s", src.Repo, src.Path)@@ -1024,8 +1044,10 @@ func ProbeSkills(input string) (*Probe, error) {p.Candidates = candidates(tmp, src.Path)p.Left = tookLeftOut(tmp, src.Path)keepProbe(input, p, tmp)+ } else if _, ok, err := gitSource(input); ok && err != nil {+ return nil, err} else {- return nil, fmt.Errorf("that's neither a GitHub repository nor a folder's full path")+ return nil, fmt.Errorf("that's neither a git repository's link (GitHub, GitLab or another host) nor a folder's full path")}if p.Candidates == nil {p.Candidates = []Candidate{}@@ -1104,6 +1126,8 @@ func fromSameSource(s *Skill, src Source, path, from string) bool {switch src.Kind {case "github":return strings.EqualFold(s.Source.Repo, src.Repo) && s.Source.Path == path+ case "git":+ return sameGitRepo(s.Source.Repo, src.Repo) && s.Source.Path == pathcase "folder":return realDir(s.Source.Dir) == realDir(from)}@@ -1152,7 +1176,7 @@ func installFrom(l *Library, p *Probe, paths, agents []string, shown bool, in *iswitch {case src.Kind == "folder" && linked(dir) && realDir(dir) == realDir(from):src.Dir = from- case src.Kind == "github" && !linked(dir) && sameTree(dir, from):+ case src.remote() && !linked(dir) && sameTree(dir, from):src.Path = c.Pathcase src.Kind == "folder" && realDir(from) == realDir(dir):// a folder already in the library's own (#595): linked to@@ -1193,6 +1217,9 @@ func installFrom(l *Library, p *Probe, paths, agents []string, shown bool, in *iin.added = append(in.added, c.Name)}sk := &Skill{Name: c.Name, Source: &src, Agents: slices.Clone(agents)}+ if src.Kind == "git" {+ sk.Hash, sk.Commit = hashDir(dir), gitHeadOf(p.root)+ }if src.Kind == "github" {sk.Hash = hashDir(dir)// every skill the picker showed was offered: a check@@ -1228,7 +1255,7 @@ func UpdateSkill(name string, replace bool) (*Result, error) {f := &fetcher{}defer f.clean()if edited, _ := l.editState(s, Targets()); edited && !replace {- return nil, &EditedError{Name: name}+ return nil, editedError(s)}up, err := f.prepare(s)if err != nil {@@ -1239,7 +1266,7 @@ func UpdateSkill(name string, replace bool) (*Result, error) {if s := l.skill(name); s != nil && !replace {// changed while it was fetchedif edited, _ := l.editState(s, targets); edited {- return &EditedError{Name: name}+ return editedError(s)}}return up.apply(l, targets)@@ -1303,7 +1330,7 @@ func updateSkills(names []string) (*Result, error) {for _, up := range ups {if s := l.skill(up.name); s != nil {if edited, _ := l.editState(s, targets); edited {- failed = append(failed, Problem{What: "skill:" + up.name, Error: (&EditedError{Name: up.name}).Error()})+ failed = append(failed, Problem{What: "skill:" + up.name, Error: editedError(s).Error()})continue}}@@ -1327,10 +1354,10 @@ func updateSkills(names []string) (*Result, error) {return res, nil}-// updatable is whether a skill can be fetched again: one from GitHub, or-// one CC Switch installed from there.+// updatable is whether a skill can be fetched again: one from GitHub or+// another git repository, or one CC Switch installed from GitHub.func updatable(s *Skill) bool {- if s.Source != nil && s.Source.Kind == "github" {+ if s.Source.remote() {return true}_, ok := ccSwitchOrigin(s)@@ -1382,21 +1409,22 @@ func (f *fetcher) clean() {// skillUpdate is a skill fetched again, ready to take the old one's place.type skillUpdate struct {- name string- src *Source- adopt bool- from string+ name string+ src *Source+ adopt bool+ from string+ commit string // the commit a git repository was fetched at}func (f *fetcher) prepare(s *Skill) (*skillUpdate, error) {name := s.Namesrc, adopt := s.Source, false- if src == nil || src.Kind != "github" {+ if !src.remote() {// one CC Switch installed from GitHub becomes the library's own,// fetched from there, leaving CC Switch's folder as it iso, ok := ccSwitchOrigin(s)if !ok {- return nil, fmt.Errorf("%s isn't from GitHub; it's kept as it is", name)+ return nil, fmt.Errorf("%s isn't from GitHub or a git repository; it's kept as it is", name)}src, adopt = &o, true} else {@@ -1422,7 +1450,11 @@ func (f *fetcher) prepare(s *Skill) (*skillUpdate, error) {if _, ok := readMeta(from); !ok {return nil, fmt.Errorf("%s has no SKILL.md at %s any more", src.Repo, src.Path)}- return &skillUpdate{name: name, src: src, adopt: adopt, from: from}, nil+ up := &skillUpdate{name: name, src: src, adopt: adopt, from: from}+ if src.Kind == "git" {+ up.commit = gitHeadOf(tmp)+ }+ return up, nil}// apply puts the fetched skill in the old one's place; the agents' links@@ -1465,8 +1497,8 @@ func (up *skillUpdate) apply(l *Library, targets []*Target) error {s.Source = up.src}// the commit it's at is known again once a check finds the files- // GitHub has to be these- s.Hash, s.Commit = hash, ""+ // GitHub has to be these; a git repository's is the one fetched+ s.Hash, s.Commit = hash, up.commit}forgetCheck(name)if old == "" {diff --git a/internal/library/sync.go b/internal/library/sync.goindex 4c185d29c..41fd4289c 100644--- a/internal/library/sync.go+++ b/internal/library/sync.go@@ -326,7 +326,7 @@ type SkillView struct {Name string `json:"name"`Description string `json:"description"`Source string `json:"source,omitempty"`- Kind string `json:"kind"` // github, folder, or "" for one kept in the library+ Kind string `json:"kind"` // github, git, folder, or "" for one kept in the libraryOrigin string `json:"origin,omitempty"` // on GitHub, as CC Switch installed it: it can be updated from thereRepo string `json:"repo,omitempty"` // the repository it came from, however it came in, for the page to group byIcon string `json:"icon,omitempty"`diff --git a/internal/tui/library.go b/internal/tui/library.goindex 87db01153..a6c52feed 100644--- a/internal/tui/library.go+++ b/internal/tui/library.go@@ -340,12 +340,12 @@ func (m *model) openLibAdd() {input: newInput("filter"),items: []agent.Option{{Value: "mcp server", Note: "a URL, or a command it runs"},- {Value: "skills", Note: "from a GitHub repository, or a folder on this machine"},+ {Value: "skills", Note: "from GitHub, GitLab or any git repository, or a folder on this machine"},},onPick: func(v string) tea.Cmd {return func() tea.Msg {if v == "skills" {- in := newInput("a GitHub link (owner/repo, or a folder in one) or a folder's full path")+ in := newInput("owner/repo, a GitHub or GitLab link, a git address (git@host:group/repo.git), or a folder's full path")in.CharLimit = 400return askMsg{ask{crumbs: []string{"library", "add", "skills"}, input: in,hint: "magpie looks there for skills, then you pick one",