Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
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=41&format=json
522 linesFirst import 94% · review 6%Last change review in version 40, 2 versions changed it

You're reading version 41. The newest is 318, and 5 versions since then changed this file. Go to the newestCompare with 318

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;
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;
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;
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;
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;
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: "abso-hooks",
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 abso-view mod (#12), from client/view. */
117export const VIEW_MOD: ModSpec = {
118 name: "abso-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/** The skills folders the mods had before the rename; an install moves them out of the way (see retireOldMod). */
125export const OLD_MOD_NAMES: Readonly<Record<string, string>> = { "abso-hooks": "avcs", "abso-view": "avcs-view" };
127/** Where Claude Code's skills folder keeps a mod. */
128export const skillsFolder = (name: string, env: Readonly<Record<string, string | undefined>> = process.env) =>
129 join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "skills", name);
131export const modInstalled = (env: Readonly<Record<string, string | undefined>> = process.env) =>
132 existsSync(at(skillsFolder(AVCS_MOD.name, env), MANIFEST)) ||
133 existsSync(at(skillsFolder(OLD_MOD_NAMES[AVCS_MOD.name]!, env), MANIFEST));
135/**
136 * After the new mod is in, the folder it replaces (skills/avcs, skills/avcs-view) would load beside it, so it
137 * is moved, not deleted, to ~/.abso/retired-mods/<name>-<stamp>. Returns where it went, or undefined when there was none.
138 */
139export function retireOldMod(
140 spec: ModSpec,
141 env: Readonly<Record<string, string | undefined>> = process.env,
142 now: Date = new Date(),
143): string | undefined {
144 const old = OLD_MOD_NAMES[spec.name];
145 if (old === undefined) return undefined;
146 const from = skillsFolder(old, env);
147 if (!existsSync(from)) return undefined;
148 const to = join(homedir(), ".abso", "retired-mods", `${old}-${now.toISOString().replace(/[:.]/g, "-")}`);
149 mkdirSync(dirname(to), { recursive: true });
150 renameRetrying(from, to);
151 return to;
154/** 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). */
155export function versionFor(spec: ModSpec, commit?: string | null): string {
156 const manifest = JSON.parse(readFileSync(at(spec.from, MANIFEST), "utf8")) as { version?: unknown };
157 const base = String(manifest.version ?? "0.0.0").split("+")[0]!;
158 const c = commit === undefined ? modCommit(spec) : commit;
159 return c ? `${base}+${c}` : base;
162function modCommit(spec: ModSpec): string | null {
163 const git = (...args: string[]) => spawnSync("git", ["-C", spec.from, ...args], { encoding: "utf8" });
164 const last = git("log", "-1", "--format=%H", "--", ...spec.files);
165 if (last.status !== 0 || !/^[0-9a-f]{40}/.test(last.stdout)) return null;
166 const changed = git("status", "--porcelain", "--", ...spec.files).stdout.trim() !== "";
167 return `${last.stdout.slice(0, 7)}${changed ? ".dirty" : ""}`;
170/** The files to install, stamped with `version`, in install order. */
171function filesFor(spec: ModSpec, version: string): Map<string, Buffer> {
172 if (!/^[\w.+-]+$/.test(version)) throw new Error(`can't stamp the version ${JSON.stringify(version)}`);
173 const out = new Map<string, Buffer>();
174 for (const rel of spec.files) {
175 let data = readFileSync(at(spec.from, rel));
176 if (rel === MANIFEST) {
177 const manifest = JSON.parse(data.toString("utf8")) as Record<string, unknown>;
178 data = Buffer.from(`${JSON.stringify({ ...manifest, version }, null, 2)}\n`);
179 } else if (rel === STAMP_FILE) {
180 const text = data.toString("utf8");
181 const stamped = text.replace(/(STAMP[^=\n]*=\s*)undefined/, `$1'${version}'`);
182 if (stamped === text) throw new Error(`${rel} has no "STAMP ... = undefined" line to stamp`);
183 data = Buffer.from(stamped);
184 }
185 out.set(rel, data);
186 }
187 return out;
190function readRecord(target: string): InstallRecord | undefined {
191 try {
192 return JSON.parse(readFileSync(join(target, RECORD), "utf8")) as InstallRecord;
193 } catch {
194 return undefined;
195 }
198function writeRecord(target: string, record: InstallRecord): void {
199 writeFileSync(join(target, `${RECORD}.next`), `${JSON.stringify(record, null, 2)}\n`);
200 renameRetrying(join(target, `${RECORD}.next`), join(target, RECORD));
203/** What is installed now. A folder from before .avcs-install.json: the spec's files that are there. */
204function installedNow(spec: ModSpec, target: string, record: InstallRecord | undefined): Install | undefined {
205 const files = (record?.files ?? spec.files).filter((rel) => existsSync(at(target, rel)));
206 if (files.length === 0) return undefined;
207 if (record) return { version: record.version, files, from: record.from, at: record.at };
208 let version = "unknown";
209 try {
210 version = String(
211 (JSON.parse(readFileSync(at(target, MANIFEST), "utf8")) as { version?: unknown }).version ?? version,
212 );
213 } catch {}
214 return { version, files, from: "unknown", at: "unknown" };
217/** Sleeps without an event loop, between tries of a rename. */
218function pause(ms: number): void {
219 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
222/** A rename, tried for about a second while Windows says another process has the file open. */
223function renameRetrying(from: string, to: string): void {
224 for (let i = 0; ; i++) {
225 try {
226 renameSync(from, to);
227 return;
228 } catch (err) {
229 const code = (err as NodeJS.ErrnoException).code ?? "";
230 if (i >= 20 || !["EPERM", "EBUSY", "EACCES"].includes(code)) throw err;
231 pause(50);
232 }
233 }
236/** Holds the mod folder's lock while fn runs. */
237function locked<T>(target: string, fn: () => T): T {
238 const file = join(target, LOCK);
239 try {
240 if (Date.now() - statSync(file).mtimeMs > STALE_LOCK_MS) rmSync(file, { force: true });
241 } catch {}
242 try {
243 closeSync(openSync(file, "wx"));
244 } catch {
245 throw new Error(`another install is running in ${target} (it holds ${LOCK}; if none is, delete that file)`);
246 }
247 try {
248 return fn();
249 } finally {
250 rmSync(file, { force: true });
251 }
254/**
255 * Moves `next` into place in the mod's folder, keeping the files that were
256 * there as .prev files. Each file goes in with a rename, in `next`'s order;
257 * if one fails, the ones already moved are put back and the error is thrown.
258 */
259function moveIn(
260 spec: ModSpec,
261 target: string,
262 next: ReadonlyMap<string, Buffer>,
263 install: Install,
264 rename: (from: string, to: string) => void,
265): Install | undefined {
266 const record = readRecord(target);
267 const current = installedNow(spec, target, record);
268 // After an install that stopped midway, the folder is a mix and the .prev files still hold the last whole install.
269 const prev = record?.moving ? record.prev : current;
270 if (!record?.moving) {
271 for (const rel of new Set([...(record?.prev?.files ?? []), ...(current?.files ?? [])]))
272 rmSync(at(target, rel, ".prev"), { force: true });
273 for (const rel of current?.files ?? []) copyFileSync(at(target, rel), at(target, rel, ".prev"));
274 }
275 const before: InstallRecord = { mod: spec.name, ...(current ?? install), ...(prev ? { prev } : {}) };
276 writeRecord(target, { ...before, moving: install.version });
278 const moved: string[] = [];
279 try {
280 for (const [rel, data] of next) {
281 mkdirSync(dirname(at(target, rel)), { recursive: true });
282 writeFileSync(at(target, rel, ".next"), data);
283 }
284 for (const rel of next.keys()) {
285 rename(at(target, rel, ".next"), at(target, rel));
286 moved.push(rel);
287 }
288 } catch (err) {
289 for (const rel of moved.reverse()) {
290 if (prev?.files.includes(rel)) {
291 copyFileSync(at(target, rel, ".prev"), at(target, rel, ".next"));
292 renameRetrying(at(target, rel, ".next"), at(target, rel));
293 } else {
294 rmSync(at(target, rel), { force: true });
295 }
296 }
297 for (const rel of next.keys()) rmSync(at(target, rel, ".next"), { force: true });
298 if (current) writeRecord(target, before);
299 else rmSync(join(target, RECORD), { force: true });
300 throw err;
301 }
302 // Files the old install had and this one doesn't.
303 for (const rel of current?.files ?? []) if (!next.has(rel)) rmSync(at(target, rel), { force: true });
304 writeRecord(target, { mod: spec.name, ...install, ...(prev ? { prev } : {}) });
305 return prev;
308/** Whether the folder holds exactly `next`. */
309function holds(target: string, files: readonly string[], next: ReadonlyMap<string, Buffer>): boolean {
310 return (
311 files.length === next.size && files.every((rel) => next.get(rel)?.equals(readFileSync(at(target, rel))) ?? false)
312 );
315/** Removes the folders a first install made, if they are empty. */
316function removeEmpty(target: string, files: Iterable<string>): void {
317 const dirs = new Set<string>();
318 for (const rel of files) for (let d = dirname(at(target, rel)); d.length > target.length; d = dirname(d)) dirs.add(d);
319 for (const d of [...dirs, target].sort((a, b) => b.length - a.length)) {
320 try {
321 rmdirSync(d);
322 } catch {}
323 }
326/** Installs the mod from `spec.from` into `options.target` (see the top of this file). */
327export function installMod(spec: ModSpec, options: InstallOptions): Installed {
328 const target = resolve(options.target);
329 const version = versionFor(spec, options.commit);
330 const next = filesFor(spec, version);
331 const existed = existsSync(target);
332 mkdirSync(target, { recursive: true });
333 try {
334 return locked(target, () => {
335 const record = readRecord(target);
336 const current = installedNow(spec, target, record);
337 if (!record?.moving && current && holds(target, current.files, next)) {
338 return { changed: false, version, previous: record?.prev?.version, files: next.size };
339 }
340 const staged = mkdtempSync(join(tmpdir(), `${spec.name}-install-`));
341 try {
342 for (const [rel, data] of next) {
343 mkdirSync(dirname(at(staged, rel)), { recursive: true });
344 writeFileSync(at(staged, rel), data);
345 }
346 const why = options.check(staged);
347 if (why !== undefined) throw new Error(`the staged copy failed its check, so nothing was changed:\n${why}`);
348 } finally {
349 rmSync(staged, { recursive: true, force: true });
350 }
351 const install: Install = {
352 version,
353 files: [...next.keys()],
354 from: spec.from,
355 at: (options.now ?? new Date()).toISOString(),
356 };
357 const prev = moveIn(spec, target, next, install, options.rename ?? renameRetrying);
358 return { changed: true, version, previous: prev?.version, files: next.size };
359 });
360 } catch (err) {
361 // A first install that didn't happen leaves no folder behind.
362 if (!existed) removeEmpty(target, next.keys());
363 throw err;
364 }
367/** Puts the install kept in the .prev files back; the one it replaces becomes the .prev one. */
368export function rollbackMod(spec: ModSpec, options: Pick<InstallOptions, "target" | "rename" | "now">): Installed {
369 const target = resolve(options.target);
370 if (!existsSync(target)) throw new Error(`nothing is installed in ${target}`);
371 return locked(target, () => {
372 const record = readRecord(target);
373 const prev = record?.prev;
374 if (!prev) throw new Error(`no earlier install is kept in ${target}`);
375 const missing = prev.files.filter((rel) => !existsSync(at(target, rel, ".prev")));
376 if (missing.length > 0)
377 throw new Error(
378 `the earlier install's ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} missing from ${target}`,
379 );
380 const next = new Map(prev.files.map((rel) => [rel, readFileSync(at(target, rel, ".prev"))]));
381 const kept = moveIn(spec, target, next, prev, options.rename ?? renameRetrying);
382 return { changed: true, version: prev.version, previous: kept?.version, files: next.size };
383 });
386/** `claude plugin validate`, then the mod's own tests in Claude Code's plugin test kit, on a staged copy. */
387export function checkWithClaude(spec: ModSpec): (dir: string) => string | undefined {
388 // claude is a .cmd on Windows, so it runs through the shell; the folder is quoted.
389 const claude = (what: string, dir: string) =>
390 spawnSync(`claude plugin ${what} "${dir}"`, { shell: true, encoding: "utf8", timeout: 180_000 });
391 const tail = (r: { stdout: string; stderr: string }) =>
392 `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split("\n").slice(-15).join("\n");
393 return (dir) => {
394 const valid = claude("validate", dir);
395 if (valid.status !== 0) return `claude plugin validate failed (--unchecked skips the check):\n${tail(valid)}`;
396 if (spec.test === undefined) return undefined;
397 copyFileSync(at(spec.from, spec.test), at(dir, spec.test));
398 const tests = claude("test", dir);
399 if (tests.status !== 0) return `the mod's tests failed on the staged copy:\n${tail(tests)}`;
400 return undefined;
401 };
404/** The installers' command line: [folder] [--rollback] [--unchecked]. */
405export function runInstaller(
406 spec: ModSpec,
407 script: string,
408 defaultTarget: string,
409 argv: readonly string[] = process.argv.slice(2),
410): void {
411 const options = argv.filter((a) => a.startsWith("--"));
412 const folders = argv.filter((a) => !a.startsWith("--"));
413 const unknown = options.find((o) => o !== "--rollback" && o !== "--unchecked");
414 if (unknown !== undefined || folders.length > 1) {
415 console.error(
416 `usage: node client/${script} [folder] [--rollback] [--unchecked]${unknown ? ` (unknown option ${unknown})` : ""}`,
417 );
418 process.exit(2);
419 }
420 const target = resolve(folders[0] ?? defaultTarget);
421 try {
422 if (options.includes("--rollback")) {
423 const r = rollbackMod(spec, { target });
424 console.log(
425 `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.`,
426 );
427 return;
428 }
429 const unchecked = options.includes("--unchecked");
430 const r = installMod(spec, { target, check: unchecked ? () => undefined : checkWithClaude(spec) });
431 // Only for the real skills folder: an install to another folder leaves the old mod alone.
432 const retired = target === resolve(skillsFolder(spec.name)) ? retireOldMod(spec) : undefined;
433 if (retired) console.log(`Moved the old ${OLD_MOD_NAMES[spec.name]} mod out of the skills folder, to ${retired}.`);
434 if (!r.changed) {
435 console.log(`The ${spec.name} mod ${r.version} is already installed in ${target}; nothing changed.`);
436 return;
437 }
438 const kept = r.previous ? ` The one it replaced (${r.previous}) is kept; --rollback puts it back.` : "";
439 console.log(
440 `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.`,
441 );
442 } catch (err) {
443 console.error(
444 `The ${spec.name} mod was not ${options.includes("--rollback") ? "rolled back" : "installed"}: ${(err as Error).message}`,
445 );
446 process.exit(1);
447 }
450export interface ModInstall {
451 readonly name: string;
452 readonly folder: string;
453 /** Undefined when it isn't installed. */
454 readonly version: string | undefined;
455 /** When it was installed (mods installed before .avcs-install.json have none). */
456 readonly at: string | undefined;
457 /** What an install from this client would stamp now. */
458 readonly current: string;
461/** `avcs --version`: this client, and the mods installed on this machine, compared with this client's. */
462export function versionReport(env: Readonly<Record<string, string | undefined>>): {
463 text: string;
464 json: Record<string, unknown>;
465} {
466 const client = clientVersion();
467 const lines = [`abso ${client} (${clientPlace()})`];
468 const mods: ModInstall[] = [];
469 for (const [spec, installer] of [
470 [AVCS_MOD, "install-mod.ts"],
471 [VIEW_MOD, "install-view.ts"],
472 ] as const) {
473 const folder = skillsFolder(spec.name, env);
474 const field = (rel: string, key: string): string | undefined => {
475 try {
476 const value = (JSON.parse(readFileSync(at(folder, rel), "utf8")) as Record<string, unknown>)[key];
477 return typeof value === "string" ? value : undefined;
478 } catch {
479 return undefined;
480 }
481 };
482 const m: ModInstall = {
483 name: spec.name,
484 folder,
485 version: field(MANIFEST, "version"),
486 at: field(RECORD, "at"),
487 current: (() => {
488 try {
489 return versionFor(spec);
490 } catch {
491 return "not in this copy";
492 }
493 })(),
494 };
495 mods.push(m);
496 if (m.version === undefined) {
497 lines.push(`the ${m.name} mod: not installed (node client/${installer})`);
498 continue;
499 }
500 const when = m.at ? `, installed ${m.at.slice(0, 16).replace("T", " ")} UTC` : "";
501 const behind =
502 m.version === m.current ? "" : `; this client has ${m.current}: node client/${installer} installs it`;
503 lines.push(`the ${m.name} mod: ${m.version} in ${m.folder}${when}${behind}`);
504 }
505 return { text: lines.join("\n"), json: { client, folder: CLIENT_DIR, mods } };
508/**
509 * For `abso status` (abso issue 41: every chat ran a mod a day behind main,
510 * and only `--version` would have said so): each installed mod this client
511 * would install differently. Says nothing unless this client knows its mod's
512 * commit (a git checkout, as the shared one is) and the installed one has one.
513 */
514export function modsBehindText(env: Readonly<Record<string, string | undefined>>): string[] {
515 const installers: Record<string, string> = { [AVCS_MOD.name]: "install-mod.ts", [VIEW_MOD.name]: "install-view.ts" };
516 return (versionReport(env).json.mods as ModInstall[])
517 .filter((m) => m.version?.includes("+") && /\+[0-9a-f]{7}$/.test(m.current) && m.version !== m.current)
518 .map(
519 (m) =>
520 `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).`,
521 );