library: a Variables tab gives environment variables to Claude Code and Codex (paopao_baobao on X)
An environment variable is kept once in the Library and written into each agent picked: Claude Code's settings.json "env", Codex's config.toml [shell_environment_policy.set] (a sub-table or inline set is edited; a dotted spelling is refused). It follows Hooks: Applied.Env records what magpie wrote, so turning it off or removing it takes out only that, and a value the user set or changed in the file is never overridden (a conflict is a problem on the row). An unreadable file is an error, nothing is written. The tab has name, value and agent chips, an edit sheet and a row Remove with a confirm; its sidebar entry is in "Every agent". Not carried in backups, as hooks first were. docs/subsystems/library.md updated. Run (mica, sandbox HOME): internal/library and internal/gui go tests ok; gofmt clean; go vet darwin, linux -tags nogui, windows clean; GUI library-*, i18n-* in chromium and webkit (en, zh, zh-TW, ja, de, 440px): all green except "the Library while it loads", red on the merge base too (not from this change). Existing tab-list assertions in library-hooks, -subagents, -groups, -loading now include Variables. Broken by hand: syncEnv overwriting the user's value turns TestEnvNeverOverridesTheUsers red. Not tried: real Claude Code / Codex reading the written env; other agents (Gemini .env, Qwen, Droid); WSL; env in backup carry.
This commit is contained in:
@@ -34,6 +34,7 @@ Pi's extensions and packages.
|
||||
| Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. That checkout is the one git finds (`provider.GitAt` in `gitRepoOf`): an empty `.git` between the skill and its checkout is passed over, as git passes it over, and a `.git` file that names no repository (a worktree left behind) is none (#3675, `TestSkillRepoTraced`). A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in plugins/library/client.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). | [`skill_from.go`](../../internal/library/skill_from.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) |
|
||||
| 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) |
|
||||
| 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 `<claude dir>/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.<Event>]]` array tables with a `[[hooks.<Event>.hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:<Event>` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) |
|
||||
| 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:<name>`), 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 not carried in backups or a WebDAV bundle (`carry.go` names its fields). 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` (`<name>.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) |
|
||||
| Claude plugins | A `Plugin` (FakeshadowzZ on X) is a Claude Code plugin kept as one item: `.claude-plugin/plugin.json`, `skills/<name>/SKILL.md`, `agents/*.md`, `hooks/hooks.json` and `.mcp.json`, from a folder, a git address or a marketplace.json (`ProbePlugins`, `InstallPlugins`; a marketplace entry with a relative path, or a github/url/git source, is fetched when installed). Its files are copied to `<library>/plugins/<name>`; `${CLAUDE_PLUGIN_ROOT}` is that folder and `${CLAUDE_PLUGIN_DATA}` is `<library>/plugin-data/<name>`, which an update keeps. Its parts are ordinary library skills, MCP servers, hooks and subagents, each tagged `Bundle: <plugin>`, so every agent gets them through the code of its kind and the old tabs go on working; the plugin holds the names, its agents and `Off`. `PluginAgents` sets every part's agents, `PluginOn` clears them (kept in `Agents` for turning it on again) or gives them back, `RemovePlugin` removes the parts, and `UpdatePlugin` reads the source again. A hook whose Claude event and matcher have a portable event becomes it (Stop turn-end, PostToolUse after-tool, PreToolUse before-tool, UserPromptSubmit prompt, SessionStart session-start; Bash is shell, Edit/Write/MultiEdit is edit); any other event is `claude:<Event>`, for Claude Code only. Subagents go to the agents in `SubagentAgents`. A part whose name the library has gets the prefix `<plugin>-`: the user's own item is never written over or removed. Slash commands, LSP servers and hooks that aren't a command are listed in `Left` and shown, not carried. A backup file carries the parts but not the plugin record or its folder, so on another computer they are ordinary items whose `${CLAUDE_PLUGIN_ROOT}` paths don't exist (`TestPluginImportCarryOnOffRemove`, `TestPluginNameClashKeepsTheUsersOwn`, `TestPluginMarketplaceAndUpdate`, `TestPluginRefusesWhatIsNone`, `library-plugins.test.cjs`). | [`plugin.go`](../../internal/library/plugin.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) |
|
||||
| Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) |
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// The sections a page's list is cut into, by tab id: a section none of whose
|
||||
// tabs shows has no name (app.js navSubs), as does a list of one section.
|
||||
window.NAV_SUB_GROUPS = {
|
||||
library: { instructions: "Every agent", memory: "Every agent", mcp: "Every agent", skills: "Every agent", hooks: "Every agent", subagents: "Every agent", plugins: "One agent", pi: "One agent", rtk: "magpie", bili: "magpie" },
|
||||
library: { instructions: "Every agent", memory: "Every agent", mcp: "Every agent", skills: "Every agent", hooks: "Every agent", env: "Every agent", subagents: "Every agent", plugins: "One agent", pi: "One agent", rtk: "magpie", bili: "magpie" },
|
||||
};
|
||||
// the tabs [tab, its place in the strip, its section's name where one starts],
|
||||
// in sections in order, each in the strip's order
|
||||
@@ -24,6 +24,7 @@ window.NAV_SUB_IC = {
|
||||
skills: "M8 2.5l1.4 3.6 3.6 1.4-3.6 1.4L8 12.5 6.6 8.9 3 7.5l3.6-1.4z",
|
||||
plugins: "M6.5 3h3v2a1.2 1.2 0 0 0 2.4 0V3h1.1v10.5H3.5v-3.2h2a1.2 1.2 0 0 0 0-2.4h-2V3z",
|
||||
hooks: "M10.5 2.5v6.5a3 3 0 0 1-6 0V7.5 M3 9l1.5-1.5L6 9",
|
||||
env: "M5.5 3.5h-1.5v9h1.5 M10.5 3.5h1.5v9h-1.5 M6.5 8h3",
|
||||
subagents: "M6 3a2.2 2.2 0 1 0 0 4.4A2.2 2.2 0 0 0 6 3z M2 13c.5-2.2 2-3.4 4-3.4s3.5 1.2 4 3.4 M11.5 7.5a1.5 1.5 0 1 0 0 .01 M10.2 12.5c.3-1.3 1.1-2 2.3-2s1.6.5 1.9 1.4",
|
||||
rtk: "M2.5 3.5h11v9h-11z M5 6.5l1.5 1.5L5 9.5 M8.5 9.5h2.5",
|
||||
bili: "M8 2v4 M6 4.2 8 6l2-1.8 M8 14v-4 M6 11.8 8 10l2 1.8 M3 8h10",
|
||||
|
||||
@@ -441,7 +441,7 @@ magpie.plugin("library", (ctx) => {
|
||||
// What All did, said of the item: on for how many of the agents it went
|
||||
// to, and which of them couldn't be given it, and why.
|
||||
function reportAll(v, me) {
|
||||
const what = ({ servers: "mcp:", hooks: "hook:", subagents: "subagent:" }[me.list] || "skill:") + me.name;
|
||||
const what = ({ servers: "mcp:", hooks: "hook:", env: "env:", subagents: "subagent:" }[me.list] || "skill:") + me.name;
|
||||
const shown = [...me.box.children].filter((x) => x.dataset.agent && !cannot(x)).map((x) => x.dataset.agent);
|
||||
const n = shown.filter((id) => me.want.includes(id)).length;
|
||||
const bad = (v.result?.problems || []).filter((p) => p.what === what && shown.includes(p.agent));
|
||||
@@ -703,7 +703,7 @@ magpie.plugin("library", (ctx) => {
|
||||
ul.append(li);
|
||||
}
|
||||
if (ul.childElementCount) card.append(ul);
|
||||
const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), subagents: t("Subagents"), plugins: t("Claude plugins") };
|
||||
const tabNames = { instructions: t("Instructions"), mcp: t("MCP servers"), skills: t("Skills"), hooks: t("Hooks"), env: t("Variables"), subagents: t("Subagents"), plugins: t("Claude plugins") };
|
||||
const others = Object.keys(away).filter((k) => k in tabNames);
|
||||
if (others.length) {
|
||||
const more = el("div", "lib-problems-away");
|
||||
@@ -739,7 +739,7 @@ magpie.plugin("library", (ctx) => {
|
||||
}
|
||||
// the tab a problem is about; "" is one shown on every tab
|
||||
function problemTab(what) {
|
||||
return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", subagent: "subagents", plugin: "plugins" }[what.split(":")[0]] || "";
|
||||
return { instructions: "instructions", mcp: "mcp", skill: "skills", skills: "skills", project: "skills", hook: "hooks", hooks: "hooks", env: "env", subagent: "subagents", plugin: "plugins" }[what.split(":")[0]] || "";
|
||||
}
|
||||
function problemWhat(what) {
|
||||
const [kind, ...rest] = what.split(":");
|
||||
@@ -851,6 +851,7 @@ magpie.plugin("library", (ctx) => {
|
||||
["mcp", t("MCP servers") + n("mcp")],
|
||||
["skills", t("Skills") + n("skills")],
|
||||
["hooks", t("Hooks") + n("hooks")],
|
||||
["env", t("Variables") + n("env")],
|
||||
["subagents", t("Subagents") + n("subagents")],
|
||||
["plugins", t("Claude plugins") + n("plugins")],
|
||||
["rtk", "RTK"],
|
||||
@@ -911,7 +912,7 @@ magpie.plugin("library", (ctx) => {
|
||||
if (agentless()) tab = "mcp";
|
||||
// Pi's tab only while a Pi is here; the pick is kept for when one is
|
||||
else if (tab === "pi" && !hasPi()) tab = "instructions";
|
||||
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, subagents: (lib.subagents || []).length, plugins: (lib.plugins || []).length });
|
||||
const head = libHead({ mcp: lib.servers.length, skills: lib.skills.length, hooks: (lib.hooks || []).length, env: (lib.env || []).length, subagents: (lib.subagents || []).length, plugins: (lib.plugins || []).length });
|
||||
page.append(head);
|
||||
head.classList.toggle("stuck", top > 0);
|
||||
// what changed in a tab is drawn in place: only another tab (or the
|
||||
@@ -929,6 +930,7 @@ magpie.plugin("library", (ctx) => {
|
||||
else if (tab === "memory") renderMemory(body);
|
||||
else if (tab === "pi") renderPi(body);
|
||||
else if (tab === "hooks") renderHooks(body);
|
||||
else if (tab === "env") renderEnv(body);
|
||||
else if (tab === "subagents") renderSubagents(body);
|
||||
else if (tab === "plugins") renderPlugins(body);
|
||||
else renderSkills(body);
|
||||
@@ -965,7 +967,7 @@ magpie.plugin("library", (ctx) => {
|
||||
if (JSON.stringify(follow) !== JSON.stringify(was) && lib && page.isConnected) render();
|
||||
}
|
||||
function followNote() {
|
||||
const part = tab === "memory" ? "memory" : ["instructions", "mcp", "skills", "hooks", "subagents", "plugins"].includes(tab) ? "library" : "";
|
||||
const part = tab === "memory" ? "memory" : ["instructions", "mcp", "skills", "hooks", "env", "subagents", "plugins"].includes(tab) ? "library" : "";
|
||||
if (!part || !follow?.[part]) return null;
|
||||
const p = el("p", "lib-intro lib-follow", t("This computer follows the server: what you change here is replaced by the next sync.") + " ");
|
||||
const go = button(t("Sync settings"), "link", (e) => openSettingsAt(e, "sync", "#syncList .sync-follows"));
|
||||
@@ -3131,6 +3133,12 @@ magpie.plugin("library", (ctx) => {
|
||||
t("Servers your agents have that aren't in the library stay as they are."),
|
||||
]);
|
||||
}
|
||||
function confirmRemoveEnv(v) {
|
||||
confirmRemoveOne("env", v.name, t("Remove the variable {name}?", { name: v.name }), [
|
||||
takenFromOne(v),
|
||||
t("Variables your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file."),
|
||||
]);
|
||||
}
|
||||
function confirmRemoveHook(h) {
|
||||
confirmRemoveOne("hooks", h.name, t("Remove the hook {name}?", { name: h.name }), [
|
||||
takenFromOne(h),
|
||||
@@ -4147,6 +4155,89 @@ magpie.plugin("library", (ctx) => {
|
||||
openLib(ed);
|
||||
}
|
||||
|
||||
// ---------- variables ----------
|
||||
|
||||
// An environment variable the agent's own settings give every run of it
|
||||
// (a proxy, an API base URL): Claude Code's settings.json "env", Codex's
|
||||
// shell_environment_policy.set. It is kept once and written into each
|
||||
// agent picked (env.go); a value the user set in the file is left alone.
|
||||
const envAgentOf = (id) => (lib.envAgents || []).find((x) => x.id === id);
|
||||
const envAgents = () => shownAgents().filter((a) => envAgentOf(a.id));
|
||||
const envBlocked = () => (a) => {
|
||||
const ea = envAgentOf(a.id);
|
||||
if (ea && !ea.no) return "";
|
||||
return ea?.wsl ? t("magpie gives variables only to agents on this computer, not yet to {agent} in WSL", { agent: a.name }) : t("{agent} has no environment settings magpie can write", { agent: a.name });
|
||||
};
|
||||
function renderEnv(body) {
|
||||
body.append(intro(t("An environment variable is set for an agent every time it runs: a proxy, an API base URL. Add it once and magpie writes it into each agent you pick, in that agent's own settings.")));
|
||||
const all = envAgents();
|
||||
const vars = lib.env || [];
|
||||
if (!vars.length) {
|
||||
body.append(empty(t("No variables in the library yet"), t("Add one, and pick the agents that get it."), button(t("+ Add a variable"), "action", () => editEnv(null))));
|
||||
return;
|
||||
}
|
||||
const list = el("div", "list lib-list");
|
||||
list.append(...[...vars].sort((a, b) => a.name.localeCompare(b.name)).map((v) => envRow(v, all)));
|
||||
body.append(list);
|
||||
const after = el("div", "after-list");
|
||||
after.append(button(t("+ Add variable"), "", () => editEnv(null)));
|
||||
body.append(after);
|
||||
}
|
||||
function envRow(v, all) {
|
||||
const row = el("div", "row lib-row click lib-env");
|
||||
const who = el("div", "who");
|
||||
who.append(el("div", "name mono", v.name));
|
||||
const val = el("div", "sub mono lib-envval", v.value);
|
||||
val.title = v.value;
|
||||
who.append(val);
|
||||
row.append(glyph(GLYPH.hook), who, ...removeAct(() => confirmRemoveEnv(v)),
|
||||
agentChips(withGone(all, v.agents), v.agents, chipsChange("env/agents", v.name, "env", (x) => envRow(x, all)), { problems: v.problems, blocked: envBlocked(), all: true }));
|
||||
row.onclick = () => editEnv(v);
|
||||
row.title = t("Edit {name}", { name: v.name });
|
||||
return row;
|
||||
}
|
||||
function editEnv(v) {
|
||||
const all = envAgents();
|
||||
const d = v ? { name: v.name, value: v.value, agents: [...(v.agents || [])] } : { name: "", value: "", agents: all.filter((a) => !envBlocked()(a)).map((a) => a.id) };
|
||||
const ed = el("div", "editor lib-editor lib-envedit");
|
||||
const head = el("div", "ehead");
|
||||
head.append(glyph(GLYPH.hook), el("b", "", v ? v.name : t("New variable")));
|
||||
ed.append(head);
|
||||
const err = el("div", "editor-error");
|
||||
const name = field2(d.name, t("e.g. HTTPS_PROXY"), (x) => { d.name = x.trim(); });
|
||||
name.classList.add("mono");
|
||||
ed.append(...field(t("Name"), name, t("Letters, digits and _")));
|
||||
const val = field2(d.value, t("e.g. http://127.0.0.1:7890"), (x) => { d.value = x; });
|
||||
val.classList.add("mono");
|
||||
ed.append(...field(t("Value"), val));
|
||||
const agentsBox = el("div");
|
||||
ed.append(...field(t("Agents"), agentsBox), err);
|
||||
const drawAgents = () => agentsBox.replaceChildren(agentChips(all, d.agents, (next) => { d.agents = next; drawAgents(); }, { names: true, blocked: envBlocked(), all: true }));
|
||||
drawAgents();
|
||||
const bar = el("div", "bar");
|
||||
if (v) bar.append(button(t("Remove from the library"), "danger", async () => {
|
||||
if (!await confirmRemoval(v.name, "It will be removed from the library and the agents it was given to.")) return;
|
||||
if (await change("env/remove", { name: v.name }, t("{name} is out of the library and the agents it was given to", { name: v.name }))) closeLibModal(true);
|
||||
}));
|
||||
bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal));
|
||||
const save = async () => {
|
||||
err.textContent = "";
|
||||
try {
|
||||
const env = { name: d.name, value: d.value, agents: d.agents.filter((id) => !envBlocked()(agentOf(id) || { id })) };
|
||||
take(await api("library/env/save", { old: v ? v.name : "", env }));
|
||||
report(lib.result, v ? t("{name} saved", { name: d.name }) : "");
|
||||
closeLibModal(true);
|
||||
render();
|
||||
} catch (e) { err.textContent = e.message; }
|
||||
};
|
||||
bar.append(button(v ? t("Save") : t("Add"), "primary", save));
|
||||
ed.append(bar);
|
||||
const original = JSON.stringify(d);
|
||||
modal = { save, dirty: () => JSON.stringify(d) !== original };
|
||||
openLib(ed);
|
||||
if (!v) requestAnimationFrame(() => name.focus());
|
||||
}
|
||||
|
||||
// ---------- hooks ----------
|
||||
|
||||
// A hook (#1790, AllenReder) is a command an agent runs at a point of
|
||||
|
||||
@@ -641,6 +641,20 @@ magpie.strings({
|
||||
"magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie 还不能给 {agents} 写入 Hook:它们的图标是灰的,悬停可看原因。",
|
||||
"magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie 目前只给这台电脑上的 Agent 写入 Hook,还不支持 WSL 里的 {agent}",
|
||||
"New hook": "新 Hook",
|
||||
"Variables": "变量",
|
||||
"Remove the variable {name}?": "删除变量 {name}?",
|
||||
"Variables your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "Agent 里不在资源库中的变量保持原样,你在 Agent 文件里改过的那个也一样。",
|
||||
"magpie gives variables only to agents on this computer, not yet to {agent} in WSL": "magpie 目前只给本机上的 Agent 写入变量,还不支持 WSL 中的 {agent}",
|
||||
"{agent} has no environment settings magpie can write": "magpie 还不能给 {agent} 写入环境设置",
|
||||
"An environment variable is set for an agent every time it runs: a proxy, an API base URL. Add it once and magpie writes it into each agent you pick, in that agent's own settings.": "环境变量会在 Agent 每次运行时生效,例如代理、API 地址。添加一次,magpie 就会写入你选中的每个 Agent 自己的设置中。",
|
||||
"No variables in the library yet": "资源库里还没有变量",
|
||||
"Add one, and pick the agents that get it.": "添加一个,并选择要使用它的 Agent。",
|
||||
"+ Add a variable": "+ 添加变量",
|
||||
"+ Add variable": "+ 添加变量",
|
||||
"New variable": "新变量",
|
||||
"e.g. HTTPS_PROXY": "例如 HTTPS_PROXY",
|
||||
"Letters, digits and _": "字母、数字和 _",
|
||||
"e.g. http://127.0.0.1:7890": "例如 http://127.0.0.1:7890",
|
||||
"No hooks in the library yet": "资源库里还没有 Hook",
|
||||
"Pick hooks to turn them on or off together": "选中 Hook,一起开启或关闭",
|
||||
"Pick some hooks and turn them on or off together": "选中多个 Hook,一起开启或关闭",
|
||||
@@ -1624,6 +1638,20 @@ magpie.strings({
|
||||
"magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie 還不能給 {agents} 寫入 Hook:它們的圖示是灰的,懸停可看原因。",
|
||||
"magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie 目前只給這台電腦上的 Agent 寫入 Hook,還不支援 WSL 裡的 {agent}",
|
||||
"New hook": "新 Hook",
|
||||
"Variables": "變數",
|
||||
"Remove the variable {name}?": "刪除變數 {name}?",
|
||||
"Variables your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "Agent 裡不在資源庫中的變數保持原樣,你在 Agent 檔案裡改過的那個也一樣。",
|
||||
"magpie gives variables only to agents on this computer, not yet to {agent} in WSL": "magpie 目前只給本機上的 Agent 寫入變數,還不支援 WSL 中的 {agent}",
|
||||
"{agent} has no environment settings magpie can write": "magpie 還不能給 {agent} 寫入環境設定",
|
||||
"An environment variable is set for an agent every time it runs: a proxy, an API base URL. Add it once and magpie writes it into each agent you pick, in that agent's own settings.": "環境變數會在 Agent 每次執行時生效,例如代理、API 位址。新增一次,magpie 就會寫入你選中的每個 Agent 自己的設定中。",
|
||||
"No variables in the library yet": "資源庫裡還沒有變數",
|
||||
"Add one, and pick the agents that get it.": "新增一個,並選擇要使用它的 Agent。",
|
||||
"+ Add a variable": "+ 新增變數",
|
||||
"+ Add variable": "+ 新增變數",
|
||||
"New variable": "新變數",
|
||||
"e.g. HTTPS_PROXY": "例如 HTTPS_PROXY",
|
||||
"Letters, digits and _": "字母、數字和 _",
|
||||
"e.g. http://127.0.0.1:7890": "例如 http://127.0.0.1:7890",
|
||||
"No hooks in the library yet": "資源庫裡還沒有 Hook",
|
||||
"Pick hooks to turn them on or off together": "選中 Hook,一起開啟或關閉",
|
||||
"Pick some hooks and turn them on or off together": "選中多個 Hook,一起開啟或關閉",
|
||||
@@ -2598,6 +2626,20 @@ magpie.strings({
|
||||
"magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie はまだ {agents} にフックを渡せません。チップはグレーになっていて、理由を表示します。",
|
||||
"magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie がフックを渡せるのはこのコンピューター上のエージェントだけで、WSL の {agent} にはまだ渡せません",
|
||||
"New hook": "新しいフック",
|
||||
"Variables": "変数",
|
||||
"Remove the variable {name}?": "変数 {name} を削除しますか?",
|
||||
"Variables your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "ライブラリにないエージェントの変数はそのまま残ります。エージェントのファイルで自分で変更したものも同様です。",
|
||||
"magpie gives variables only to agents on this computer, not yet to {agent} in WSL": "magpie がエージェントに変数を渡せるのはこのコンピューター上のものだけで、WSL の {agent} にはまだ渡せません",
|
||||
"{agent} has no environment settings magpie can write": "magpie は {agent} の環境設定に書き込めません",
|
||||
"An environment variable is set for an agent every time it runs: a proxy, an API base URL. Add it once and magpie writes it into each agent you pick, in that agent's own settings.": "環境変数は、エージェントが実行されるたびに設定されます(プロキシや API の URL など)。一度追加すれば、選んだ各エージェント自身の設定に magpie が書き込みます。",
|
||||
"No variables in the library yet": "ライブラリにはまだ変数がありません",
|
||||
"Add one, and pick the agents that get it.": "追加して、使うエージェントを選びます。",
|
||||
"+ Add a variable": "+ 変数を追加",
|
||||
"+ Add variable": "+ 変数を追加",
|
||||
"New variable": "新しい変数",
|
||||
"e.g. HTTPS_PROXY": "例: HTTPS_PROXY",
|
||||
"Letters, digits and _": "英数字と _",
|
||||
"e.g. http://127.0.0.1:7890": "例: http://127.0.0.1:7890",
|
||||
"No hooks in the library yet": "ライブラリにはまだフックがありません",
|
||||
"Pick hooks to turn them on or off together": "フックを選んでまとめてオン・オフする",
|
||||
"Pick some hooks and turn them on or off together": "複数のフックを選んでまとめてオン・オフする",
|
||||
@@ -3577,6 +3619,20 @@ magpie.strings({
|
||||
"magpie can't give hooks to {agents} yet: their chips are greyed, and say why.": "magpie kann {agents} noch keine Hooks geben: Ihre Chips sind ausgegraut und sagen, warum.",
|
||||
"magpie gives hooks only to agents on this computer, not yet to {agent} in WSL": "magpie gibt Hooks nur Agenten auf diesem Computer, noch nicht {agent} in WSL",
|
||||
"New hook": "Neuer Hook",
|
||||
"Variables": "Variablen",
|
||||
"Remove the variable {name}?": "Variable {name} entfernen?",
|
||||
"Variables your agents have that aren't in the library stay as they are, and so does one you changed in an agent's file.": "Variablen, die Ihre Agenten haben und die nicht in der Bibliothek sind, bleiben unverändert, ebenso eine, die Sie in der Datei eines Agenten geändert haben.",
|
||||
"magpie gives variables only to agents on this computer, not yet to {agent} in WSL": "magpie gibt Variablen nur Agenten auf diesem Computer, noch nicht {agent} in WSL",
|
||||
"{agent} has no environment settings magpie can write": "magpie kann für {agent} keine Umgebungseinstellungen schreiben",
|
||||
"An environment variable is set for an agent every time it runs: a proxy, an API base URL. Add it once and magpie writes it into each agent you pick, in that agent's own settings.": "Eine Umgebungsvariable gilt bei jedem Lauf eines Agenten: ein Proxy, eine API-Adresse. Einmal hinzufügen, und magpie schreibt sie in die eigenen Einstellungen jedes gewählten Agenten.",
|
||||
"No variables in the library yet": "Noch keine Variablen in der Bibliothek",
|
||||
"Add one, and pick the agents that get it.": "Fügen Sie eine hinzu und wählen Sie die Agenten, die sie bekommen.",
|
||||
"+ Add a variable": "+ Variable hinzufügen",
|
||||
"+ Add variable": "+ Variable hinzufügen",
|
||||
"New variable": "Neue Variable",
|
||||
"e.g. HTTPS_PROXY": "z. B. HTTPS_PROXY",
|
||||
"Letters, digits and _": "Buchstaben, Ziffern und _",
|
||||
"e.g. http://127.0.0.1:7890": "z. B. http://127.0.0.1:7890",
|
||||
"No hooks in the library yet": "Noch keine Hooks in der Bibliothek",
|
||||
"Pick hooks to turn them on or off together": "Hooks auswählen, um sie gemeinsam ein- oder auszuschalten",
|
||||
"Pick some hooks and turn them on or off together": "Mehrere Hooks auswählen und gemeinsam ein- oder ausschalten",
|
||||
|
||||
@@ -659,7 +659,8 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
|
||||
Paths []string
|
||||
Names []string // the skills to update, of those a check found changed; to bring in, of those found in the agents
|
||||
Server library.Server
|
||||
Hook library.Hook // a hook saved (#1790)
|
||||
Hook library.Hook // a hook saved (#1790)
|
||||
Env library.EnvVar // a variable saved
|
||||
// a subagent saved (#2283)
|
||||
Subagent library.Subagent
|
||||
Agent string // the agent whose own skill is in the library's way
|
||||
@@ -740,6 +741,12 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
|
||||
res, err = library.RemoveFoundServer(in.Name)
|
||||
case "hooks/save":
|
||||
res, err = library.SaveHook(in.Old, in.Hook)
|
||||
case "env/save":
|
||||
res, err = library.SaveEnv(in.Old, in.Env)
|
||||
case "env/agents":
|
||||
res, err = library.EnvAgents(in.Name, in.Agents)
|
||||
case "env/remove":
|
||||
res, err = library.RemoveEnv(in.Name)
|
||||
case "hooks/agents":
|
||||
res, err = library.HookAgents(in.Name, in.Agents)
|
||||
case "hooks/agents-some":
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// paopao_baobao on X: Variables, the Library's tab for environment
|
||||
// variables. One is kept once and given to agents with the chips every other
|
||||
// tab has; an agent magpie can't write one for has its chip greyed, saying
|
||||
// why, and a click on it posts nothing. A row's chip posts env/agents; Add
|
||||
// opens the editor and Save posts env/save; a row's Remove asks first and
|
||||
// posts env/remove. At 440px wide in en, zh, zh-TW, ja and de: no sideways
|
||||
// scroll. 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 { strings } = require("./strings.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const HOME = "/Users/allen";
|
||||
const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });
|
||||
const ENV_AGENTS = [
|
||||
{ id: "claude", file: `${HOME}/.claude/settings.json` },
|
||||
{ id: "codex", file: `${HOME}/.codex/config.toml` },
|
||||
{ id: "cursor", no: "Cursor has no environment settings magpie can write" },
|
||||
];
|
||||
const lib = (env) => ({
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [agent("claude", "Claude Code"), agent("codex", "Codex"), agent("cursor", "Cursor")],
|
||||
instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [], problems: [],
|
||||
env, envAgents: ENV_AGENTS,
|
||||
});
|
||||
|
||||
let I18N;
|
||||
function tr(lang, key, vars = {}) {
|
||||
let s = key;
|
||||
if (lang !== "en") {
|
||||
assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`);
|
||||
s = I18N[lang][key];
|
||||
}
|
||||
return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
|
||||
}
|
||||
|
||||
function server(lang, state, posts) {
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
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 json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/library") return json(lib(state.env));
|
||||
if (url.pathname.startsWith("/api/library/") && req.method() === "POST" && !url.pathname.endsWith("/reveal")) {
|
||||
const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", "");
|
||||
posts.push({ what, body });
|
||||
if (what === "env/agents") state.env = state.env.map((x) => (x.name === body.name ? { ...x, agents: body.agents.filter((a) => a !== "cursor") } : x));
|
||||
if (what === "env/save") state.env = [...state.env.filter((x) => x.name !== body.old), body.env];
|
||||
if (what === "env/remove") state.env = state.env.filter((x) => x.name !== body.name);
|
||||
return json({ ...lib(state.env), result: { changed: ["claude"] } });
|
||||
}
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" });
|
||||
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)];
|
||||
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
const sideways = (page) => page.evaluate(() => {
|
||||
const over = [];
|
||||
const w = document.documentElement.clientWidth;
|
||||
if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth);
|
||||
for (const e of document.querySelectorAll("#view-library .lib-env, #view-library .lib-tabs, #modal .lib-envedit *")) {
|
||||
const r = e.getBoundingClientRect();
|
||||
if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "-" + Math.round(r.right));
|
||||
}
|
||||
return over;
|
||||
});
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": the Library's Variables tab", async (t) => {
|
||||
I18N = strings().I18N;
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
await t.test(lang, async () => {
|
||||
const w = (key, vars) => tr(lang, key, vars);
|
||||
const state = { env: [{ name: "HTTPS_PROXY", value: "http://127.0.0.1:7890", agents: ["codex"] }] };
|
||||
const posts = [], errors = [];
|
||||
const ctx = await browser.newContext({ viewport: { width: 440, height: 1000 }, reducedMotion: "reduce" });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "env"); } catch {} });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); });
|
||||
await page.route("**/*", server(lang, state, posts));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator('button[data-view="library"]').click();
|
||||
const v = page.locator("#view-library");
|
||||
await v.locator(".lib-env").first().waitFor();
|
||||
const row = (name) => v.locator(".lib-env").filter({ has: page.locator(".name", { hasText: new RegExp("^" + name + "$") }) });
|
||||
|
||||
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
|
||||
assert(tabs.includes(w("Variables") + " · 1"), tabs.join("|"));
|
||||
assert.equal((await row("HTTPS_PROXY").locator(".lib-envval").textContent()).trim(), "http://127.0.0.1:7890");
|
||||
assert.deepEqual(await sideways(page), []);
|
||||
|
||||
// Cursor's chip is greyed, says why, and a click posts nothing
|
||||
const cur = row("HTTPS_PROXY").locator('.lib-ag[data-agent="cursor"]');
|
||||
assert.equal(await cur.getAttribute("aria-disabled"), "true");
|
||||
assert.equal(await cur.getAttribute("title"), w("{agent} has no environment settings magpie can write", { agent: "Cursor" }));
|
||||
await cur.click({ force: true });
|
||||
await page.waitForTimeout(150);
|
||||
assert.equal(posts.length, 0);
|
||||
|
||||
// a chip posts env/agents
|
||||
await row("HTTPS_PROXY").locator('.lib-ag[data-agent="claude"]').click();
|
||||
await page.waitForFunction(() => true);
|
||||
for (let i = 0; i < 40 && !posts.length; i++) await page.waitForTimeout(50);
|
||||
assert.equal(posts[0].what, "env/agents");
|
||||
assert.deepEqual([...posts[0].body.agents].sort(), ["claude", "codex"]);
|
||||
|
||||
// Add opens the editor; Save posts env/save with what was typed
|
||||
await v.getByRole("button", { name: w("+ Add variable") }).click();
|
||||
const m = page.locator("#modal");
|
||||
await m.locator("input").first().fill("NO_PROXY");
|
||||
await m.locator("input").nth(1).fill("localhost");
|
||||
assert.deepEqual(await sideways(page), []);
|
||||
await m.getByRole("button", { name: w("Add"), exact: true }).click();
|
||||
for (let i = 0; i < 40 && posts.length < 2; i++) await page.waitForTimeout(50);
|
||||
assert.equal(posts[1].what, "env/save");
|
||||
assert.equal(posts[1].body.old, "");
|
||||
assert.equal(posts[1].body.env.name, "NO_PROXY");
|
||||
assert.equal(posts[1].body.env.value, "localhost");
|
||||
await row("NO_PROXY").waitFor();
|
||||
|
||||
// a row's Remove asks first, naming it, and posts env/remove
|
||||
await row("NO_PROXY").locator(".lib-rm").click();
|
||||
await page.locator("#modal .lib-rmone").filter({ hasText: w("Remove the variable {name}?", { name: "NO_PROXY" }) }).waitFor();
|
||||
assert.equal(posts.length, 2, "removed before it asked");
|
||||
await page.locator("#modal .lib-rmone .primary").click();
|
||||
for (let i = 0; i < 40 && posts.length < 3; i++) await page.waitForTimeout(50);
|
||||
assert.equal(posts[2].what, "env/remove");
|
||||
assert.equal(posts[2].body.name, "NO_PROXY");
|
||||
assert.deepEqual(errors, []);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -79,14 +79,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
t.after(() => context.close());
|
||||
await page.waitForFunction(() => document.querySelector("#side .nav-sub .nav-sl"));
|
||||
const rows = await order(page);
|
||||
assert.equal(rows.length, 13, rows.join(","));
|
||||
assert.equal(rows.length, 14, rows.join(","));
|
||||
assert.deepEqual(rows.filter((x) => x[0] === "#"), ["#" + a, "#" + b, "#" + c]);
|
||||
// the order inside each: the shared six, then Claude's and Pi's, then magpie's
|
||||
// the order inside each: the shared seven, then Claude's and Pi's, then magpie's
|
||||
assert.equal(rows[0], "#" + a);
|
||||
assert.equal(rows[7], "#" + b);
|
||||
assert.equal(rows[10], "#" + c);
|
||||
assert.equal(rows[8], "#" + b);
|
||||
assert.equal(rows[11], "#" + c);
|
||||
// a name is no tab: picking by keyboard skips it, the rows are still the tabs
|
||||
assert.equal(await page.locator("#side .nav-sub .nav-s").count(), 10);
|
||||
assert.equal(await page.locator("#side .nav-sub .nav-s").count(), 11);
|
||||
// the page's own strip is as it was: no names in it
|
||||
assert.equal(await page.locator("#view-library .lib-tabs .nav-sl").count(), 0);
|
||||
// the name is quiet: the muted ink, no left border, no ground
|
||||
@@ -105,11 +105,11 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.waitForFunction(() => document.querySelector("#side .nav-sub .nav-sl"));
|
||||
// Claude plugins and Pi packages hidden: "One agent" has nothing to list
|
||||
await page.evaluate(() => { for (const b of document.querySelectorAll("#view-library .lib-tabs button")) if (["plugins", "pi"].includes(b.dataset.seg)) b.hidden = true; navSubs(); });
|
||||
await page.waitForFunction(() => !document.querySelector("#side .nav-sub .nav-s[data-of]") || document.querySelectorAll("#side .nav-sub .nav-s").length === 8);
|
||||
await page.waitForFunction(() => !document.querySelector("#side .nav-sub .nav-s[data-of]") || document.querySelectorAll("#side .nav-sub .nav-s").length === 9);
|
||||
assert.deepEqual(await heads(page), ["Every agent", "magpie"]);
|
||||
// one section left: no names at all
|
||||
await page.evaluate(() => { for (const b of document.querySelectorAll("#view-library .lib-tabs button")) if (["rtk", "bili"].includes(b.dataset.seg)) b.hidden = true; navSubs(); });
|
||||
await page.waitForFunction(() => document.querySelectorAll("#side .nav-sub .nav-s").length === 6);
|
||||
await page.waitForFunction(() => document.querySelectorAll("#side .nav-sub .nav-s").length === 7);
|
||||
assert.deepEqual(await heads(page), []);
|
||||
});
|
||||
|
||||
|
||||
@@ -152,7 +152,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
|
||||
// the tab, with its count, between Skills and Subagents
|
||||
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
|
||||
assert.deepEqual(tabs.slice(3, 8), [w("Skills"), w("Hooks") + " · 2", w("Subagents"), w("Claude plugins"), "RTK"]);
|
||||
assert.deepEqual(tabs.slice(3, 9), [w("Skills"), w("Hooks") + " · 2", w("Variables"), w("Subagents"), w("Claude plugins"), "RTK"]);
|
||||
// each hook says when it runs, in words, and what it runs
|
||||
assert.equal((await row("fmt").locator(".lib-hookev").textContent()).trim(), w("After a tool runs") + " · " + w("File edits"));
|
||||
assert.equal((await row("bark").locator(".lib-hookev").textContent()).trim(), w("When a turn ends"));
|
||||
|
||||
@@ -73,7 +73,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.equal(await skel.getAttribute("aria-busy"), "true");
|
||||
|
||||
const tabs = v.locator(".lib-head .lib-tabs .opt");
|
||||
assert.deepEqual(await tabs.allTextContents(), ["Instructions", "Memory", "MCP servers", "Skills", "Hooks", "Subagents", "RTK", "billion-context"]);
|
||||
assert.deepEqual(await tabs.allTextContents(), ["Instructions", "Memory", "MCP servers", "Skills", "Hooks", "Variables", "Subagents", "RTK", "billion-context"]);
|
||||
assert.equal(await v.locator(".lib-tabs .opt.on").textContent(), "Skills");
|
||||
assert.ok(await v.locator(".lib-head .lib-more").isDisabled(), "the folder waits for the library");
|
||||
// Skills in outline: rows with a switch, no section heading
|
||||
@@ -90,7 +90,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
open();
|
||||
await v.locator(".lib-head .lib-more:not([disabled])").waitFor();
|
||||
assert.equal(await v.locator(".lib-skel").count(), 0, "the outline goes");
|
||||
assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "Memory", "MCP servers · 1", "Skills · 1", "Hooks", "Subagents", "RTK", "billion-context", "Pi packages"]);
|
||||
assert.deepEqual(await v.locator(".lib-tabs .opt").allTextContents(), ["Instructions", "Memory", "MCP servers · 1", "Skills · 1", "Hooks", "Variables", "Subagents", "RTK", "billion-context", "Pi packages"]);
|
||||
assert.equal(await v.locator(".lib-tabs .opt.on").textContent(), "Instructions");
|
||||
assert.equal(await v.locator(".lib-head .lib-more").getAttribute("title"), "~/.magpie/library");
|
||||
const after = await v.locator(".lib-tabs").boundingBox();
|
||||
|
||||
@@ -172,7 +172,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
|
||||
// the tab, with its count, between Hooks and RTK
|
||||
const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim());
|
||||
assert.deepEqual(tabs.slice(4, 8), [w("Hooks"), w("Subagents") + " · 1", w("Claude plugins"), "RTK"]);
|
||||
assert.deepEqual(tabs.slice(4, 9), [w("Hooks"), w("Variables"), w("Subagents") + " · 1", w("Claude plugins"), "RTK"]);
|
||||
// the row: what it is for, and what it binds
|
||||
assert.equal((await row("reviewer").locator(".lib-subagentdesc").textContent()).trim(), LONG);
|
||||
assert.equal((await row("reviewer").locator(".lib-subagentuses").textContent()).trim(), w("Skills: {names}", { names: "tdd" }) + " · " + w("MCP servers: {names}", { names: "github" }));
|
||||
@@ -199,8 +199,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.waitForTimeout(200);
|
||||
assert.deepEqual(posts.shift(), { what: "subagents/agents", body: { name: "reviewer", agents: ["claude", "codex", "cursor"] } });
|
||||
assert.deepEqual(agentsOf("reviewer"), ["claude", "codex", "cursor"]);
|
||||
await press(page, v.locator(".lib-tabs button").nth(4));
|
||||
await press(page, v.locator(".lib-tabs button").nth(5));
|
||||
await press(page, v.locator(".lib-tabs button").nth(6));
|
||||
await v.locator(".lib-subagents-cursor").filter({ hasText: w("The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents.") }).waitFor();
|
||||
await v.locator(".lib-subagents-noskills").filter({ hasText: w("{agents} can't bind skills to a subagent: theirs gets its prompt, and every skill the agent has.", { agents: "Codex, Cursor" }) }).waitFor();
|
||||
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/jsonc"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
)
|
||||
|
||||
// Environment variables (paopao_baobao on X) are set once in the library
|
||||
// and written into each agent ticked for them, in the place that agent
|
||||
// keeps variables it sets for what it runs:
|
||||
//
|
||||
// Claude Code <claude dir>/settings.json env: {NAME: "value"} (its settings docs: "Environment variables
|
||||
// that will be applied to every session")
|
||||
// Codex <codex home>/config.toml [shell_environment_policy.set] NAME = "value" (its config docs:
|
||||
// "set" is the variables forced into the environment of every command it runs)
|
||||
//
|
||||
// What magpie wrote is recorded name and value (Applied.Env). A variable
|
||||
// the file already has is the user's: another value is never written over
|
||||
// it, and one the user changed after magpie wrote it is theirs from then
|
||||
// on. Turning a variable off takes out only what is still as magpie wrote
|
||||
// it.
|
||||
|
||||
// EnvVar is a variable the agents ticked for it are given.
|
||||
type EnvVar struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
Agents []string `json:"agents"`
|
||||
}
|
||||
|
||||
// EnvEntry is a variable magpie wrote into an agent, with its value.
|
||||
type EnvEntry struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// envAgents are the agents magpie can give variables to.
|
||||
var envAgents = []string{"claude", "codex"}
|
||||
|
||||
const (
|
||||
maxEnvName = 128
|
||||
maxEnvValue = 8192
|
||||
)
|
||||
|
||||
var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
|
||||
|
||||
func (e *EnvVar) check() error {
|
||||
if !envName.MatchString(e.Name) || len(e.Name) > maxEnvName {
|
||||
return fmt.Errorf("%q isn't a variable name: letters, digits and _, not starting with a digit", e.Name)
|
||||
}
|
||||
if strings.ContainsRune(e.Value, 0) || !utf8.ValidString(e.Value) || len(e.Value) > maxEnvValue {
|
||||
return fmt.Errorf("%s has a value that can't be written into an agent's settings", e.Name)
|
||||
}
|
||||
for _, a := range e.Agents {
|
||||
if !slices.Contains(envAgents, a) {
|
||||
return fmt.Errorf("magpie gives variables to Claude Code and Codex, not %s", a)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *Library) env(name string) *EnvVar {
|
||||
for _, e := range l.Env {
|
||||
if e.Name == name {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// envFile is where t keeps the variables it sets, or why magpie can't give
|
||||
// it any.
|
||||
func envFile(t *Target) (string, string) {
|
||||
switch {
|
||||
case !slices.Contains(envAgents, t.Agent.ID):
|
||||
return "", fmt.Sprintf("%s has no setting for variables magpie can write", t.Agent.Name)
|
||||
case t.Agent.WSL != "":
|
||||
return "", fmt.Sprintf("magpie gives variables only to agents on this computer, not yet to %s in WSL", t.Agent.Name)
|
||||
case t.Agent.ID == "claude":
|
||||
return filepath.Join(claudeDir(), "settings.json"), ""
|
||||
}
|
||||
return filepath.Join(codexDir(), "config.toml"), ""
|
||||
}
|
||||
|
||||
// the table Codex's variables are in
|
||||
const codexEnvTable = "shell_environment_policy"
|
||||
|
||||
// readEnv is the variables path holds, in the setting this agent keeps
|
||||
// them in. A file that can't be read as that is an error, never "none".
|
||||
func readEnv(id, path string) (map[string]string, error) {
|
||||
out := map[string]string{}
|
||||
if id == "claude" {
|
||||
doc, err := readHooksFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e := gjson.GetBytes(doc, "env")
|
||||
if !e.Exists() {
|
||||
return out, nil
|
||||
}
|
||||
if !e.IsObject() {
|
||||
return nil, fmt.Errorf("%s has an env that isn't an object: it is left as it is", path)
|
||||
}
|
||||
e.ForEach(func(k, v gjson.Result) bool {
|
||||
out[k.String()] = v.String()
|
||||
return true
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
raw, err := edit.Read(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var doc map[string]any
|
||||
if err := toml.Unmarshal(edit.TrimBOM(raw), &doc); err != nil {
|
||||
return nil, fmt.Errorf("%s isn't TOML magpie can read: it is left as it is", path)
|
||||
}
|
||||
pol, ok := doc[codexEnvTable]
|
||||
if !ok {
|
||||
return out, nil
|
||||
}
|
||||
pm, ok := pol.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s has a %s that isn't a table: it is left as it is", path, codexEnvTable)
|
||||
}
|
||||
s, ok := pm["set"]
|
||||
if !ok {
|
||||
return out, nil
|
||||
}
|
||||
sm, ok := s.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s has a %s.set that isn't a table: it is left as it is", path, codexEnvTable)
|
||||
}
|
||||
for k, v := range sm {
|
||||
out[k] = fmt.Sprint(v)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// codexHasSet is whether the file has a shell_environment_policy.set, in
|
||||
// any spelling.
|
||||
func codexHasSet(path string) bool {
|
||||
raw, err := edit.Read(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
var doc struct {
|
||||
Policy map[string]any `toml:"shell_environment_policy"`
|
||||
}
|
||||
if toml.Unmarshal(edit.TrimBOM(raw), &doc) != nil {
|
||||
return false
|
||||
}
|
||||
_, ok := doc.Policy["set"]
|
||||
return ok
|
||||
}
|
||||
|
||||
// writeEnv sets and takes out variables where the agent keeps them,
|
||||
// leaving the rest of the file as it is.
|
||||
func writeEnv(id, path string, set map[string]string, del []string) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if id == "claude" {
|
||||
raw, err := edit.Read(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
raw = []byte("{}\n")
|
||||
}
|
||||
var kvs []edit.KV
|
||||
for _, k := range slices.Sorted(maps.Keys(set)) {
|
||||
kvs = append(kvs, edit.KV{Path: "env." + k, Value: set[k]})
|
||||
}
|
||||
var dels []string
|
||||
for _, k := range del {
|
||||
dels = append(dels, "env."+k)
|
||||
}
|
||||
out, err := edit.PatchJSON(raw, kvs, dels)
|
||||
if err == nil && len(del) > 0 && len(set) == 0 {
|
||||
// an env left empty by magpie goes with what it held
|
||||
if e := gjson.GetBytes(jsonc.ToJSON(edit.TrimBOM(out)), "env"); e.IsObject() && len(e.Map()) == 0 {
|
||||
out, err = edit.PatchJSON(out, nil, []string{"env"})
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return edit.WriteAtomic(path, out)
|
||||
}
|
||||
// Codex: [shell_environment_policy.set] is a table of its own, unless
|
||||
// the user wrote `set` inline in [shell_environment_policy], which is
|
||||
// then rewritten as the one key it is
|
||||
tables, err := edit.TOMLTables(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sub := codexEnvTable + ".set"
|
||||
if !slices.Contains(tables, sub) {
|
||||
cur, err := readEnv(id, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if codexHasSet(path) {
|
||||
keys, err := edit.GetTOMLTable(path, codexEnvTable)
|
||||
if err != nil || !slices.Contains(tables, codexEnvTable) {
|
||||
return fmt.Errorf("%s has its set variables in a spelling magpie doesn't edit: it is left as it is", path)
|
||||
}
|
||||
for k := range keys {
|
||||
if strings.HasPrefix(k, "set.") {
|
||||
return fmt.Errorf("%s has its set variables as dotted keys, which magpie doesn't edit: it is left as it is", path)
|
||||
}
|
||||
}
|
||||
for _, k := range del {
|
||||
delete(cur, k)
|
||||
}
|
||||
maps.Copy(cur, set)
|
||||
var in edit.Inline
|
||||
for _, k := range slices.Sorted(maps.Keys(cur)) {
|
||||
in = append(in, edit.KV{Path: k, Value: cur[k]})
|
||||
}
|
||||
return edit.SetTOMLKey(path, codexEnvTable, "set", in)
|
||||
}
|
||||
}
|
||||
for _, k := range slices.Sorted(maps.Keys(set)) {
|
||||
if err := edit.SetTOMLKey(path, sub, k, set[k]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, k := range del {
|
||||
if err := edit.DelTOMLKey(path, sub, k); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *Library) syncEnv(t *Target, b *backups, res *Result) {
|
||||
id := t.Agent.ID
|
||||
a := l.applied(id)
|
||||
want := map[string]string{}
|
||||
for _, e := range l.Env {
|
||||
if slices.Contains(e.Agents, id) {
|
||||
want[e.Name] = e.Value
|
||||
}
|
||||
}
|
||||
if len(a.Env) == 0 && len(want) == 0 {
|
||||
return
|
||||
}
|
||||
path, why := envFile(t)
|
||||
if path == "" {
|
||||
for _, n := range slices.Sorted(maps.Keys(want)) {
|
||||
res.fail(id, "env:"+n, errors.New(why))
|
||||
}
|
||||
return
|
||||
}
|
||||
failAll := func(err error) {
|
||||
for _, n := range slices.Sorted(maps.Keys(want)) {
|
||||
res.fail(id, "env:"+n, err)
|
||||
}
|
||||
if len(want) == 0 {
|
||||
res.fail(id, "env", err)
|
||||
}
|
||||
}
|
||||
cur, err := readEnv(id, path)
|
||||
if err != nil {
|
||||
failAll(err)
|
||||
return
|
||||
}
|
||||
var kept []EnvEntry
|
||||
set := map[string]string{}
|
||||
var del []string
|
||||
mine := map[string]bool{} // names whose record stands, or whose value magpie is writing
|
||||
for _, rec := range a.Env {
|
||||
v, there := cur[rec.Name]
|
||||
switch w, wanted := want[rec.Name]; {
|
||||
case !there || v != rec.Value:
|
||||
// gone, or changed by the user: theirs now
|
||||
case wanted && w == rec.Value:
|
||||
kept = append(kept, rec)
|
||||
mine[rec.Name] = true
|
||||
case wanted:
|
||||
set[rec.Name] = w
|
||||
kept = append(kept, EnvEntry{Name: rec.Name, Value: w})
|
||||
mine[rec.Name] = true
|
||||
default:
|
||||
del = append(del, rec.Name)
|
||||
}
|
||||
}
|
||||
for _, n := range slices.Sorted(maps.Keys(want)) {
|
||||
if mine[n] {
|
||||
continue
|
||||
}
|
||||
if v, there := cur[n]; there {
|
||||
// the user's own: the same value is no change, another is
|
||||
// never written over it
|
||||
if v != want[n] {
|
||||
res.fail(id, "env:"+n, fmt.Errorf("%s already sets %s to another value: magpie leaves it as it is", path, n))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if t.Gone {
|
||||
continue
|
||||
}
|
||||
set[n] = want[n]
|
||||
kept = append(kept, EnvEntry{Name: n, Value: want[n]})
|
||||
}
|
||||
if len(set) == 0 && len(del) == 0 {
|
||||
a.Env = kept
|
||||
return
|
||||
}
|
||||
if err := b.keep(id, path); err != nil {
|
||||
failAll(err)
|
||||
return
|
||||
}
|
||||
if err := writeEnv(id, path, set, del); err != nil {
|
||||
failAll(fmt.Errorf("%s: %w", path, err))
|
||||
return
|
||||
}
|
||||
res.changed(id)
|
||||
a.Env = kept
|
||||
}
|
||||
|
||||
// ---- changes ---------------------------------------------------------------
|
||||
|
||||
// SaveEnv adds a variable, or replaces the one called old (renaming it).
|
||||
func SaveEnv(old string, e EnvVar) (*Result, error) {
|
||||
if err := e.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return change(func(l *Library) error {
|
||||
if e.Name != old && l.env(e.Name) != nil {
|
||||
return fmt.Errorf("the library already has a variable called %s", e.Name)
|
||||
}
|
||||
if old != "" {
|
||||
i := slices.IndexFunc(l.Env, func(x *EnvVar) bool { return x.Name == old })
|
||||
if i < 0 {
|
||||
return fmt.Errorf("no variable called %s", old)
|
||||
}
|
||||
l.Env = slices.Delete(l.Env, i, i+1)
|
||||
}
|
||||
e.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(e.Agents))))
|
||||
l.Env = append(l.Env, &e)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// EnvAgents sets which agents get a variable.
|
||||
func EnvAgents(name string, agents []string) (*Result, error) {
|
||||
return change(func(l *Library) error {
|
||||
e := l.env(name)
|
||||
if e == nil {
|
||||
return fmt.Errorf("no variable called %s", name)
|
||||
}
|
||||
c := *e
|
||||
c.Agents = agents
|
||||
if err := c.check(); err != nil {
|
||||
return err
|
||||
}
|
||||
e.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(agents))))
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// RemoveEnv takes a variable out of the library, and what magpie wrote of
|
||||
// it out of every agent.
|
||||
func RemoveEnv(name string) (*Result, error) {
|
||||
return change(func(l *Library) error {
|
||||
if l.env(name) == nil {
|
||||
return fmt.Errorf("no variable called %s", name)
|
||||
}
|
||||
l.Env = slices.DeleteFunc(l.Env, func(e *EnvVar) bool { return e.Name == name })
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ---- the page --------------------------------------------------------------
|
||||
|
||||
// EnvView is a library variable, and why an agent couldn't be given it.
|
||||
type EnvView struct {
|
||||
*EnvVar
|
||||
Problems map[string]string `json:"problems,omitempty"`
|
||||
}
|
||||
|
||||
// EnvAgentView is an agent the Variables tab lists: File is where its
|
||||
// variables are, No why magpie can't give it any.
|
||||
type EnvAgentView struct {
|
||||
ID string `json:"id"`
|
||||
File string `json:"file,omitempty"`
|
||||
No string `json:"no,omitempty"`
|
||||
WSL bool `json:"wsl,omitempty"`
|
||||
}
|
||||
|
||||
func (l *Library) envView(targets []*Target, of func(string) map[string]string) ([]EnvView, []EnvAgentView) {
|
||||
agents := []EnvAgentView{}
|
||||
for _, t := range targets {
|
||||
f, why := envFile(t)
|
||||
agents = append(agents, EnvAgentView{ID: t.Agent.ID, File: f, No: why, WSL: t.Agent.WSL != ""})
|
||||
}
|
||||
vars := []EnvView{}
|
||||
for _, e := range l.Env {
|
||||
c := *e
|
||||
c.Agents = orNone(c.Agents)
|
||||
ev := EnvView{EnvVar: &c, Problems: of("env:" + e.Name)}
|
||||
for _, av := range agents {
|
||||
if av.No != "" && slices.Contains(e.Agents, av.ID) {
|
||||
if ev.Problems == nil {
|
||||
ev.Problems = map[string]string{}
|
||||
}
|
||||
if ev.Problems[av.ID] == "" {
|
||||
ev.Problems[av.ID] = av.No
|
||||
}
|
||||
}
|
||||
}
|
||||
vars = append(vars, ev)
|
||||
}
|
||||
return vars, agents
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/jsonc"
|
||||
)
|
||||
|
||||
func claudeEnv(t *testing.T, p string) map[string]string {
|
||||
t.Helper()
|
||||
out := map[string]string{}
|
||||
gjson.GetBytes(jsonc.ToJSON([]byte(read(t, p))), "env").ForEach(func(k, v gjson.Result) bool {
|
||||
out[k.String()] = v.String()
|
||||
return true
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func codexSet(t *testing.T, p string) map[string]any {
|
||||
t.Helper()
|
||||
var doc map[string]any
|
||||
if err := toml.Unmarshal([]byte(read(t, p)), &doc); err != nil {
|
||||
t.Fatalf("config.toml is not TOML: %v\n%s", err, read(t, p))
|
||||
}
|
||||
pol, _ := doc["shell_environment_policy"].(map[string]any)
|
||||
set, _ := pol["set"].(map[string]any)
|
||||
return set
|
||||
}
|
||||
|
||||
// A variable lands in Claude Code's settings.json env and Codex's
|
||||
// [shell_environment_policy.set], beside what the user has there, and
|
||||
// turning it off takes out that and nothing else.
|
||||
func TestEnvWrittenAndTakenOut(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
settings := filepath.Join(h, ".claude/settings.json")
|
||||
cfg := filepath.Join(h, ".codex/config.toml")
|
||||
write(t, settings, "{\n // mine\n \"model\": \"opus\",\n \"env\": {\"MINE\": \"1\"}\n}\n")
|
||||
write(t, cfg, "model = \"gpt-5\"\n\n[shell_environment_policy]\ninherit = \"core\"\nexclude = [\"AWS_*\"]\n")
|
||||
|
||||
ok(t)(SaveEnv("", EnvVar{Name: "HTTP_PROXY", Value: "http://127.0.0.1:7890", Agents: []string{"claude", "codex"}}))
|
||||
|
||||
if got := claudeEnv(t, settings); got["HTTP_PROXY"] != "http://127.0.0.1:7890" || got["MINE"] != "1" || len(got) != 2 {
|
||||
t.Errorf("claude env: %v", got)
|
||||
}
|
||||
if s := read(t, settings); !strings.Contains(s, "// mine") || !strings.Contains(s, `"model": "opus"`) {
|
||||
t.Errorf("claude's settings lost the user's own:\n%s", s)
|
||||
}
|
||||
if got := codexSet(t, cfg); got["HTTP_PROXY"] != "http://127.0.0.1:7890" || len(got) != 1 {
|
||||
t.Errorf("codex set: %v", got)
|
||||
}
|
||||
if s := read(t, cfg); !strings.Contains(s, `inherit = "core"`) || !strings.Contains(s, `exclude = ["AWS_*"]`) {
|
||||
t.Errorf("codex's config lost the user's own:\n%s", s)
|
||||
}
|
||||
|
||||
// unticking Codex takes it from Codex alone
|
||||
ok(t)(EnvAgents("HTTP_PROXY", []string{"claude"}))
|
||||
if got := codexSet(t, cfg); len(got) != 0 {
|
||||
t.Errorf("codex still has %v", got)
|
||||
}
|
||||
if s := read(t, cfg); !strings.Contains(s, `inherit = "core"`) || strings.Contains(s, "HTTP_PROXY") || strings.Contains(s, "shell_environment_policy.set") {
|
||||
t.Errorf("codex's config after:\n%s", s)
|
||||
}
|
||||
if got := claudeEnv(t, settings); got["HTTP_PROXY"] == "" {
|
||||
t.Errorf("claude lost it: %v", got)
|
||||
}
|
||||
|
||||
ok(t)(RemoveEnv("HTTP_PROXY"))
|
||||
if got := claudeEnv(t, settings); len(got) != 1 || got["MINE"] != "1" {
|
||||
t.Errorf("claude env after remove: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A variable the user set themselves is never written over, and never
|
||||
// taken out; one they changed after magpie wrote it is theirs from then on.
|
||||
func TestEnvNeverOverridesTheUsers(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
settings := filepath.Join(h, ".claude/settings.json")
|
||||
cfg := filepath.Join(h, ".codex/config.toml")
|
||||
write(t, settings, `{"env": {"FOO": "mine", "SAME": "x"}}`)
|
||||
write(t, cfg, "[shell_environment_policy.set]\nFOO = \"mine\"\n")
|
||||
|
||||
res, err := SaveEnv("", EnvVar{Name: "FOO", Value: "magpie", Agents: []string{"claude", "codex"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(res.Problems) != 2 {
|
||||
t.Errorf("want a problem for each agent, got %+v", res.Problems)
|
||||
}
|
||||
if got := claudeEnv(t, settings); got["FOO"] != "mine" {
|
||||
t.Errorf("claude's own FOO was overridden: %v", got)
|
||||
}
|
||||
if got := codexSet(t, cfg); got["FOO"] != "mine" {
|
||||
t.Errorf("codex's own FOO was overridden: %v", got)
|
||||
}
|
||||
// the same value is the user's too: removing it leaves it
|
||||
if _, err := RemoveEnv("FOO"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ok(t)(SaveEnv("", EnvVar{Name: "SAME", Value: "x", Agents: []string{"claude"}}))
|
||||
ok(t)(RemoveEnv("SAME"))
|
||||
if got := claudeEnv(t, settings); got["FOO"] != "mine" || got["SAME"] != "x" {
|
||||
t.Errorf("claude's own variables were taken out: %v", got)
|
||||
}
|
||||
if got := codexSet(t, cfg); got["FOO"] != "mine" {
|
||||
t.Errorf("codex's own variable was taken out: %v", got)
|
||||
}
|
||||
|
||||
// one magpie wrote and the user then changed is theirs
|
||||
ok(t)(SaveEnv("", EnvVar{Name: "BAR", Value: "1", Agents: []string{"claude", "codex"}}))
|
||||
if !strings.Contains(read(t, settings), `"BAR":"1"`) {
|
||||
t.Fatalf("settings: %s", read(t, settings))
|
||||
}
|
||||
write(t, settings, strings.Replace(read(t, settings), `"BAR":"1"`, `"BAR":"edited"`, 1))
|
||||
write(t, cfg, strings.Replace(read(t, cfg), `BAR = "1"`, `BAR = "edited"`, 1))
|
||||
ok(t)(RemoveEnv("BAR"))
|
||||
if got := claudeEnv(t, settings); got["BAR"] != "edited" {
|
||||
t.Errorf("claude's edited BAR was taken out: %v", got)
|
||||
}
|
||||
if got := codexSet(t, cfg); got["BAR"] != "edited" {
|
||||
t.Errorf("codex's edited BAR was taken out: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Changing a value changes it where magpie wrote it, and only there.
|
||||
func TestEnvValueChanged(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
settings := filepath.Join(h, ".claude/settings.json")
|
||||
cfg := filepath.Join(h, ".codex/config.toml")
|
||||
ok(t)(SaveEnv("", EnvVar{Name: "A", Value: "1", Agents: []string{"claude", "codex"}}))
|
||||
ok(t)(SaveEnv("A", EnvVar{Name: "A", Value: "2", Agents: []string{"claude", "codex"}}))
|
||||
if got := claudeEnv(t, settings); got["A"] != "2" || len(got) != 1 {
|
||||
t.Errorf("claude: %v", got)
|
||||
}
|
||||
if got := codexSet(t, cfg); got["A"] != "2" || len(got) != 1 {
|
||||
t.Errorf("codex: %v", got)
|
||||
}
|
||||
// a rename takes the old name out
|
||||
ok(t)(SaveEnv("A", EnvVar{Name: "B", Value: "2", Agents: []string{"claude", "codex"}}))
|
||||
if got := claudeEnv(t, settings); got["B"] != "2" || len(got) != 1 {
|
||||
t.Errorf("claude after rename: %v", got)
|
||||
}
|
||||
if got := codexSet(t, cfg); got["B"] != "2" || len(got) != 1 {
|
||||
t.Errorf("codex after rename: %v", got)
|
||||
}
|
||||
ok(t)(RemoveEnv("B"))
|
||||
if s := strings.TrimSpace(read(t, settings)); strings.Contains(s, "env") {
|
||||
t.Errorf("claude's empty env stayed: %s", s)
|
||||
}
|
||||
}
|
||||
|
||||
// Codex's `set` written inline by the user is edited in place, never
|
||||
// defined a second time.
|
||||
func TestEnvCodexInlineSet(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
cfg := filepath.Join(h, ".codex/config.toml")
|
||||
write(t, cfg, "[shell_environment_policy]\ninherit = \"all\"\nset = { MINE = \"1\" }\n")
|
||||
ok(t)(SaveEnv("", EnvVar{Name: "A", Value: "x y", Agents: []string{"codex"}}))
|
||||
if got := codexSet(t, cfg); got["A"] != "x y" || got["MINE"] != "1" || len(got) != 2 {
|
||||
t.Errorf("set: %v\n%s", got, read(t, cfg))
|
||||
}
|
||||
ok(t)(RemoveEnv("A"))
|
||||
if got := codexSet(t, cfg); got["MINE"] != "1" || len(got) != 1 {
|
||||
t.Errorf("set after: %v\n%s", got, read(t, cfg))
|
||||
}
|
||||
if !strings.Contains(read(t, cfg), `inherit = "all"`) {
|
||||
t.Errorf("lost inherit:\n%s", read(t, cfg))
|
||||
}
|
||||
}
|
||||
|
||||
// A file that doesn't parse is left as it is, and the variable says why.
|
||||
func TestEnvUnreadableFileLeftAlone(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
settings := filepath.Join(h, ".claude/settings.json")
|
||||
cfg := filepath.Join(h, ".codex/config.toml")
|
||||
write(t, settings, `{"env": `)
|
||||
write(t, cfg, "[shell_environment_policy\n")
|
||||
res, err := SaveEnv("", EnvVar{Name: "A", Value: "1", Agents: []string{"claude", "codex"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(res.Problems) != 2 {
|
||||
t.Errorf("problems: %+v", res.Problems)
|
||||
}
|
||||
if read(t, settings) != `{"env": ` || read(t, cfg) != "[shell_environment_policy\n" {
|
||||
t.Errorf("a file that doesn't parse was written")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvChecked(t *testing.T) {
|
||||
sandbox(t)
|
||||
for _, e := range []EnvVar{{Name: "1A"}, {Name: "A-B"}, {Name: ""}, {Name: "A", Value: "x\x00"}, {Name: "A", Agents: []string{"gemini"}}} {
|
||||
if _, err := SaveEnv("", e); err == nil {
|
||||
t.Errorf("%+v was saved", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,9 @@ type Library struct {
|
||||
// Hooks are commands the agents ticked for each run at a point of
|
||||
// their turn (hooks.go, #1790)
|
||||
Hooks []*Hook `json:"hooks,omitempty"`
|
||||
// Env are the environment variables the agents ticked for each are
|
||||
// given in their own settings (env.go)
|
||||
Env []*EnvVar `json:"env,omitempty"`
|
||||
// Subagents are agents of their own the agents ticked for each can
|
||||
// hand a task to (subagents.go, #2283)
|
||||
Subagents []*Subagent `json:"subagents,omitempty"`
|
||||
@@ -147,6 +150,9 @@ type Applied struct {
|
||||
// Hooks are the entries magpie wrote into the agent's hooks, each
|
||||
// exactly as written: one changed since is the user's (hooks.go)
|
||||
Hooks []HookEntry `json:"hooks,omitempty"`
|
||||
// Env are the variables magpie wrote into the agent's settings, with
|
||||
// their values: one there with another value since is the user's
|
||||
Env []EnvEntry `json:"env,omitempty"`
|
||||
// Subagents are the files magpie wrote for the subagents, each with
|
||||
// the hash of what it wrote: one changed since is the user's
|
||||
Subagents []SubagentFile `json:"subagents,omitempty"`
|
||||
@@ -172,7 +178,7 @@ type Applied struct {
|
||||
// it looked at the agent through (#4247).
|
||||
func (a *Applied) empty() bool {
|
||||
return !a.Instructions && a.InstrHash == "" && len(a.MCP) == 0 && len(a.Skills) == 0 &&
|
||||
len(a.ToolsOff) == 0 && len(a.ToolRules) == 0 && len(a.Hooks) == 0 &&
|
||||
len(a.ToolsOff) == 0 && len(a.ToolRules) == 0 && len(a.Hooks) == 0 && len(a.Env) == 0 &&
|
||||
len(a.Subagents) == 0 && len(a.Startup) == 0 && len(a.Picked) == 0 && !a.Router && len(a.RouterRules) == 0
|
||||
}
|
||||
|
||||
@@ -227,6 +233,10 @@ func (l *Library) save() error {
|
||||
for _, h := range l.Hooks {
|
||||
h.Agents = orNone(h.Agents)
|
||||
}
|
||||
sort.Slice(l.Env, func(i, j int) bool { return l.Env[i].Name < l.Env[j].Name })
|
||||
for _, e := range l.Env {
|
||||
e.Agents = orNone(e.Agents)
|
||||
}
|
||||
sort.Slice(l.Subagents, func(i, j int) bool { return l.Subagents[i].Name < l.Subagents[j].Name })
|
||||
for _, s := range l.Subagents {
|
||||
s.Agents = orNone(s.Agents)
|
||||
|
||||
@@ -111,6 +111,7 @@ func syncSteps(all, gone []*Target, b *backups, res *Result) []func(*Library) {
|
||||
l.syncInstructions(t, b, res, true)
|
||||
l.syncMCP(t, b, res)
|
||||
l.syncHooks(t, b, res)
|
||||
l.syncEnv(t, b, res)
|
||||
l.syncSubagents(t, b, res)
|
||||
})
|
||||
}
|
||||
@@ -122,6 +123,7 @@ func syncSteps(all, gone []*Target, b *backups, res *Result) []func(*Library) {
|
||||
steps = append(steps, func(l *Library) {
|
||||
l.syncMCP(t, b, res)
|
||||
l.syncHooks(t, b, res)
|
||||
l.syncEnv(t, b, res)
|
||||
l.syncSkills(t, res, all)
|
||||
})
|
||||
}
|
||||
@@ -510,6 +512,10 @@ type View struct {
|
||||
// this computer can take of them (hooks.go)
|
||||
Hooks []HookView `json:"hooks"`
|
||||
HookAgents []HookAgentView `json:"hookAgents"`
|
||||
// Env are the library's variables, and EnvAgents what each agent on
|
||||
// this computer can take of them (env.go)
|
||||
Env []EnvView `json:"env"`
|
||||
EnvAgents []EnvAgentView `json:"envAgents"`
|
||||
// Subagents are the library's subagents, and SubagentAgents what
|
||||
// each agent on this computer makes of them (subagents.go)
|
||||
Subagents []SubagentView `json:"subagents"`
|
||||
@@ -709,6 +715,7 @@ func readView(problems []Problem, glance bool) (*View, error) {
|
||||
v.Servers = append(v.Servers, sv)
|
||||
}
|
||||
v.Hooks, v.HookAgents = l.hooksView(append(slices.Clone(targets), gone...), asleep, of)
|
||||
v.Env, v.EnvAgents = l.envView(append(slices.Clone(targets), gone...), of)
|
||||
v.Subagents, v.SubagentAgents = l.subagentsView(targets, asleep, of)
|
||||
v.Plugins = l.pluginsView()
|
||||
tr := &tracer{}
|
||||
|
||||
@@ -998,12 +998,13 @@ func (l *Library) held(have []*Target) []*Target {
|
||||
in[t.Agent.ID] = true
|
||||
}
|
||||
has := func(id string) bool {
|
||||
if a := l.Applied[id]; a != nil && (len(a.Skills) > 0 || len(a.MCP) > 0 || len(a.Hooks) > 0 || a.Router || len(a.RouterRules) > 0) {
|
||||
if a := l.Applied[id]; a != nil && (len(a.Skills) > 0 || len(a.MCP) > 0 || len(a.Hooks) > 0 || len(a.Env) > 0 || a.Router || len(a.RouterRules) > 0) {
|
||||
return true
|
||||
}
|
||||
return slices.ContainsFunc(l.Skills, func(s *Skill) bool { return s.gives(id) }) ||
|
||||
slices.ContainsFunc(l.MCP, func(s *Server) bool { return slices.Contains(s.Agents, id) }) ||
|
||||
slices.ContainsFunc(l.Hooks, func(h *Hook) bool { return slices.Contains(h.Agents, id) })
|
||||
slices.ContainsFunc(l.Hooks, func(h *Hook) bool { return slices.Contains(h.Agents, id) }) ||
|
||||
slices.ContainsFunc(l.Env, func(e *EnvVar) bool { return slices.Contains(e.Agents, id) })
|
||||
}
|
||||
var out []*Target
|
||||
for _, a := range append(apps(), agent.All()...) {
|
||||
|
||||
Reference in New Issue
Block a user