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/launch.mjs?draft=login-timeout&format=json
254 linesspeed 100%0 versions changed it
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.
23import { execFileSync, spawn } from "node:child_process";
24import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
25import { createRequire } from "node:module";
26import { homedir } from "node:os";
27import { dirname, join, resolve } from "node:path";
28import { fileURLToPath, pathToFileURL } from "node:url";
30const repo = dirname(dirname(fileURLToPath(import.meta.url)));
31const state = join(homedir(), ".abso");
32const stamp = join(state, "client-update.stamp");
33const every = 5 * 60 * 1000;
34const bundle = join(repo, "client", "dist", "abso.mjs");
35const bundleCommit = `${bundle}.commit`;
36/** Set on the background step's own node, which updates the checkout and exits. */
37const 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. */
39const STARTED = "__absoBundleStarted";
41/**
42 * The checkout's git folders: its own (HEAD) and the shared one (refs, info/exclude). They are the same
43 * folder in a plain clone; in a worktree .git is a file naming its own folder, which names the shared one.
44 */
45function gitDirs(root = repo) {
46 const dot = join(root, ".git");
47 try {
48 if (statSync(dot).isDirectory()) return { own: dot, common: dot };
49 const own = resolve(
50 root,
51 readFileSync(dot, "utf8")
52 .trim()
53 .replace(/^gitdir:\s*/, ""),
54 );
55 let common = own;
56 try {
57 common = resolve(own, readFileSync(join(own, "commondir"), "utf8").trim());
58 } catch {}
59 return { own, common };
60 } catch {
61 return undefined;
62 }
65/** The checkout's commit, read from .git without running git; undefined if it can't be read. */
66function headCommit(root = repo) {
67 const dirs = gitDirs(root);
68 if (!dirs) return undefined;
69 try {
70 const head = readFileSync(join(dirs.own, "HEAD"), "utf8").trim();
71 if (!head.startsWith("ref:")) return head;
72 const ref = head.slice(4).trim();
73 for (const dir of [dirs.own, dirs.common]) {
74 try {
75 return readFileSync(join(dir, ...ref.split("/")), "utf8").trim();
76 } catch {}
77 }
78 const line = readFileSync(join(dirs.common, "packed-refs"), "utf8")
79 .split("\n")
80 .find((l) => l.endsWith(` ${ref}`));
81 return line?.split(" ")[0];
82 } catch {
83 return undefined;
84 }
87/**
88 * Runs fn under a lock folder, or not at all when another run holds it. A lock older than 10 minutes is a
89 * dead run's: it is renamed aside before it's removed, so of two runs that find it stale only one takes it
90 * over, and one that renamed away a lock taken over a moment ago puts it back.
91 */
92function locked(lock, fn) {
93 const stale = (path) => Date.now() - statSync(path).mtimeMs > 10 * 60 * 1000;
94 try {
95 if (stale(lock)) {
96 const aside = `${lock}.${process.pid}.stale`;
97 renameSync(lock, aside);
98 if (stale(aside)) rmSync(aside, { recursive: true, force: true });
99 else {
100 renameSync(aside, lock);
101 return;
102 }
103 }
104 } catch {}
105 try {
106 mkdirSync(lock);
107 } catch {
108 return;
109 }
110 try {
111 fn();
112 } finally {
113 rmSync(lock, { recursive: true, force: true });
114 }
117/** One line in the launcher's log, never on the command's own output. */
118function note(text) {
119 try {
120 mkdirSync(state, { recursive: true });
121 appendFileSync(join(state, "launcher.log"), `${new Date().toISOString()} abso launch: ${text}\n`);
122 } catch {}
125/**
126 * The background step, one at a time under a lock (a second one finds it taken and exits): fast-forward,
127 * install when the lock file moved, then the bundle.
128 */
129function update() {
130 const git = (...a) => execFileSync("git", ["-C", repo, ...a], { encoding: "utf8", windowsHide: true });
131 mkdirSync(state, { recursive: true });
132 locked(join(state, "client-update.lock"), () => {
133 try {
134 if (git("branch", "--show-current").trim() === "main") {
135 const before = git("rev-parse", "HEAD").trim();
136 git("fetch", "-q", "origin", "main");
137 git("merge", "-q", "--ff-only", "origin/main");
138 if (git("diff", "--name-only", before, "HEAD", "--", "package-lock.json").trim())
139 execFileSync("npm", ["install", "--no-audit", "--no-fund"], {
140 cwd: repo,
141 stdio: "ignore",
142 windowsHide: true,
143 shell: true,
144 });
145 }
146 } catch {}
147 try {
148 build(git("rev-parse", "HEAD").trim());
149 } catch (e) {
150 note(`the bundle wasn't built (${String(e?.message).split("\n")[0]}); client/abso.ts runs until it is`);
151 }
152 });
155/** Builds the bundle for this commit, unless it's already current or the checkout has no esbuild. */
156function build(head) {
157 try {
158 if (readFileSync(bundleCommit, "utf8").trim() === head) return;
159 } catch {}
160 const require = createRequire(import.meta.url);
161 let esbuild;
162 try {
163 esbuild = require(require.resolve("esbuild", { paths: [join(repo, "worker"), repo] }));
164 } catch {
165 return;
166 }
167 const exclude = join(gitDirs()?.common ?? join(repo, ".git"), "info", "exclude");
168 try {
169 if (!readFileSync(exclude, "utf8").split(/\r?\n/).includes("client/dist/"))
170 appendFileSync(exclude, "\nclient/dist/\n");
171 } catch {}
172 mkdirSync(dirname(bundle), { recursive: true });
173 const tmp = bundle.replace(/\.mjs$/, `.${process.pid}.tmp.mjs`);
174 try {
175 esbuild.buildSync({
176 entryPoints: [join(repo, "client", "abso.ts")],
177 bundle: true,
178 platform: "node",
179 format: "esm",
180 target: "node24",
181 outfile: tmp,
182 logLevel: "silent",
183 // A bundled CommonJS package (yaml) calls require("process") lazily, which an ES module
184 // bundle can't do without a real require. The flag says the bundle started running.
185 banner: {
186 js: `globalThis.${STARTED} = true; import { createRequire as __absoCreateRequire } from "node:module"; const require = __absoCreateRequire(import.meta.url);`,
187 },
188 });
189 const from = createRequire(bundle);
190 for (const m of readFileSync(tmp, "utf8").matchAll(/__require\("([^"]+)"\)/g)) from.resolve(m[1]);
191 execFileSync(process.execPath, [tmp, "--version"], { cwd: repo, stdio: "ignore", windowsHide: true });
192 renameSync(tmp, bundle);
193 writeFileSync(bundleCommit, `${head}\n`);
194 } finally {
195 rmSync(tmp, { force: true });
196 }
199/** Runs client/abso.ts in a second node, and exits with its code. */
200function runTs() {
201 const child = spawn(process.execPath, [join(repo, "client", "abso.ts"), ...process.argv.slice(2)], {
202 stdio: "inherit",
203 });
204 child.on("exit", (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
207/** Starts the background step when it's due: every 5 minutes, or within 30 seconds of a stale bundle. */
208function maybeUpdate(fresh) {
209 try {
210 let last = 0;
211 try {
212 last = statSync(stamp).mtimeMs;
213 } catch {}
214 if (Date.now() - last <= (fresh ? every : 30_000)) return;
215 mkdirSync(state, { recursive: true });
216 writeFileSync(stamp, `${new Date().toISOString()}\n`);
217 spawn(process.execPath, [fileURLToPath(import.meta.url)], {
218 detached: true,
219 stdio: "ignore",
220 windowsHide: true,
221 env: { ...process.env, [UPDATE]: "1" },
222 }).unref();
223 } catch {}
226/** The command: the bundle when it matches the checkout, else client/abso.ts. */
227async function run() {
228 const head = headCommit();
229 let fresh = false;
230 try {
231 fresh = head !== undefined && readFileSync(bundleCommit, "utf8").trim() === head;
232 } catch {}
233 maybeUpdate(fresh);
234 if (!fresh) return runTs();
235 // In this process: the client reads its arguments from process.argv, as if run as `node client/dist/abso.mjs`.
236 const args = process.argv;
237 process.argv = [args[0], bundle, ...args.slice(2)];
238 try {
239 await import(pathToFileURL(bundle).href);
240 } catch (e) {
241 // Only a bundle that never started falls back: one that can't be found or parsed, or imports
242 // something missing. Anything else came from the command itself, which the .ts would repeat.
243 const code = e?.code;
244 const loading =
245 e instanceof SyntaxError || code === "ERR_MODULE_NOT_FOUND" || code === "ERR_UNSUPPORTED_ESM_URL_SCHEME";
246 if (!loading || globalThis[STARTED] === true) throw e;
247 note(`the bundle didn't load (${code ?? e?.name}: ${String(e?.message).split("\n")[0]}), ran client/abso.ts`);
248 process.argv = args;
249 runTs();
250 }
253if (process.env[UPDATE] === "1") update();
254else await run();