- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/install.ts?version=0&format=json
496 linesFirst import 100%Last change First import in version 0, 1 version changed it
You're reading version 0. The newest is 318, and 6 versions since then changed this file.
1// Installing a mod without breaking the sessions that run it (#29). The avcs
2// mod and avcs-view are folders in Claude Code's skills folder, which every
3// session on the machine loads when it starts (an open chat keeps the mod it
4// started with, #37). So an install (client/install-mod.ts, client/install-view.ts):
5//
6// 1. Stages the new files in a temp folder. plugin.json's version gets the
7// last commit that changed the mod's own files (0.1.0+702c616, or
8// 0.1.0+702c616.dirty when they differ from it), and hooks/stamp.ts says
9// the same, so the mod sends it with each call to the server
10// (X-Avcs-Client). A commit that changes none of them changes nothing to
11// install, and nothing to restart for.
12// 2. Checks the staged copy: `claude plugin validate`, then the mod's own
13// tests in Claude Code's plugin test kit. If either fails, nothing in the
14// installed folder changes.
15// 3. Keeps each installed file as <file>.prev, then moves each new file into
16// place with a rename, so no session reads a half-written file: what the
17// hook imports first, plugin.json last. If a rename fails, the files
18// already moved are put back.
19//
20// The renames follow each other within a few milliseconds, but a session can
21// still start between two of them. With what the hook imports going in
22// first, a new hook never loads without its imports; a core.ts that drops an
23// export the old hook uses can fail that one start, and a restart after the
24// install brings the whole new mod.
25//
26// A rollback swaps the .prev files back in, and the files it replaces become
27// the .prev ones, so a second rollback undoes the first. .avcs-install.json
28// in the mod's folder says what is installed and what the .prev files hold.
29// `avcs --version` reports the installed mods (versionReport).
31import { spawnSync } from "node:child_process";
32import {
33 closeSync,
34 copyFileSync,
35 existsSync,
36 mkdirSync,
37 mkdtempSync,
38 openSync,
39 readFileSync,
40 renameSync,
41 rmdirSync,
42 rmSync,
43 statSync,
44 writeFileSync,
45} from "node:fs";
46import { homedir, tmpdir } from "node:os";
47import { dirname, join, resolve } from "node:path";
48import { CLIENT_DIR, clientPlace, clientVersion } from "./client-version.ts";
50export interface ModSpec {
51 /** The mod's name, as its plugin.json has it. */
52 readonly name: string;
53 /** The folder its files come from. */
54 readonly from: string;
55 /** Its files, relative to `from`, in the order they go into place: what the hook imports first, plugin.json last. */
56 readonly files: readonly string[];
57 /** Its tests for the plugin test kit, relative to `from`: staged for the check, never installed. */
58 readonly test?: string;
59}
61/** One install, as .avcs-install.json records it. */
62export interface Install {
63 readonly version: string;
64 /** In the order they went into place. */
65 readonly files: readonly string[];
66 readonly from: string;
67 readonly at: string;
68}
70export interface InstallRecord extends Install {
71 readonly mod: string;
72 /** What the .prev files hold. */
73 readonly prev?: Install;
74 /** Set while files are being moved into place; still set means an install stopped midway. */
75 readonly moving?: string;
76}
78export interface Installed {
79 /** False when the folder already had exactly these files. */
80 readonly changed: boolean;
81 readonly version: string;
82 /** The version the .prev files now hold. */
83 readonly previous: string | undefined;
84 readonly files: number;
85}
87export interface InstallOptions {
88 /** The mod's folder: in the skills folder, or a scratch folder. */
89 readonly target: string;
90 /** Checks a staged copy of the mod: undefined when it passes, else why not. */
91 readonly check: (dir: string) => string | undefined;
92 /** For tests: the commit to stamp (null: none), instead of asking git. */
93 readonly commit?: string | null;
94 /** For tests: the rename that moves each file into place. */
95 readonly rename?: (from: string, to: string) => void;
96 readonly now?: Date;
97}
99const RECORD = ".avcs-install.json";
100const LOCK = ".avcs-install.lock";
101const MANIFEST = ".claude-plugin/plugin.json";
102const STAMP_FILE = "hooks/stamp.ts";
103/** A lock older than this was left by an install that died. */
104const STALE_LOCK_MS = 10 * 60_000;
106const at = (dir: string, rel: string, suffix = "") => join(dir, ...rel.split("/")) + suffix;
108/** The abso mod: what the hook imports first, plugin.json last. src/core.ts is the only client file it imports. */
109export const AVCS_MOD: ModSpec = {
110 name: "avcs",
111 from: CLIENT_DIR,
112 files: ["src/core.ts", "hooks/stamp.ts", "hooks/register.ts", "hooks/hooks.json", ".claude-plugin/plugin.json"],
113 test: "hooks/register.test.ts",
114};
116/** The avcs-view mod (#12), from client/view. */
117export const VIEW_MOD: ModSpec = {
118 name: "avcs-view",
119 from: join(CLIENT_DIR, "view"),
120 files: ["types/index.d.ts", "hooks/stamp.ts", "hooks/register.tsx", "hooks/hooks.json", ".claude-plugin/plugin.json"],
121 test: "hooks/register.test.ts",
122};
124/** Where Claude Code's skills folder keeps a mod. */
125export const skillsFolder = (name: string, env: Readonly<Record<string, string | undefined>> = process.env) =>
126 join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "skills", name);
128export const modInstalled = (env: Readonly<Record<string, string | undefined>> = process.env) =>
129 existsSync(at(skillsFolder(AVCS_MOD.name, env), MANIFEST));
131/** The version an install of `spec` gets: plugin.json's, plus the last commit that changed its files (and .dirty when they differ from it). */
132export function versionFor(spec: ModSpec, commit?: string | null): string {
133 const manifest = JSON.parse(readFileSync(at(spec.from, MANIFEST), "utf8")) as { version?: unknown };
134 const base = String(manifest.version ?? "0.0.0").split("+")[0]!;
135 const c = commit === undefined ? modCommit(spec) : commit;
136 return c ? `${base}+${c}` : base;
137}
139function modCommit(spec: ModSpec): string | null {
140 const git = (...args: string[]) => spawnSync("git", ["-C", spec.from, ...args], { encoding: "utf8" });
141 const last = git("log", "-1", "--format=%H", "--", ...spec.files);
142 if (last.status !== 0 || !/^[0-9a-f]{40}/.test(last.stdout)) return null;
143 const changed = git("status", "--porcelain", "--", ...spec.files).stdout.trim() !== "";
144 return `${last.stdout.slice(0, 7)}${changed ? ".dirty" : ""}`;
145}
147/** The files to install, stamped with `version`, in install order. */
148function filesFor(spec: ModSpec, version: string): Map<string, Buffer> {
149 if (!/^[\w.+-]+$/.test(version)) throw new Error(`can't stamp the version ${JSON.stringify(version)}`);
150 const out = new Map<string, Buffer>();
151 for (const rel of spec.files) {
152 let data = readFileSync(at(spec.from, rel));
153 if (rel === MANIFEST) {
154 const manifest = JSON.parse(data.toString("utf8")) as Record<string, unknown>;
155 data = Buffer.from(`${JSON.stringify({ ...manifest, version }, null, 2)}\n`);
156 } else if (rel === STAMP_FILE) {
157 const text = data.toString("utf8");
158 const stamped = text.replace(/(STAMP[^=\n]*=\s*)undefined/, `$1'${version}'`);
159 if (stamped === text) throw new Error(`${rel} has no "STAMP ... = undefined" line to stamp`);
160 data = Buffer.from(stamped);
161 }
162 out.set(rel, data);
163 }
164 return out;
165}
167function readRecord(target: string): InstallRecord | undefined {
168 try {
169 return JSON.parse(readFileSync(join(target, RECORD), "utf8")) as InstallRecord;
170 } catch {
171 return undefined;
172 }
173}
175function writeRecord(target: string, record: InstallRecord): void {
176 writeFileSync(join(target, `${RECORD}.next`), `${JSON.stringify(record, null, 2)}\n`);
177 renameRetrying(join(target, `${RECORD}.next`), join(target, RECORD));
178}
180/** What is installed now. A folder from before .avcs-install.json: the spec's files that are there. */
181function installedNow(spec: ModSpec, target: string, record: InstallRecord | undefined): Install | undefined {
182 const files = (record?.files ?? spec.files).filter((rel) => existsSync(at(target, rel)));
183 if (files.length === 0) return undefined;
184 if (record) return { version: record.version, files, from: record.from, at: record.at };
185 let version = "unknown";
186 try {
187 version = String(
188 (JSON.parse(readFileSync(at(target, MANIFEST), "utf8")) as { version?: unknown }).version ?? version,
189 );
190 } catch {}
191 return { version, files, from: "unknown", at: "unknown" };
192}
194/** Sleeps without an event loop, between tries of a rename. */
195function pause(ms: number): void {
196 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
197}
199/** A rename, tried for about a second while Windows says another process has the file open. */
200function renameRetrying(from: string, to: string): void {
201 for (let i = 0; ; i++) {
202 try {
203 renameSync(from, to);
204 return;
205 } catch (err) {
206 const code = (err as NodeJS.ErrnoException).code ?? "";
207 if (i >= 20 || !["EPERM", "EBUSY", "EACCES"].includes(code)) throw err;
208 pause(50);
209 }
210 }
211}
213/** Holds the mod folder's lock while fn runs. */
214function locked<T>(target: string, fn: () => T): T {
215 const file = join(target, LOCK);
216 try {
217 if (Date.now() - statSync(file).mtimeMs > STALE_LOCK_MS) rmSync(file, { force: true });
218 } catch {}
219 try {
220 closeSync(openSync(file, "wx"));
221 } catch {
222 throw new Error(`another install is running in ${target} (it holds ${LOCK}; if none is, delete that file)`);
223 }
224 try {
225 return fn();
226 } finally {
227 rmSync(file, { force: true });
228 }
229}
231/**
232 * Moves `next` into place in the mod's folder, keeping the files that were
233 * there as .prev files. Each file goes in with a rename, in `next`'s order;
234 * if one fails, the ones already moved are put back and the error is thrown.
235 */
236function moveIn(
237 spec: ModSpec,
238 target: string,
239 next: ReadonlyMap<string, Buffer>,
240 install: Install,
241 rename: (from: string, to: string) => void,
242): Install | undefined {
243 const record = readRecord(target);
244 const current = installedNow(spec, target, record);
245 // After an install that stopped midway, the folder is a mix and the .prev files still hold the last whole install.
246 const prev = record?.moving ? record.prev : current;
247 if (!record?.moving) {
248 for (const rel of new Set([...(record?.prev?.files ?? []), ...(current?.files ?? [])]))
249 rmSync(at(target, rel, ".prev"), { force: true });
250 for (const rel of current?.files ?? []) copyFileSync(at(target, rel), at(target, rel, ".prev"));
251 }
252 const before: InstallRecord = { mod: spec.name, ...(current ?? install), ...(prev ? { prev } : {}) };
253 writeRecord(target, { ...before, moving: install.version });
255 const moved: string[] = [];
256 try {
257 for (const [rel, data] of next) {
258 mkdirSync(dirname(at(target, rel)), { recursive: true });
259 writeFileSync(at(target, rel, ".next"), data);
260 }
261 for (const rel of next.keys()) {
262 rename(at(target, rel, ".next"), at(target, rel));
263 moved.push(rel);
264 }
265 } catch (err) {
266 for (const rel of moved.reverse()) {
267 if (prev?.files.includes(rel)) {
268 copyFileSync(at(target, rel, ".prev"), at(target, rel, ".next"));
269 renameRetrying(at(target, rel, ".next"), at(target, rel));
270 } else {
271 rmSync(at(target, rel), { force: true });
272 }
273 }
274 for (const rel of next.keys()) rmSync(at(target, rel, ".next"), { force: true });
275 if (current) writeRecord(target, before);
276 else rmSync(join(target, RECORD), { force: true });
277 throw err;
278 }
279 // Files the old install had and this one doesn't.
280 for (const rel of current?.files ?? []) if (!next.has(rel)) rmSync(at(target, rel), { force: true });
281 writeRecord(target, { mod: spec.name, ...install, ...(prev ? { prev } : {}) });
282 return prev;
283}
285/** Whether the folder holds exactly `next`. */
286function holds(target: string, files: readonly string[], next: ReadonlyMap<string, Buffer>): boolean {
287 return (
288 files.length === next.size && files.every((rel) => next.get(rel)?.equals(readFileSync(at(target, rel))) ?? false)
289 );
290}
292/** Removes the folders a first install made, if they are empty. */
293function removeEmpty(target: string, files: Iterable<string>): void {
294 const dirs = new Set<string>();
295 for (const rel of files) for (let d = dirname(at(target, rel)); d.length > target.length; d = dirname(d)) dirs.add(d);
296 for (const d of [...dirs, target].sort((a, b) => b.length - a.length)) {
297 try {
298 rmdirSync(d);
299 } catch {}
300 }
301}
303/** Installs the mod from `spec.from` into `options.target` (see the top of this file). */
304export function installMod(spec: ModSpec, options: InstallOptions): Installed {
305 const target = resolve(options.target);
306 const version = versionFor(spec, options.commit);
307 const next = filesFor(spec, version);
308 const existed = existsSync(target);
309 mkdirSync(target, { recursive: true });
310 try {
311 return locked(target, () => {
312 const record = readRecord(target);
313 const current = installedNow(spec, target, record);
314 if (!record?.moving && current && holds(target, current.files, next)) {
315 return { changed: false, version, previous: record?.prev?.version, files: next.size };
316 }
317 const staged = mkdtempSync(join(tmpdir(), `${spec.name}-install-`));
318 try {
319 for (const [rel, data] of next) {
320 mkdirSync(dirname(at(staged, rel)), { recursive: true });
321 writeFileSync(at(staged, rel), data);
322 }
323 const why = options.check(staged);
324 if (why !== undefined) throw new Error(`the staged copy failed its check, so nothing was changed:\n${why}`);
325 } finally {
326 rmSync(staged, { recursive: true, force: true });
327 }
328 const install: Install = {
329 version,
330 files: [...next.keys()],
331 from: spec.from,
332 at: (options.now ?? new Date()).toISOString(),
333 };
334 const prev = moveIn(spec, target, next, install, options.rename ?? renameRetrying);
335 return { changed: true, version, previous: prev?.version, files: next.size };
336 });
337 } catch (err) {
338 // A first install that didn't happen leaves no folder behind.
339 if (!existed) removeEmpty(target, next.keys());
340 throw err;
341 }
342}
344/** Puts the install kept in the .prev files back; the one it replaces becomes the .prev one. */
345export function rollbackMod(spec: ModSpec, options: Pick<InstallOptions, "target" | "rename" | "now">): Installed {
346 const target = resolve(options.target);
347 if (!existsSync(target)) throw new Error(`nothing is installed in ${target}`);
348 return locked(target, () => {
349 const record = readRecord(target);
350 const prev = record?.prev;
351 if (!prev) throw new Error(`no earlier install is kept in ${target}`);
352 const missing = prev.files.filter((rel) => !existsSync(at(target, rel, ".prev")));
353 if (missing.length > 0)
354 throw new Error(
355 `the earlier install's ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} missing from ${target}`,
356 );
357 const next = new Map(prev.files.map((rel) => [rel, readFileSync(at(target, rel, ".prev"))]));
358 const kept = moveIn(spec, target, next, prev, options.rename ?? renameRetrying);
359 return { changed: true, version: prev.version, previous: kept?.version, files: next.size };
360 });
361}
363/** `claude plugin validate`, then the mod's own tests in Claude Code's plugin test kit, on a staged copy. */
364export function checkWithClaude(spec: ModSpec): (dir: string) => string | undefined {
365 // claude is a .cmd on Windows, so it runs through the shell; the folder is quoted.
366 const claude = (what: string, dir: string) =>
367 spawnSync(`claude plugin ${what} "${dir}"`, { shell: true, encoding: "utf8", timeout: 180_000 });
368 const tail = (r: { stdout: string; stderr: string }) =>
369 `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split("\n").slice(-15).join("\n");
370 return (dir) => {
371 const valid = claude("validate", dir);
372 if (valid.status !== 0) return `claude plugin validate failed (--unchecked skips the check):\n${tail(valid)}`;
373 if (spec.test === undefined) return undefined;
374 copyFileSync(at(spec.from, spec.test), at(dir, spec.test));
375 const tests = claude("test", dir);
376 if (tests.status !== 0) return `the mod's tests failed on the staged copy:\n${tail(tests)}`;
377 return undefined;
378 };
379}
381/** The installers' command line: [folder] [--rollback] [--unchecked]. */
382export function runInstaller(
383 spec: ModSpec,
384 script: string,
385 defaultTarget: string,
386 argv: readonly string[] = process.argv.slice(2),
387): void {
388 const options = argv.filter((a) => a.startsWith("--"));
389 const folders = argv.filter((a) => !a.startsWith("--"));
390 const unknown = options.find((o) => o !== "--rollback" && o !== "--unchecked");
391 if (unknown !== undefined || folders.length > 1) {
392 console.error(
393 `usage: node client/${script} [folder] [--rollback] [--unchecked]${unknown ? ` (unknown option ${unknown})` : ""}`,
394 );
395 process.exit(2);
396 }
397 const target = resolve(folders[0] ?? defaultTarget);
398 try {
399 if (options.includes("--rollback")) {
400 const r = rollbackMod(spec, { target });
401 console.log(
402 `Rolled the ${spec.name} mod back to ${r.version} in ${target}. ${r.previous ? `${r.previous} is kept; --rollback again puts it back. ` : ""}Restart open chats to load it.`,
403 );
404 return;
405 }
406 const unchecked = options.includes("--unchecked");
407 const r = installMod(spec, { target, check: unchecked ? () => undefined : checkWithClaude(spec) });
408 if (!r.changed) {
409 console.log(`The ${spec.name} mod ${r.version} is already installed in ${target}; nothing changed.`);
410 return;
411 }
412 const kept = r.previous ? ` The one it replaced (${r.previous}) is kept; --rollback puts it back.` : "";
413 console.log(
414 `Installed the ${spec.name} mod ${r.version} in ${target} (${r.files} files${unchecked ? ", unchecked" : ", validated and tested first"}).${kept} New chats load it; restart open ones to load it.`,
415 );
416 } catch (err) {
417 console.error(
418 `The ${spec.name} mod was not ${options.includes("--rollback") ? "rolled back" : "installed"}: ${(err as Error).message}`,
419 );
420 process.exit(1);
421 }
422}
424export interface ModInstall {
425 readonly name: string;
426 readonly folder: string;
427 /** Undefined when it isn't installed. */
428 readonly version: string | undefined;
429 /** When it was installed (mods installed before .avcs-install.json have none). */
430 readonly at: string | undefined;
431 /** What an install from this client would stamp now. */
432 readonly current: string;
433}
435/** `avcs --version`: this client, and the mods installed on this machine, compared with this client's. */
436export function versionReport(env: Readonly<Record<string, string | undefined>>): {
437 text: string;
438 json: Record<string, unknown>;
439} {
440 const client = clientVersion();
441 const lines = [`abso ${client} (${clientPlace()})`];
442 const mods: ModInstall[] = [];
443 for (const [spec, installer] of [
444 [AVCS_MOD, "install-mod.ts"],
445 [VIEW_MOD, "install-view.ts"],
446 ] as const) {
447 const folder = skillsFolder(spec.name, env);
448 const field = (rel: string, key: string): string | undefined => {
449 try {
450 const value = (JSON.parse(readFileSync(at(folder, rel), "utf8")) as Record<string, unknown>)[key];
451 return typeof value === "string" ? value : undefined;
452 } catch {
453 return undefined;
454 }
455 };
456 const m: ModInstall = {
457 name: spec.name,
458 folder,
459 version: field(MANIFEST, "version"),
460 at: field(RECORD, "at"),
461 current: (() => {
462 try {
463 return versionFor(spec);
464 } catch {
465 return "not in this copy";
466 }
467 })(),
468 };
469 mods.push(m);
470 if (m.version === undefined) {
471 lines.push(`the ${m.name} mod: not installed (node client/${installer})`);
472 continue;
473 }
474 const when = m.at ? `, installed ${m.at.slice(0, 16).replace("T", " ")} UTC` : "";
475 const behind =
476 m.version === m.current ? "" : `; this client has ${m.current}: node client/${installer} installs it`;
477 lines.push(`the ${m.name} mod: ${m.version} in ${m.folder}${when}${behind}`);
478 }
479 return { text: lines.join("\n"), json: { client, folder: CLIENT_DIR, mods } };
480}
482/**
483 * For `abso status` (abso issue 41: every chat ran a mod a day behind main,
484 * and only `--version` would have said so): each installed mod this client
485 * would install differently. Says nothing unless this client knows its mod's
486 * commit (a git checkout, as the shared one is) and the installed one has one.
487 */
488export function modsBehindText(env: Readonly<Record<string, string | undefined>>): string[] {
489 const installers: Record<string, string> = { [AVCS_MOD.name]: "install-mod.ts", [VIEW_MOD.name]: "install-view.ts" };
490 return (versionReport(env).json.mods as ModInstall[])
491 .filter((m) => m.version?.includes("+") && /\+[0-9a-f]{7}$/.test(m.current) && m.version !== m.current)
492 .map(
493 (m) =>
494 `The ${m.name} mod installed on this machine is ${m.version}, and this client has ${m.current}: node client/${installers[m.name]} installs it (new chats load it).`,
495 );
496}