- 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=293&format=json
611 linesFirst import 79% · speed 10% · pinch 7% · review 5%Last change pinch in version 293, 7 versions changed it
You're reading version 293. The newest is 318, and no version 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-Abso-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 { builtCopy, CLIENT_DIR, clientPlace, clientVersion, headCommit } 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 /** For tests: the command stamped as HOOK_COMMAND, instead of this client's own `abso hook`. */
98 readonly hookCommand?: readonly string[];
99}
101const RECORD = ".avcs-install.json";
102const LOCK = ".avcs-install.lock";
103const MANIFEST = ".claude-plugin/plugin.json";
104const STAMP_FILE = "hooks/stamp.ts";
105/** A lock older than this was left by an install that died. */
106const STALE_LOCK_MS = 10 * 60_000;
108const at = (dir: string, rel: string, suffix = "") => join(dir, ...rel.split("/")) + suffix;
110/** The abso mod: what the hook imports first, plugin.json last. src/core.ts is the only client file it imports. */
111export const AVCS_MOD: ModSpec = {
112 name: "abso-hooks",
113 from: CLIENT_DIR,
114 files: ["src/core.ts", "hooks/stamp.ts", "hooks/register.ts", "hooks/hooks.json", ".claude-plugin/plugin.json"],
115 test: "hooks/register.test.ts",
116};
118/** The abso-view mod (#12), from client/view. */
119export const VIEW_MOD: ModSpec = {
120 name: "abso-view",
121 from: join(CLIENT_DIR, "view"),
122 files: ["types/index.d.ts", "hooks/stamp.ts", "hooks/register.tsx", "hooks/hooks.json", ".claude-plugin/plugin.json"],
123 test: "hooks/register.test.ts",
124};
126/** The skills folders the mods had before the rename; an install moves them out of the way (see retireOldMod). */
127export const OLD_MOD_NAMES: Readonly<Record<string, string>> = { "abso-hooks": "avcs", "abso-view": "avcs-view" };
129/** Where Claude Code's skills folder keeps a mod. */
130export const skillsFolder = (name: string, env: Readonly<Record<string, string | undefined>> = process.env) =>
131 join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "skills", name);
133export const modInstalled = (env: Readonly<Record<string, string | undefined>> = process.env) =>
134 existsSync(at(skillsFolder(AVCS_MOD.name, env), MANIFEST)) ||
135 existsSync(at(skillsFolder(OLD_MOD_NAMES[AVCS_MOD.name]!, env), MANIFEST));
137/** Whether the installed abso mod hands a local project's edits to abso hook: it was installed with a HOOK_COMMAND. */
138export function modHandsLocal(env: Readonly<Record<string, string | undefined>> = process.env): boolean {
139 try {
140 return /HOOK_COMMAND[^=\n]*=\s*\[/.test(readFileSync(at(skillsFolder(AVCS_MOD.name, env), STAMP_FILE), "utf8"));
141 } catch {
142 return false;
143 }
144}
146/**
147 * After the new mod is in, the folder it replaces (skills/avcs, skills/avcs-view) would load beside it, so it
148 * is moved, not deleted, to ~/.abso/retired-mods/<name>-<stamp>. Returns where it went, or undefined when there was none.
149 */
150export function retireOldMod(
151 spec: ModSpec,
152 env: Readonly<Record<string, string | undefined>> = process.env,
153 now: Date = new Date(),
154): string | undefined {
155 const old = OLD_MOD_NAMES[spec.name];
156 if (old === undefined) return undefined;
157 const from = skillsFolder(old, env);
158 if (!existsSync(from)) return undefined;
159 const to = join(homedir(), ".abso", "retired-mods", `${old}-${now.toISOString().replace(/[:.]/g, "-")}`);
160 mkdirSync(dirname(to), { recursive: true });
161 renameRetrying(from, to);
162 return to;
163}
165/** 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). */
166export function versionFor(spec: ModSpec, commit?: string | null): string {
167 const manifest = JSON.parse(readFileSync(at(spec.from, MANIFEST), "utf8")) as { version?: unknown };
168 const base = String(manifest.version ?? "0.0.0").split("+")[0]!;
169 const c = commit === undefined ? modCommit(spec) : commit;
170 return c ? `${base}+${c}` : base;
171}
173function modCommit(spec: ModSpec): string | null {
174 const git = (...args: string[]) => spawnSync("git", ["-C", spec.from, ...args], { encoding: "utf8" });
175 const last = git("log", "-1", "--format=%H", "--", ...spec.files);
176 if (last.status !== 0 || !/^[0-9a-f]{40}/.test(last.stdout)) return null;
177 const changed = git("status", "--porcelain", "--", ...spec.files).stdout.trim() !== "";
178 return `${last.stdout.slice(0, 7)}${changed ? ".dirty" : ""}`;
179}
181/** A file changed this close to when an answer was kept can't be told apart from one changed just after it. */
182const RACY_MS = 2_000;
184interface KeptModCommit {
185 readonly head: string;
186 readonly files: readonly string[];
187 readonly at: number;
188 readonly commit: string | null;
189}
191/**
192 * modCommit for the version report, which `abso status` asks on every run: it runs git twice per mod, so
193 * the answer is kept in ~/.abso/mod-commits.json. A kept answer holds while the checkout's commit (read
194 * from .git, without git) and each of the mod's files (size, modified time, inode) are as they were, and
195 * every file was changed clearly before the answer was kept; anything else asks git again. Outside a git
196 * checkout there is no commit, and git isn't run at all.
197 */
198export function keptModCommit(spec: ModSpec, home: string = homedir()): string | null {
199 const head = headCommit(spec.from);
200 if (head === undefined) return null;
201 const at = Date.now();
202 const files = spec.files.map((rel) => {
203 try {
204 const s = statSync(join(spec.from, ...rel.split("/")));
205 return `${s.size}:${s.mtimeMs}:${s.ino}`;
206 } catch {
207 return "-";
208 }
209 });
210 const newest = Math.max(...files.map((f) => (f === "-" ? 0 : Number(f.split(":")[1]))));
211 const path = join(home, ".abso", "mod-commits.json");
212 const key = `${resolve(spec.from)}|${spec.files.join("|")}`;
213 let kept: Record<string, KeptModCommit> = {};
214 try {
215 const parsed = JSON.parse(readFileSync(path, "utf8")) as { format?: unknown; mods?: unknown };
216 if (parsed.format === 1 && typeof parsed.mods === "object" && parsed.mods !== null)
217 kept = parsed.mods as Record<string, KeptModCommit>;
218 } catch {}
219 const was = kept[key];
220 if (
221 was !== undefined &&
222 was.head === head &&
223 Array.isArray(was.files) &&
224 was.files.join() === files.join() &&
225 newest < was.at - RACY_MS
226 )
227 return was.commit;
228 const commit = modCommit(spec);
229 try {
230 mkdirSync(dirname(path), { recursive: true });
231 const next = `${path}.${process.pid}.tmp`;
232 writeFileSync(next, JSON.stringify({ format: 1, mods: { ...kept, [key]: { head, files, at, commit } } }));
233 renameSync(next, path);
234 } catch {
235 // Best effort: the next run asks git again.
236 }
237 return commit;
238}
240/** The command that runs this checkout's `abso hook`: what the mod hands a local project's edits to. */
241export const hookCommand = (): readonly string[] => [process.execPath, join(CLIENT_DIR, "abso.ts"), "hook"];
243/** The files to install, stamped with `version` (and HOOK_COMMAND, where a stamp.ts has it), in install order. */
244function filesFor(spec: ModSpec, version: string, hook: readonly string[] = hookCommand()): Map<string, Buffer> {
245 if (!/^[\w.+-]+$/.test(version)) throw new Error(`can't stamp the version ${JSON.stringify(version)}`);
246 const out = new Map<string, Buffer>();
247 for (const rel of spec.files) {
248 let data = readFileSync(at(spec.from, rel));
249 if (rel === MANIFEST) {
250 const manifest = JSON.parse(data.toString("utf8")) as Record<string, unknown>;
251 data = Buffer.from(`${JSON.stringify({ ...manifest, version }, null, 2)}\n`);
252 } else if (rel === STAMP_FILE) {
253 const text = data.toString("utf8");
254 const stamped = text.replace(/(STAMP[^=\n]*=\s*)undefined/, `$1'${version}'`);
255 if (stamped === text) throw new Error(`${rel} has no "STAMP ... = undefined" line to stamp`);
256 data = Buffer.from(
257 stamped.replace(/(HOOK_COMMAND[^=\n]*=\s*)undefined/, (_, head: string) => head + JSON.stringify(hook)),
258 );
259 }
260 out.set(rel, data);
261 }
262 return out;
263}
265function readRecord(target: string): InstallRecord | undefined {
266 try {
267 return JSON.parse(readFileSync(join(target, RECORD), "utf8")) as InstallRecord;
268 } catch {
269 return undefined;
270 }
271}
273function writeRecord(target: string, record: InstallRecord): void {
274 writeFileSync(join(target, `${RECORD}.next`), `${JSON.stringify(record, null, 2)}\n`);
275 renameRetrying(join(target, `${RECORD}.next`), join(target, RECORD));
276}
278/** What is installed now. A folder from before .avcs-install.json: the spec's files that are there. */
279function installedNow(spec: ModSpec, target: string, record: InstallRecord | undefined): Install | undefined {
280 const files = (record?.files ?? spec.files).filter((rel) => existsSync(at(target, rel)));
281 if (files.length === 0) return undefined;
282 if (record) return { version: record.version, files, from: record.from, at: record.at };
283 let version = "unknown";
284 try {
285 version = String(
286 (JSON.parse(readFileSync(at(target, MANIFEST), "utf8")) as { version?: unknown }).version ?? version,
287 );
288 } catch {}
289 return { version, files, from: "unknown", at: "unknown" };
290}
292/** Sleeps without an event loop, between tries of a rename. */
293function pause(ms: number): void {
294 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
295}
297/** A rename, tried for about a second while Windows says another process has the file open. */
298function renameRetrying(from: string, to: string): void {
299 for (let i = 0; ; i++) {
300 try {
301 renameSync(from, to);
302 return;
303 } catch (err) {
304 const code = (err as NodeJS.ErrnoException).code ?? "";
305 if (i >= 20 || !["EPERM", "EBUSY", "EACCES"].includes(code)) throw err;
306 pause(50);
307 }
308 }
309}
311/** Holds the mod folder's lock while fn runs. */
312function locked<T>(target: string, fn: () => T): T {
313 const file = join(target, LOCK);
314 try {
315 if (Date.now() - statSync(file).mtimeMs > STALE_LOCK_MS) rmSync(file, { force: true });
316 } catch {}
317 try {
318 closeSync(openSync(file, "wx"));
319 } catch {
320 throw new Error(`another install is running in ${target} (it holds ${LOCK}; if none is, delete that file)`);
321 }
322 try {
323 return fn();
324 } finally {
325 rmSync(file, { force: true });
326 }
327}
329/**
330 * Moves `next` into place in the mod's folder, keeping the files that were
331 * there as .prev files. Each file goes in with a rename, in `next`'s order;
332 * if one fails, the ones already moved are put back and the error is thrown.
333 */
334function moveIn(
335 spec: ModSpec,
336 target: string,
337 next: ReadonlyMap<string, Buffer>,
338 install: Install,
339 rename: (from: string, to: string) => void,
340): Install | undefined {
341 const record = readRecord(target);
342 const current = installedNow(spec, target, record);
343 // After an install that stopped midway, the folder is a mix and the .prev files still hold the last whole install.
344 const prev = record?.moving ? record.prev : current;
345 if (!record?.moving) {
346 for (const rel of new Set([...(record?.prev?.files ?? []), ...(current?.files ?? [])]))
347 rmSync(at(target, rel, ".prev"), { force: true });
348 for (const rel of current?.files ?? []) copyFileSync(at(target, rel), at(target, rel, ".prev"));
349 }
350 const before: InstallRecord = { mod: spec.name, ...(current ?? install), ...(prev ? { prev } : {}) };
351 writeRecord(target, { ...before, moving: install.version });
353 const moved: string[] = [];
354 try {
355 for (const [rel, data] of next) {
356 mkdirSync(dirname(at(target, rel)), { recursive: true });
357 writeFileSync(at(target, rel, ".next"), data);
358 }
359 for (const rel of next.keys()) {
360 rename(at(target, rel, ".next"), at(target, rel));
361 moved.push(rel);
362 }
363 } catch (err) {
364 for (const rel of moved.reverse()) {
365 if (prev?.files.includes(rel)) {
366 copyFileSync(at(target, rel, ".prev"), at(target, rel, ".next"));
367 renameRetrying(at(target, rel, ".next"), at(target, rel));
368 } else {
369 rmSync(at(target, rel), { force: true });
370 }
371 }
372 for (const rel of next.keys()) rmSync(at(target, rel, ".next"), { force: true });
373 if (current) writeRecord(target, before);
374 else rmSync(join(target, RECORD), { force: true });
375 throw err;
376 }
377 // Files the old install had and this one doesn't.
378 for (const rel of current?.files ?? []) if (!next.has(rel)) rmSync(at(target, rel), { force: true });
379 writeRecord(target, { mod: spec.name, ...install, ...(prev ? { prev } : {}) });
380 return prev;
381}
383/** Whether the folder holds exactly `next`. */
384function holds(target: string, files: readonly string[], next: ReadonlyMap<string, Buffer>): boolean {
385 return (
386 files.length === next.size && files.every((rel) => next.get(rel)?.equals(readFileSync(at(target, rel))) ?? false)
387 );
388}
390/** Removes the folders a first install made, if they are empty. */
391function removeEmpty(target: string, files: Iterable<string>): void {
392 const dirs = new Set<string>();
393 for (const rel of files) for (let d = dirname(at(target, rel)); d.length > target.length; d = dirname(d)) dirs.add(d);
394 for (const d of [...dirs, target].sort((a, b) => b.length - a.length)) {
395 try {
396 rmdirSync(d);
397 } catch {}
398 }
399}
401/** Installs the mod from `spec.from` into `options.target` (see the top of this file). */
402export function installMod(spec: ModSpec, options: InstallOptions): Installed {
403 const target = resolve(options.target);
404 const version = versionFor(spec, options.commit);
405 const next = filesFor(spec, version, options.hookCommand);
406 const existed = existsSync(target);
407 mkdirSync(target, { recursive: true });
408 try {
409 return locked(target, () => {
410 const record = readRecord(target);
411 const current = installedNow(spec, target, record);
412 if (!record?.moving && current && holds(target, current.files, next)) {
413 return { changed: false, version, previous: record?.prev?.version, files: next.size };
414 }
415 const staged = mkdtempSync(join(tmpdir(), `${spec.name}-install-`));
416 try {
417 for (const [rel, data] of next) {
418 mkdirSync(dirname(at(staged, rel)), { recursive: true });
419 writeFileSync(at(staged, rel), data);
420 }
421 const why = options.check(staged);
422 if (why !== undefined) throw new Error(`the staged copy failed its check, so nothing was changed:\n${why}`);
423 } finally {
424 rmSync(staged, { recursive: true, force: true });
425 }
426 const install: Install = {
427 version,
428 files: [...next.keys()],
429 from: spec.from,
430 at: (options.now ?? new Date()).toISOString(),
431 };
432 const prev = moveIn(spec, target, next, install, options.rename ?? renameRetrying);
433 return { changed: true, version, previous: prev?.version, files: next.size };
434 });
435 } catch (err) {
436 // A first install that didn't happen leaves no folder behind.
437 if (!existed) removeEmpty(target, next.keys());
438 throw err;
439 }
440}
442/** Puts the install kept in the .prev files back; the one it replaces becomes the .prev one. */
443export function rollbackMod(spec: ModSpec, options: Pick<InstallOptions, "target" | "rename" | "now">): Installed {
444 const target = resolve(options.target);
445 if (!existsSync(target)) throw new Error(`nothing is installed in ${target}`);
446 return locked(target, () => {
447 const record = readRecord(target);
448 const prev = record?.prev;
449 if (!prev) throw new Error(`no earlier install is kept in ${target}`);
450 const missing = prev.files.filter((rel) => !existsSync(at(target, rel, ".prev")));
451 if (missing.length > 0)
452 throw new Error(
453 `the earlier install's ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} missing from ${target}`,
454 );
455 const next = new Map(prev.files.map((rel) => [rel, readFileSync(at(target, rel, ".prev"))]));
456 const kept = moveIn(spec, target, next, prev, options.rename ?? renameRetrying);
457 return { changed: true, version: prev.version, previous: kept?.version, files: next.size };
458 });
459}
461/** `claude plugin validate`, then the mod's own tests in Claude Code's plugin test kit, on a staged copy. */
462export function checkWithClaude(spec: ModSpec): (dir: string) => string | undefined {
463 // claude is a .cmd on Windows, so it runs through the shell; the folder is quoted.
464 const claude = (what: string, dir: string) =>
465 spawnSync(`claude plugin ${what} "${dir}"`, { shell: true, encoding: "utf8", timeout: 180_000 });
466 const tail = (r: { stdout: string; stderr: string }) =>
467 `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split("\n").slice(-15).join("\n");
468 return (dir) => {
469 const valid = claude("validate", dir);
470 if (valid.status !== 0) return `claude plugin validate failed (--unchecked skips the check):\n${tail(valid)}`;
471 if (spec.test === undefined) return undefined;
472 copyFileSync(at(spec.from, spec.test), at(dir, spec.test));
473 const tests = claude("test", dir);
474 if (tests.status !== 0) return `the mod's tests failed on the staged copy:\n${tail(tests)}`;
475 return undefined;
476 };
477}
479/** The installers' command line: [folder] [--rollback] [--unchecked]. */
480export function runInstaller(
481 spec: ModSpec,
482 script: string,
483 defaultTarget: string,
484 argv: readonly string[] = process.argv.slice(2),
485): void {
486 const options = argv.filter((a) => a.startsWith("--"));
487 const folders = argv.filter((a) => !a.startsWith("--"));
488 const unknown = options.find((o) => o !== "--rollback" && o !== "--unchecked");
489 if (unknown !== undefined || folders.length > 1) {
490 console.error(
491 `usage: node client/${script} [folder] [--rollback] [--unchecked]${unknown ? ` (unknown option ${unknown})` : ""}`,
492 );
493 process.exit(2);
494 }
495 const target = resolve(folders[0] ?? defaultTarget);
496 try {
497 if (options.includes("--rollback")) {
498 const r = rollbackMod(spec, { target });
499 console.log(
500 `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.`,
501 );
502 return;
503 }
504 const unchecked = options.includes("--unchecked");
505 const r = installMod(spec, { target, check: unchecked ? () => undefined : checkWithClaude(spec) });
506 // Only for the real skills folder: an install to another folder leaves the old mod alone.
507 const retired = target === resolve(skillsFolder(spec.name)) ? retireOldMod(spec) : undefined;
508 if (retired) console.log(`Moved the old ${OLD_MOD_NAMES[spec.name]} mod out of the skills folder, to ${retired}.`);
509 if (!r.changed) {
510 console.log(`The ${spec.name} mod ${r.version} is already installed in ${target}; nothing changed.`);
511 return;
512 }
513 const kept = r.previous ? ` The one it replaced (${r.previous}) is kept; --rollback puts it back.` : "";
514 console.log(
515 `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.`,
516 );
517 } catch (err) {
518 console.error(
519 `The ${spec.name} mod was not ${options.includes("--rollback") ? "rolled back" : "installed"}: ${(err as Error).message}`,
520 );
521 process.exit(1);
522 }
523}
525export interface ModInstall {
526 readonly name: string;
527 readonly folder: string;
528 /** Undefined when it isn't installed. */
529 readonly version: string | undefined;
530 /** When it was installed (mods installed before .avcs-install.json have none). */
531 readonly at: string | undefined;
532 /** What an install from this client would stamp now. */
533 readonly current: string;
534}
536/**
537 * The command that runs one of this client's installers (client/install-mod.ts or install-view.ts), by its full
538 * path. They are .ts files, which Node runs itself from 22.18, so on an older Node it says which one it needs.
539 */
540export function installerCommand(installer: string): string {
541 const command = `node ${join(CLIENT_DIR, installer)}`;
542 return (process.features as { typescript?: unknown }).typescript
543 ? command
544 : `${command} (with Node 22.18 or later, which runs .ts files; this is Node ${process.versions.node})`;
545}
547/** `abso --version`: this client, and the mods installed on this machine, compared with this client's. */
548export function versionReport(env: Readonly<Record<string, string | undefined>>): {
549 text: string;
550 json: Record<string, unknown>;
551} {
552 const client = clientVersion();
553 const lines = [`abso ${client} (${clientPlace()})`];
554 const mods: ModInstall[] = [];
555 for (const [spec, installer] of [
556 [AVCS_MOD, "install-mod.ts"],
557 [VIEW_MOD, "install-view.ts"],
558 ] as const) {
559 const folder = skillsFolder(spec.name, env);
560 const field = (rel: string, key: string): string | undefined => {
561 try {
562 const value = (JSON.parse(readFileSync(at(folder, rel), "utf8")) as Record<string, unknown>)[key];
563 return typeof value === "string" ? value : undefined;
564 } catch {
565 return undefined;
566 }
567 };
568 const m: ModInstall = {
569 name: spec.name,
570 folder,
571 version: field(MANIFEST, "version"),
572 at: field(RECORD, "at"),
573 current: (() => {
574 try {
575 return versionFor(spec, keptModCommit(spec));
576 } catch {
577 return "not in this copy";
578 }
579 })(),
580 };
581 mods.push(m);
582 // A built copy has no mod files to compare with or install from: it reports what is installed.
583 if (m.version === undefined) {
584 lines.push(`the ${m.name} mod: not installed${builtCopy() ? "" : ` (${installerCommand(installer)})`}`);
585 continue;
586 }
587 const when = m.at ? `, installed ${m.at.slice(0, 16).replace("T", " ")} UTC` : "";
588 const behind =
589 builtCopy() || m.version === m.current
590 ? ""
591 : `; this client has ${m.current}: ${installerCommand(installer)} installs it`;
592 lines.push(`the ${m.name} mod: ${m.version} in ${m.folder}${when}${behind}`);
593 }
594 return { text: lines.join("\n"), json: { client, folder: CLIENT_DIR, mods } };
595}
597/**
598 * For `abso status` (abso issue 41: every chat ran a mod a day behind main,
599 * and only `--version` would have said so): each installed mod this client
600 * would install differently. Says nothing unless this client knows its mod's
601 * commit (a git checkout, as the shared one is) and the installed one has one.
602 */
603export function modsBehindText(env: Readonly<Record<string, string | undefined>>): string[] {
604 const installers: Record<string, string> = { [AVCS_MOD.name]: "install-mod.ts", [VIEW_MOD.name]: "install-view.ts" };
605 return (versionReport(env).json.mods as ModInstall[])
606 .filter((m) => m.version?.includes("+") && /\+[0-9a-f]{7}$/.test(m.current) && m.version !== m.current)
607 .map(
608 (m) =>
609 `The ${m.name} mod installed on this machine is ${m.version}, and this client has ${m.current}: ${installerCommand(installers[m.name]!)} installs it (new chats load it).`,
610 );
611}