@a2f0/agent-tool 0.1.69 → 0.1.71

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.
@@ -1,320 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { existsSync, lstatSync, mkdirSync, readdirSync, readlinkSync, realpathSync, renameSync, statSync, symlinkSync, unlinkSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import path from "node:path";
5
- import { readRegularFile } from "../system/files";
6
-
7
- /**
8
- * User-wide skills: a repository declares them by name in `skills.user`, and `skills link`
9
- * links each into every user skill directory, so every harness session sees them whatever
10
- * repository it starts in. Claude Code reads `<config dir>/skills` for each config directory;
11
- * `~/.agents/skills` is the user-level counterpart of a project's `.agents/skills`.
12
- */
13
- export type UserSkillHarness = "claude" | "agents";
14
- export interface UserSkillDirectory { harness: UserSkillHarness; directory: string }
15
-
16
- /**
17
- * What a link path holds: nothing (`create`); a symbolic link that does not resolve to a skill
18
- * directory, or that resolves to another copy of the skill in this repository (`repair`); a link
19
- * to this repository's source (`unchanged`); a link to the same skill elsewhere, such as another
20
- * clone (`kept`); or anything else (`conflict`): a file or directory, or a link to a different
21
- * skill. Only `create` and `repair` are ever written.
22
- */
23
- export type SkillLinkStatus = "create" | "repair" | "unchanged" | "kept" | "conflict";
24
- /** One declared skill in one user skill directory: `status` is the plan's classification and `current` an existing link's own text. */
25
- export interface SkillLinkPlan { skill: string; directory: string; path: string; target: string; status: SkillLinkStatus; current?: string }
26
- /**
27
- * A planned entry and, only when an applied write was attempted, its `result`: `written`, or
28
- * `failed` with `error` saying why. An entry without one was not written.
29
- */
30
- export type SkillLink = SkillLinkPlan & ({ result?: never; error?: never } | { result: "written"; error?: never } | { result: "failed"; error: string });
31
-
32
- type Environment = Record<string, string | undefined>;
33
- const errorCode = (error: unknown) => (error as NodeJS.ErrnoException).code ?? "";
34
- /** Errors that mean a path, or what a link names, does not exist as asked. */
35
- const ABSENT = ["ENOENT", "ENOTDIR", "ELOOP"];
36
-
37
- function statOrNull(file: string) {
38
- try { return statSync(file); } catch (error) { if (ABSENT.includes(errorCode(error))) return null; throw error; }
39
- }
40
- function isLink(file: string): boolean {
41
- try { return lstatSync(file).isSymbolicLink(); } catch (error) { if (ABSENT.includes(errorCode(error))) return false; throw error; }
42
- }
43
- const isDirectory = (file: string) => statOrNull(file)?.isDirectory() ?? false;
44
- /** A directory holding a regular `SKILL.md`, following links as the harnesses do. */
45
- const holdsSkill = (directory: string) => isDirectory(directory) && (statOrNull(path.join(directory, "SKILL.md"))?.isFile() ?? false);
46
- function within(parent: string, child: string): boolean {
47
- const relative = path.relative(parent, child);
48
- return !relative || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
49
- }
50
-
51
- /** The home directory, from `HOME` first so tests and callers can isolate it. */
52
- export function userHome(env: Environment = process.env): string {
53
- return path.resolve(env.HOME || homedir());
54
- }
55
-
56
- /** Keeps the first of each real path, so links and aliases name one directory once. */
57
- function unique<T>(items: T[], key: (item: T) => string): T[] {
58
- const seen = new Set<string>();
59
- return items.filter(item => { const value = key(item); if (seen.has(value)) return false; seen.add(value); return true; });
60
- }
61
-
62
- /**
63
- * The real path of a directory that may not exist yet: its nearest existing ancestor's, then the
64
- * rest, following a dangling link to where it points, so a link to a directory not created yet
65
- * names that directory. A link loop stops after 40 links, at whichever name it reached, which
66
- * planning then refuses as a link that does not resolve to a directory.
67
- */
68
- function realDirectory(directory: string, hops = 0): string {
69
- try { return realpathSync(directory); }
70
- catch (error) { if (!ABSENT.includes(errorCode(error))) throw error; }
71
- const parent = path.dirname(directory);
72
- if (parent === directory) return directory;
73
- const resolved = path.join(realDirectory(parent, hops), path.basename(directory));
74
- if (hops >= 40 || !isLink(resolved)) return resolved;
75
- return realDirectory(path.resolve(path.dirname(resolved), readlinkSync(resolved)), hops + 1);
76
- }
77
-
78
- /**
79
- * Claude Code config directories, in this order: the one `CLAUDE_CONFIG_DIR` names when it is set
80
- * to an absolute path; `~/.claude`; then every other directory directly in home whose name starts with
81
- * `.claude` and that holds `settings.json` or `.claude.json`, such as `~/.claude2`. Claude Code
82
- * writes `.claude.json` into a directory it runs with, and provisioning links `settings.json` into
83
- * one. Only existing directories count, so files such as `~/.claude.json` never do, and a
84
- * directory reached twice, by a link or by `CLAUDE_CONFIG_DIR`, counts once, by real path.
85
- */
86
- export function claudeConfigDirectories(env: Environment = process.env): string[] {
87
- const home = userHome(env);
88
- const candidates: string[] = [];
89
- // Only an absolute path: a relative one depends on where Claude Code started, which is unknown here.
90
- if (env.CLAUDE_CONFIG_DIR && path.isAbsolute(env.CLAUDE_CONFIG_DIR)) candidates.push(path.normalize(env.CLAUDE_CONFIG_DIR));
91
- candidates.push(path.join(home, ".claude"));
92
- let names: string[] = [];
93
- try { names = readdirSync(home).sort(); } catch (error) { if (!ABSENT.includes(errorCode(error))) throw error; }
94
- for (const name of names) {
95
- if (!name.startsWith(".claude") || name === ".claude") continue;
96
- const directory = path.join(home, name);
97
- if (["settings.json", ".claude.json"].some(marker => existsSync(path.join(directory, marker)))) candidates.push(directory);
98
- }
99
- return unique(candidates.filter(isDirectory), directory => realpathSync(directory));
100
- }
101
-
102
- /**
103
- * `~/.agents/skills`, then `<dir>/skills` for each Claude Code config directory. A skills
104
- * directory reached twice, such as `~/.claude2/skills` linked to `~/.claude/skills`, counts once,
105
- * under the name that is not itself a link, so a link to a directory not created yet resolves
106
- * once that directory is created.
107
- */
108
- export function userSkillDirectories(env: Environment = process.env): UserSkillDirectory[] {
109
- const directories = [
110
- { harness: "agents" as const, directory: path.join(userHome(env), ".agents", "skills") },
111
- ...claudeConfigDirectories(env).map(directory => ({ harness: "claude" as const, directory: path.join(directory, "skills") })),
112
- ].map(item => ({ ...item, key: realDirectory(item.directory), link: isLink(item.directory) }));
113
- const chosen = new Map<string, typeof directories[number]>();
114
- for (const item of directories) {
115
- const first = chosen.get(item.key);
116
- if (!first || (first.link && !item.link)) chosen.set(item.key, item);
117
- }
118
- return directories.filter(item => chosen.get(item.key) === item).map(({ harness, directory }) => ({ harness, directory }));
119
- }
120
-
121
- /**
122
- * The repository directory a harness links to for one skill: its installed copy for that harness
123
- * when it holds `SKILL.md` (`.claude/skills/<name>` or `.agents/skills/<name>`), otherwise the
124
- * repository-owned `skills/<name>`, as an absolute real path inside the repository.
125
- */
126
- export function skillSource(root: string, harness: UserSkillHarness, name: string): string {
127
- const installed = harness === "claude" ? ".claude/skills" : ".agents/skills";
128
- const found = [`${installed}/${name}`, `skills/${name}`].find(relative => holdsSkill(path.join(root, relative)));
129
- if (!found) throw new Error(`Declared user skill '${name}' has no SKILL.md in ${installed}/${name} or skills/${name}.`);
130
- const source = realpathSync(path.join(root, found));
131
- if (!within(root, source)) throw new Error(`Declared user skill '${name}' resolves outside the repository: ${found}.`);
132
- // Links are matched to skills by name, so a source must be the skill it is declared as.
133
- const named = skillName(source);
134
- if (named !== name) throw new Error(`Declared user skill '${name}' is named '${named}' in ${found}/SKILL.md.`);
135
- return source;
136
- }
137
-
138
- /** The skill a directory holds: its `SKILL.md` front matter `name`, else the directory's name; none without `SKILL.md`. */
139
- function skillName(directory: string): string | undefined {
140
- if (!holdsSkill(directory)) return undefined;
141
- // One non-blocking, link-refusing read of the resolved file, so a FIFO cannot stall the check.
142
- let file: string;
143
- try { file = realpathSync(path.join(directory, "SKILL.md")); }
144
- catch (error) { if (ABSENT.includes(errorCode(error))) return undefined; throw error; }
145
- const read = readRegularFile(file);
146
- if (read.status !== "file") return undefined;
147
- const front = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(read.contents)?.[1];
148
- const raw = front === undefined ? undefined : /^name:[ \t]*(.*?)[ \t]*$/m.exec(front)?.[1];
149
- // A quoted value keeps everything inside its quotes; a YAML comment may follow either form.
150
- const name = raw === undefined ? undefined : /^(["'])(.*?)\1(?:\s+#.*)?$/.exec(raw)?.[2] ?? raw.replace(/(?:^|\s+)#.*$/, "");
151
- return name || path.basename(directory);
152
- }
153
-
154
- /** Whether anything, even a dangling link, exists at `file`; an entry that cannot be inspected counts. */
155
- function hasEntry(file: string): boolean {
156
- try { lstatSync(file); return true; } catch (error) { return errorCode(error) !== "ENOENT"; }
157
- }
158
-
159
- /** Inside the repository and not inside a repository nested in it, such as a workspace's checkouts. */
160
- function inRepository(root: string, file: string): boolean {
161
- if (!within(root, file)) return false;
162
- for (let directory = file; directory !== root && within(root, directory); directory = path.dirname(directory)) {
163
- if (hasEntry(path.join(directory, ".git"))) return false;
164
- }
165
- return true;
166
- }
167
-
168
- /** Classify one link path against its intended target without changing anything. */
169
- function classify(root: string, file: string, target: string, skill: string): Pick<SkillLinkPlan, "status" | "current"> {
170
- let link: boolean;
171
- try { link = lstatSync(file).isSymbolicLink(); }
172
- catch (error) { if (errorCode(error) === "ENOENT") return { status: "create" }; throw error; }
173
- if (!link) return { status: "conflict" };
174
- const current = readlinkSync(file);
175
- let resolved: string;
176
- try { resolved = realpathSync(file); }
177
- catch (error) { if (ABSENT.includes(errorCode(error))) return { status: "repair", current }; throw error; }
178
- if (resolved === target) return { status: "unchanged", current };
179
- const name = skillName(resolved);
180
- if (name === undefined) return { status: "repair", current };
181
- if (name !== skill) return { status: "conflict", current };
182
- // This repository owns both copies, so the link moves to the one this harness should load.
183
- return { status: inRepository(root, resolved) ? "repair" : "kept", current };
184
- }
185
-
186
- /** Whether a user skill directory exists; one that names anything but a directory is refused. */
187
- function directoryExists(directory: string): boolean {
188
- try { lstatSync(directory); }
189
- catch (error) {
190
- if (errorCode(error) === "ENOENT") return false;
191
- // A parent that is a file or a link loop: refused below as not a directory.
192
- if (errorCode(error) !== "ENOTDIR" && errorCode(error) !== "ELOOP") throw error;
193
- }
194
- if (isDirectory(directory)) return true;
195
- if (isLink(directory)) throw new Error(`User skill directory is a link that does not resolve to a directory: ${directory} -> ${readlinkSync(directory)}`);
196
- throw new Error(`User skill directory is not a directory: ${directory}`);
197
- }
198
-
199
- /**
200
- * One entry per declared skill and user skill directory. Every source resolves first, for both
201
- * harnesses, so a declaration without one fails on every machine and before anything is read
202
- * from home. Only the declared names are ever examined.
203
- */
204
- export function planSkillLinks(rootDir: string, names: string[], env: Environment = process.env): SkillLinkPlan[] {
205
- if (!names.length) return [];
206
- const root = realpathSync(rootDir);
207
- const sources = {
208
- agents: names.map(name => skillSource(root, "agents", name)),
209
- claude: names.map(name => skillSource(root, "claude", name)),
210
- };
211
- const links: SkillLinkPlan[] = [];
212
- for (const { harness, directory } of userSkillDirectories(env)) {
213
- const exists = directoryExists(directory);
214
- names.forEach((skill, index) => {
215
- const target = sources[harness][index]!, file = path.join(directory, skill);
216
- links.push({ skill, directory, path: file, target, ...(exists ? classify(root, file, target, skill) : { status: "create" as const }) });
217
- });
218
- }
219
- return links;
220
- }
221
-
222
- /**
223
- * Replace a link through a fresh temporary link and a rename, so the name is never missing. Only
224
- * the link the plan classified is replaced: the path must still hold a link with the same text
225
- * just before the rename. Node has no exchanging rename, so a writer racing that instant is
226
- * outside this guard; only another process writing the user's skill directories could do it.
227
- */
228
- function replaceLink(link: SkillLinkPlan): void {
229
- const temporary = path.join(link.directory, `.${link.skill}.agent-tool-${randomUUID()}.tmp`);
230
- symlinkSync(link.target, temporary, "dir");
231
- let renamed = false;
232
- try {
233
- let current: string | undefined;
234
- // EINVAL: not a link.
235
- try { current = readlinkSync(link.path); } catch (error) { if (!["ENOENT", "ENOTDIR", "EINVAL"].includes(errorCode(error))) throw error; }
236
- if (current === undefined || current !== link.current) throw new Error(`Refusing to replace ${link.path}, which changed since the plan.`);
237
- renameSync(temporary, link.path);
238
- renamed = true;
239
- } finally {
240
- // Best effort: the original error matters more than a temporary link left behind.
241
- if (!renamed) try { unlinkSync(temporary); } catch {}
242
- }
243
- }
244
-
245
- /**
246
- * Writes a plan's `create` and `repair` entries. Each write stands alone: one that fails, such as
247
- * a create whose path was taken since the plan, records its `error` and the rest still run, so
248
- * the result says exactly what was written. Nothing that is not a link is replaced or removed,
249
- * and a plan with a conflict writes nothing. `linkSkills` also refuses linked worktrees first;
250
- * this is exported so tests can change the filesystem between the plan and the writes.
251
- */
252
- export function applySkillLinks(changes: SkillLinkPlan[]): SkillLink[] {
253
- if (changes.some(change => change.status === "conflict")) return changes;
254
- return changes.map((change): SkillLink => {
255
- if (change.status !== "create" && change.status !== "repair") return change;
256
- try {
257
- if (change.status === "create") {
258
- mkdirSync(change.directory, { recursive: true, mode: 0o700 });
259
- // Fails rather than overwrites if anything appeared since the plan.
260
- symlinkSync(change.target, change.path, "dir");
261
- } else replaceLink(change);
262
- return { ...change, result: "written" };
263
- } catch (error) {
264
- return { ...change, result: "failed", error: error instanceof Error ? error.message : String(error) };
265
- }
266
- });
267
- }
268
-
269
- /** Whether a directory is, or is inside, a `modules` directory of a Git directory. */
270
- function insideModules(directory: string): boolean {
271
- for (let current = directory; path.dirname(current) !== current; current = path.dirname(current)) {
272
- if (path.basename(current) === "modules" && existsSync(path.join(path.dirname(current), "HEAD"))) return true;
273
- }
274
- return false;
275
- }
276
-
277
- /**
278
- * Whether the checkout lives in a linked worktree. `git rev-parse --git-common-dir` would miss a
279
- * submodule inside a linked worktree, so this reads the layout: the checkout's `.git` is a file
280
- * naming a Git directory that, or one of whose ancestors up to the enclosing `.git` directory,
281
- * holds `commondir`, which Git writes only into a linked worktree's Git directory. The ancestors
282
- * cover a submodule checked out inside a linked worktree, whose Git directory sits under that
283
- * worktree's `modules/`. The walk stops at the outermost Git directory, so a stray `commondir`
284
- * above the repository never counts.
285
- */
286
- function linkedWorktree(root: string): boolean {
287
- const read = readRegularFile(path.join(root, ".git"));
288
- const gitdir = read.status === "file" ? /^gitdir:[ \t]*(.+?)[ \t]*$/m.exec(read.contents)?.[1] : undefined;
289
- if (gitdir === undefined) return false;
290
- for (let directory = path.resolve(root, gitdir); ; directory = path.dirname(directory)) {
291
- if (existsSync(path.join(directory, "commondir"))) return true;
292
- const parent = path.dirname(directory);
293
- if (parent === directory || path.basename(directory) === ".git") return false;
294
- // A Git directory that is not a submodule's, under another Git directory's `modules/`, is the
295
- // outermost, as with `--separate-git-dir`.
296
- if (existsSync(path.join(directory, "HEAD")) && !insideModules(parent)) return false;
297
- }
298
- }
299
-
300
- /**
301
- * Previews by default. With `apply`, creates missing links, creating a missing skills directory
302
- * (mode 0700), and repairs broken ones. A conflict anywhere blocks every write. Links follow the
303
- * checked-out working tree, so a linked worktree, which is removed when its work is done, is refused.
304
- * `applied` is true only when every write succeeded; a failed one carries `error`.
305
- */
306
- export function linkSkills(rootDir: string, names: string[], apply = false, env: Environment = process.env): { applied: boolean; changes: SkillLink[] } {
307
- const changes = planSkillLinks(rootDir, names, env);
308
- if (!apply || changes.some(change => change.status === "conflict")) return { applied: false, changes };
309
- if (changes.some(change => change.status === "create" || change.status === "repair") && linkedWorktree(realpathSync(rootDir))) {
310
- throw new Error("Refusing to link user-wide skills from a linked worktree, whose removal would break them; run skills link from the main checkout.");
311
- }
312
- const applied = applySkillLinks(changes);
313
- return { applied: applied.every(change => change.result !== "failed"), changes: applied };
314
- }
315
-
316
- /** Read-only: ok while every declared link is unchanged or kept, so health reports can gate on it. */
317
- export function checkSkillLinks(rootDir: string, names: string[], env: Environment = process.env): { ok: boolean; changes: SkillLink[] } {
318
- const changes = planSkillLinks(rootDir, names, env);
319
- return { ok: changes.every(change => change.status === "unchanged" || change.status === "kept"), changes };
320
- }