diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 7bb31101c..456a3d582 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -20,7 +20,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first (`sweepShared`, then `syncShared` for the Put skills in setting), so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) | | 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. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `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). A command named bare that magpie's PATH lacks is started from where `proc.FindTool` finds it (fnm's Nodes on Windows among the folders), with that folder on the check's PATH, since npx's package runs the node beside it by name (`stdioProgram`, #2685, `TestStdioProgramFindsWhatPathLacks`). 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/`), 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 refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and each Codex target's `.credentials.json` beside its config.toml for a flattened entry of them, the file codex-rs falls back to when its config's `mcp_oauth_credentials_store` is `file` or the keyring is missing, whose executor's own entries are no `codex mcp login` (#3508); and the row says "signed in in Claude Code (Ubuntu)" — or Codex — instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in nor Codex's keyring store. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#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:/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). The editor's command is a box that wraps, so a long line is read whole, and Enter still saves it (hema_17384 on Discord). Its Form | JSON switch shows the server as JSON in Claude Code's `.mcp.json` shape, the one Copy config… gives for it (`jsonOf` in plugins/library/client.js), with `${NAME}` references as written. An edit there is read as a paste is (`serversIn`) and becomes the form's at once. JSON that isn't one server's keeps the dialog from saving or going back to the form, and counts as unsaved. The agents and sync stay in the form (`library-mcp-json.test.cjs`). 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). A server run as `npx -y args` (a registry package, no other npx flag) is given to an agent on this machine as `node args` (`npxDirect`): magpie installs the package with npm into a folder of its own under `mcp-npm` in the background, the next sync writes the node form, and until then, or when npm fails (tried again after an hour), the agent keeps npx. npx otherwise stays as the server's parent for its whole life, a node and two cmd.exe beside each instance on Windows (#3885). An unpinned spec is installed again after a day, as npx would fetch the newer one; an install no library server runs goes a day after its last. The library, a server's check, Copy config… and agents in WSL keep npx (`TestNpxServerRunsByNode`, `TestReadNpx`). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_npx.go`](../../internal/library/mcp_npx.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.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. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `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). A command named bare that magpie's PATH lacks is started from where `proc.FindTool` finds it (fnm's Nodes on Windows among the folders), with that folder on the check's PATH, since npx's package runs the node beside it by name (`stdioProgram`, #2685, `TestStdioProgramFindsWhatPathLacks`). 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/`), 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 refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and each Codex target's `.credentials.json` beside its config.toml for a flattened entry of them, the file codex-rs falls back to when its config's `mcp_oauth_credentials_store` is `file` or the keyring is missing, whose executor's own entries are no `codex mcp login` (#3508); and the row says "signed in in Claude Code (Ubuntu)" — or Codex — instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in nor Codex's keyring store. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#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:/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). The editor's command is a box that wraps, so a long line is read whole, and Enter still saves it (hema_17384 on Discord). Its Form | JSON switch shows the server as JSON in Claude Code's `.mcp.json` shape, the one Copy config… gives for it (`jsonOf` in plugins/library/client.js), with `${NAME}` references as written. An edit there is read as a paste is (`serversIn`) and becomes the form's at once. JSON that isn't one server's keeps the dialog from saving or going back to the form, and counts as unsaved. The note, the agents and sync stay in the form (`library-mcp-json.test.cjs`). A server's and a skill's `Note` (youyo.p_10001 on Discord) is the user's own word on what it is for: one line of at most `maxNote` (200) characters, whitespace run together (`checkNote`), as a hook's description is. The row shows it in place of the command or description, and its tooltip still gives that line. The skills' filter reads it too. A sync carries it (a server whole, a skill as `CarriedSkill.Note`), and no agent is given it, through the MCP router or not (`TestNoteNeverGiven`, `TestNoteCarried`). A skill's is set by itself (`SkillNote`, `skills/note`) from the skill's reader. 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). A server run as `npx -y args` (a registry package, no other npx flag) is given to an agent on this machine as `node args` (`npxDirect`): magpie installs the package with npm into a folder of its own under `mcp-npm` in the background, the next sync writes the node form, and until then, or when npm fails (tried again after an hour), the agent keeps npx. npx otherwise stays as the server's parent for its whole life, a node and two cmd.exe beside each instance on Windows (#3885). An unpinned spec is installed again after a day, as npx would fetch the newer one; an install no library server runs goes a day after its last. The library, a server's check, Copy config… and agents in WSL keep npx (`TestNpxServerRunsByNode`, `TestReadNpx`). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_npx.go`](../../internal/library/mcp_npx.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) | | MCP router | With `MCPHub` on, `syncMCP` gives each agent that can take it one entry, `magpie`, at the gateway's `/mcp/magpie/hub/`, in place of the servers ticked for it; magpie runs those servers itself, once for every agent. | [MCP router](mcp-router.md), [`mcp_hub.go`](../../internal/library/mcp_hub.go) | | MCP market | `MarketServers` lists the featured servers that match a search, then the MCP Registry's; a search that is an address (a repository, a page, an endpoint, a package; `market_addr.go`) finds the ones at it, and `CustomAt` offers one to fill in by hand when none is. The registry lists no server by a repository's folder, so a GitHub address naming one (`#subdirectory=`, `/tree//…`, `parseRepoAt`) is read first: the folder's `pyproject.toml` names the program, and the README's `"env": {…}` examples the keys, offered as `uvx --from git+https://github.com/o/r#subdirectory=p ` (`fromRepo`, CyberCaius on Discord: volcengine/mcp-server's askecho search). A bare repository is read so only when the registry has nothing at it, and a PyPI page, or a one-word search naming mcp the registry lists nothing by, asks PyPI (`fromPyPI`, `uvx `). Of several README keys none is required, since a README often has the user pick one way to sign in (`envInputs`; `TestMarketServerInRepoFolder`). Only Python projects are read from a folder; a Node one there still gets the blank form. | [`market.go`](../../internal/library/market.go), [`market_repo.go`](../../internal/library/market_repo.go) | | Skills | A skill is a folder with a `SKILL.md`. It goes by the `name` its front matter gives, made fit for a file name (ASCII letters, digits, `_` and `-`); a name that would lose a letter or digit that way (one in another script, `CTF•密码学`) or none goes by its folder's name instead, and a skill at a repository's top by the repository's (`nameFor`, `srcFolder`). Two skills a probe names alike are listed once (`unhiddenFirst`), so names that fell to `CTF`, `Strix` and nothing listed asdfgh1445/ctf-super-hub's 35 skills as 16 (tnt1223 on Discord, `TestSkillsNamedInAnotherScriptAllListed`). It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree//`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- ` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro gets a link too, to the distro's one copy of the skill, magpie's, in `~/.local/share/magpie/skills` (`Target.Store`, `storeSkill`; cutemmuu on X): the distro can't follow a link to the library's folder on Windows, and a link Windows makes through `\\wsl.localhost` is an empty folder in the distro, which in turn shows Windows its own links as entries it can't read, follow or remove, so the link is made, read and taken away in the distro by wsl.exe (`agent.WSLSymlink`, `WSLReadlink`, `WSLRemoveLink`; `TestWSLLinksLive` and `TestWSLSkillsLinkedLive` on a real distro with `MAGPIE_WSL_TEST_DISTRO`). An edit made through the link is in the distro's copy, which `takeEdits` reads as any copy of magpie's (`TestWSLEditThroughLinkReachesTheLibrary`); a copy no agent there links to or is given any more goes, to the backups when edited (`sweepWSLStores`, `TestWSLStoreSweepKeepsEdits`); a folder there that isn't magpie's is never touched, and each agent it is in the way of says so. The copy isn't put in the distro's `~/.agents/skills`, since every agent there reading that folder would get each skill, ticked for it or not. An agent set to copies gets one of its own, as does one whose skills folder or the store is on a Windows drive (#4502), where the distro's link is one Windows can't read. A copy an agent there was given before is made a link on the next sync, its edit taken first and a losing edit set aside (`wslRelink`, `TestWSLOldCopiesBecomeLinks`). A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), only as far as the caller reads: a link to a folder and an update ask GitHub for that folder's own list (`treeUnder`, git's `ref:path`; the whole list when that fails), the market fetches only the skills whose folder is the one it installs (#2794, sickn33/agentic-awesome-skills' 8,589 skills are 287 MB together), and a fetcher keeps such a part apart from another skill's of the same repository, which would otherwise read as removed (`fetcher.get`, `TestMarketSkillFromAHugeRepository`). GitHub's list is read up to `maxTree` (64 MB; that repository's is 11 MB) and an answer over the cap a caller gives `apiGet`, or one cut off, is an error saying so, never a body cut short for JSON to trip on (ye4241's `TestRepoTreeBigList`, `TestApiGetWholeAnswer`); a list GitHub truncated itself is too big (`TestTruncatedListIsTooBig`). And a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go), [`skill_beside.go`](../../internal/library/skill_beside.go) | diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index e376d6e48..5bf953992 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1719,6 +1719,7 @@ const I18N = { "{agent} is on the routing group {group}, {model} here among its members — click to change": "{agent} 正在使用路由组 {group},{model} 为其成员 — 点击更改", "e.g. My Relay": "例如 My Relay", "Name": "名称", + "Note": "备注", "Form": "表单", "OpenAI compatible": "OpenAI 兼容", "Base URL: type the {api} URL, or pick the API the URL you have is for": "Base URL:请填写 {api} 的地址,或改选你已有地址所属的协议", @@ -6271,6 +6272,7 @@ const I18N = { "{agent} is on the routing group {group}, {model} here among its members — click to change": "{agent} 正在使用路由組 {group},{model} 為其成員 — 點選更改", "e.g. My Relay": "例如 My Relay", "Name": "名稱", + "Note": "備註", "Form": "表單", "OpenAI compatible": "OpenAI 相容", "Base URL: type the {api} URL, or pick the API the URL you have is for": "Base URL:請填寫 {api} 的位址,或改選你已有位址所屬的協議", @@ -10799,6 +10801,7 @@ const I18N = { "{agent} is on the routing group {group}, {model} here among its members — click to change": "{agent} はルーティンググループ {group} を使用中で、ここの {model} はそのメンバーです — クリックして変更", "e.g. My Relay": "例:My Relay", "Name": "名前", + "Note": "メモ", "Form": "フォーム", "OpenAI compatible": "OpenAI 互換", "Base URL: type the {api} URL, or pick the API the URL you have is for": "Base URL:{api} の URL を入力するか、お持ちの URL が対応する API を選んでください", @@ -15358,6 +15361,7 @@ const I18N = { "{agent} is on the routing group {group}, {model} here among its members — click to change": "{agent} nutzt die Weiterleitungsgruppe {group}, zu der {model} gehört — zum Ändern klicken", "e.g. My Relay": "z. B. Mein Relay", "Name": "Name", + "Note": "Notiz", "Form": "Formular", "OpenAI compatible": "OpenAI-kompatibel", "Base URL: type the {api} URL, or pick the API the URL you have is for": "Base URL: Gib die {api}-URL ein, oder wähle die API, für die deine URL ist", diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 96246694e..152be4da6 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -2076,6 +2076,17 @@ magpie.plugin("library", (ctx) => { openLib(ed); } + // a row's line under its name: the user's note when there is one, in + // the place of what it would say (a skill's description, a server's + // command), which its tooltip then gives after the note. A row keeps its + // height either way + function noteSub(note, sub, said) { + if (!note) return sub; + const n = el("div", "sub lib-subnote", note); + n.title = said ? note + "\n\n" + said : note; + return n; + } + function serverRow(s, all) { const row = el("div", "row lib-row click lib-server"); const who = el("div", "who"); @@ -2091,7 +2102,7 @@ magpie.plugin("library", (ctx) => { who.append(nm, healthEl(s.name)); const sub = el("div", "sub mono", serverLine(s)); sub.title = serverLine(s); - who.append(sub, toolsEl(s.name)); + who.append(noteSub(s.note, sub, serverLine(s)), toolsEl(s.name)); row.append(mark(s.icon, s.transport === "stdio" ? GLYPH.cmd : GLYPH.web), who, ...removeAct(() => confirmRemoveServer(s)), agentChips(withGone(all, s.agents), s.agents, chipsChange("servers/agents", s.name, "servers", (x) => serverRow(x, all)), { problems: s.problems, blocked: sseBlocked(s), all: true })); if (picking) return pickRow(row, s.name); @@ -2743,6 +2754,24 @@ magpie.plugin("library", (ctx) => { return ta; } + // noteBox is the user's note on a server or a skill (youyo.p on Discord: + // with many, which is which and when to use it). One line of at most 200 + // characters, as a hook's description (#2011); the library alone keeps + // it, and no agent is given it. + const NOTE_MAX = 200; + function noteBox(value, placeholder, onInput) { + const ta = el("textarea", "lib-text small lib-notein"); + ta.rows = 1; + ta.value = value || ""; + ta.placeholder = placeholder; + ta.maxLength = NOTE_MAX; + ta.oninput = () => onInput(ta.value); + ta.onkeydown = (e) => { e.stopPropagation(); if (e.isComposing || e.keyCode === 229) return; if (e.key === "Escape") closeLibModal(); else if (e.key === "Enter" && modal?.save) { e.preventDefault(); modal.save(); } }; + autosize(ta, 27); + return ta; + } + const noteHint = () => t("Optional: what it's for and when to use it, in any language. Only the library keeps it; no agent is given it"); + // refHint: how a value is read from a variable (#1250) const refHint = () => t("A value can name a variable, as {ref}: each agent is given it in its own way, so the token stays out of its settings", { ref: "${NAME}" }); @@ -2757,14 +2786,15 @@ magpie.plugin("library", (ctx) => { if (!d.env) d.env = {}; if (!d.headers) d.headers = {}; d.local = !!d.local; + d.note = d.note || ""; const ed = el("div", "editor lib-editor"); const head = el("div", "ehead lib-serverhead"); head.append(mark(s?.icon, d.transport === "stdio" ? GLYPH.cmd : GLYPH.web), el("b", "", s ? s.name : t("New MCP server"))); if (!s) head.append(el("span", "note", t("or paste its JSON anywhere here"))); // the form, or the server as JSON (hema_17384 on Discord), in Claude // Code's .mcp.json shape, as Copy config gives it: read whole, edited, - // pasted over. The agents and sync are the library's own and stay in - // the form below it + // pasted over. The note, the agents and sync are the library's own and + // stay in the form below it let view = "form", jsonBad = ""; const viewBox = el("div", "lib-viewpick"); const viewSegs = () => segs([["form", t("Form")], ["json", "JSON"]], view, (v) => { @@ -2829,6 +2859,8 @@ magpie.plugin("library", (ctx) => { const nameF = field(t("Name"), name, t("Letters, digits, - and _ — what the agents call it")), kindF = field(t("Runs as"), kindBox); const top = el("div", "lib-slot"); ed.append(top); + const note = noteBox(d.note, t("e.g. The shop's database, read only"), (v) => { d.note = v; }); + ed.append(...field(t("Note"), note, noteHint())); const slot = el("div", "lib-slot"); ed.append(slot); const agentsBox = el("div"); @@ -2960,7 +2992,7 @@ magpie.plugin("library", (ctx) => { // send saves the form; s is then the server as saved, for a save after // a sign-in's to be of it const send = async () => { - const body = { old: s ? s.name : "", server: { name: d.name, transport: d.transport, agents: d.agents, startupTimeout: d.startupTimeout || 0, local: !!d.local, hub: d.hub || "" } }; + const body = { old: s ? s.name : "", server: { name: d.name, transport: d.transport, agents: d.agents, startupTimeout: d.startupTimeout || 0, local: !!d.local, hub: d.hub || "", note: d.note || "" } }; if (d.transport === "stdio") Object.assign(body.server, { command: d.command, args: d.args, env: d.env }); else Object.assign(body.server, { url: d.url, headers: d.headers, oauth: d.transport === "http" && d.oauth?.clientId ? d.oauth : null }); take(await api("library/servers/save", body)); @@ -3700,7 +3732,7 @@ magpie.plugin("library", (ctx) => { if (pick !== "source") { const skills = [...lib.skills].sort(byName(pick)); const g = { key: "flat", repo: "", skills, parts: null, - text: new Map(skills.map((s) => [s, (s.name + " " + (s.description || "") + " " + skillRepo(s)).toLowerCase()])) }; + text: new Map(skills.map((s) => [s, (s.name + " " + (s.note || "") + " " + (s.description || "") + " " + skillRepo(s)).toLowerCase()])) }; grouped = { lib, pick, groups: [g] }; return grouped.groups; } @@ -3748,7 +3780,7 @@ magpie.plugin("library", (ctx) => { ...mine.filter((g) => g.skills.length && mineHere(g)), ...down.sort(byRepo), ...(by.has("local") ? [by.get("local")] : [])]; for (const g of groups) { g.skills.sort((a, b) => a.name.localeCompare(b.name)); - g.text = new Map(g.skills.map((s) => [s, (s.name + " " + (s.description || "") + " " + (g.mine || (g.owner ? skillRepo(s) : g.repo))).toLowerCase()])); + g.text = new Map(g.skills.map((s) => [s, (s.name + " " + (s.note || "") + " " + (s.description || "") + " " + (g.mine || (g.owner ? skillRepo(s) : g.repo))).toLowerCase()])); g.parts = g.mine ? null : partsOf(g); } grouped = { lib, pick, groups }; @@ -5441,7 +5473,7 @@ magpie.plugin("library", (ctx) => { if (hereLine) who.append(hereLine); const sub = el("div", "sub", s.missing ? t("Its folder is gone from the library") : s.description || ""); sub.title = s.description || ""; - who.append(sub); + who.append(s.missing ? sub : noteSub(s.note, sub, s.description || "")); if (s.source) { const src = el("div", "lib-src"); if (s.kind === "github") { @@ -5696,10 +5728,28 @@ magpie.plugin("library", (ctx) => { head.append(mark(s.icon, GLYPH.skill), el("b", "", s.name), pick, el("span", "grow")); const body = el("div", "lib-skillbody"); const bar = el("div", "bar"); - ed.append(head, body, bar); + // the user's note on it (youyo.p_10001 on Discord), over its files: + // the library's own, never in a file an agent reads. Save shows once + // it's changed, and saves the file being edited with it + let was = s.note || "", note = was; + const noteDirty = () => note.trim() !== was; + const keep = button(t("Save"), "primary", () => save()); + keep.hidden = true; + const noteIn = noteBox(was, t("e.g. For the weekly report; the other PDF skill is for forms"), (v) => { note = v; keep.hidden = !!ta || !noteDirty(); }); + const noteRow = el("div", "lib-skillnote"); + noteRow.append(...field(t("Note"), noteIn, noteHint())); + ed.append(head, noteRow, body, bar); let cur = null, ta = null; const lf = (x) => x.replace(/\r\n?/g, "\n"); - modal = { dirty: () => !!(ta && cur && ta.value !== lf(cur.text)) }; + const fileDirty = () => !!(ta && cur && ta.value !== lf(cur.text)); + modal = { save: () => save(), dirty: () => fileDirty() || noteDirty() }; + const saveNote = async () => { + if (!noteDirty()) return true; + if (!(await change("skills/note", { name: s.name, note }, t("{name} saved", { name: s.name })))) return false; + was = note = note.trim(); + keep.hidden = true; + return true; + }; const read = async (f) => { body.replaceChildren(el("pre", "lib-md", "…")); try { @@ -5711,7 +5761,7 @@ magpie.plugin("library", (ctx) => { } }; const swap = async (f) => { - if (f === cur?.file || modal.dirty() && !(await confirmDiscard())) return; + if (f === cur?.file || fileDirty() && !(await confirmDiscard())) return; ta = null; read(f); }; @@ -5726,7 +5776,8 @@ magpie.plugin("library", (ctx) => { body.replaceChildren(rendered(cur)); const where = el("span", "note"); where.append(pathLink(cur.path)); - bar.replaceChildren(where, el("span", "grow"), button(t("Edit"), "", edit), button(t("Close"), "", closeLibModal)); + keep.hidden = !noteDirty(); + bar.replaceChildren(where, el("span", "grow"), button(t("Edit"), "", edit), button(t("Close"), "", closeLibModal), keep); }; const edit = () => { ta = el("textarea", "lib-text lib-skilltext"); @@ -5740,13 +5791,13 @@ magpie.plugin("library", (ctx) => { }; body.replaceChildren(ta); const note = el("span", "note lib-reaches", t("Saved in the library: every agent given {name} gets it", { name: s.name }) + " · " + (/^Mac/.test(navigator.platform) ? "⌘S" : "Ctrl+S")); - bar.replaceChildren(note, el("span", "grow"), button(t("Cancel"), "", async () => { if (!modal.dirty() || await confirmDiscard()) show(); }), button(t("Save"), "primary", save)); + bar.replaceChildren(note, el("span", "grow"), button(t("Cancel"), "", async () => { if (!fileDirty() || await confirmDiscard()) show(); }), button(t("Save"), "primary", save)); ta.focus({ preventScroll: true }); ta.setSelectionRange(0, 0); }; const save = async () => { - if (!ta) return; - if (!modal.dirty()) return show(); + if (!(await saveNote()) || !ta) return; + if (!fileDirty()) return show(); const f = cur.file; if (await change("skills/save", { name: s.name, file: f, text: ta.value, was: cur.text }, t("{name} saved", { name: f }))) { ta = null; diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index f5f660026..23fdac53b 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -452,6 +452,9 @@ magpie.strings({ "As Claude Code's .mcp.json has it. A value naming a variable, as {ref}, stays a name here": "与 Claude Code 的 .mcp.json 格式相同。像 {ref} 这样引用变量的值,在这里仍然是变量名", "This isn't an MCP server's JSON": "这不是 MCP 服务器的 JSON", "Only one server here; paste several outside this box to add them": "这里只能写一个服务器;要一次添加多个,请粘贴到这个框外面", + "Optional: what it's for and when to use it, in any language. Only the library keeps it; no agent is given it": "可选:用任何语言写下它的用途、什么时候用。只保存在资源库里,不会交给任何 Agent", + "e.g. The shop's database, read only": "例如:店里的数据库,只读", + "e.g. For the weekly report; the other PDF skill is for forms": "例如:写周报用;另一个 PDF 技能是填表用的", "Copy as an agent's project file": "按 agent 的项目配置文件复制", "{agent} can't take {names} from a project's file": "{agent} 的项目配置文件放不了 {names}", "Copied for {agent}, to paste into {file} in your project. Left out, as {agent} can't take them there: {names}": "已按 {agent} 的格式复制,粘贴到项目里的 {file} 即可。{agent} 在那里放不了、没有复制的:{names}", @@ -1222,6 +1225,9 @@ magpie.strings({ "As Claude Code's .mcp.json has it. A value naming a variable, as {ref}, stays a name here": "與 Claude Code 的 .mcp.json 格式相同。像 {ref} 這樣引用變數的值,在這裡仍然是變數名稱", "This isn't an MCP server's JSON": "這不是 MCP 伺服器的 JSON", "Only one server here; paste several outside this box to add them": "這裡只能寫一個伺服器;要一次加入多個,請貼到這個框外面", + "Optional: what it's for and when to use it, in any language. Only the library keeps it; no agent is given it": "選填:用任何語言寫下它的用途、什麼時候用。只儲存在資源庫裡,不會交給任何 Agent", + "e.g. The shop's database, read only": "例如:店裡的資料庫,唯讀", + "e.g. For the weekly report; the other PDF skill is for forms": "例如:寫週報用;另一個 PDF 技能是填表用的", "Copy as an agent's project file": "按 agent 的專案設定檔複製", "{agent} can't take {names} from a project's file": "{agent} 的專案設定檔放不了 {names}", "Copied for {agent}, to paste into {file} in your project. Left out, as {agent} can't take them there: {names}": "已按 {agent} 的格式複製,貼到專案裡的 {file} 即可。{agent} 在那裡放不了、沒有複製的:{names}", @@ -1987,6 +1993,9 @@ magpie.strings({ "As Claude Code's .mcp.json has it. A value naming a variable, as {ref}, stays a name here": "Claude Code の .mcp.json と同じ形式です。{ref} のように変数を参照する値は、ここでは変数名のままです", "This isn't an MCP server's JSON": "MCP サーバーの JSON ではありません", "Only one server here; paste several outside this box to add them": "ここに書けるサーバーは 1 つです。複数をまとめて追加するには、この欄の外に貼り付けてください", + "Optional: what it's for and when to use it, in any language. Only the library keeps it; no agent is given it": "任意:用途やいつ使うかを好きな言語で。ライブラリにだけ保存され、どのエージェントにも渡されません", + "e.g. The shop's database, read only": "例:店のデータベース、読み取り専用", + "e.g. For the weekly report; the other PDF skill is for forms": "例:週報用。もう一つの PDF スキルはフォーム用", "Copy as an agent's project file": "エージェントのプロジェクト設定ファイルの形でコピー", "{agent} can't take {names} from a project's file": "{agent} のプロジェクト設定ファイルには {names} を入れられません", "Copied for {agent}, to paste into {file} in your project. Left out, as {agent} can't take them there: {names}": "{agent} 用にコピーしました。プロジェクトの {file} に貼り付けてください。{agent} がそこで使えないため除いたもの:{names}", @@ -2755,6 +2764,9 @@ magpie.strings({ "As Claude Code's .mcp.json has it. A value naming a variable, as {ref}, stays a name here": "So, wie es in Claude Codes .mcp.json steht. Ein Wert, der eine Variable nennt, etwa {ref}, bleibt hier ein Name", "This isn't an MCP server's JSON": "Das ist kein JSON eines MCP-Servers", "Only one server here; paste several outside this box to add them": "Hier steht nur ein Server; mehrere fügst du hinzu, indem du sie außerhalb dieses Felds einfügst", + "Optional: what it's for and when to use it, in any language. Only the library keeps it; no agent is given it": "Optional: wofür er da ist und wann man ihn nimmt, in jeder Sprache. Nur die Bibliothek speichert sie; kein Agent bekommt sie", + "e.g. The shop's database, read only": "z. B. Die Datenbank des Shops, nur lesend", + "e.g. For the weekly report; the other PDF skill is for forms": "z. B. Für den Wochenbericht; der andere PDF-Skill ist für Formulare", "Copy as an agent's project file": "Als Projektdatei eines Agenten kopieren", "{agent} can't take {names} from a project's file": "{agent} kann {names} nicht aus einer Projektdatei lesen", "Copied for {agent}, to paste into {file} in your project. Left out, as {agent} can't take them there: {names}": "Für {agent} kopiert, zum Einfügen in {file} im Projekt. Weggelassen, da {agent} sie dort nicht lesen kann: {names}", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index 3a6ac407c..25a27a0be 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -821,16 +821,22 @@ body.window .lib-list .lib-row { --lib-indent: 38px; } .lib-browserask-pick:hover { background: var(--accent-soft); } .lib-browserask-pick .ic { width: 14px; height: 14px; } -/* an MCP server's command wraps, read whole (hema_17384 on Discord): it - starts as tall as an input beside it */ -.lib-editor .lib-cmd { min-height: 0; height: 27px; padding: 4px 9px; border-radius: 7px; line-height: 17px; overflow: hidden; } +/* an MCP server's command wraps, read whole (hema_17384 on Discord), and + a note is a line too: each starts as tall as an input beside it */ +.lib-editor :is(.lib-cmd, .lib-notein) { min-height: 0; height: 27px; padding: 4px 9px; border-radius: 7px; line-height: 17px; overflow: hidden; } .lib-editor .lib-cmd { font-size: 12px; white-space: pre-wrap; overflow-wrap: anywhere; } +.lib-editor .lib-notein { font: inherit; font-size: 12.5px; line-height: 17px; } /* the server as JSON: wrapped, so a long argument never scrolls sideways */ .lib-editor .lib-json { min-height: 160px; font-size: 12px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; } .lib-editor .lib-json[aria-invalid="true"], .lib-editor .lib-json[aria-invalid="true"]:focus { border-color: var(--red); } .lib-serverhead { flex-wrap: wrap; row-gap: 6px; } .lib-serverhead .lib-viewpick { margin-left: auto; flex: none; } .lib-serverhead .note + .lib-viewpick { margin-left: 0; } +/* a row's note, the user's own words, over the muted line it stands for */ +.lib-row .sub.lib-subnote { color: var(--fg-2); } +/* a skill's note, over its SKILL.md */ +.lib-skillnote { display: flex; flex-direction: column; gap: 4px; } +.lib-reader .lib-skillnote label { text-align: left; padding-top: 0; } @media (max-width: 760px), (pointer: coarse) and (max-width: 1024px) { - body.web .lib-editor .lib-cmd { min-height: 44px; font-size: 16px; line-height: 22px; padding: 10px 9px; } + body.web .lib-editor :is(.lib-cmd, .lib-notein) { min-height: 44px; font-size: 16px; line-height: 22px; padding: 10px 9px; } } diff --git a/internal/gui/library.go b/internal/gui/library.go index a3fbd4e16..e0f03ea52 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -458,7 +458,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { Subagent library.Subagent Agent string // the agent whose own skill is in the library's way App string // the app the MCP hub is added to (servers/hub-open) - Note string // what the MCP router says of itself (servers/hub-note) + Note string // what the MCP router says of itself (servers/hub-note), or a skill's note (skills/note) ID string // a market server's, or a market skill's in its repository Values map[string]string // what a market server needs Dir string // a project's folder @@ -558,6 +558,9 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.SaveSkillFile(in.Name, in.File, in.Text, in.Was) case "skills/here": res, err = library.SkillHere(in.Name, in.On) + case "skills/note": + // the user's own note on it, which no agent is given + res, err = library.SkillNote(in.Name, in.Note) case "skills/agents-all": res, err = library.EverySkillAgents(in.Agents, in.On) case "skills/agents-some": diff --git a/internal/gui/tests/library-mcp-json.test.cjs b/internal/gui/tests/library-mcp-json.test.cjs index 5455a6859..fa8a0aac2 100644 --- a/internal/gui/tests/library-mcp-json.test.cjs +++ b/internal/gui/tests/library-mcp-json.test.cjs @@ -5,8 +5,13 @@ // too, and the editor shows the server as JSON as well, in Claude Code's // .mcp.json shape, to read whole and edit: an edit there is what is saved, // and JSON that isn't a server's keeps the dialog from saving or going -// back to the form. Every language, Chromium and WebKit, 1100 and 390 -// wide; nothing scrolls sideways. No backend: +// back to the form. +// youyo.p_10001 on Discord: with many skills and servers, which is which. +// Each takes a note, the library's own: saved with the server or by +// itself for a skill, shown in the row in place of its command or +// description (which the tooltip still gives), found by the skills' +// filter, and asked about before it is lost. Every language, Chromium +// and WebKit, 1100 and 390 wide; nothing scrolls sideways. No backend: // the API is faked here. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); @@ -29,7 +34,12 @@ function server(lang, calls) { agents: [agent("claude", "Claude Code")], instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], servers: [{ name: "db", transport: "stdio", command: "npx", args: ARGS, env: { DB_TOKEN: "${DB_TOKEN}" }, agents: ["claude"] }], - skills: [], + skills: [ + { name: "pdf", description: "Read and fill PDF files", kind: "folder", agents: ["claude"] }, + { name: "weekly", description: "Write a report from the week's commits", kind: "folder", agents: ["claude"] }, + // enough of them for the filter, which shows over eight + ...["docx", "xlsx", "pptx", "slides", "review", "deploy", "notes"].map((name) => ({ name, description: "Work with " + name, kind: "folder", agents: ["claude"] })), + ], }; return async (route) => { const req = route.request(), url = new URL(req.url()); @@ -39,6 +49,10 @@ function server(lang, calls) { if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); if (url.pathname === "/api/library") return route.fulfill({ json: lib }); if (url.pathname === "/api/library/mcp/check") return route.fulfill({ json: { servers: {} } }); + if (url.pathname === "/api/library/skill") { + const name = url.searchParams.get("name"); + return route.fulfill({ json: { file: "SKILL.md", files: ["SKILL.md"], text: "---\nname: " + name + "\n---\n\nWrite it up.\n", path: `${HOME}/.magpie/library/skills/${name}` } }); + } if (url.pathname === "/api/library/servers/save") { const { old, server: s } = req.postDataJSON(); calls.push(["save", s]); @@ -46,6 +60,13 @@ function server(lang, calls) { lib.servers[i] = { ...lib.servers[i], ...s }; return route.fulfill({ json: { ...lib, result: { changed: ["claude"] } } }); } + if (url.pathname === "/api/library/skills/note") { + const b = req.postDataJSON(); + calls.push(["note", b]); + const s = lib.skills.find((x) => x.name === b.name); + s.note = b.note.trim(); + return route.fulfill({ json: { ...lib, result: {} } }); + } 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 } } }); @@ -57,7 +78,7 @@ function server(lang, calls) { } for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { - test(engine + ": an MCP server's command read whole, and as JSON", async (t) => { + test(engine + ": an MCP server's command read whole, as JSON, and notes", async (t) => { assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); const errors = []; @@ -71,7 +92,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const w = (s) => tr(lang, s); const calls = []; const ctx = await browser.newContext({ viewport: { width, height: 800 } }); - await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} }); + // the MCP tab first; the skills' once the test has picked it + await ctx.addInitScript(() => { try { if (!localStorage.getItem("magpie.libTab")) localStorage.setItem("magpie.libTab", "mcp"); } catch {} }); const page = await ctx.newPage(); page.setDefaultTimeout(5000); page.setDefaultNavigationTimeout(60000); @@ -134,6 +156,50 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(calls.at(-1)[1].args, [...ARGS.slice(0, -1), "shop", "--readonly"]); assert.deepEqual(calls.at(-1)[1].env, { DB_TOKEN: "${DB_TOKEN}", MODE: "ro" }); + // a note on the server: saved with it, shown in its row, its command in the tooltip + await open(); + const note = ed.locator("textarea.lib-notein"); + await note.fill("店里的库存数据库,只读"); + await note.press("Enter"); + await ed.waitFor({ state: "detached" }); + assert.equal(calls.at(-1)[1].note, "店里的库存数据库,只读"); + const sub = row.locator(".sub.lib-subnote"); + await sub.waitFor(); + assert.equal(await sub.textContent(), "店里的库存数据库,只读"); + assert((await sub.getAttribute("title")).endsWith(LINE.replace("shop_inventory_reporting", "shop") + " --readonly")); + assert.equal(await row.locator(".sub.mono").count(), 0); + + // a skill's note, over its SKILL.md + await page.evaluate(() => { try { localStorage.setItem("magpie.libTab", "skills"); } catch {} }); + await page.reload(); + await page.locator('button[data-view="library"]').click(); + const skill = (name) => page.locator("#view-library .lib-skill", { has: page.locator(".name", { hasText: new RegExp("^" + name + "$") }) }); + await skill("weekly").locator(".name").click(); + await ed.waitFor(); + const keep = ed.locator(":scope > .bar button.primary"); + assert.equal(await keep.isVisible(), false, "Save shown with nothing changed"); + await ed.locator("textarea.lib-notein").fill("周报用"); + await keep.waitFor(); + assert.equal(await keep.textContent(), w("Save")); + // asked before it's lost + await page.keyboard.press("Escape"); + await page.locator("dialog.action-confirm button:not(.primary)").last().click(); + assert.equal(await ed.count(), 1, "a changed note closed without asking"); + // saved where it is, the skill's file still open; nothing then to ask about + await ed.locator("textarea.lib-notein").press("Enter"); + await keep.waitFor({ state: "hidden" }); + assert.deepEqual(calls.at(-1), ["note", { name: "weekly", note: "周报用" }]); + assert.equal(await ed.locator(".lib-skillbody").count(), 1); + await page.keyboard.press("Escape"); + await ed.waitFor({ state: "detached" }); + const ssub = skill("weekly").locator(".sub.lib-subnote"); + await ssub.waitFor(); + assert.equal(await ssub.textContent(), "周报用"); + assert.equal(await ssub.getAttribute("title"), "周报用\n\nWrite a report from the week's commits"); + // the filter finds it by its note + await page.locator("#view-library input.lib-skillq").fill("周报"); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-skill").length === 1); + assert.equal(await skill("weekly").count(), 1); assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll"); await ctx.close(); }); diff --git a/internal/library/carry.go b/internal/library/carry.go index 5ab3f0024..093804c85 100644 --- a/internal/library/carry.go +++ b/internal/library/carry.go @@ -45,6 +45,8 @@ type CarriedSkill struct { Left []string `json:"left,omitempty"` // files too big to carry // Called is the name its SKILL.md gives, when that isn't Name Called string `json:"called,omitempty"` + // Note is the user's note on it (Skill.Note) + Note string `json:"note,omitempty"` } // A skill's file bigger than maxCarried is left out, and so are the @@ -104,7 +106,7 @@ func Collect() (*Bundle, error) { } for i, c := range readSkills(dirs) { s := skills[i] - c.Name, c.Source, c.Agents, c.Called = s.Name, s.Source, orNone(slices.Sorted(slices.Values(s.Agents))), s.Called + c.Name, c.Source, c.Agents, c.Called, c.Note = s.Name, s.Source, orNone(slices.Sorted(slices.Values(s.Agents))), s.Called, s.Note b.Skills = append(b.Skills, c) } subs := []*Subagent{} @@ -416,7 +418,7 @@ func Put(b *Bundle) (*Result, error) { for _, s := range b.Skills { // turned off here stays off here: that is this computer's own off := l.skill(s.Name) != nil && l.skill(s.Name).OffHere - skills = append(skills, &Skill{Name: s.Name, Source: s.Source, Agents: slices.Clone(orNone(s.Agents)), OffHere: off, Called: s.Called}) + skills = append(skills, &Skill{Name: s.Name, Source: s.Source, Agents: slices.Clone(orNone(s.Agents)), OffHere: off, Called: s.Called, Note: s.Note}) if keep[s.Name] { continue } diff --git a/internal/library/mcp.go b/internal/library/mcp.go index ae256ad12..0bf074cf7 100644 --- a/internal/library/mcp.go +++ b/internal/library/mcp.go @@ -68,6 +68,10 @@ type Server struct { // off, for a server that reads its project from the folder it is // started in, or keeps a session's state (#4382, cuipengcx90). Hub string `json:"hub,omitempty"` + // Note is the user's own word on what the server is for (youyo.p on + // Discord: with many of them, which is which). Only the library keeps + // it, and a sync carries it; no agent is given it (TestNoteNeverGiven). + Note string `json:"note,omitempty"` // about is the hub entry's description, for an agent that shows a // server by one before it has connected (Pi, hubServerFor) @@ -154,6 +158,9 @@ func (s *Server) check() error { s.OAuth = nil } } + if err := checkNote(&s.Note); err != nil { + return fmt.Errorf("%s: %w", s.Name, err) + } if s.StartupTimeout < 0 || s.StartupTimeout > maxStartupTimeout { return fmt.Errorf("%s: the startup timeout is between 0 (the agent's own) and %d seconds", s.Name, maxStartupTimeout) } diff --git a/internal/library/note_test.go b/internal/library/note_test.go new file mode 100644 index 000000000..35ab214f5 --- /dev/null +++ b/internal/library/note_test.go @@ -0,0 +1,134 @@ +package library + +import ( + "encoding/json" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +// The notes on a server and a skill (youyo.p on Discord: with many of +// them, which is which and when to use it) are the library's alone: +// nothing magpie writes for an agent holds them, whichever format the +// agent reads, through the MCP router or not. +func TestNoteNeverGiven(t *testing.T) { + h := sandbox(t) + const serverNote, skillNote = "备注 the shop's SQL Server, read only", "备注 for the weekly report" + agents := []string{"claude", "codex", "opencode", "gemini"} + ok(t)(SaveServer("", Server{Name: "db", Transport: "stdio", Command: "npx", + Args: []string{"-y", "universal-db-mcp", "--type", "sqlserver"}, Agents: agents, Note: serverNote})) + ok(t)(SaveServer("", Server{Name: "docs", Transport: "http", URL: "https://example.com/mcp", Agents: agents, Note: serverNote})) + skill(t, filepath.Join(h, "src/pdf"), "pdf", "Read PDFs") + ok(t)(InstallSkills(filepath.Join(h, "src"), []string{"pdf"}, agents)) + ok(t)(SkillNote("pdf", skillNote)) + // given as copies too, whose files are the agents' own + ok(t)(SetSkillHow("claude", "copy")) + + // kept, and shown on the page + if s := serverIn(t, "db"); s == nil || s.Note != serverNote { + t.Fatalf("the server's note wasn't kept: %+v", s) + } + if v := offView(t, "pdf"); v.Note != skillNote { + t.Fatalf("the skill's note wasn't kept: %+v", v) + } + + given := func(when string) { + t.Helper() + own := filepath.Clean(settings.Dir()) + n := 0 + filepath.WalkDir(h, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + if d.IsDir() && filepath.Clean(p) == own { + return filepath.SkipDir // magpie's own: library.json, its backups + } + if !d.Type().IsRegular() { + return nil + } + b, err := os.ReadFile(p) + if err != nil { + return nil + } + n++ + if s := string(b); strings.Contains(s, "备注") { + t.Errorf("%s: %s has a note in it:\n%s", when, p, s) + } + return nil + }) + if n == 0 { + t.Fatalf("%s: no agent file was read", when) + } + } + for _, f := range []string{".claude.json", ".codex/config.toml", ".claude/skills/pdf/SKILL.md"} { + if _, err := os.Stat(filepath.Join(h, f)); err != nil { + t.Fatalf("not given to the agents: %v", err) + } + } + given("each agent's own entry") + + ok(t)(SetMCPHub(true)) + given("through the router") + for _, s := range []string{"db", "docs"} { + b, _ := json.Marshal(hubServerOf(serverIn(t, s))) + if strings.Contains(string(b), "备注") { + t.Fatalf("the router tells an agent of %s with its note: %s", s, b) + } + } +} + +// A note is carried to the other computers with the rest of the server +// or the skill, and taking it away is carried too. +func TestNoteCarried(t *testing.T) { + a := sandbox(t) + setUpLibrary(t, a) // the server fs and the skill pdf + s := serverIn(t, "fs") + s.Note = "the project's files" + ok(t)(SaveServer("fs", *s)) + ok(t)(SkillNote("pdf", " when a PDF\nis attached ")) + if v := offView(t, "pdf"); v.Note != "when a PDF is attached" { + t.Fatalf("a note is one line: %q", v.Note) + } + fromA := carry(t) + + b := sandbox(t) + ok(t)(Put(&fromA)) + if s := serverIn(t, "fs"); s == nil || s.Note != "the project's files" { + t.Fatalf("the server's note didn't come: %+v", s) + } + if v := offView(t, "pdf"); v.Note != "when a PDF is attached" { + t.Fatalf("the skill's note didn't come: %+v", v) + } + + ok(t)(SkillNote("pdf", "")) + fromB := carry(t) + at(t, a) + ok(t)(Put(&fromB)) + if v := offView(t, "pdf"); v.Note != "" { + t.Fatalf("a note taken away on B is still on A: %q", v.Note) + } + at(t, b) +} + +// A note is a line, not a document: a longer one is turned away whole, +// rather than cut. +func TestNoteTooLong(t *testing.T) { + h := sandbox(t) + skill(t, filepath.Join(h, "src/pdf"), "pdf", "Read PDFs") + ok(t)(InstallSkills(filepath.Join(h, "src"), []string{"pdf"}, []string{"claude"})) + long := strings.Repeat("备", maxNote+1) + if _, err := SkillNote("pdf", long); err == nil { + t.Fatal("a skill's note over the limit was kept") + } + if _, err := SaveServer("", Server{Name: "x", Transport: "stdio", Command: "x", Note: long}); err == nil { + t.Fatal("a server's note over the limit was kept") + } + ok(t)(SkillNote("pdf", strings.Repeat("备", maxNote))) + if _, err := SkillNote("nope", "a"); err == nil { + t.Fatal("a note on no skill") + } +} diff --git a/internal/library/skills.go b/internal/library/skills.go index 17a67cf8d..974d3bcd1 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -21,6 +21,7 @@ import ( "sync" "time" "unicode" + "unicode/utf8" "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/source" @@ -59,6 +60,11 @@ type Skill struct { // under another because a skill from elsewhere had that name first // (skill_beside.go). Its SKILL.md is named as the library names it. Called string `json:"called,omitempty"` + // Note is the user's own word on what the skill is for or when to + // use it, beside its SKILL.md's description (youyo.p on Discord). + // Only the library keeps it, and a sync carries it; no agent is + // given it: the skill's folder is the agents', and this isn't in it. + Note string `json:"note,omitempty"` } // gives reports whether the agent id gets the skill on this computer: it @@ -80,6 +86,35 @@ func SkillHere(name string, on bool) (*Result, error) { }) } +// maxNote is how long a note on a server or a skill can be, in +// characters: a line that says what it is for, as a hook's description. +const maxNote = 200 + +// checkNote makes a note one line, as the page shows it, and holds it to +// maxNote. +func checkNote(n *string) error { + *n = strings.Join(strings.Fields(*n), " ") + if utf8.RuneCountInString(*n) > maxNote { + return fmt.Errorf("a note is at most %d characters", maxNote) + } + return nil +} + +// SkillNote sets the user's note on a skill; "" takes it away. +func SkillNote(name, note string) (*Result, error) { + if err := checkNote(¬e); err != nil { + return nil, err + } + return change(func(l *Library) error { + s := l.skill(name) + if s == nil { + return fmt.Errorf("no skill called %s", name) + } + s.Note = note + return nil + }) +} + // Source is where a skill came from: a GitHub repository it can be updated // 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 diff --git a/internal/library/sync.go b/internal/library/sync.go index a136832ac..bcc7a1984 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -475,6 +475,8 @@ type SkillView struct { // OffHere is set when it is turned off on this computer alone: Agents // are still the ones a sync carries to the others OffHere bool `json:"offHere,omitempty"` + // Note is the user's own note on it (Skill.Note) + Note string `json:"note,omitempty"` } // View is the Library page. @@ -667,7 +669,7 @@ func readView(problems []Problem, glance bool) (*View, error) { v.Subagents, v.SubagentAgents = l.subagentsView(targets, asleep, of) tr := &tracer{} for _, s := range l.Skills { - sv := SkillView{Name: s.Name, Agents: append([]string{}, s.Agents...), Icon: skillIcon(s), Problems: of("skill:" + s.Name), Repo: tr.repoOf(s), OffHere: s.OffHere} + sv := SkillView{Name: s.Name, Agents: append([]string{}, s.Agents...), Icon: skillIcon(s), Problems: of("skill:" + s.Name), Repo: tr.repoOf(s), OffHere: s.OffHere, Note: s.Note} if s.Source != nil { sv.Source, sv.Kind = s.Source.String(), s.Source.Kind } diff --git a/internal/tui/library.go b/internal/tui/library.go index 21be38d4d..f8257913e 100644 --- a/internal/tui/library.go +++ b/internal/tui/library.go @@ -424,8 +424,9 @@ func saveServer(old *library.Server, line string) tea.Cmd { if old != nil { was, done = old.Name, "saved "+s.Name // and its OAuth app and startup timeout, which only the GUI edits - // and whether it is kept to this computer, and out of the hub - s.Agents, s.Env, s.Headers, s.OAuth, s.StartupTimeout, s.Local, s.Hub = old.Agents, old.Env, old.Headers, old.OAuth, old.StartupTimeout, old.Local, old.Hub + // and whether it is kept to this computer, and out of the hub, + // and the user's note on it + s.Agents, s.Env, s.Headers, s.OAuth, s.StartupTimeout, s.Local, s.Hub, s.Note = old.Agents, old.Env, old.Headers, old.OAuth, old.StartupTimeout, old.Local, old.Hub, old.Note } return libCmd(func() (*library.Result, error) { return library.SaveServer(was, s) }, done)() }