@toolmesh/agent-deck 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { INSTALLED_DIR } from "../paths.mjs";
5
+
6
+ /**
7
+ * Native mode for Claude Code: `.ai/installed/` is a local marketplace registered at
8
+ * local scope, and each plugin is installed from it. Claude then reads
9
+ * `.ai/installed/plugins/<id>/` in place, with hooks, commands, MCP, and
10
+ * `${CLAUDE_PLUGIN_ROOT}` handled by Claude itself.
11
+ *
12
+ * Writing `.claude/settings.local.json` by hand is not enough: the install is
13
+ * also recorded in the user's plugin registry, so agent-deck drives the `claude` CLI.
14
+ */
15
+
16
+ export const MARKETPLACE = "agent-deck";
17
+
18
+ let found;
19
+
20
+ /** The `claude` executable, or null. `AGENT_DECK_CLAUDE_BIN` overrides PATH. Looked up once per run. */
21
+ export function claudeBin() {
22
+ const explicit = process.env.AGENT_DECK_CLAUDE_BIN;
23
+ if (explicit) return fs.existsSync(explicit) ? explicit : null;
24
+ if (found === undefined) {
25
+ const r = spawnSync("claude", ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
26
+ found = r.status === 0 ? "claude" : null;
27
+ }
28
+ return found;
29
+ }
30
+
31
+ /** Claude has this plugin enabled from the agent-deck marketplace at local scope. */
32
+ export function isEnabled(projectRoot, name) {
33
+ return localSettings(projectRoot).enabledPlugins?.[`${name}@${MARKETPLACE}`] === true;
34
+ }
35
+
36
+ function claude(bin, projectRoot, args) {
37
+ const r = spawnSync(bin, args, {
38
+ cwd: projectRoot,
39
+ encoding: "utf8",
40
+ stdio: ["ignore", "pipe", "pipe"],
41
+ });
42
+ if (r.error) throw new Error(`claude ${args.join(" ")}: ${r.error.message}`);
43
+ return { ok: r.status === 0, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
44
+ }
45
+
46
+ function must(result, what) {
47
+ if (!result.ok) throw new Error(`${what} failed: ${result.out}`);
48
+ return result;
49
+ }
50
+
51
+ function localSettings(projectRoot) {
52
+ const file = path.join(projectRoot, ".claude", "settings.local.json");
53
+ if (!fs.existsSync(file)) return {};
54
+ try {
55
+ return JSON.parse(fs.readFileSync(file, "utf8"));
56
+ } catch {
57
+ return {};
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Register `.ai/installed/` as the `agent-deck` marketplace at local scope. A directory
63
+ * marketplace is read in place: a plugin added to its catalog installs without
64
+ * `marketplace update`.
65
+ */
66
+ export function ensureMarketplace(bin, projectRoot) {
67
+ const installedDir = path.join(projectRoot, INSTALLED_DIR);
68
+ const known = localSettings(projectRoot).extraKnownMarketplaces?.[MARKETPLACE]?.source;
69
+ if (known?.source === "directory" && path.resolve(known.path) === path.resolve(installedDir)) return;
70
+ if (known) claude(bin, projectRoot, ["plugin", "marketplace", "remove", MARKETPLACE]);
71
+ must(
72
+ claude(bin, projectRoot, ["plugin", "marketplace", "add", installedDir, "--scope", "local"]),
73
+ "claude plugin marketplace add",
74
+ );
75
+ }
76
+
77
+ /**
78
+ * @param {string} bin
79
+ * @param {string} projectRoot
80
+ * @param {string} name plugin manifest name (see materialize.pluginName)
81
+ */
82
+ export function nativeInstall(bin, projectRoot, name) {
83
+ // Already installed: Claude reads .ai/installed/plugins/<id> in place, so new content needs no call.
84
+ if (isEnabled(projectRoot, name)) return;
85
+ ensureMarketplace(bin, projectRoot);
86
+ const id = `${name}@${MARKETPLACE}`;
87
+ must(claude(bin, projectRoot, ["plugin", "install", id, "--scope", "local"]), `claude plugin install ${id}`);
88
+ }
89
+
90
+ export function nativeUninstall(bin, projectRoot, name) {
91
+ const id = `${name}@${MARKETPLACE}`;
92
+ if (localSettings(projectRoot).enabledPlugins?.[id] === undefined) return;
93
+ claude(bin, projectRoot, ["plugin", "uninstall", id, "--scope", "local"]);
94
+ }
95
+
96
+ /** Unregister the agent-deck marketplace once no plugin is installed from it. Reads settings before calling Claude. */
97
+ export function releaseMarketplace(projectRoot) {
98
+ const settings = localSettings(projectRoot);
99
+ if (!settings.extraKnownMarketplaces?.[MARKETPLACE]) return false;
100
+ const stillEnabled = Object.keys(settings.enabledPlugins ?? {}).some((id) => id.endsWith(`@${MARKETPLACE}`));
101
+ if (stillEnabled) return false;
102
+ const bin = claudeBin();
103
+ if (!bin) return false;
104
+ claude(bin, projectRoot, ["plugin", "marketplace", "remove", MARKETPLACE]);
105
+ return true;
106
+ }
107
+
108
+ /** Plugin ids Claude reports as installed from the agent-deck marketplace. */
109
+ export function nativeInstalled(bin, projectRoot) {
110
+ const r = claude(bin, projectRoot, ["plugin", "list", "--json"]);
111
+ if (!r.ok) return null;
112
+ return [...new Set([...r.out.matchAll(/"([\w.-]+)@agent-deck"/g)].map((m) => m[1]))].sort();
113
+ }
@@ -0,0 +1,279 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { HOSTS, pluginAssetRel } from "../paths.mjs";
4
+ import { ownerOf } from "../state.mjs";
5
+
6
+ /**
7
+ * Copy mode: vendor a normalized plugin (`.ai/installed/plugins/<id>/`) into the
8
+ * project paths each host scans. Used when a host cannot load the plugin
9
+ * natively. Hooks are not activated in this mode; the result says so.
10
+ */
11
+
12
+ const NOT_ASSETS = new Set([
13
+ "skills",
14
+ "agents",
15
+ "commands",
16
+ "rules",
17
+ "hooks",
18
+ ".claude-plugin",
19
+ ".cursor-plugin",
20
+ "plugin.json",
21
+ "mcp.json",
22
+ ]);
23
+
24
+ /** Relative paths that can point at plugin files outside a skill directory. */
25
+ const RELATIVE_PATH = /(?:\.\.?\/)+(?:[\w.@+-]+\/)*[\w.@+-]+/g;
26
+
27
+ function isInside(parent, candidate) {
28
+ const rel = path.relative(parent, candidate);
29
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
30
+ }
31
+
32
+ function walkFiles(dir) {
33
+ const files = [];
34
+ if (!fs.existsSync(dir)) return files;
35
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
36
+ const abs = path.join(dir, entry.name);
37
+ if (entry.isDirectory()) files.push(...walkFiles(abs));
38
+ else files.push(abs);
39
+ }
40
+ return files;
41
+ }
42
+
43
+ function listDirs(dir) {
44
+ if (!fs.existsSync(dir)) return [];
45
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
46
+ }
47
+
48
+ function listFilesRel(dir) {
49
+ return walkFiles(dir).map((abs) => path.relative(dir, abs)).sort();
50
+ }
51
+
52
+ function readMcpFile(filePath) {
53
+ if (!fs.existsSync(filePath)) return { mcpServers: {} };
54
+ const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
55
+ if (raw.mcpServers) return raw;
56
+ return { mcpServers: raw };
57
+ }
58
+
59
+ function writeMcpFile(filePath, doc) {
60
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
61
+ fs.writeFileSync(filePath, `${JSON.stringify(doc, null, 2)}\n`, "utf8");
62
+ }
63
+
64
+ export function mcpNamespace(id, serverName) {
65
+ return `agent-deck__${id}__${serverName}`;
66
+ }
67
+
68
+ /** Replace `${CLAUDE_PLUGIN_ROOT}` / `${CURSOR_PLUGIN_ROOT}` / `${PLUGIN_ROOT}` in a string. */
69
+ function substituteRoot(text, value) {
70
+ return text.replace(/\$\{(?:CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT|PLUGIN_ROOT)\}/g, value);
71
+ }
72
+
73
+ function substituteDeep(value, root) {
74
+ if (typeof value === "string") return substituteRoot(value, root);
75
+ if (Array.isArray(value)) return value.map((item) => substituteDeep(item, root));
76
+ if (value && typeof value === "object") {
77
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, substituteDeep(v, root)]));
78
+ }
79
+ return value;
80
+ }
81
+
82
+ /**
83
+ * Point skill-relative links at the per-plugin asset directory so two plugins
84
+ * can both ship a CONVENTIONS.md without sharing one path, and replace plugin
85
+ * root variables with that directory.
86
+ */
87
+ function rewriteSkillFiles(pluginDir, skillName, destSkillDir, assetDir, projectRoot) {
88
+ const sourceSkillDir = path.join(pluginDir, "skills", skillName);
89
+ for (const file of walkFiles(destSkillDir)) {
90
+ if (!/\.(md|mdc|markdown|txt|sh|json|ya?ml)$/.test(file)) continue;
91
+ const relInSkill = path.relative(destSkillDir, file);
92
+ const sourceFile = path.join(sourceSkillDir, relInSkill);
93
+ let text = fs.readFileSync(file, "utf8");
94
+ const original = text;
95
+ if (file.endsWith(".md")) {
96
+ const replacements = [];
97
+ for (const token of new Set(text.match(RELATIVE_PATH) || [])) {
98
+ const resolved = path.resolve(path.dirname(sourceFile), token);
99
+ if (!isInside(pluginDir, resolved) || isInside(sourceSkillDir, resolved)) continue;
100
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) continue;
101
+ const vendored = path.join(assetDir, path.relative(pluginDir, resolved));
102
+ if (!fs.existsSync(vendored)) continue;
103
+ const rewritten = path.relative(path.dirname(file), vendored);
104
+ if (rewritten !== token) replacements.push([token, rewritten]);
105
+ }
106
+ replacements.sort((a, b) => b[0].length - a[0].length);
107
+ for (const [from, to] of replacements) text = text.split(from).join(to);
108
+ }
109
+ text = substituteRoot(text, path.relative(projectRoot, assetDir) || ".");
110
+ if (text !== original) fs.writeFileSync(file, text);
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Refuse to write over a path another plugin owns, or that agent-deck did not write.
116
+ * `previous` paths belong to this plugin already.
117
+ */
118
+ function claim(projectRoot, rel, id, state, previous, force) {
119
+ if (previous.has(rel)) return;
120
+ const owner = ownerOf(state, rel);
121
+ if (owner && owner !== id) {
122
+ throw new Error(`${id}: ${rel} is already installed by "${owner}". Give one of them another skill name, or remove "${owner}".`);
123
+ }
124
+ if (!owner && !force && fs.existsSync(path.join(projectRoot, rel))) {
125
+ throw new Error(`${id}: ${rel} already exists and was not written by agent-deck. Move it, or pass --force to replace it.`);
126
+ }
127
+ }
128
+
129
+ /**
130
+ * @param {string} projectRoot
131
+ * @param {string} id
132
+ * @param {string} pluginDir normalized plugin directory
133
+ * @param {{ hosts: Array<keyof typeof HOSTS>, state: import("../state.mjs").State, previous?: import("../state.mjs").StateEntry, force?: boolean }} options
134
+ * @returns {{ paths: string[], mcpKeys: Record<string, string[]>, warnings: string[] }}
135
+ */
136
+ export function copyInstall(projectRoot, id, pluginDir, options) {
137
+ const previous = new Set(options.previous?.paths ?? []);
138
+ const paths = [];
139
+ const mcpKeys = {};
140
+ const warnings = [];
141
+ const plan = [];
142
+
143
+ const skills = listDirs(path.join(pluginDir, "skills")).filter((name) =>
144
+ fs.existsSync(path.join(pluginDir, "skills", name, "SKILL.md")),
145
+ );
146
+ const agents = listFilesRel(path.join(pluginDir, "agents"));
147
+ const commands = listFilesRel(path.join(pluginDir, "commands"));
148
+ const rules = listFilesRel(path.join(pluginDir, "rules"));
149
+ const assets = fs.readdirSync(pluginDir).filter((name) => !NOT_ASSETS.has(name) && !name.startsWith("."));
150
+
151
+ for (const hostName of options.hosts) {
152
+ const host = HOSTS[hostName];
153
+ for (const skill of skills) plan.push(path.join(host.skills, skill));
154
+ for (const rel of agents) plan.push(path.join(host.agents, rel));
155
+ for (const rel of commands) plan.push(path.join(host.commands, id, rel));
156
+ if (host.rules) for (const rel of rules) plan.push(path.join(host.rules, id, rel));
157
+ if (!host.rules && rules.length > 0) {
158
+ warnings.push(`${hostName}: ${rules.length} rule file(s) skipped (no rules support)`);
159
+ }
160
+ }
161
+ for (const rel of plan) claim(projectRoot, rel, id, options.state, previous, options.force);
162
+
163
+ for (const hostName of options.hosts) {
164
+ const host = HOSTS[hostName];
165
+ const assetRel = pluginAssetRel(host, id);
166
+ const assetDir = path.join(projectRoot, assetRel);
167
+ fs.rmSync(assetDir, { recursive: true, force: true });
168
+ if (assets.length > 0) {
169
+ fs.mkdirSync(assetDir, { recursive: true });
170
+ for (const name of assets) {
171
+ fs.cpSync(path.join(pluginDir, name), path.join(assetDir, name), { recursive: true });
172
+ }
173
+ paths.push(assetRel);
174
+ }
175
+
176
+ for (const skill of skills) {
177
+ const rel = path.join(host.skills, skill);
178
+ const dest = path.join(projectRoot, rel);
179
+ fs.rmSync(dest, { recursive: true, force: true });
180
+ fs.mkdirSync(dest, { recursive: true });
181
+ fs.cpSync(path.join(pluginDir, "skills", skill), dest, { recursive: true });
182
+ rewriteSkillFiles(pluginDir, skill, dest, assetDir, projectRoot);
183
+ paths.push(rel);
184
+ }
185
+
186
+ const copyFiles = (kind, list, targetRoot) => {
187
+ for (const relFile of list) {
188
+ const rel = path.join(targetRoot, relFile);
189
+ const dest = path.join(projectRoot, rel);
190
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
191
+ fs.copyFileSync(path.join(pluginDir, kind, relFile), dest);
192
+ paths.push(rel);
193
+ }
194
+ };
195
+ copyFiles("agents", agents, host.agents);
196
+ copyFiles("commands", commands, path.join(host.commands, id));
197
+ if (host.rules) copyFiles("rules", rules, path.join(host.rules, id));
198
+
199
+ const mcpFile = path.join(pluginDir, "mcp.json");
200
+ if (fs.existsSync(mcpFile)) {
201
+ const servers = JSON.parse(fs.readFileSync(mcpFile, "utf8")).mcpServers ?? {};
202
+ const abs = path.join(projectRoot, host.mcp);
203
+ const doc = readMcpFile(abs);
204
+ const keys = [];
205
+ const root = `./${path.relative(projectRoot, assetDir)}`;
206
+ for (const [serverName, config] of Object.entries(servers)) {
207
+ const key = mcpNamespace(id, serverName);
208
+ doc.mcpServers[key] = substituteDeep(config, root);
209
+ keys.push(key);
210
+ }
211
+ writeMcpFile(abs, doc);
212
+ mcpKeys[host.mcp] = keys;
213
+ }
214
+
215
+ if (fs.existsSync(path.join(pluginDir, "hooks", "hooks.json"))) {
216
+ warnings.push(`${hostName}: hooks are not active in copy mode`);
217
+ }
218
+ }
219
+
220
+ paths.sort();
221
+ return { paths: [...new Set(paths)], mcpKeys, warnings };
222
+ }
223
+
224
+ /**
225
+ * The paths copy mode writes for a plugin, from its lock entry's components:
226
+ * what `copyInstall` would claim, plus its support-file folder whether or not
227
+ * the plugin has support files. Known without installing, so a plugin of a
228
+ * profile that is not active has its paths too.
229
+ * @param {string} id
230
+ * @param {{ skills?: string[], agents?: string[], commands?: string[], rules?: string[] }} components
231
+ * @param {Array<keyof typeof HOSTS>} hostNames hosts in copy mode
232
+ * @returns {string[]}
233
+ */
234
+ export function plannedCopyPaths(id, components, hostNames) {
235
+ const paths = [];
236
+ for (const hostName of hostNames) {
237
+ const host = HOSTS[hostName];
238
+ paths.push(pluginAssetRel(host, id));
239
+ for (const skill of components?.skills ?? []) paths.push(path.join(host.skills, skill));
240
+ for (const rel of components?.agents ?? []) paths.push(path.join(host.agents, rel));
241
+ for (const rel of components?.commands ?? []) paths.push(path.join(host.commands, id, rel));
242
+ if (host.rules) for (const rel of components?.rules ?? []) paths.push(path.join(host.rules, id, rel));
243
+ }
244
+ return paths;
245
+ }
246
+
247
+ /** Delete the files and MCP keys a state entry recorded. */
248
+ export function removeInstalledFiles(projectRoot, record) {
249
+ const removed = [];
250
+ for (const rel of record?.paths || []) {
251
+ const abs = path.join(projectRoot, rel);
252
+ if (fs.existsSync(abs)) {
253
+ fs.rmSync(abs, { recursive: true, force: true });
254
+ removed.push(rel);
255
+ pruneEmptyParents(projectRoot, path.dirname(abs));
256
+ }
257
+ }
258
+ for (const [mcpRel, keys] of Object.entries(record?.mcpKeys || {})) {
259
+ const abs = path.join(projectRoot, mcpRel);
260
+ if (!fs.existsSync(abs)) continue;
261
+ const doc = readMcpFile(abs);
262
+ for (const key of keys) delete doc.mcpServers[key];
263
+ if (Object.keys(doc.mcpServers).length === 0) fs.rmSync(abs, { force: true });
264
+ else writeMcpFile(abs, doc);
265
+ }
266
+ return { removed };
267
+ }
268
+
269
+ /** Remove now-empty per-plugin directories such as .cursor/rules/<id>/. */
270
+ function pruneEmptyParents(projectRoot, dir) {
271
+ let current = dir;
272
+ while (isInside(projectRoot, current) && current !== projectRoot) {
273
+ const base = path.basename(current);
274
+ if ([".claude", ".cursor", "skills", "agents", "commands", "rules", "plugins"].includes(base)) return;
275
+ if (!fs.existsSync(current) || fs.readdirSync(current).length > 0) return;
276
+ fs.rmdirSync(current);
277
+ current = path.dirname(current);
278
+ }
279
+ }
package/src/init.mjs ADDED
@@ -0,0 +1,65 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { copiesToIgnore, writeGitignoreBlock } from "./gitignore.mjs";
4
+ import { hostModes } from "./install.mjs";
5
+ import { PLUGINS_FILE } from "./paths.mjs";
6
+ import { emptyPlugins, readPlugins, writePlugins } from "./plugins.mjs";
7
+ import { readState } from "./state.mjs";
8
+
9
+ /**
10
+ * Wire agent-deck into a project. Safe to run again: each step only adds what is
11
+ * missing, and the result lists what changed.
12
+ *
13
+ * ai-plugin.json created when missing; --commit-copies sets "gitignoreCopies": false
14
+ * .gitignore created when missing; agent-deck's managed block written
15
+ * AGENTS.md created when missing (agent-deck install fills its Skills block)
16
+ * CLAUDE.md created when missing; imports @AGENTS.md so Claude reads what Cursor reads
17
+ */
18
+
19
+ export const AGENTS_IMPORT = "@AGENTS.md";
20
+
21
+ /**
22
+ * @param {string} projectRoot
23
+ * @param {{ commitCopies?: boolean }} [options]
24
+ * @returns {string[]} what was done, one line per change
25
+ */
26
+ export function initProject(projectRoot, options = {}) {
27
+ const done = [];
28
+
29
+ let doc = readPlugins(projectRoot);
30
+ if (!doc) {
31
+ doc = emptyPlugins();
32
+ done.push(`created ${PLUGINS_FILE}`);
33
+ }
34
+ if (options.commitCopies && doc.gitignoreCopies !== false) {
35
+ doc = { ...doc, gitignoreCopies: false };
36
+ done.push(`set "gitignoreCopies": false in ${PLUGINS_FILE} (copies in .claude/ and .cursor/ are committed)`);
37
+ }
38
+ if (done.length > 0) writePlugins(projectRoot, doc);
39
+
40
+ const state = readState(projectRoot);
41
+ const copies = copiesToIgnore(projectRoot, state, doc, hostModes(doc));
42
+ const ignore = writeGitignoreBlock(projectRoot, { copies, create: true });
43
+ if (ignore.created) done.push("created .gitignore with agent-deck's block");
44
+ else if (ignore.wrote) done.push("wrote agent-deck's block in .gitignore");
45
+
46
+ const agents = path.join(projectRoot, "AGENTS.md");
47
+ if (!fs.existsSync(agents)) {
48
+ fs.writeFileSync(agents, "# Agents\n");
49
+ done.push("created AGENTS.md");
50
+ }
51
+
52
+ const claude = path.join(projectRoot, "CLAUDE.md");
53
+ if (!fs.existsSync(claude)) {
54
+ fs.writeFileSync(claude, `${AGENTS_IMPORT}\n`);
55
+ done.push(`created CLAUDE.md (imports ${AGENTS_IMPORT})`);
56
+ } else {
57
+ const text = fs.readFileSync(claude, "utf8");
58
+ if (!text.split(/\r?\n/).includes(AGENTS_IMPORT)) {
59
+ const sep = text.length === 0 || text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
60
+ fs.writeFileSync(claude, `${text}${sep}${AGENTS_IMPORT}\n`);
61
+ done.push(`added ${AGENTS_IMPORT} to CLAUDE.md`);
62
+ }
63
+ }
64
+ return done;
65
+ }