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

Versions 37 to 38

Compare

+214 −0 in 1 place
new file, 214 lines
1+// Runs abso from a git checkout of it and keeps that checkout current.
2+//
3+// Point a command at this file (node <checkout>/client/launch.mjs <args>) and it:
4+// - runs the client: a plain-JS bundle of it in this process when one matches the checkout's commit,
5+// otherwise client/abso.ts in a second node. Node strips types from every client file on every run,
6+// so the bundle starts several times faster;
7+// - at most every 5 minutes, and within 30 seconds of a stale bundle, starts a background step that
8+// fast-forwards the checkout (on main only), runs npm install when package-lock.json changed, and
9+// builds the bundle. That step never blocks or fails the command, and only one runs at a time.
10+//
11+// stdin, stdout, stderr, the arguments and the exit code pass through untouched: the exit codes carry
12+// meaning (2 refused, 3 still queued). The launcher's own notices go only to ~/.abso/launcher.log.
13+//
14+// The bundle is client/dist/abso.mjs, with the commit it was built from in client/dist/abso.mjs.commit.
15+// It sits one folder under client/, so the client's own folder (client-version.ts) is still client/.
16+// It is built with esbuild when the checkout has it (in worker/ or at the root): bundled, for node24,
17+// as an ES module, with no build commit stamped in, since a stamped client calls itself a downloaded
18+// copy. It is built to a temporary file and renamed into place, and marked current only after every
19+// require left in it resolves and it runs --version. If it still fails to load, the same run falls
20+// back to client/abso.ts and writes one line to the log, so edit hooks keep recording.
21+//
22+// Plain JS on purpose: this file is loaded on every command, before any bundle.
23+import { execFileSync, spawn } from "node:child_process";
24+import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
25+import { createRequire } from "node:module";
26+import { homedir } from "node:os";
27+import { dirname, join } from "node:path";
28+import { fileURLToPath, pathToFileURL } from "node:url";
30+const repo = dirname(dirname(fileURLToPath(import.meta.url)));
31+const state = join(homedir(), ".abso");
32+const stamp = join(state, "client-update.stamp");
33+const every = 5 * 60 * 1000;
34+const bundle = join(repo, "client", "dist", "abso.mjs");
35+const bundleCommit = `${bundle}.commit`;
36+/** Set on the background step's own node, which updates the checkout and exits. */
37+const UPDATE = "ABSO_LAUNCH_UPDATE";
38+/** Set by the bundle's first line: an error after it came from the command, so it's never run again. */
39+const STARTED = "__absoBundleStarted";
41+/** The checkout's commit, read from .git without running git; undefined if it can't be read. */
42+function headCommit(root = repo) {
43+ try {
44+ const head = readFileSync(join(root, ".git", "HEAD"), "utf8").trim();
45+ if (!head.startsWith("ref:")) return head;
46+ const ref = head.slice(4).trim();
47+ try {
48+ return readFileSync(join(root, ".git", ...ref.split("/")), "utf8").trim();
49+ } catch {
50+ const line = readFileSync(join(root, ".git", "packed-refs"), "utf8")
51+ .split("\n")
52+ .find((l) => l.endsWith(` ${ref}`));
53+ return line?.split(" ")[0];
54+ }
55+ } catch {
56+ return undefined;
57+ }
58+}
60+/** Runs fn under a lock folder; a lock older than 10 minutes is a dead run's and is cleared. */
61+function locked(lock, fn) {
62+ try {
63+ if (Date.now() - statSync(lock).mtimeMs > 10 * 60 * 1000) rmSync(lock, { recursive: true, force: true });
64+ } catch {}
65+ try {
66+ mkdirSync(lock);
67+ } catch {
68+ return;
69+ }
70+ try {
71+ fn();
72+ } finally {
73+ rmSync(lock, { recursive: true, force: true });
74+ }
75+}
77+/** One line in the launcher's log, never on the command's own output. */
78+function note(text) {
79+ try {
80+ mkdirSync(state, { recursive: true });
81+ appendFileSync(join(state, "launcher.log"), `${new Date().toISOString()} abso launch: ${text}\n`);
82+ } catch {}
83+}
85+/**
86+ * The background step, one at a time under a lock (a second one finds it taken and exits): fast-forward,
87+ * install when the lock file moved, then the bundle.
88+ */
89+function update() {
90+ const git = (...a) => execFileSync("git", ["-C", repo, ...a], { encoding: "utf8", windowsHide: true });
91+ mkdirSync(state, { recursive: true });
92+ locked(join(state, "client-update.lock"), () => {
93+ try {
94+ if (git("branch", "--show-current").trim() === "main") {
95+ const before = git("rev-parse", "HEAD").trim();
96+ git("fetch", "-q", "origin", "main");
97+ git("merge", "-q", "--ff-only", "origin/main");
98+ if (git("diff", "--name-only", before, "HEAD", "--", "package-lock.json").trim())
99+ execFileSync("npm", ["install", "--no-audit", "--no-fund"], {
100+ cwd: repo,
101+ stdio: "ignore",
102+ windowsHide: true,
103+ shell: true,
104+ });
105+ }
106+ } catch {}
107+ try {
108+ build(git("rev-parse", "HEAD").trim());
109+ } catch (e) {
110+ note(`the bundle wasn't built (${String(e?.message).split("\n")[0]}); client/abso.ts runs until it is`);
111+ }
112+ });
113+}
115+/** Builds the bundle for this commit, unless it's already current or the checkout has no esbuild. */
116+function build(head) {
117+ try {
118+ if (readFileSync(bundleCommit, "utf8").trim() === head) return;
119+ } catch {}
120+ const require = createRequire(import.meta.url);
121+ let esbuild;
122+ try {
123+ esbuild = require(require.resolve("esbuild", { paths: [join(repo, "worker"), repo] }));
124+ } catch {
125+ return;
126+ }
127+ const exclude = join(repo, ".git", "info", "exclude");
128+ try {
129+ if (!readFileSync(exclude, "utf8").split(/\r?\n/).includes("client/dist/"))
130+ appendFileSync(exclude, "\nclient/dist/\n");
131+ } catch {}
132+ mkdirSync(dirname(bundle), { recursive: true });
133+ const tmp = bundle.replace(/\.mjs$/, `.${process.pid}.tmp.mjs`);
134+ try {
135+ esbuild.buildSync({
136+ entryPoints: [join(repo, "client", "abso.ts")],
137+ bundle: true,
138+ platform: "node",
139+ format: "esm",
140+ target: "node24",
141+ outfile: tmp,
142+ logLevel: "silent",
143+ // A bundled CommonJS package (yaml) calls require("process") lazily, which an ES module
144+ // bundle can't do without a real require. The flag says the bundle started running.
145+ banner: {
146+ js: `globalThis.${STARTED} = true; import { createRequire as __absoCreateRequire } from "node:module"; const require = __absoCreateRequire(import.meta.url);`,
147+ },
148+ });
149+ const from = createRequire(bundle);
150+ for (const m of readFileSync(tmp, "utf8").matchAll(/__require\("([^"]+)"\)/g)) from.resolve(m[1]);
151+ execFileSync(process.execPath, [tmp, "--version"], { cwd: repo, stdio: "ignore", windowsHide: true });
152+ renameSync(tmp, bundle);
153+ writeFileSync(bundleCommit, `${head}\n`);
154+ } finally {
155+ rmSync(tmp, { force: true });
156+ }
157+}
159+/** Runs client/abso.ts in a second node, and exits with its code. */
160+function runTs() {
161+ const child = spawn(process.execPath, [join(repo, "client", "abso.ts"), ...process.argv.slice(2)], {
162+ stdio: "inherit",
163+ });
164+ child.on("exit", (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
165+}
167+/** Starts the background step when it's due: every 5 minutes, or within 30 seconds of a stale bundle. */
168+function maybeUpdate(fresh) {
169+ try {
170+ let last = 0;
171+ try {
172+ last = statSync(stamp).mtimeMs;
173+ } catch {}
174+ if (Date.now() - last <= (fresh ? every : 30_000)) return;
175+ mkdirSync(state, { recursive: true });
176+ writeFileSync(stamp, `${new Date().toISOString()}\n`);
177+ spawn(process.execPath, [fileURLToPath(import.meta.url)], {
178+ detached: true,
179+ stdio: "ignore",
180+ windowsHide: true,
181+ env: { ...process.env, [UPDATE]: "1" },
182+ }).unref();
183+ } catch {}
184+}
186+/** The command: the bundle when it matches the checkout, else client/abso.ts. */
187+async function run() {
188+ const head = headCommit();
189+ let fresh = false;
190+ try {
191+ fresh = head !== undefined && readFileSync(bundleCommit, "utf8").trim() === head;
192+ } catch {}
193+ maybeUpdate(fresh);
194+ if (!fresh) return runTs();
195+ // In this process: the client reads its arguments from process.argv, as if run as `node client/dist/abso.mjs`.
196+ const args = process.argv;
197+ process.argv = [args[0], bundle, ...args.slice(2)];
198+ try {
199+ await import(pathToFileURL(bundle).href);
200+ } catch (e) {
201+ // Only a bundle that never started falls back: one that can't be found or parsed, or imports
202+ // something missing. Anything else came from the command itself, which the .ts would repeat.
203+ const code = e?.code;
204+ const loading =
205+ e instanceof SyntaxError || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_UNSUPPORTED_ESM_URL_SCHEME";
206+ if (!loading || globalThis[STARTED] === true) throw e;
207+ note(`the bundle didn't load (${code ?? e?.name}: ${String(e?.message).split("\n")[0]}), ran client/abso.ts`);
208+ process.argv = args;
209+ runTs();
210+ }
211+}
213+if (process.env[UPDATE] === "1") update();
214+else await run();
MCP
compare on this site's /mcp
CLI
abso diff 37 38 client/launch.mjs --json
JSON
/christopher/abso-core/compare/37..38?file=client%2Flaunch.mjs&format=json