@toolmesh/agent-deck 0.0.0-stage → 0.1.1

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,184 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { INSTALLED_DIR, pluginRel } from "./paths.mjs";
5
+
6
+ /**
7
+ * Write a located plugin to `.ai/installed/plugins/<id>/` in the layout both hosts read
8
+ * without help: skills/, agents/, commands/, rules/, hooks/hooks.json, mcp.json,
9
+ * the plugin's support files, and freshly generated manifests.
10
+ *
11
+ * Only the components the request selected are written. The tree is what
12
+ * `--plugin-dir`, Claude's local marketplace, and copy mode all read.
13
+ */
14
+
15
+ const COMPONENT_DIRS = new Set(["skills", "agents", "commands", "rules", "hooks"]);
16
+ const SKIP_TOP = new Set([
17
+ ".git",
18
+ ".github",
19
+ ".claude-plugin",
20
+ ".cursor-plugin",
21
+ "plugin.json",
22
+ "mcp.json",
23
+ ".mcp.json",
24
+ "marketplace.json",
25
+ ]);
26
+ const AGENT_PLUGINS_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json";
27
+
28
+ /** Plugin manifest name: Cursor wants lowercase kebab-case, Claude accepts it. */
29
+ export function pluginName(id) {
30
+ return id.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "plugin";
31
+ }
32
+
33
+ function copyFiltered(src, dest, skip = () => false) {
34
+ fs.cpSync(src, dest, {
35
+ recursive: true,
36
+ filter: (from) => {
37
+ const rel = path.relative(src, from);
38
+ if (rel === "") return true;
39
+ const first = rel.split(path.sep)[0];
40
+ return first !== ".git" && !skip(rel, from);
41
+ },
42
+ });
43
+ }
44
+
45
+ /**
46
+ * @param {string} projectRoot
47
+ * @param {string} id
48
+ * @param {import("./sources/locate.mjs").Located} located
49
+ * @param {{ fallbackVersion?: string }} [options] version for a plugin that declares none
50
+ */
51
+ export function materialize(projectRoot, id, located, { fallbackVersion } = {}) {
52
+ const rel = pluginRel(id);
53
+ const dest = path.join(projectRoot, rel);
54
+ fs.rmSync(dest, { recursive: true, force: true });
55
+ fs.mkdirSync(dest, { recursive: true });
56
+ const { dir, components, meta } = located;
57
+
58
+ // Support files keep their place so a skill's ../../CONVENTIONS.md still resolves.
59
+ const skillIsRoot = components.skills.some((s) => path.resolve(s.dir) === path.resolve(dir));
60
+ if (!skillIsRoot) {
61
+ for (const name of fs.readdirSync(dir)) {
62
+ if (SKIP_TOP.has(name) || COMPONENT_DIRS.has(name) || /^\.[\w-]+-plugin$/.test(name)) continue;
63
+ copyFiltered(path.join(dir, name), path.join(dest, name));
64
+ }
65
+ }
66
+
67
+ const snippets = [];
68
+ for (const skill of components.skills) {
69
+ const usage = path.join(skill.dir, "DEFAULT_USAGE.md");
70
+ if (fs.existsSync(usage)) {
71
+ const body = fs.readFileSync(usage, "utf8").trimEnd();
72
+ if (body) snippets.push({ skill: skill.name, body });
73
+ }
74
+ const skillDest = path.join(dest, "skills", skill.name);
75
+ copyFiltered(skill.dir, skillDest, (relPath) =>
76
+ relPath === "DEFAULT_USAGE.md" ||
77
+ // A root SKILL.md plugin: do not copy nested plugin metadata into the skill.
78
+ (skillIsRoot && SKIP_TOP.has(relPath.split(path.sep)[0])),
79
+ );
80
+ }
81
+
82
+ for (const kind of ["agents", "commands", "rules"]) {
83
+ for (const item of components[kind]) {
84
+ const target = path.join(dest, kind, item.rel);
85
+ fs.mkdirSync(path.dirname(target), { recursive: true });
86
+ fs.copyFileSync(item.file, target);
87
+ }
88
+ }
89
+
90
+ if (components.hooks) {
91
+ const target = path.join(dest, "hooks", "hooks.json");
92
+ fs.mkdirSync(path.dirname(target), { recursive: true });
93
+ if (components.hooks.file) {
94
+ fs.copyFileSync(components.hooks.file, target);
95
+ } else {
96
+ const inline = components.hooks.inline;
97
+ writeJson(target, inline.hooks ? inline : { hooks: inline });
98
+ }
99
+ }
100
+
101
+ if (components.mcpServers) {
102
+ writeJson(path.join(dest, "mcp.json"), { mcpServers: components.mcpServers });
103
+ }
104
+
105
+ const version = meta.version ? String(meta.version) : fallbackVersion;
106
+ const manifest = {
107
+ name: pluginName(id),
108
+ ...(version ? { version } : {}),
109
+ ...(meta.description ? { description: meta.description } : {}),
110
+ ...(meta.author && typeof meta.author === "object" ? { author: meta.author } : {}),
111
+ };
112
+ writeJson(path.join(dest, ".claude-plugin", "plugin.json"), manifest);
113
+ writeJson(path.join(dest, ".cursor-plugin", "plugin.json"), manifest);
114
+ writeJson(path.join(dest, "plugin.json"), {
115
+ $schema: AGENT_PLUGINS_SCHEMA,
116
+ name: manifest.name,
117
+ ...(manifest.version ? { version: manifest.version } : {}),
118
+ ...(manifest.description ? { description: manifest.description } : {}),
119
+ });
120
+
121
+ return {
122
+ rel,
123
+ dir: dest,
124
+ integrity: treeIntegrity(dest),
125
+ components: summarize(components),
126
+ agentsSnippets: snippets.sort((a, b) => a.skill.localeCompare(b.skill)),
127
+ pluginVersion: meta.version ?? null,
128
+ };
129
+ }
130
+
131
+ export function summarize(components) {
132
+ return {
133
+ skills: components.skills.map((s) => s.name),
134
+ agents: components.agents.map((a) => a.rel),
135
+ commands: components.commands.map((c) => c.rel),
136
+ rules: components.rules.map((r) => r.rel),
137
+ hooks: Boolean(components.hooks),
138
+ mcp: Object.keys(components.mcpServers ?? {}).sort(),
139
+ };
140
+ }
141
+
142
+ function writeJson(file, value) {
143
+ fs.mkdirSync(path.dirname(file), { recursive: true });
144
+ fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
145
+ }
146
+
147
+ /** sha256 over sorted relative paths, executable bits, and contents. */
148
+ export function treeIntegrity(dir) {
149
+ const files = [];
150
+ const walk = (abs) => {
151
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
152
+ const child = path.join(abs, entry.name);
153
+ if (entry.isDirectory()) walk(child);
154
+ else if (entry.isFile()) files.push(child);
155
+ }
156
+ };
157
+ walk(dir);
158
+ files.sort();
159
+ const hash = createHash("sha256");
160
+ for (const file of files) {
161
+ const rel = path.relative(dir, file).split(path.sep).join("/");
162
+ const exec = fs.statSync(file).mode & 0o111 ? "x" : "-";
163
+ hash.update(`${rel}\0${exec}\0`);
164
+ hash.update(fs.readFileSync(file));
165
+ hash.update("\0");
166
+ }
167
+ return `sha256-${hash.digest("hex")}`;
168
+ }
169
+
170
+ /** `.ai/installed/.claude-plugin/marketplace.json`: the local marketplace Claude installs from. */
171
+ export function writeMarketplace(projectRoot, ids) {
172
+ const file = path.join(projectRoot, INSTALLED_DIR, ".claude-plugin", "marketplace.json");
173
+ writeJson(file, {
174
+ name: "agent-deck",
175
+ owner: { name: "@toolmesh/agent-deck" },
176
+ description: "Plugins installed by @toolmesh/agent-deck for this project",
177
+ plugins: [...ids].sort().map((id) => ({ name: pluginName(id), source: `./plugins/${id}` })),
178
+ });
179
+ return file;
180
+ }
181
+
182
+ export function removeMaterialized(projectRoot, id) {
183
+ fs.rmSync(path.join(projectRoot, pluginRel(id)), { recursive: true, force: true });
184
+ }
@@ -0,0 +1,91 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { loadProject } from "./project.mjs";
3
+ import { descriptorFor } from "./sources/spec.mjs";
4
+
5
+ /**
6
+ * Compare each lock pin with what its request points to now, like npm outdated.
7
+ * current what the lock pins
8
+ * wanted what `agent-deck update <id>` would pin (the ref or range, resolved today)
9
+ * latest the newest release: highest semver tag (git) or `latest` (npm)
10
+ *
11
+ * @typedef {{ id: string, type: string, current: string, wanted: string | null, latest: string | null, note?: string }} Row
12
+ * @returns {Row[]}
13
+ */
14
+ export function outdated(projectRoot) {
15
+ const { lock } = loadProject(projectRoot);
16
+ return lock.plugins.map((entry) => {
17
+ const { request, resolved } = entry;
18
+ try {
19
+ if (resolved.type === "git") return gitRow(entry, descriptorFor(request));
20
+ if (resolved.type === "npm") return npmRow(entry, descriptorFor(request));
21
+ if (resolved.type === "path") {
22
+ return { id: entry.id, type: "path", current: resolved.path, wanted: null, latest: null, note: "content is in the repo" };
23
+ }
24
+ return { id: entry.id, type: resolved.type, current: short(resolved.sha256 ?? resolved.sha), wanted: null, latest: null, note: "pinned by digest" };
25
+ } catch (err) {
26
+ return { id: entry.id, type: resolved.type, current: "?", wanted: null, latest: null, note: err.message.split("\n")[0] };
27
+ }
28
+ });
29
+ }
30
+
31
+ export function isOutdated(row) {
32
+ if (row.wanted && row.wanted !== row.current) return true;
33
+ return Boolean(row.latest && row.latest !== row.current);
34
+ }
35
+
36
+ function short(value) {
37
+ return value ? String(value).slice(0, 12) : "?";
38
+ }
39
+
40
+ function run(cmd, args) {
41
+ const r = spawnSync(cmd, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
42
+ if (r.status !== 0) throw new Error((r.stderr || `${cmd} failed`).trim());
43
+ return r.stdout;
44
+ }
45
+
46
+ const SEMVER_TAG = /^v?(\d+)\.(\d+)\.(\d+)$/;
47
+
48
+ function compareSemver(a, b) {
49
+ const pa = a.match(SEMVER_TAG).slice(1).map(Number);
50
+ const pb = b.match(SEMVER_TAG).slice(1).map(Number);
51
+ for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] - pb[i];
52
+ return 0;
53
+ }
54
+
55
+ function gitRow(entry, descriptor) {
56
+ const ref = entry.request.ref;
57
+ const row = { id: entry.id, type: "git", current: short(entry.resolved.sha), wanted: null, latest: null };
58
+ if (ref && /^[0-9a-f]{40}$/.test(ref)) return { ...row, note: "pinned to a commit" };
59
+
60
+ const lines = run("git", ["ls-remote", "--heads", "--tags", descriptor.url]).trim().split("\n").filter(Boolean);
61
+ const refs = new Map(lines.map((line) => line.split("\t").reverse()));
62
+ if (!ref) {
63
+ const head = run("git", ["ls-remote", descriptor.url, "HEAD"]).trim().split("\t")[0];
64
+ row.wanted = short(head);
65
+ } else {
66
+ const sha = refs.get(`refs/tags/${ref}^{}`) ?? refs.get(`refs/tags/${ref}`) ?? refs.get(`refs/heads/${ref}`);
67
+ row.wanted = sha ? short(sha) : null;
68
+ if (!sha) row.note = `ref "${ref}" no longer exists`;
69
+ }
70
+
71
+ const tags = [...refs.keys()]
72
+ .filter((name) => name.startsWith("refs/tags/") && !name.endsWith("^{}"))
73
+ .map((name) => name.slice("refs/tags/".length))
74
+ .filter((tag) => SEMVER_TAG.test(tag))
75
+ .sort(compareSemver);
76
+ const newest = tags.at(-1);
77
+ // A newer release only means something when the request follows a release tag.
78
+ if (newest && ref && SEMVER_TAG.test(ref) && compareSemver(newest, ref) > 0) {
79
+ row.latest = newest;
80
+ }
81
+ if (entry.nested) row.note = [row.note, "plugin pinned by its marketplace"].filter(Boolean).join("; ");
82
+ return row;
83
+ }
84
+
85
+ function npmRow(entry, descriptor) {
86
+ const spec = descriptor.version ? `${descriptor.package}@${descriptor.version}` : descriptor.package;
87
+ const wantedRaw = JSON.parse(run("npm", ["view", spec, "version", "--json"]) || "null");
88
+ const wanted = Array.isArray(wantedRaw) ? wantedRaw.at(-1) : wantedRaw;
89
+ const latest = JSON.parse(run("npm", ["view", descriptor.package, "version", "--json"]) || "null");
90
+ return { id: entry.id, type: "npm", current: entry.resolved.version, wanted: wanted ?? null, latest: latest ?? null };
91
+ }
package/src/paths.mjs ADDED
@@ -0,0 +1,63 @@
1
+ /** Shared paths for @toolmesh/agent-deck. */
2
+
3
+ export const PLUGINS_FILE = "ai-plugin.json";
4
+ export const LOCAL_PLUGINS_FILE = "ai-plugin.local.json";
5
+ export const LOCK_FILE = "ai-plugin.lock.json";
6
+
7
+ /** Everything AI-tooling in a project lives under .ai/. */
8
+ export const AI_DIR = ".ai";
9
+ /** Like node_modules: one normalized plugin per id, and what agent-deck wrote here. Never committed. */
10
+ export const INSTALLED_DIR = `${AI_DIR}/installed`;
11
+ export const STATE_FILE = `${INSTALLED_DIR}/state.json`;
12
+ /** .ai/current → profiles/<name>: the active profile. */
13
+ export const CURRENT_LINK_PATH = `${AI_DIR}/current`;
14
+ /** The active profile's prompt, as a Cursor rule. */
15
+ export const CURSOR_RULE_PATH = ".cursor/rules/agent-deck-profile.mdc";
16
+
17
+ /** Where copy mode writes plugin components for each host. */
18
+ export const HOSTS = {
19
+ claude: {
20
+ skills: ".claude/skills",
21
+ agents: ".claude/agents",
22
+ commands: ".claude/commands",
23
+ rules: null,
24
+ mcp: ".mcp.json",
25
+ plugins: ".claude/plugins",
26
+ rootVar: "CLAUDE_PLUGIN_ROOT",
27
+ },
28
+ cursor: {
29
+ skills: ".cursor/skills",
30
+ agents: ".cursor/agents",
31
+ commands: ".cursor/commands",
32
+ rules: ".cursor/rules",
33
+ mcp: ".cursor/mcp.json",
34
+ plugins: ".cursor/plugins",
35
+ rootVar: "CURSOR_PLUGIN_ROOT",
36
+ },
37
+ };
38
+
39
+ export function pluginsPath(projectRoot) {
40
+ return `${projectRoot}/${PLUGINS_FILE}`;
41
+ }
42
+
43
+ export function localPluginsPath(projectRoot) {
44
+ return `${projectRoot}/${LOCAL_PLUGINS_FILE}`;
45
+ }
46
+
47
+ export function lockPath(projectRoot) {
48
+ return `${projectRoot}/${LOCK_FILE}`;
49
+ }
50
+
51
+ export function pluginRel(id) {
52
+ return `${INSTALLED_DIR}/plugins/${id}`;
53
+ }
54
+
55
+ /** Filesystem-safe fragment of a marketplace id or entry id. */
56
+ export function safeSegment(value) {
57
+ return value.replace(/[^a-zA-Z0-9._@+-]+/g, "__");
58
+ }
59
+
60
+ /** Per-plugin support files (conventions, scripts, templates) for one host. */
61
+ export function pluginAssetRel(host, id) {
62
+ return `${host.plugins}/${safeSegment(id)}`;
63
+ }
@@ -0,0 +1,158 @@
1
+ import fs from "node:fs";
2
+ import { LOCAL_PLUGINS_FILE, PLUGINS_FILE, localPluginsPath, pluginsPath } from "./paths.mjs";
3
+ import { normalizeRequest } from "./sources/spec.mjs";
4
+
5
+ /**
6
+ * ai-plugin.json — what to install. Same role as package.json dependencies.
7
+ * { "plugins": [Request, …], "hosts": { "claude": "native", "cursor": "copy" }, "agentsMd": true }
8
+ *
9
+ * @typedef {import("./sources/spec.mjs").Request} Request
10
+ * @typedef {"copy" | "native" | "off"} HostMode
11
+ * @typedef {{ plugins: Request[], hosts?: { claude?: HostMode, cursor?: HostMode }, agentsMd?: boolean, gitignoreCopies?: boolean }} PluginsFile
12
+ */
13
+
14
+ const HOST_MODES = new Set(["copy", "native", "off"]);
15
+
16
+ export function emptyPlugins() {
17
+ return { plugins: [] };
18
+ }
19
+
20
+ function normalizeHosts(hosts) {
21
+ if (hosts == null) return undefined;
22
+ if (typeof hosts !== "object") throw new Error(`${PLUGINS_FILE} hosts must be an object`);
23
+ const out = {};
24
+ for (const [name, mode] of Object.entries(hosts)) {
25
+ if (!["claude", "cursor"].includes(name)) throw new Error(`${PLUGINS_FILE} hosts.${name}: unknown host`);
26
+ if (!HOST_MODES.has(mode)) {
27
+ throw new Error(`${PLUGINS_FILE} hosts.${name} must be one of ${[...HOST_MODES].join(", ")}`);
28
+ }
29
+ out[name] = mode;
30
+ }
31
+ return out;
32
+ }
33
+
34
+ function normalizeList(list, file) {
35
+ if (!Array.isArray(list)) throw new Error(`Invalid ${file}`);
36
+ const seen = new Set();
37
+ return list.map((raw, index) => {
38
+ const request = normalizeRequest(raw, `${file} plugins[${index}]`);
39
+ if (seen.has(request.id)) throw new Error(`${file}: duplicate id "${request.id}"`);
40
+ seen.add(request.id);
41
+ return request;
42
+ });
43
+ }
44
+
45
+ export function normalizePlugins(raw) {
46
+ if (!raw || typeof raw !== "object") throw new Error(`Invalid ${PLUGINS_FILE}`);
47
+ const hosts = normalizeHosts(raw.hosts);
48
+ for (const key of ["agentsMd", "gitignoreCopies"]) {
49
+ if (raw[key] != null && typeof raw[key] !== "boolean") {
50
+ throw new Error(`${PLUGINS_FILE} ${key} must be true or false`);
51
+ }
52
+ }
53
+ return {
54
+ plugins: normalizeList(raw.plugins, PLUGINS_FILE).map(({ from, ...request }) => request),
55
+ ...(hosts ? { hosts } : {}),
56
+ ...(raw.agentsMd === false ? { agentsMd: false } : {}),
57
+ ...(raw.gitignoreCopies === false ? { gitignoreCopies: false } : {}),
58
+ };
59
+ }
60
+
61
+ export function readPlugins(projectRoot) {
62
+ const file = pluginsPath(projectRoot);
63
+ if (!fs.existsSync(file)) return null;
64
+ return normalizePlugins(JSON.parse(fs.readFileSync(file, "utf8")));
65
+ }
66
+
67
+ export function writePlugins(projectRoot, doc) {
68
+ const normalized = normalizePlugins(doc);
69
+ normalized.plugins.sort((a, b) => a.id.localeCompare(b.id));
70
+ fs.writeFileSync(pluginsPath(projectRoot), `${JSON.stringify(normalized, null, 2)}\n`, "utf8");
71
+ return normalized;
72
+ }
73
+
74
+ export function ensurePlugins(projectRoot) {
75
+ return readPlugins(projectRoot) ?? writePlugins(projectRoot, emptyPlugins());
76
+ }
77
+
78
+ export function addPlugin(doc, request) {
79
+ return { ...doc, plugins: [...doc.plugins.filter((p) => p.id !== request.id), request] };
80
+ }
81
+
82
+ export function removePlugin(doc, id) {
83
+ const plugins = doc.plugins.filter((plugin) => plugin.id !== id);
84
+ if (plugins.length === doc.plugins.length) throw new Error(`No plugin with id "${id}" in ${PLUGINS_FILE}`);
85
+ return { ...doc, plugins };
86
+ }
87
+
88
+ /**
89
+ * Parse `<checkout>[@<plugin>]`. The checkout may be relative; `@` in the path
90
+ * is kept because the split is the last `@` after the last `/`.
91
+ */
92
+ export function parseLinkSpec(spec) {
93
+ const slash = Math.max(spec.lastIndexOf("/"), spec.lastIndexOf("\\"));
94
+ const at = spec.lastIndexOf("@");
95
+ if (at > slash && at > 0) {
96
+ const name = spec.slice(at + 1);
97
+ if (!name) throw new Error(`Invalid link "${spec}". Expected <checkout>[@<plugin-name>]`);
98
+ return { checkout: spec.slice(0, at), name };
99
+ }
100
+ return { checkout: spec, name: undefined };
101
+ }
102
+
103
+ // --- ai-plugin.local.json: gitignored links to working trees ---------------
104
+
105
+ export function emptyLocalPlugins() {
106
+ return { plugins: [] };
107
+ }
108
+
109
+ export function normalizeLocalPlugins(raw) {
110
+ if (!raw || typeof raw !== "object") throw new Error(`Invalid ${LOCAL_PLUGINS_FILE}`);
111
+ return { plugins: normalizeList(raw.plugins, LOCAL_PLUGINS_FILE) };
112
+ }
113
+
114
+ export function readLocalPlugins(projectRoot) {
115
+ const file = localPluginsPath(projectRoot);
116
+ if (!fs.existsSync(file)) return null;
117
+ return normalizeLocalPlugins(JSON.parse(fs.readFileSync(file, "utf8")));
118
+ }
119
+
120
+ export function deleteLocalPlugins(projectRoot) {
121
+ fs.rmSync(localPluginsPath(projectRoot), { force: true });
122
+ }
123
+
124
+ export function writeLocalPlugins(projectRoot, doc) {
125
+ const normalized = normalizeLocalPlugins(doc);
126
+ normalized.plugins.sort((a, b) => a.id.localeCompare(b.id));
127
+ fs.writeFileSync(localPluginsPath(projectRoot), `${JSON.stringify(normalized, null, 2)}\n`, "utf8");
128
+ return normalized;
129
+ }
130
+
131
+ export function addLocalPlugin(doc, request) {
132
+ return { plugins: [...doc.plugins.filter((p) => p.id !== request.id), request] };
133
+ }
134
+
135
+ export function removeLocalPlugin(doc, id) {
136
+ const plugins = doc.plugins.filter((plugin) => plugin.id !== id);
137
+ if (plugins.length === doc.plugins.length) throw new Error(`No linked plugin "${id}"`);
138
+ return { plugins };
139
+ }
140
+
141
+ /** Local links replace a committed request with the same id. */
142
+ export function mergePluginRequests(committed, local) {
143
+ const map = new Map();
144
+ for (const plugin of committed?.plugins ?? []) map.set(plugin.id, plugin);
145
+ for (const plugin of local?.plugins ?? []) map.set(plugin.id, { ...plugin, linked: true });
146
+ return {
147
+ ...(committed?.hosts ? { hosts: committed.hosts } : {}),
148
+ plugins: [...map.values()].sort((a, b) => a.id.localeCompare(b.id)),
149
+ };
150
+ }
151
+
152
+ /** Committed request plus local links. Null when neither file exists. */
153
+ export function readRequestedPlugins(projectRoot) {
154
+ const committed = readPlugins(projectRoot);
155
+ const local = readLocalPlugins(projectRoot);
156
+ if (!committed && !local) return null;
157
+ return mergePluginRequests(committed ?? emptyPlugins(), local ?? emptyLocalPlugins());
158
+ }
@@ -0,0 +1,80 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { CURSOR_RULE_PATH, PLUGINS_FILE } from "./paths.mjs";
4
+ import { CURRENT_LINK, PROFILES_DIR, isValidProfileName, profileDir } from "./project.mjs";
5
+
6
+ /**
7
+ * The prompt side of a profile. The plugins are agent-deck's usual install; the
8
+ * prompt is wired once and follows the .ai/current link:
9
+ * Claude Code CLAUDE.md imports @.ai/current/prompt.md
10
+ * Cursor .cursor/rules/agent-deck-profile.mdc (alwaysApply) holds a copy of prompt.md
11
+ * Both are local files, listed in agent-deck's .gitignore block.
12
+ */
13
+
14
+ export const IMPORT_LINE = `@${CURRENT_LINK}/prompt.md`;
15
+ export const CURSOR_RULE = CURSOR_RULE_PATH;
16
+
17
+ export function createProfile(projectRoot, name) {
18
+ if (!isValidProfileName(name)) {
19
+ throw new Error(`Invalid profile name "${name}": use letters, digits, ".", "_" or "-" (not "current")`);
20
+ }
21
+ const dir = profileDir(projectRoot, name);
22
+ if (fs.existsSync(dir)) throw new Error(`${PROFILES_DIR}/${name} already exists`);
23
+ fs.mkdirSync(dir, { recursive: true });
24
+ fs.writeFileSync(path.join(dir, "prompt.md"), `# ${name}\n\nYou are the ${name} agent of this project.\n`);
25
+ fs.writeFileSync(path.join(dir, PLUGINS_FILE), `${JSON.stringify({ plugins: [] }, null, 2)}\n`);
26
+ return dir;
27
+ }
28
+
29
+ /** Point .ai/current at a profile and wire its prompt for both hosts. */
30
+ export function useProfile(projectRoot, name) {
31
+ const link = path.join(projectRoot, CURRENT_LINK);
32
+ fs.rmSync(link, { force: true });
33
+ fs.mkdirSync(path.dirname(link), { recursive: true });
34
+ fs.symlinkSync(path.relative(path.dirname(link), profileDir(projectRoot, name)), link);
35
+ ensureClaudeImport(projectRoot);
36
+ writeCursorRule(projectRoot, name);
37
+ }
38
+
39
+ /** Drop the active profile's link, its Cursor rule, and the CLAUDE.md import. */
40
+ export function clearProfile(projectRoot) {
41
+ fs.rmSync(path.join(projectRoot, CURRENT_LINK), { force: true });
42
+ fs.rmSync(path.join(projectRoot, CURSOR_RULE), { force: true });
43
+ dropClaudeImport(projectRoot);
44
+ }
45
+
46
+ function ensureClaudeImport(projectRoot) {
47
+ const file = path.join(projectRoot, "CLAUDE.md");
48
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
49
+ if (text.split(/\r?\n/).includes(IMPORT_LINE)) return;
50
+ const sep = text.length === 0 ? "" : text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
51
+ fs.writeFileSync(file, `${text}${sep}${IMPORT_LINE}\n`);
52
+ }
53
+
54
+ function dropClaudeImport(projectRoot) {
55
+ const file = path.join(projectRoot, "CLAUDE.md");
56
+ if (!fs.existsSync(file)) return;
57
+ const text = fs.readFileSync(file, "utf8");
58
+ const next = text
59
+ .split("\n")
60
+ .filter((line) => line !== IMPORT_LINE)
61
+ .join("\n")
62
+ .replace(/\n+$/, "\n");
63
+ if (next.trim() === "") fs.rmSync(file);
64
+ else if (next !== text) fs.writeFileSync(file, next.endsWith("\n") ? next : `${next}\n`);
65
+ }
66
+
67
+ function writeCursorRule(projectRoot, name) {
68
+ const prompt = path.join(profileDir(projectRoot, name), "prompt.md");
69
+ const rule = path.join(projectRoot, CURSOR_RULE);
70
+ if (!fs.existsSync(prompt)) {
71
+ fs.rmSync(rule, { force: true });
72
+ return;
73
+ }
74
+ fs.mkdirSync(path.dirname(rule), { recursive: true });
75
+ const body = fs.readFileSync(prompt, "utf8");
76
+ fs.writeFileSync(
77
+ rule,
78
+ `---\ndescription: Active agent profile (${name}), written by agent-deck profile use\nalwaysApply: true\n---\n\n${body}`,
79
+ );
80
+ }
@@ -0,0 +1,110 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { emptyLockfile, readLockfile, writeLockfile } from "./lockfile.mjs";
4
+ import { AI_DIR, CURRENT_LINK_PATH, PLUGINS_FILE } from "./paths.mjs";
5
+ import { emptyPlugins, mergePluginRequests, readLocalPlugins, readPlugins } from "./plugins.mjs";
6
+
7
+ /**
8
+ * A project's plugin set: the base (root ai-plugin.json and lock, committed),
9
+ * plus the active profile (.ai/profiles/<name>/ai-plugin.json and lock), plus local links.
10
+ * Every command works on this merged view; locks are split back on save.
11
+ */
12
+
13
+ export const PROFILES_DIR = `${AI_DIR}/profiles`;
14
+ export const CURRENT_LINK = CURRENT_LINK_PATH;
15
+
16
+ export function profileDir(projectRoot, name) {
17
+ return path.join(projectRoot, PROFILES_DIR, name);
18
+ }
19
+
20
+ export function isValidProfileName(name) {
21
+ return typeof name === "string" && /^[A-Za-z0-9._-]+$/.test(name) && name !== "current" && !name.startsWith(".");
22
+ }
23
+
24
+ /** The active profile, from the .ai/current link, or null. */
25
+ export function activeProfile(projectRoot) {
26
+ const link = path.join(projectRoot, CURRENT_LINK);
27
+ try {
28
+ if (!fs.lstatSync(link).isSymbolicLink()) return null;
29
+ } catch {
30
+ return null;
31
+ }
32
+ const name = path.basename(fs.readlinkSync(link));
33
+ return fs.existsSync(path.join(profileDir(projectRoot, name), PLUGINS_FILE)) ? name : null;
34
+ }
35
+
36
+ /** Profile names: folders of .ai/profiles/ that hold an ai-plugin.json. */
37
+ export function listProfiles(projectRoot) {
38
+ const dir = path.join(projectRoot, PROFILES_DIR);
39
+ if (!fs.existsSync(dir)) return [];
40
+ return fs
41
+ .readdirSync(dir, { withFileTypes: true })
42
+ .filter((d) => d.isDirectory() && isValidProfileName(d.name))
43
+ .filter((d) => fs.existsSync(path.join(dir, d.name, PLUGINS_FILE)))
44
+ .map((d) => d.name)
45
+ .sort();
46
+ }
47
+
48
+ /**
49
+ * @param {string} projectRoot
50
+ * @param {{ profile?: string | null }} [options] profile to merge; default: the active one
51
+ */
52
+ export function loadProject(projectRoot, options = {}) {
53
+ const profile = options.profile === undefined ? activeProfile(projectRoot) : options.profile;
54
+ const base = readPlugins(projectRoot);
55
+ const baseLock = readLockfile(projectRoot);
56
+ const profileRoot = profile ? profileDir(projectRoot, profile) : null;
57
+ if (profileRoot && !fs.existsSync(path.join(profileRoot, PLUGINS_FILE))) {
58
+ throw new Error(`No profile "${profile}" (${path.relative(projectRoot, profileRoot)}/${PLUGINS_FILE})`);
59
+ }
60
+ const prof = profileRoot ? readPlugins(profileRoot) : null;
61
+ const profLock = profileRoot ? readLockfile(profileRoot) : null;
62
+
63
+ /** Where each committed request lives: "base" or the profile name. */
64
+ const owner = new Map();
65
+ for (const p of base?.plugins ?? []) owner.set(p.id, "base");
66
+ for (const p of prof?.plugins ?? []) {
67
+ if (owner.has(p.id)) {
68
+ throw new Error(`"${p.id}" is requested by both ${PLUGINS_FILE} and profile "${profile}". Keep one.`);
69
+ }
70
+ owner.set(p.id, profile);
71
+ }
72
+
73
+ const committed = {
74
+ ...(base?.hosts ? { hosts: base.hosts } : {}),
75
+ plugins: [...(base?.plugins ?? []), ...(prof?.plugins ?? [])],
76
+ };
77
+ const doc = mergePluginRequests(committed, readLocalPlugins(projectRoot));
78
+
79
+ const lock = emptyLockfile();
80
+ lock.writeAgentsMd = base?.agentsMd !== false;
81
+ lock.plugins = [...(baseLock?.plugins ?? []), ...(profLock?.plugins ?? [])].filter(
82
+ (entry, i, all) => all.findIndex((e) => e.id === entry.id) === i,
83
+ );
84
+
85
+ /** Split a merged lock back into the base lock and the profile lock. */
86
+ const saveLock = (merged) => {
87
+ const pick = (where) => ({
88
+ lockfileVersion: merged.lockfileVersion,
89
+ writeAgentsMd: lock.writeAgentsMd,
90
+ plugins: merged.plugins.filter((e) => owner.get(e.id) === where),
91
+ });
92
+ if (base || merged.plugins.some((e) => owner.get(e.id) === "base") || baseLock) {
93
+ writeLockfile(projectRoot, pick("base"));
94
+ }
95
+ if (profileRoot) writeLockfile(profileRoot, pick(profile));
96
+ };
97
+
98
+ return {
99
+ root: projectRoot,
100
+ profile,
101
+ profileRoot,
102
+ base: base ?? emptyPlugins(),
103
+ prof,
104
+ doc,
105
+ lock,
106
+ owner,
107
+ saveLock,
108
+ exists: Boolean(base || prof || doc.plugins.length > 0),
109
+ };
110
+ }