@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,254 @@
1
+ /**
2
+ * Request model shared by ai-plugin.json, ai-plugin.local.json and the lock.
3
+ *
4
+ * A request says what to install, not what was installed:
5
+ * { id, source, plugin?, skills?, path?, ref?, version?, sha256? }
6
+ *
7
+ * `source` is a prefixed string:
8
+ * github:owner/repo a GitHub repository
9
+ * git:<url> any git repository (https, ssh, file)
10
+ * npm:<package> an npm package (`version` picks the version or range)
11
+ * archive:<https url> a .zip or .tar.gz download (`sha256` pins the bytes)
12
+ * path:<relative> a directory inside the project (agent-deck add ./path)
13
+ * local:<abs path> a working tree on this machine (agent-deck link only)
14
+ *
15
+ * @typedef {{ id: string, source: string, plugin?: string, skills?: string[], path?: string, ref?: string, version?: string, sha256?: string, from?: string }} Request
16
+ * @typedef {{ type: "git", url: string, ref?: string, sha?: string, repo?: string }
17
+ * | { type: "npm", package: string, version?: string, registry?: string }
18
+ * | { type: "archive", url: string, sha256?: string }
19
+ * | { type: "path", path: string }
20
+ * | { type: "local", path: string }} Descriptor
21
+ */
22
+
23
+ const ID = /^[a-z0-9][a-z0-9._-]*$/i;
24
+ const GITHUB_REPO = /^[\w.-]+\/[\w.-]+$/;
25
+ const OPTIONAL_KEYS = ["plugin", "path", "ref", "version", "sha256", "from"];
26
+
27
+ export function isValidId(id) {
28
+ return typeof id === "string" && ID.test(id) && !id.includes("..");
29
+ }
30
+
31
+ /** Validate one request object and drop unknown or empty fields. */
32
+ export function normalizeRequest(raw, where = "request") {
33
+ if (!raw || typeof raw !== "object") {
34
+ throw new Error(`${where} is not an object`);
35
+ }
36
+ if (!isValidId(raw.id)) {
37
+ throw new Error(`${where} needs an id made of letters, digits, ".", "_" or "-" (got "${raw.id}")`);
38
+ }
39
+ if (typeof raw.source !== "string" || !raw.source.includes(":")) {
40
+ throw new Error(`${where} (${raw.id}) needs a source such as github:owner/repo`);
41
+ }
42
+ const descriptor = descriptorFor({ source: raw.source }, where);
43
+ const source = descriptor.type === "path" ? `path:${descriptor.path}` : raw.source;
44
+ const out = { id: raw.id, source };
45
+ for (const key of OPTIONAL_KEYS) {
46
+ if (raw[key] == null || raw[key] === "") continue;
47
+ if (typeof raw[key] !== "string") {
48
+ throw new Error(`${where} (${raw.id}).${key} must be a string`);
49
+ }
50
+ out[key] = raw[key];
51
+ }
52
+ if (raw.skills != null) {
53
+ if (!Array.isArray(raw.skills) || raw.skills.some((s) => typeof s !== "string" || !s)) {
54
+ throw new Error(`${where} (${raw.id}).skills must be a list of skill names`);
55
+ }
56
+ if (raw.skills.length > 0) out.skills = [...new Set(raw.skills)].sort();
57
+ }
58
+ if (out.path && (out.path.startsWith("/") || out.path.split("/").includes(".."))) {
59
+ throw new Error(`${where} (${raw.id}).path must stay inside the source`);
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /**
65
+ * Where to fetch a request's bytes from. `ref` and `sha` come from the request
66
+ * or, for a reproducible install, from the lock.
67
+ * @param {Pick<Request, "source" | "ref" | "version" | "sha256">} request
68
+ * @returns {Descriptor}
69
+ */
70
+ export function descriptorFor(request, where = "request") {
71
+ const at = request.source.indexOf(":");
72
+ const kind = request.source.slice(0, at);
73
+ const value = request.source.slice(at + 1);
74
+ if (!value) throw new Error(`${where}: empty source "${request.source}"`);
75
+ switch (kind) {
76
+ case "github":
77
+ if (!GITHUB_REPO.test(value)) {
78
+ throw new Error(`${where}: github source must be owner/repo (got "${value}")`);
79
+ }
80
+ return {
81
+ type: "git",
82
+ url: `https://github.com/${value}.git`,
83
+ repo: value,
84
+ ...(request.ref ? { ref: request.ref } : {}),
85
+ };
86
+ case "git":
87
+ return { type: "git", url: value, ...(request.ref ? { ref: request.ref } : {}) };
88
+ case "npm":
89
+ return { type: "npm", package: value, ...(request.version ? { version: request.version } : {}) };
90
+ case "archive":
91
+ if (!value.startsWith("https://")) {
92
+ throw new Error(`${where}: archive source must be an https URL`);
93
+ }
94
+ return { type: "archive", url: value, ...(request.sha256 ? { sha256: request.sha256 } : {}) };
95
+ case "path":
96
+ return { type: "path", path: projectRelative(value, where) };
97
+ case "local":
98
+ return { type: "local", path: value };
99
+ default:
100
+ throw new Error(`${where}: unknown source kind "${kind}" in "${request.source}"`);
101
+ }
102
+ }
103
+
104
+ /** Default id: the plugin name, else the last path or repository segment. */
105
+ export function defaultId({ source, plugin, path }) {
106
+ const raw =
107
+ plugin ||
108
+ (path ? path.split("/").filter(Boolean).pop() : null) ||
109
+ source
110
+ .slice(source.indexOf(":") + 1)
111
+ .replace(/[#?].*$/, "")
112
+ .replace(/\.git$/, "")
113
+ .replace(/\.(zip|tgz|tar\.gz)$/, "")
114
+ .replace(/@[^/]*$/, "")
115
+ .split(/[/:]/)
116
+ .filter(Boolean)
117
+ .pop();
118
+ return (raw || "plugin").replace(/^@/, "").replace(/[^a-zA-Z0-9._-]+/g, "-");
119
+ }
120
+
121
+ /**
122
+ * Parse what a user types after `agent-deck add` into a request.
123
+ *
124
+ * owner/repo@plugin plugin from a GitHub marketplace
125
+ * owner/repo single plugin, or a skills repository
126
+ * https://github.com/o/r same as o/r
127
+ * git+<url>[#ref] any git host
128
+ * git@host:o/r.git[#ref] ssh git URL
129
+ * npm:<package>[@version] npm package
130
+ * https://….zip | .tar.gz archive
131
+ * ./<path>[@plugin] a directory inside the project
132
+ *
133
+ * Flags: { ref, skills, path, id, sha256 } override what the spec says.
134
+ * @returns {Request}
135
+ */
136
+ export function parseAddSpec(spec, flags = {}) {
137
+ if (!spec) throw new Error("add requires a source (owner/repo@plugin, ./path, git+URL, npm:pkg, https://….zip)");
138
+ let request;
139
+
140
+ if (spec.startsWith("npm:")) {
141
+ const body = spec.slice(4);
142
+ const at = body.lastIndexOf("@");
143
+ const hasVersion = at > 0;
144
+ request = {
145
+ source: `npm:${hasVersion ? body.slice(0, at) : body}`,
146
+ ...(hasVersion ? { version: body.slice(at + 1) } : {}),
147
+ };
148
+ } else if (/^https:\/\/.+\.(zip|tgz|tar\.gz)(\?.*)?$/.test(spec)) {
149
+ request = { source: `archive:${spec}` };
150
+ } else if (spec.startsWith("git+") || spec.startsWith("git@") || spec.startsWith("ssh://")) {
151
+ const { rest, plugin } = splitPlugin(spec.startsWith("git+") ? spec.slice(4) : spec);
152
+ const url = rest;
153
+ const hash = url.indexOf("#");
154
+ const github = githubFromUrl(hash === -1 ? url : url.slice(0, hash));
155
+ request = {
156
+ source: github ? `github:${github}` : `git:${hash === -1 ? url : url.slice(0, hash)}`,
157
+ ...(hash === -1 ? {} : { ref: url.slice(hash + 1) }),
158
+ ...(plugin ? { plugin } : {}),
159
+ };
160
+ } else if (spec.startsWith("./") || spec.startsWith(".\\")) {
161
+ const { checkout, name } = splitPathPlugin(spec);
162
+ request = { source: `path:${checkout}`, ...(name ? { plugin: name } : {}) };
163
+ } else if (spec.startsWith("../") || spec.startsWith("..\\") || spec.startsWith("/")) {
164
+ throw new Error(
165
+ `"${spec}" is outside the project. agent-deck add takes ./path inside the project; agent-deck link takes any folder.`,
166
+ );
167
+ } else if (spec.startsWith("https://") || spec.startsWith("http://")) {
168
+ const { rest, plugin } = splitPlugin(spec);
169
+ const [url, ref] = rest.split("#");
170
+ const github = githubFromUrl(url);
171
+ request = {
172
+ source: github ? `github:${github}` : `git:${url}`,
173
+ ...(ref ? { ref } : {}),
174
+ ...(plugin ? { plugin } : {}),
175
+ };
176
+ } else {
177
+ const at = spec.match(/^([\w.-]+\/[\w.-]+)@([^@/]+)$/);
178
+ if (at) {
179
+ request = { source: `github:${at[1]}`, plugin: at[2] };
180
+ } else if (GITHUB_REPO.test(spec)) {
181
+ request = { source: `github:${spec}` };
182
+ } else {
183
+ throw new Error(
184
+ `Cannot read "${spec}". Use owner/repo@plugin, ./path, git+<url>, npm:<package>, or an https .zip URL`,
185
+ );
186
+ }
187
+ }
188
+
189
+ for (const key of ["ref", "path", "sha256"]) {
190
+ if (flags[key]) request[key] = flags[key];
191
+ }
192
+ if (flags.skills?.length) request.skills = flags.skills;
193
+ request.id = flags.id || defaultId(request);
194
+ return normalizeRequest(request, `"${spec}"`);
195
+ }
196
+
197
+ /**
198
+ * A directory inside the project, stored without a leading `./` and without `..`.
199
+ * @param {string} value path after `path:` or the `./…` the user typed
200
+ */
201
+ function projectRelative(value, where = "request") {
202
+ let rel = value.replace(/\\/g, "/");
203
+ while (rel.startsWith("./")) rel = rel.slice(2);
204
+ rel = rel.replace(/\/+$/, "");
205
+ if (!rel || rel.startsWith("/") || rel.split("/").includes("..") || rel.split("/").includes("")) {
206
+ throw new Error(`${where}: path source must stay inside the project (got "${value}")`);
207
+ }
208
+ return rel;
209
+ }
210
+
211
+ /** `./plugins@name` — the `@` splits the plugin name, same rule as agent-deck link. */
212
+ function splitPathPlugin(spec) {
213
+ const normalized = spec.replace(/\\/g, "/");
214
+ const slash = normalized.lastIndexOf("/");
215
+ const at = normalized.lastIndexOf("@");
216
+ if (at > slash && at > 0) {
217
+ const name = normalized.slice(at + 1);
218
+ if (!name) throw new Error(`Invalid path "${spec}". Expected ./<path>[@<plugin-name>]`);
219
+ return { checkout: normalized.slice(0, at), name };
220
+ }
221
+ return { checkout: normalized, name: undefined };
222
+ }
223
+
224
+ /**
225
+ * A trailing `@plugin` after a git URL (and its `#ref`). The `@` of an SSH user
226
+ * (`git@host:…`) is not one: what follows it holds a `:` or a `/`.
227
+ */
228
+ function splitPlugin(value) {
229
+ const at = value.lastIndexOf("@");
230
+ if (at <= 0) return { rest: value, plugin: undefined };
231
+ const tail = value.slice(at + 1);
232
+ if (!tail || /[/:#]/.test(tail)) return { rest: value, plugin: undefined };
233
+ return { rest: value.slice(0, at), plugin: tail };
234
+ }
235
+
236
+ /** owner/repo for a github.com URL, else null. */
237
+ export function githubFromUrl(url) {
238
+ const cleaned = url.trim().replace(/\.git$/, "").replace(/\/$/, "");
239
+ const match =
240
+ cleaned.match(/^git@github\.com:([^/]+)\/([^/]+)$/) ||
241
+ cleaned.match(/^ssh:\/\/git@github\.com\/([^/]+)\/([^/]+)$/) ||
242
+ cleaned.match(/^https?:\/\/github\.com\/([^/]+)\/([^/]+)$/);
243
+ return match ? `${match[1]}/${match[2]}` : null;
244
+ }
245
+
246
+ /** Two requests ask for the same thing (the lock pin still applies). */
247
+ export function sameRequest(a, b) {
248
+ return JSON.stringify(normalizeRequest(stripLocal(a))) === JSON.stringify(normalizeRequest(stripLocal(b)));
249
+ }
250
+
251
+ function stripLocal(request) {
252
+ const { from, ...rest } = request;
253
+ return rest;
254
+ }
package/src/state.mjs ADDED
@@ -0,0 +1,41 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { STATE_FILE } from "./paths.mjs";
4
+
5
+ /**
6
+ * What agent-deck wrote on this machine, per plugin id. Never committed: paths and
7
+ * MCP keys depend on the host modes chosen here, not on what was resolved.
8
+ * @typedef {{ paths: string[], mcpKeys: Record<string, string[]>, settings?: Record<string, string[]> }} StateEntry
9
+ * @typedef {{ version: 1, plugins: Record<string, StateEntry> }} State
10
+ */
11
+
12
+ export function emptyState() {
13
+ return { version: 1, plugins: {} };
14
+ }
15
+
16
+ export function readState(projectRoot) {
17
+ const file = path.join(projectRoot, STATE_FILE);
18
+ if (!fs.existsSync(file)) return emptyState();
19
+ const raw = JSON.parse(fs.readFileSync(file, "utf8"));
20
+ if (raw?.version !== 1 || typeof raw.plugins !== "object") return emptyState();
21
+ return raw;
22
+ }
23
+
24
+ export function writeState(projectRoot, state) {
25
+ const file = path.join(projectRoot, STATE_FILE);
26
+ fs.mkdirSync(path.dirname(file), { recursive: true });
27
+ const plugins = Object.fromEntries(
28
+ Object.keys(state.plugins)
29
+ .sort()
30
+ .map((id) => [id, state.plugins[id]]),
31
+ );
32
+ fs.writeFileSync(file, `${JSON.stringify({ version: 1, plugins }, null, 2)}\n`, "utf8");
33
+ }
34
+
35
+ /** Which plugin id wrote a project path, if any. */
36
+ export function ownerOf(state, rel) {
37
+ for (const [id, entry] of Object.entries(state.plugins)) {
38
+ if (entry.paths?.includes(rel)) return id;
39
+ }
40
+ return null;
41
+ }
package/src/status.mjs ADDED
@@ -0,0 +1,137 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { gitignoreStatus } from "./gitignore.mjs";
4
+ import { claudeBin, nativeInstalled } from "./hosts/claude-native.mjs";
5
+ import { hostModes } from "./install.mjs";
6
+ import { pluginName, treeIntegrity } from "./materialize.mjs";
7
+ import { LOCK_FILE, PLUGINS_FILE, pluginRel } from "./paths.mjs";
8
+ import { loadProject } from "./project.mjs";
9
+ import { sameRequest } from "./sources/spec.mjs";
10
+ import { readState } from "./state.mjs";
11
+
12
+ /**
13
+ * What the project asks for (base, active profile, links), what is locked and
14
+ * installed, and every mismatch. Reads only: it never fetches or writes.
15
+ *
16
+ * @typedef {{ level: "error" | "warn" | "ok", id?: string, message: string }} Finding
17
+ * @typedef {{ id: string, from: string, source: string, linked: boolean, entry: object | null }} Row
18
+ * @param {{ claude?: () => string | null }} [options] test seam for the claude CLI
19
+ * @returns {{ profile: string | null, rows: Row[], findings: Finding[] }}
20
+ */
21
+ export function status(projectRoot, options = {}) {
22
+ const project = loadProject(projectRoot);
23
+ const committed = [...project.base.plugins, ...(project.prof?.plugins ?? [])];
24
+ const side = (id) => (project.owner.get(id) === "base" ? "base" : `profile ${project.profile}`);
25
+ const rows = project.doc.plugins.map((request) => ({
26
+ id: request.id,
27
+ from: request.linked ? "link" : side(request.id),
28
+ overrides: request.linked ? (committed.find((p) => p.id === request.id) ?? null) : null,
29
+ source: request.source,
30
+ ref: request.ref,
31
+ linked: Boolean(request.linked),
32
+ entry: project.lock.plugins.find((p) => p.id === request.id) ?? null,
33
+ }));
34
+ return { profile: project.profile, rows, findings: checkProject(project, options) };
35
+ }
36
+
37
+ function checkProject(project, options) {
38
+ const projectRoot = project.root;
39
+ /** @type {Finding[]} */
40
+ const findings = [];
41
+ const error = (message, id) => findings.push({ level: "error", message, ...(id ? { id } : {}) });
42
+ const warn = (message, id) => findings.push({ level: "warn", message, ...(id ? { id } : {}) });
43
+
44
+ if (!project.exists) {
45
+ error(`No ${PLUGINS_FILE}. Run agent-deck add <source>.`);
46
+ return findings;
47
+ }
48
+ const { doc, lock } = project;
49
+ const state = readState(projectRoot);
50
+ const modes = hostModes(doc);
51
+
52
+ const wanted = new Set(doc.plugins.map((p) => p.id));
53
+ for (const request of doc.plugins) {
54
+ const { id } = request;
55
+ const entry = lock?.plugins.find((p) => p.id === id);
56
+ if (!request.linked) {
57
+ if (!entry) {
58
+ error("requested but not locked. Run agent-deck install.", id);
59
+ continue;
60
+ }
61
+ const { linked, ...clean } = request;
62
+ if (!sameRequest(entry.request, clean)) {
63
+ error(`${PLUGINS_FILE} changed since the lock was written. Run agent-deck install.`, id);
64
+ }
65
+ }
66
+
67
+ const dir = path.join(projectRoot, pluginRel(id));
68
+ if (!fs.existsSync(dir)) {
69
+ error(`${pluginRel(id)} is missing. Run agent-deck install.`, id);
70
+ continue;
71
+ }
72
+ if (entry?.integrity && !request.linked) {
73
+ const actual = treeIntegrity(dir);
74
+ if (actual !== entry.integrity) {
75
+ error(`${pluginRel(id)} differs from the lock (modified by hand?). Run agent-deck install.`, id);
76
+ }
77
+ }
78
+
79
+ const installed = state.plugins[id];
80
+ if (!installed) {
81
+ error("not activated for any host. Run agent-deck install.", id);
82
+ continue;
83
+ }
84
+ const missing = installed.paths.filter((rel) => !fs.existsSync(path.join(projectRoot, rel)));
85
+ if (missing.length > 0) {
86
+ error(`${missing.length} installed path(s) missing (${missing.slice(0, 3).join(", ")}). Run agent-deck install.`, id);
87
+ }
88
+
89
+ const components = entry?.components;
90
+ if (components?.hooks && modes.cursor === "copy") warn("ships hooks; they are not active in Cursor copy mode", id);
91
+ if (components?.hooks && !installed.native?.includes("claude") && modes.claude !== "off") {
92
+ warn("ships hooks; they are not active in Claude copy mode", id);
93
+ }
94
+ }
95
+
96
+ for (const entry of lock.plugins) {
97
+ if (!wanted.has(entry.id)) error(`locked but no longer requested. Run agent-deck install.`, entry.id);
98
+ }
99
+ for (const id of Object.keys(state.plugins)) {
100
+ if (!wanted.has(id)) error("installed but no longer requested (another profile?). Run agent-deck install.", id);
101
+ }
102
+
103
+ const owners = new Map();
104
+ for (const entry of lock.plugins) {
105
+ for (const name of entry.components.skills) {
106
+ if (owners.has(name)) {
107
+ warn(`skill "${name}" is also shipped by "${owners.get(name)}"; copy mode cannot install both`, entry.id);
108
+ } else {
109
+ owners.set(name, entry.id);
110
+ }
111
+ }
112
+ }
113
+
114
+ const nativeIds = Object.entries(state.plugins)
115
+ .filter(([, entry]) => entry.native?.includes("claude"))
116
+ .map(([id]) => id);
117
+ if (nativeIds.length > 0) {
118
+ const bin = (options.claude ?? claudeBin)();
119
+ if (!bin) {
120
+ warn("Claude native plugins are recorded but the `claude` CLI is not on PATH; cannot check them");
121
+ } else {
122
+ const listed = new Set(nativeInstalled(bin, projectRoot) ?? []);
123
+ for (const id of nativeIds) {
124
+ if (!listed.has(pluginName(id))) error(`Claude does not list ${pluginName(id)}@agent-deck. Run agent-deck install.`, id);
125
+ }
126
+ }
127
+ }
128
+
129
+ const ignore = gitignoreStatus(projectRoot);
130
+ if (!ignore?.block) warn("agent-deck's .gitignore block is missing. Run agent-deck init.");
131
+ if (ignore?.lockIgnored) warn(`${LOCK_FILE} is ignored by .gitignore; commit it instead`);
132
+
133
+ if (!findings.some((f) => f.level === "error")) {
134
+ findings.push({ level: "ok", message: `${doc.plugins.length} plugin(s) match ${PLUGINS_FILE} and ${LOCK_FILE}` });
135
+ }
136
+ return findings;
137
+ }
@@ -0,0 +1,52 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { cacheRoot } from "./sources/fetch.mjs";
5
+ import { safeSegment } from "./paths.mjs";
6
+
7
+ /**
8
+ * Copy a working tree, uncommitted files included, into the agent-deck cache.
9
+ * In a git checkout, only tracked files and untracked files that .gitignore
10
+ * does not exclude are copied: build output and caches stay behind, so the
11
+ * copy matches what a commit of that tree would hold.
12
+ * `resolved` is the checkout's HEAD commit, or "worktree" for a folder that is
13
+ * not a git checkout or has no commit yet: a linked plugin is never locked.
14
+ */
15
+ export function copyWorkingTree(source) {
16
+ const abs = path.resolve(source);
17
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) {
18
+ throw new Error(`Not a directory: ${abs}`);
19
+ }
20
+ const dest = path.join(cacheRoot(), "worktrees", safeSegment(abs));
21
+ fs.rmSync(dest, { recursive: true, force: true });
22
+ fs.mkdirSync(dest, { recursive: true });
23
+
24
+ const files = gitFiles(abs);
25
+ if (files) {
26
+ for (const rel of files) {
27
+ const from = path.join(abs, rel);
28
+ if (!fs.existsSync(from) || !fs.statSync(from).isFile()) continue; // deleted, or a submodule
29
+ const to = path.join(dest, rel);
30
+ fs.mkdirSync(path.dirname(to), { recursive: true });
31
+ fs.copyFileSync(from, to);
32
+ fs.chmodSync(to, fs.statSync(from).mode);
33
+ }
34
+ } else {
35
+ fs.cpSync(abs, dest, { recursive: true });
36
+ }
37
+
38
+ const head = spawnSync("git", ["-C", abs, "rev-parse", "--verify", "-q", "HEAD"], { encoding: "utf8" });
39
+ return { root: dest, resolved: head.status === 0 ? head.stdout.trim() : "worktree" };
40
+ }
41
+
42
+ /** Tracked and unignored untracked files, relative to `dir`; null outside a git work tree. */
43
+ function gitFiles(dir) {
44
+ const inside = spawnSync("git", ["-C", dir, "rev-parse", "--show-prefix"], { encoding: "utf8" });
45
+ if (inside.status !== 0) return null;
46
+ const r = spawnSync("git", ["-C", dir, "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "."], {
47
+ encoding: "utf8",
48
+ maxBuffer: 64 * 1024 * 1024,
49
+ });
50
+ if (r.status !== 0) return null;
51
+ return r.stdout.split("\0").filter(Boolean);
52
+ }