diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 2d90f6966..2ddfb4b92 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -32,7 +32,7 @@ Pi's extensions and packages. | Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`), in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills), go first, marked official: `magpie-setup` has an agent set magpie up as the user asks through its commands (providers, accounts, agents, routing groups and rules, gateway keys and limits, models, the library), and `magpie-quota` lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Their commands live in magpie's CLI, so a change to a command either uses gets the skill updated in that repository. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) | | Skills a repository or folder added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). A git repository on another host has no such list: when `git ls-remote` gives its ref a head, `findNewGit` reads the fetch the check shares (`fetcher`), once per head while its finds are kept (`gitLooked`), and offers the skills under `newBase` with the address as the library has it, `.git` and all, so an Add keeps the same `repo@ref`. A folder the user added linked skills from is kept as `folder:` in `SeenSkills` (`offered`, at install), which is also how the library knows which folder to look in again: `findNewFolder` reads it as Add from folder does and offers a skill folder there the library doesn't link, hasn't offered, and has no skill by that name of; a folder that can't be read keeps what was found. `View.CheckFolders` (`addedFromFolders`, which reads no folder) puts Check for updates on the page with only linked skills, and makes `checkDue` true. A check never adds or writes a skill: each is offered, and one the user removed or set aside isn't offered again. A folder added before this kept no `folder:` key and is looked in only once the user adds from it again (refeccd on Discord; `TestCheckSkillsFindsNewInGitRepo`, `TestCheckSkillsFindsNewInFolder`, `skill-new-in-repo.test.cjs`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) | | Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. That checkout is the one git finds (`provider.GitAt` in `gitRepoOf`): an empty `.git` between the skill and its checkout is passed over, as git passes it over, and a `.git` file that names no repository (a worktree left behind) is none (#3675, `TestSkillRepoTraced`). A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in plugins/library/client.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). A group's, part's, project's or agent's heading opened or folded stays where it was clicked, its rows coming in below it (jinpwng on X, `library-group-steady.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. What installing a skill's dependencies or running it writes in its folder is no change (`fromInstall`: `node_modules`, `.venv`, `venv`, `__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache` folders, `*.pyc`/`*.pyo`, and `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock`, `bun.lockb`, `uv.lock` written again; ggbr on Discord): `Own` is the hash of the files as fetched leaving those aside (`ownHash`), and `onlyInstalled` compares the folder with it, or for a skill fetched before `Own` was kept with `Hash` (so a lock file the install wrote again still reads as changed until its next update). An update carries those entries over to the version fetched where it has none of its own (`carryInstalled`), so they aren't installed again. `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 are found from its fetch (`findNewGit`, above); Group again, icons and the market are GitHub's only. A skill whose source was read whole and no longer has its folder or `SKILL.md` was removed there (`goneFrom`; スライム on Discord): `UpdateSkill` returns `*GoneError`, `UpdateSkills`/`UpdateSomeSkills` list it in `Result.Gone`, not `Unupdated`, and a check gives it status `gone`. Each records `Skill.Gone` (the view's `gone`), cleared when a check or an update finds it there again. A fetch that failed, a skill left out of a fetch as too big (`leftOutAt`) and a folder that can't be read are unknown, never gone. Nothing is taken out by itself: `RemoveGoneSkills` (`POST /api/library/skills/remove-gone`, `magpie library skill rm --gone [--yes]`, the TUI's `d` on the row) takes the ones named, or every one marked, as `RemoveSkills` does, folders to the backups, and keeps one found in its source again. The page tags such a row Removed upstream with no Update, says them apart from failures after Update all, and offers Clean up N in the group's heading (in the bar with one group), which asks first, naming each one and which was changed here (`confirmRemoveGone`, `skill-gone.test.cjs`). | [`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) | +| 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. What installing a skill's dependencies or running it writes in its folder is no change (`fromInstall`: `node_modules`, `.venv`, `venv`, `__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache` folders, `*.pyc`/`*.pyo`, and `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock`, `bun.lockb`, `uv.lock` written again; ggbr on Discord): `Own` is the hash of the files as fetched leaving those aside (`ownHash`), and `onlyInstalled` compares the folder with it, or for a skill fetched before `Own` was kept with `Hash` (so a lock file the install wrote again still reads as changed until its next update). An update carries those entries over to the version fetched where it has none of its own (`carryInstalled`), so they aren't installed again. `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 are found from its fetch (`findNewGit`, above); Group again, icons and the market are GitHub's only. A skill whose source was read whole and no longer has its folder or `SKILL.md` was removed there (`goneFrom`; スライム on Discord): `UpdateSkill` returns `*GoneError`, `UpdateSkills`/`UpdateSomeSkills` list it in `Result.Gone`, not `Unupdated`, and a check gives it status `gone`. Each records `Skill.Gone` (the view's `gone`), cleared when a check or an update finds it there again. A fetch that failed, a skill left out of a fetch as too big (`leftOutAt`) and a folder that can't be read are unknown, never gone. Nothing is taken out by itself: `RemoveGoneSkills` (`POST /api/library/skills/remove-gone`, `magpie library skill rm --gone [--yes]`, the TUI's `d` on the row) takes the ones named, or every one marked, as `RemoveSkills` does, folders to the backups, and keeps one found in its source again. The page tags such a row Removed upstream with no Update, says them apart from failures after Update all, and offers Clean up N in the group's heading (in the bar with one group), which asks first, naming each one and which was changed here (`confirmRemoveGone`, `skill-gone.test.cjs`). Updates by themselves (`AutoUpdateSkills` in library.json, this computer's own; 0xYaCo on X): off by default; on, `KeepSkillsCurrent` (a `gateway.WhileServing` loop) runs `AutoUpdateTick` two minutes after the gateway starts and hourly after, which, every `checkEvery`, runs `CheckSkills` and `UpdateSomeSkills` on the skills it found at `update`, so everything above holds: one changed here stays in `Unupdated` and keeps its Update button, one removed there is only marked, a replaced version that was changed goes to the backups. Updated names and a new error are logged. Set by the Skills tab's Update by themselves switch under the list, shown while a skill comes from GitHub or git (`skillAutoPart`, `POST /api/library/skills/auto-update` with `on`), and `magpie library skill auto-update on\|off` (`TestAutoUpdateSkills`, `skill-auto-update.test.cjs`). | [`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. A session-start hook can be narrowed to some starts (#5604, NEKO-CwC: re-inject a file after compaction alone), one or more of `HookStarts` (startup, resume, clear, compact, fork, Claude Code's words) joined by `|`; `startMatcher` writes each agent's own matcher for them. Claude Code and Codex take the starts as written (Codex reads a `|` list as exact names). Gemini CLI has startup, resume and clear only and compares its matcher whole, so it takes one of them. Grok has `new` (startup and /clear) and `load` (resume), so it takes exactly one of those groups. Cursor's sessionStart takes no matcher. Starts an agent doesn't have are dropped, and one that has all that are left is given the hook whole. An agent that can't run it at exactly the starts picked is refused with why, as for any other per-agent limit: never widened to every start, which would run it at the starts the user narrowed away (a fork per subagent), nor written with a matcher it never matches. The written matcher is in `Applied.Hooks`, so an agent's own edit of the entry is still theirs. `HookAgentView.Starts` lists the matchers each agent takes, and the editor's At which starts app menu greys the chips of those that can't. A bundle carrying a narrowed hook to a magpie before this writes it whole. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `/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.]]` array tables with a `[[hooks..hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:` 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) | | Variables | An `EnvVar` (paopao_baobao on X) is a name, a value and the agents ticked for it (`internal/library/env.go`). Claude Code gets it in `settings.json`'s `env`, Codex in `config.toml`'s `[shell_environment_policy.set]` (`envFile`, `writeEnv`); an agent with no such setting is greyed on the tab, saying why. `syncEnv` records what it wrote in `Applied.Env` and never overrides the user: a name the file already sets to another value is left as it is and reported as a problem on the row (`env:`), and a recorded value the user changed in the file is theirs from then on (the record is dropped, a removal or a turn-off leaves it). Turning an agent off or removing the variable takes out only the recorded, unchanged value. Codex's spelling is respected: a `set` sub-table or an inline `set = {…}` is edited, a dotted spelling is refused with `left as it is`. An unreadable or wrongly typed file is an error, never empty, and nothing is written. Names are `[A-Za-z_][A-Za-z0-9_]*`, at most 128, values at most 8192 bytes. Variables are carried with the library (see below). Tests: `TestEnvWrittenAndTakenOut`, `TestEnvNeverOverridesTheUsers`, `TestEnvValueChanged`, `TestEnvCodexInlineSet`, `TestEnvUnreadableFileLeftAlone`, `TestEnvChecked`, `library-env.test.cjs`. | | 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` (`.agent.md`); a TOML role (`name`, `description`, `model` when set, `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. A subagent's optional `Model` (a model or routing group of Codex's list, `subagentModels` in `/api/library`) is written only into Codex's role (luckymanjc on Discord): the role file is a config layer, and Codex lays its `model` over the one its lead names in spawn_agent (`apply_spawn_agent_role` after `apply_requested_spawn_agent_model_overrides` in codex-rs `core/src/agent/child_config.rs`), so the subagent's requests carry it and the gateway routes them as any other. Codex's subagent model on the Agents page (`CodexSubagentModel`), when set, still rewrites every subagent's request, and the editor says so. Without one, a Codex subagent runs on the model its lead names, else the lead's own. The page lists, per agent, whether it binds skills, servers and a model (`SubagentAgentView`), names the agents that run a subagent on their own pick, and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) | @@ -125,11 +125,13 @@ go test -race ./internal/mcpauth go test -tags nogui ./internal/library go test -tags nogui ./internal/library -run 'TestWSLStopped' go test -tags nogui ./internal/library -run 'TestRTKWSL' +go test -tags nogui ./internal/library -run 'TestAutoUpdateSkills' go test -tags nogui ./internal/library -run 'TestBili|TestParseBiliList' go test -tags nogui ./internal/gui -run TestBiliSettingsRoute go test -tags nogui ./internal/library -run 'TestPi' node --test internal/gui/tests/library-pi-extensions.test.cjs internal/gui/tests/library-pi-market.test.cjs node --test internal/gui/tests/library-rtk-wsl.test.cjs +node --test internal/gui/tests/skill-auto-update.test.cjs node --test internal/gui/tests/library-wsl-asleep.test.cjs node --test internal/gui/tests/skill-off-here.test.cjs internal/gui/tests/mcp-local-server.test.cjs internal/gui/tests/mcp-server-here.test.cjs internal/gui/tests/skill-handover.test.cjs node --test internal/gui/tests/mcp-accounts.test.cjs internal/gui/tests/library-items.test.cjs internal/gui/tests/library-mcp-hub.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-gone.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-subagents-import.test.cjs internal/gui/tests/library-plugins.test.cjs internal/gui/tests/library-mcp-health.test.cjs internal/gui/tests/library-mcp-health-wsl.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 diff --git a/internal/cli/library_cli.go b/internal/cli/library_cli.go index b0f2a115d..844050893 100644 --- a/internal/cli/library_cli.go +++ b/internal/cli/library_cli.go @@ -50,6 +50,7 @@ const libraryUsage = `magpie library what the library gives magpie library skill how link|copy [agent] give skills as links to the library's or as copies: every agent's way, or one agent's magpie library skill how default the agent goes the library's way again magpie library skill where agents|shared skills go to the agents ticked, or also into ~/.agents/skills for every agent and tool that reads it + magpie library skill auto-update on|off fetch each skill from GitHub or git again by itself when it changes there (one changed here stays) magpie library skill use-library an agent's own skill by that name is in the way: set it aside, link the library's magpie library skill keep-own …or keep the agent's, and take the agent off the library's magpie library project … a project folder's own skills (Library › Projects): magpie library project help @@ -273,6 +274,8 @@ func libraryCmd(args []string) error { res, err = library.SetSkillHow(agent, how) case len(rest) == 2 && rest[0] == "where" && (rest[1] == library.SkillsInAgents || rest[1] == library.SkillsInShared): res, err = library.SetSkillsWhere(rest[1]) + case len(rest) == 2 && rest[0] == "auto-update" && (rest[1] == "on" || rest[1] == "off"): + res, err = library.SetAutoUpdateSkills(rest[1] == "on") default: return fmt.Errorf("usage:\n %s", libraryUsage) } diff --git a/internal/cli/main.go b/internal/cli/main.go index 41dabc231..28181ddf9 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -25,6 +25,7 @@ import ( "github.com/yetone/magpie/internal/davsync" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/imagemcp" + "github.com/yetone/magpie/internal/library" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/notices" "github.com/yetone/magpie/internal/plugin" @@ -512,6 +513,9 @@ func run(args []string) error { // server's, a container's), at Claude Code's newest release: its runs // turn its own updater off gateway.WhileServing = append(gateway.WhileServing, claudecode.KeepCurrent) + // and the library's skills from GitHub and git repositories, fetched + // again by themselves when that is switched on (0xYaCo on X) + gateway.WhileServing = append(gateway.WhileServing, library.KeepSkillsCurrent) // and the request archive, when it is on, goes to the bucket sync is to gateway.ArchiveBucket = func() (gateway.Putter, bool) { if b, ok := davsync.S3Bucket(); ok { diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 172569cb0..3025a3a9c 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -5328,7 +5328,7 @@ magpie.plugin("library", (ctx) => { drawSkills(box, all); body.append(box); // under the list, so the skills stay where they were above it - if (all.length) body.append(skillHowBar(), skillWhereBar(), ...skillRouterPart()); + if (all.length) body.append(skillHowBar(), skillWhereBar(), ...skillAutoPart(), ...skillRouterPart()); if (picking) body.append(pickBar(all)); } if (lib.newSkills?.length) renderNewSkills(body); @@ -6878,6 +6878,23 @@ magpie.plugin("library", (ctx) => { return bar; } + // Updates by themselves (0xYaCo on X): with the switch on, magpie checks + // the skills from GitHub and git repositories as this page does and + // fetches again each one changed there; one changed here keeps its + // Update button (skill_autoupdate.go). Only with such a skill to update. + function skillAutoPart() { + if (!lib.autoUpdateSkills && !lib.skills.some((s) => s.kind === "github" || s.kind === "git")) return []; + const list = el("div", "list lib-list lib-hublist lib-skillauto"); + const row = el("div", "row lib-row lib-hub"); + const who = el("div", "who"); + who.append(el("div", "name", t("Update by themselves"))); + who.append(el("div", "sub wraps", t("Fetch skills from GitHub and git again when they change there. One you changed here stays as it is."))); + row.append(glyph(GLYPH.down), who, toggle(!!lib.autoUpdateSkills, t("Update by themselves"), (on) => + change("skills/auto-update", { on }, on ? t("Skills update by themselves now") : t("Skills wait for you to update them now")))); + list.append(row); + return [list]; + } + // The skill router: each agent is given one skill, magpie-skills, whose // SKILL.md lists the skills ticked for it, in place of a link of each; // the agent reads one's SKILL.md when a task fits it (skill_router.go). diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 493b79889..590506cf8 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -2,6 +2,10 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "Update by themselves": "自动更新", + "Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "GitHub 和 git 上的技能有改动时自动重新获取。你在这里改过的技能保持不变。", + "Skills update by themselves now": "技能现在会自动更新", + "Skills wait for you to update them now": "技能现在等你手动更新", "+ Add account": "+ 添加账号", "Account {n}": "账号 {n}", "New skill": "新建技能", @@ -1041,6 +1045,10 @@ magpie.strings({ "{name} read again from its source": "已重新从来源读取 {name}", }, "zh-TW": { + "Update by themselves": "自動更新", + "Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "GitHub 和 git 上的技能有變動時自動重新取得。你在這裡改過的技能保持不變。", + "Skills update by themselves now": "技能現在會自動更新", + "Skills wait for you to update them now": "技能現在等你手動更新", "+ Add account": "+ 新增帳號", "Account {n}": "帳號 {n}", "New skill": "新增技能", @@ -2080,6 +2088,10 @@ magpie.strings({ "{name} read again from its source": "已重新從來源讀取 {name}", }, ja: { + "Update by themselves": "自動で更新", + "Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "GitHub や git でスキルが変わったら自動で取得し直します。ここで変更したスキルはそのままです。", + "Skills update by themselves now": "スキルは自動で更新されるようになりました", + "Skills wait for you to update them now": "スキルは手動で更新するようになりました", "+ Add account": "+ アカウントを追加", "Account {n}": "アカウント {n}", "New skill": "新しいスキル", @@ -3119,6 +3131,10 @@ magpie.strings({ "{name} read again from its source": "{name} をソースから読み直しました", }, de: { + "Update by themselves": "Selbst aktualisieren", + "Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "Skills von GitHub und git neu laden, wenn sie sich dort ändern. Ein hier geänderter Skill bleibt, wie er ist.", + "Skills update by themselves now": "Skills aktualisieren sich jetzt selbst", + "Skills wait for you to update them now": "Skills warten jetzt, bis du sie aktualisierst", "+ Add account": "+ Konto hinzufügen", "Account {n}": "Konto {n}", "New skill": "Neuer Skill", diff --git a/internal/gui/library.go b/internal/gui/library.go index 571762fe1..59079053b 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -873,6 +873,9 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { case "skills/where": // each agent's own folder, or ~/.agents/skills too (skills_shared.go) res, err = library.SetSkillsWhere(in.How) + case "skills/auto-update": + // fetched again by themselves when changed there (skill_autoupdate.go) + res, err = library.SetAutoUpdateSkills(in.On) case "skills/router": // magpie's one skill listing the rest (skill_router.go) res, err = library.SetSkillRouter(in.On) diff --git a/internal/gui/tests/skill-auto-update.test.cjs b/internal/gui/tests/skill-auto-update.test.cjs new file mode 100644 index 000000000..2282995e2 --- /dev/null +++ b/internal/gui/tests/skill-auto-update.test.cjs @@ -0,0 +1,109 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// 0xYaCo on X: "skill 能自动化升级吗?". The Skills tab has a switch, Update +// by themselves, under the list while a skill came from GitHub or git: it +// posts skills/auto-update and shows the state the library answers. A +// library of the user's own folders only has nothing to update and no +// switch. In every language, in Chromium and WebKit. 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/yaco"; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills` }); +const gh = (name) => ({ name, description: name + " skill", kind: "github", source: `https://github.com/anthropics/skills/tree/HEAD/skills/${name}`, agents: ["claude"] }); +const mine = (name) => ({ name, description: name + " of mine", kind: "folder", source: `${HOME}/skills/${name}`, agents: ["claude"] }); +const lib = (st) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("claude", "Claude Code")], + instructions: { agents: [] }, servers: [], foundServers: [], projects: [], foundSkills: [], newSkills: [], + checkDue: false, autoUpdateSkills: st.on, + skills: st.github ? [gh("pdf"), gh("docx"), mine("notes")] : [mine("notes"), mine("todo")], +}); + +function server(lang, posts, st) { + 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(st) }); + if (url.pathname.startsWith("/api/library/skills/")) { + const what = url.pathname.split("/").pop(), body = req.postDataJSON(); + posts.push({ what, body }); + if (what === "auto-update") st.on = body.on; + return route.fulfill({ json: { ...lib(st), 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: { name: "Update by themselves", on: "Skills update by themselves now", off: "Skills wait for you to update them now" }, + zh: { name: "自动更新", on: "技能现在会自动更新", off: "技能现在等你手动更新" }, + "zh-TW": { name: "自動更新", on: "技能現在會自動更新", off: "技能現在等你手動更新" }, + ja: { name: "自動で更新", on: "スキルは自動で更新されるようになりました", off: "スキルは手動で更新するようになりました" }, + de: { name: "Selbst aktualisieren", on: "Skills aktualisieren sich jetzt selbst", off: "Skills warten jetzt, bis du sie aktualisierst" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Skills tab's Update by themselves switch", 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 lang of Object.keys(words)) { + await t.test(lang, async () => { + const w = words[lang], posts = [], st = { on: false, github: true }; + const ctx = await browser.newContext({ viewport: { width: 400, height: 900 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, posts, st)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const v = page.locator("#view-library"); + const row = v.locator(".lib-skillauto .lib-row"); + await row.waitFor(); + assert.equal((await row.locator(".name").textContent()).trim(), w.name); + const sw = row.locator('[role="switch"]'); + assert.equal(await sw.getAttribute("aria-checked"), "false"); + assert.equal(await sw.getAttribute("aria-label"), w.name); + // the row fits a narrow window + const box = await row.boundingBox(); + assert(box.x >= 0 && box.x + box.width <= 400, `row out of the window: ${JSON.stringify(box)}`); + + await sw.click(); + await page.waitForFunction((x) => document.querySelector("#status").textContent.trim() === x, w.on); + await page.waitForFunction(() => document.querySelector('.lib-skillauto [role="switch"]')?.getAttribute("aria-checked") === "true"); + await v.locator('.lib-skillauto [role="switch"]').click(); + await page.waitForFunction((x) => document.querySelector("#status").textContent.trim() === x, w.off); + assert.deepEqual(posts, [{ what: "auto-update", body: { on: true } }, { what: "auto-update", body: { on: false } }]); + + // nothing from GitHub or git: nothing to update, no switch + st.github = false; + await page.reload(); + await page.locator('button[data-view="library"]').click(); + await v.locator(".lib-skill").first().waitFor(); + assert.equal(await v.locator(".lib-skillauto").count(), 0); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/library/library.go b/internal/library/library.go index a75d50ac2..db0bce77c 100644 --- a/internal/library/library.go +++ b/internal/library/library.go @@ -63,6 +63,10 @@ type Library struct { // that reads it (usrname1833, skills_shared.go). This computer's // own: Collect doesn't carry it SharedSkills bool `json:"sharedSkills,omitempty"` + // AutoUpdateSkills fetches again by itself each skill its GitHub or + // git repository has changed (0xYaCo on X, skill_autoupdate.go). This + // computer's own: Collect doesn't carry it + AutoUpdateSkills bool `json:"autoUpdateSkills,omitempty"` // MCPHub gives each agent that can reach it magpie's one MCP server, // which hands each call on to the library's servers ticked for it, in // place of their own entries (#2679, mcp_hub.go) diff --git a/internal/library/skill_autoupdate.go b/internal/library/skill_autoupdate.go new file mode 100644 index 000000000..b4c85ab25 --- /dev/null +++ b/internal/library/skill_autoupdate.go @@ -0,0 +1,113 @@ +package library + +// Skills kept up to date by themselves (0xYaCo on X: "skill 能自动化升级吗?"). +// With the switch on (AutoUpdateSkills), the gateway checks the skills +// from GitHub and other git repositories as the Library page does, a +// little after magpie starts and every checkEvery after, and fetches +// again each one the check found changed there. Everything an update by +// hand does holds: a skill changed here is left as it is and keeps its +// Update button (updateSkills refuses it), one removed there is only +// marked, and a replaced version that was changed goes to the backups. +// Off, the default, the page shows what changed and the user updates it. + +import ( + "context" + "log" + "slices" + "strings" + "sync" + "time" +) + +// SetAutoUpdateSkills turns updating the skills by themselves on or off. +func SetAutoUpdateSkills(on bool) (*Result, error) { + return change(func(l *Library) error { + l.AutoUpdateSkills = on + return nil + }) +} + +const ( + // autoUpdateFirst is how long after magpie starts the first look is: + // the start itself has enough to do + autoUpdateFirst = 2 * time.Minute + // autoUpdatePoll is how often the loop asks whether a look is due, so + // switching on is acted on within the hour + autoUpdatePoll = time.Hour +) + +// autoUpdate is when the last look by itself was, and its error, said +// once in the log until it changes. +var autoUpdate struct { + sync.Mutex + at time.Time + err string +} + +// AutoUpdateTick looks for changed skills and updates them, when the +// switch is on and no look was made for checkEvery. It returns what the +// update did, nil when nothing was due or nothing had changed. +func AutoUpdateTick(now time.Time) (*Result, error) { + mu.Lock() + l, err := load() + mu.Unlock() + if err != nil { + return nil, err + } + if !l.AutoUpdateSkills || !slices.ContainsFunc(l.Skills, func(s *Skill) bool { return s.Source.remote() }) { + return nil, nil + } + autoUpdate.Lock() + due := autoUpdate.at.IsZero() || now.Sub(autoUpdate.at) >= checkEvery + if due { + autoUpdate.at = now + } + autoUpdate.Unlock() + if !due { + return nil, nil + } + checks, err := CheckSkills() + if err != nil { + return nil, err + } + var names []string + for _, c := range checks { + if c.Status == "update" { + names = append(names, c.Name) + } + } + if len(names) == 0 { + return nil, nil + } + return UpdateSomeSkills(names) +} + +// KeepSkillsCurrent runs AutoUpdateTick while the gateway serves. +func KeepSkillsCurrent(ctx context.Context) { + t := time.NewTimer(autoUpdateFirst) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + } + t.Reset(autoUpdatePoll) + res, err := AutoUpdateTick(time.Now()) + autoUpdate.Lock() + msg := "" + if err != nil { + msg = err.Error() + } + if msg != autoUpdate.err { + if msg != "" { + log.Printf("updating skills by themselves: %s", msg) + } + autoUpdate.err = msg + } + autoUpdate.Unlock() + if res != nil && len(res.Updated) > 0 { + log.Printf("skills updated by themselves: %s", strings.Join(res.Updated, ", ")) + } + } +} diff --git a/internal/library/skill_autoupdate_test.go b/internal/library/skill_autoupdate_test.go new file mode 100644 index 000000000..9d8e07920 --- /dev/null +++ b/internal/library/skill_autoupdate_test.go @@ -0,0 +1,66 @@ +package library + +import ( + "os" + "path/filepath" + "slices" + "testing" + "time" +) + +// 0xYaCo on X: "skill 能自动化升级吗?". With the switch on, a skill its +// repository changed is fetched again by itself; off, it waits for the +// user; one changed here is left as it is; a look isn't made again until +// checkEvery has gone by. +func TestAutoUpdateSkills(t *testing.T) { + sandbox(t) + autoUpdate.Lock() + autoUpdate.at = time.Time{} + autoUpdate.Unlock() + addr, commit := gitRepo(t, map[string]string{ + "skills/pdf/SKILL.md": "---\nname: pdf\ndescription: PDFs\n---\n", + "skills/pdf/notes.md": "one", + }) + if _, err := InstallSkills(addr, []string{"skills/pdf"}, []string{"claude"}); err != nil { + t.Fatal(err) + } + notes := func() string { + b, _ := os.ReadFile(filepath.Join(skillDir("pdf"), "notes.md")) + return string(b) + } + commit(map[string]string{"skills/pdf/notes.md": "two"}) + now := time.Now() + + // off, the default: nothing is fetched + if res, err := AutoUpdateTick(now); err != nil || res != nil || notes() != "one" { + t.Fatalf("off: %+v %v, notes %q", res, err, notes()) + } + + if _, err := SetAutoUpdateSkills(true); err != nil { + t.Fatal(err) + } + if v, err := Read(nil); err != nil || !v.AutoUpdateSkills { + t.Fatalf("the view doesn't say it is on: %v", err) + } + res, err := AutoUpdateTick(now) + if err != nil || res == nil || !slices.Equal(res.Updated, []string{"pdf"}) || notes() != "two" { + t.Fatalf("on: %+v %v, notes %q", res, err, notes()) + } + + // not due again within checkEvery + commit(map[string]string{"skills/pdf/notes.md": "three"}) + if res, err := AutoUpdateTick(now.Add(time.Hour)); err != nil || res != nil || notes() != "two" { + t.Fatalf("an hour later: %+v %v, notes %q", res, err, notes()) + } + if res, err := AutoUpdateTick(now.Add(checkEvery)); err != nil || res == nil || notes() != "three" { + t.Fatalf("after checkEvery: %+v %v, notes %q", res, err, notes()) + } + + // changed here: left as it is + write(t, filepath.Join(skillDir("pdf"), "notes.md"), "mine") + commit(map[string]string{"skills/pdf/notes.md": "four"}) + res, err = AutoUpdateTick(now.Add(2 * checkEvery)) + if err != nil || res == nil || len(res.Updated) != 0 || len(res.Unupdated) != 1 || notes() != "mine" { + t.Fatalf("changed here: %+v %v, notes %q", res, err, notes()) + } +} diff --git a/internal/library/sync.go b/internal/library/sync.go index 5aa657e0e..836b77063 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -548,6 +548,9 @@ type View struct { // (skills_shared.go), at SharedDir SharedSkills bool `json:"sharedSkills"` SharedDir string `json:"sharedDir"` + // AutoUpdateSkills: the skills from GitHub and git repositories are + // updated by themselves (skill_autoupdate.go) + AutoUpdateSkills bool `json:"autoUpdateSkills"` // MCPHub: the agents are given magpie's one MCP server in place of // the library's (#2679), at HubPath on the gateway MCPHub bool `json:"mcpHub"` @@ -626,7 +629,7 @@ func readView(problems []Problem, glance bool) (*View, error) { // the agents are found once for the whole read: finding them looks // through every agent's folders, in WSL too (#1624) targets, asleep := targetsAsleep(false) - v := &View{Agents: []AgentView{}, Servers: []ServerView{}, Skills: []SkillView{}, FoundSkills: []FoundSkill{}, Instructions: l.instructionsView(targets, asleep), Dir: Dir(), Backups: BackupDir(), CopySkills: l.CopySkills, SharedSkills: l.SharedSkills, SharedDir: sharedSkillsDir(), MCPHub: l.MCPHub, SkillRouter: l.SkillRouter, HubPath: gateway.HubMCPPath, HubNote: settings.Shared().RouterNote, HubName: gateway.HostName(), HubAllTools: settings.Shared().RouterAllTools, Partial: glance} + v := &View{Agents: []AgentView{}, Servers: []ServerView{}, Skills: []SkillView{}, FoundSkills: []FoundSkill{}, Instructions: l.instructionsView(targets, asleep), Dir: Dir(), Backups: BackupDir(), CopySkills: l.CopySkills, SharedSkills: l.SharedSkills, SharedDir: sharedSkillsDir(), AutoUpdateSkills: l.AutoUpdateSkills, MCPHub: l.MCPHub, SkillRouter: l.SkillRouter, HubPath: gateway.HubMCPPath, HubNote: settings.Shared().RouterNote, HubName: gateway.HostName(), HubAllTools: settings.Shared().RouterAllTools, Partial: glance} for _, t := range targets { av := AgentView{ID: t.Agent.ID, Name: t.Agent.Name, Icon: t.Agent.Icon, Instructions: t.Instructions, Skills: t.Skills, SkillsAlso: t.SkillsAlso, Note: t.Note, MCPVia: t.MCPVia, ProjectSkills: ProjectSkillsDir(t.Agent.ID), ProjectMCP: ProjectMCPFile(t.Agent.ID), ProjectSubagents: ProjectSubagentsDir(t.Agent.ID),