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/box-commands.ts?draft=login-timeout&format=json
624 linesFirst import 92% · review 6% · infra-split 1% · pinch 1% · trials 1%0 versions changed it
1// The commands that work in the agent's box: run, prep, bisect, serve, shot, fetch and logs.
2
3import { spawnSync } from "node:child_process";
4import { createHash } from "node:crypto";
5import { appendFileSync, readdirSync, readFileSync, statSync } from "node:fs";
6import { join, relative, resolve, sep } from "node:path";
7import { Api } from "./api.ts";
8import { bool, type Parsed, str, UsageError } from "./args.ts";
9import { globTest, snapshotAt, snapshotEntries } from "./at.ts";
10import { type Env, EXIT, type Output, open, plural } from "./command-env.ts";
11import { LISTED, recordFolder } from "./commands.ts";
12import { findRoot } from "./config.ts";
13import { fromEnv, withOldNames } from "./env-names.ts";
14import { fetchedText, fetchFromBox } from "./fetch.ts";
15import { absolute, isLocalOnly, loadIgnore, readText, walk, writeFileAtomic } from "./folder.ts";
16import { onDisk, PLAIN, readKnownModes } from "./modes.ts";
17import { unsafePath } from "./safety.ts";
18import { stateDir } from "./state-dir.ts";
19import { type TarEntry, tarGz } from "./tar.ts";
21/** One word for the box's shell (POSIX sh), quoted only when it needs it. */
22export function shellWord(word: string): string {
23 return /^[A-Za-z0-9_/.,:=+@%-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
26/**
27 * The command line `abso run` sends. After `--` the words are a program and
28 * its arguments, each quoted for the box's shell, so quotes, backslashes and
29 * regex text reach the program as typed. Without `--` they are a shell
30 * command, joined with spaces as before.
31 */
32export function runCommand(args: Parsed): string {
33 if (bool(args, "parallel")) {
34 if (args.dashed !== undefined)
35 throw new UsageError(
36 '--parallel takes each command as one quoted word: abso run --parallel "npm test" "node bench.js"',
37 );
38 return parallelScript(args.positionals);
39 }
40 if (args.dashed === 0) return args.positionals.map(shellWord).join(" ");
41 return args.positionals.join(" ");
44/**
45 * One sh script that runs the commands at once in the box (one upload, one
46 * run): every line a command prints gets its label, [1], [2], ..., stdout
47 * staying stdout and stderr staying stderr; then each command's exit code,
48 * and the script exits with the worst (highest) of them.
49 */
50export function parallelScript(commands: readonly string[]): string {
51 // awk, flushing every line, so each command's lines arrive as they are printed.
52 const tag = (n: number) => `awk '{ print "[${n}] " $0; fflush() }'`;
53 const out = ["d=$(mktemp -d)"];
54 commands.forEach((c, i) => out.push(`printf '[%s] %s\\n' ${i + 1} ${shellWord(c)}`));
55 commands.forEach((c, i) => {
56 const n = i + 1;
57 // The command's stderr goes through one awk to stderr, its stdout through another to stdout.
58 out.push(
59 `{ { { sh -c ${shellWord(c)}; echo $? > "$d/${n}"; } 2>&1 1>&3 3>&- | ${tag(n)} 1>&2; } 3>&1 | ${tag(n)}; } &`,
60 );
61 });
62 out.push("wait", "worst=0");
63 commands.forEach((c, i) => {
64 const n = i + 1;
65 out.push(
66 `c=$(cat "$d/${n}" 2>/dev/null || echo 1); printf '[%s] exit %s: %s\\n' ${n} "$c" ${shellWord(c)}; if [ "$c" -gt "$worst" ]; then worst=$c; fi`,
67 );
68 });
69 out.push('rm -rf "$d"', "exit $worst");
70 return out.join("\n");
73/**
74 * abso run --with <box path>=<local path>[,...]: files for one run only (#37,
75 * for A/B runs), sent with the folder and never written to it or
76 * recorded. A local folder sends every file under it. Text goes with LF line
77 * endings, as the folder's files do.
78 */
79export function withEntries(spec: string, cwd: string): TarEntry[] {
80 const out: TarEntry[] = [];
81 for (const pair of spec
82 .split(",")
83 .map((p) => p.trim())
84 .filter((p) => p !== "")) {
85 const eq = pair.indexOf("=");
86 if (eq <= 0 || eq === pair.length - 1)
87 throw new UsageError(
88 `--with takes <box path>=<local path> (got ${JSON.stringify(pair)}), like --with _ab/run.ts=../scratch/run.ts`,
89 );
90 const box = pair.slice(0, eq).replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
91 const local = resolve(cwd, pair.slice(eq + 1));
92 const why = unsafePath(box) ?? (isLocalOnly(box) ? "it is under .git, .claude, .abso or node_modules" : undefined);
93 if (why !== undefined) throw new UsageError(`--with can't put a file at ${JSON.stringify(box)}: ${why}`);
94 let st;
95 try {
96 st = statSync(local);
97 } catch {
98 throw new UsageError(`--with: ${local} doesn't exist`);
99 }
100 const files = st.isDirectory()
101 ? readdirSync(local, { recursive: true, withFileTypes: true })
102 .filter((e) => e.isFile())
103 .map((e) => relative(local, join(e.parentPath, e.name)).split(sep).join("/"))
104 .sort()
105 .map((rel) => [`${box}/${rel}`, join(local, rel)] as const)
106 : [[box, local] as const];
107 for (const [path, from] of files) {
108 const text = readText(from);
109 const data =
110 text !== undefined && text.includes("\r") ? Buffer.from(text.replace(/\r\n?/g, "\n")) : readFileSync(from);
111 const exec = (statSync(from).mode & 0o111) !== 0 || (data[0] === 0x23 && data[1] === 0x21);
112 out.push({ path, data, ...(exec ? { mode: 0o755 } : {}) });
113 }
114 }
115 if (out.length === 0) throw new UsageError("--with named no files");
116 return out;
119/** A word Git Bash made into a Windows path: W:/out, or --out=W:/out. */
120const DRIVE_PATH = /^((?:--?[\w.-]+=)?)([A-Za-z]:\/.*)$/;
122/** Git's cygpath: each Windows path back to the POSIX one Git Bash made it from, or undefined when it can't. */
123function cygpath(paths: readonly string[]): string[] | undefined {
124 const r = spawnSync("cygpath", ["-u", "--", ...paths], { encoding: "utf8" });
125 const lines = r.status === 0 ? r.stdout.split(/\r?\n/).filter((l) => l !== "") : [];
126 return lines.length === paths.length ? lines : undefined;
129/**
130 * Git Bash, every chat's Bash tool on Windows, rewrites a word that starts
131 * with / before abso sees it: /w/out arrives as W:/out, /tmp/x as
132 * C:/Users/.../Temp/x. No Windows path means anything in the Linux box, so
133 * under Git Bash (MSYSTEM set) such words go back to what was typed, by
134 * cygpath, which knows Git Bash's mounts. Without it, the run is refused.
135 */
136export function undoGitBashPaths(
137 words: readonly string[],
138 env: Readonly<Record<string, string | undefined>>,
139 toPosix: (paths: readonly string[]) => string[] | undefined = cygpath,
140): { words: string[]; undone: { from: string; to: string }[] } {
141 if (!env.MSYSTEM || env.MSYS_NO_PATHCONV) return { words: [...words], undone: [] };
142 const at = words
143 .map((w, i) => [i, DRIVE_PATH.exec(w)] as const)
144 .filter((m): m is readonly [number, RegExpExecArray] => m[1] !== null);
145 if (at.length === 0) return { words: [...words], undone: [] };
146 const back = toPosix(at.map(([, m]) => m[2]!));
147 if (back === undefined) {
148 throw new UsageError(
149 `Git Bash turned ${at.map(([i]) => words[i]).join(", ")} into Windows paths before abso saw them, and they mean nothing in the box. ` +
150 "Run it as MSYS_NO_PATHCONV=1 abso run -- ..., or write the path with two slashes (//w/out).",
151 );
152 }
153 const out = [...words];
154 const undone = at.map(([i, m], k) => {
155 out[i] = `${m[1]}${back[k]}`;
156 return { from: words[i]!, to: out[i]! };
157 });
158 return { words: out, undone };
161/** abso prep <command>: set up this agent's box once and keep the result as what it starts from (#37). --forget drops it. */
162export async function runPrep(args: Parsed, env: Env): Promise<Output> {
163 if (bool(args, "forget")) {
164 const { api } = open(env);
165 api.box = boxOf(args, env);
166 const forgot = await api.unprep();
167 rememberPrep(findRoot(env.cwd)!, api.box, null);
168 return {
169 text: forgot ? "Forgot the prep: the box starts from the plain image again." : "The box had no prep.",
170 json: { forgot },
171 };
172 }
173 if (args.positionals.length === 0)
174 throw new UsageError('give the setup command: abso prep "npm ci && npx playwright install chromium"');
175 return runRun(args, env, "prep");
178/**
179 * abso bisect [--good N] [--bad N] -- <check>: the first version of the folder's
180 * space where the check fails (#37). Each step is an abso run
181 * --at in the box. Without --good it walks back from --bad (newest by default)
182 * in doubling steps until a version passes, then halves the gap.
183 */
184export async function runBisect(args: Parsed, env: Env): Promise<Output> {
185 if (args.positionals.length === 0)
186 throw new UsageError("give the check: abso bisect [--good N] [--bad N] -- <program> <arg...>");
187 const num = (name: string): number | undefined => {
188 const raw = str(args, name);
189 if (raw === undefined) return undefined;
190 if (!/^\d+$/.test(raw)) throw new UsageError(`--${name} is a version number (got ${JSON.stringify(raw)})`);
191 return Number(raw);
192 };
193 const { api } = open(env);
194 const diff = await api.diff();
195 const where = { draft: diff.draft };
196 let bad = num("bad") ?? (await api.log(where, 1)).version;
197 let good = num("good");
198 if (good !== undefined && good >= bad) throw new UsageError(`--good (${good}) must be older than --bad (${bad})`);
199 const say = env.writeErr ?? env.write;
200 const quiet: Env = { ...env, write: () => {}, writeErr: () => {} };
201 const tried = new Map<number, number>();
202 // Exit 125 means the check can't judge that version (it doesn't build, say), as in git bisect run:
203 // it counts neither way. A box or server error throws and ends the bisect.
204 const SKIP = 125;
205 const test = async (v: number): Promise<"pass" | "fail" | "skip"> => {
206 let exit = tried.get(v);
207 if (exit === undefined) {
208 const flags = new Map(args.flags);
209 flags.set("at", String(v));
210 flags.delete("good");
211 flags.delete("bad");
212 exit = (await runRun({ ...args, flags }, { ...quiet, runKind: "bisect" })).exit ?? 0;
213 tried.set(v, exit);
214 say(
215 `abso bisect: version ${v} ${exit === 0 ? "passes" : exit === SKIP ? "can't be tested (exit 125); skipped" : `fails (exit ${exit})`}\n`,
216 );
217 }
218 return exit === 0 ? "pass" : exit === SKIP ? "skip" : "fail";
219 };
220 const first = await test(bad);
221 if (first === "pass")
222 return {
223 text: `Version ${bad} passes, so there's nothing to find. Give --bad <a version that fails>.`,
224 json: { firstBad: null, runs: tried.size },
225 };
226 if (first === "skip")
227 return {
228 exit: EXIT.refused,
229 text: `--bad ${bad} can't be tested (exit 125): give a version that fails.`,
230 json: { firstBad: null, runs: tried.size },
231 };
232 if (good !== undefined) {
233 const g = await test(good);
234 if (g !== "pass")
235 return {
236 exit: EXIT.refused,
237 text: `--good ${good} ${g === "skip" ? "can't be tested (exit 125)" : "fails too"}: give a version that passes.`,
238 json: { firstBad: null, runs: tried.size },
239 };
240 } else {
241 // Back from bad in doubling steps until one passes; a skipped version moves nothing.
242 for (let step = 1; good === undefined; step *= 2) {
243 const v = Math.max(0, bad - step);
244 const r = await test(v);
245 if (r === "pass") good = v;
246 else if (v === 0)
247 return {
248 exit: EXIT.refused,
249 text: "No version tried passes, back to version 0: there is no passing version to start from.",
250 json: { firstBad: null, runs: tried.size },
251 };
252 else if (r === "fail") bad = v;
253 }
254 }
255 // Halve the gap; a skipped middle tries its nearest untested neighbour inside the range.
256 const skipped = (v: number) => tried.get(v) === SKIP;
257 while (bad - good > 1) {
258 const mid = Math.floor((good + bad) / 2);
259 let pick: number | undefined;
260 for (let d = 0; pick === undefined && d < bad - good; d++) {
261 for (const c of d === 0 ? [mid] : [mid + d, mid - d]) {
262 if (c > good && c < bad && !skipped(c)) {
263 pick = c;
264 break;
265 }
266 }
267 }
268 if (pick === undefined) {
269 const space = diff.draft === null ? "shared" : `draft ${diff.draft}`;
270 return {
271 text: `The first failing version of ${space} is somewhere in ${good + 1}..${bad}: every version between ${good} (passes) and ${bad} (fails) was skipped (exit 125). ${plural(tried.size, "run")} in the box.`,
272 json: { firstBad: null, range: [good + 1, bad], lastGood: good, runs: tried.size },
273 };
274 }
275 const r = await test(pick);
276 if (r === "pass") good = pick;
277 else if (r === "fail") bad = pick;
278 }
279 const v = await api.show(bad, where);
280 const space = diff.draft === null ? "shared" : `draft ${diff.draft}`;
281 return {
282 text: [
283 `First failing version of ${space}: ${bad}, by ${v.agent}: ${v.message}`,
284 ` ${plural(v.files.length, "file")}: ${v.files.slice(0, LISTED).join(", ")}${v.files.length > LISTED ? `, and ${v.files.length - LISTED} more` : ""}`,
285 `Version ${good} passes. ${plural(tried.size, "run")} in the box. abso show ${bad} has its changes.`,
286 ].join("\n"),
287 json: { firstBad: bad, lastGood: good, agent: v.agent, message: v.message, files: v.files, runs: tried.size },
288 };
291export async function runRun(args: Parsed, env: Env, as: "run" | "prep" = "run"): Promise<Output> {
292 if (args.positionals.length === 0)
293 throw new UsageError("give the command to run: abso run <command>, or abso run -- <program> <arg...>");
294 // A glob before -- next to a list flag is a second value given the wrong way (#37: --fetch 'a' 'b' -- cmd ran "b"
295 // as the command, joined with the words after --, which lost their quoting).
296 // Once a plain word comes, run keeps the rest as typed, -- included; so the words before a literal -- are the suspects.
297 const before = args.dashed !== undefined ? args.dashed : args.positionals.indexOf("--");
298 if (before > 0) {
299 const listFlag = ["fetch", "files", "with"].find((f) => str(args, f) !== undefined);
300 const stray = args.positionals
301 .slice(0, before)
302 .filter((w) => /[*?[]/.test(w) || (listFlag === "with" && w.includes("=")));
303 if (listFlag !== undefined && stray.length > 0) {
304 throw new UsageError(
305 `${stray.join(" ")} came before -- but isn't part of the command: --${listFlag} takes several values in one argument, comma-separated: --${listFlag} '${[str(args, listFlag), ...stray].join(",")}'`,
306 );
307 }
308 }
309 // avcs's own lines (on stderr); --quiet drops them, and the box's stdout and stderr stay as they are (#37).
310 const notice = bool(args, "quiet") ? (_text: string): void => {} : (env.writeErr ?? env.write);
311 // What the box said about its prep (X-Abso-Prep): null when it has none.
312 let prepState: string | null | undefined;
313 const posix = undoGitBashPaths(args.positionals, env.env);
314 if (posix.undone.length > 0) {
315 args = { ...args, positionals: posix.words };
316 notice(
317 `abso: Git Bash rewrote ${posix.undone.map((u) => `${u.to} as ${u.from}`).join(", ")}; sending ${posix.undone.map((u) => u.to).join(", ")} to the box. (MSYS_NO_PATHCONV=1 stops Git Bash rewriting.)\n`,
318 );
319 }
320 const command = runCommand(args);
321 // The box's sh reads a quoted command once more: point at -- when the text holds what that trips on (Backtracker).
322 if (
323 args.dashed === undefined &&
324 !bool(args, "parallel") &&
325 (/\\/.test(command) || (/'/.test(command) && /"/.test(command)))
326 ) {
327 notice(
328 "abso: the box's sh reads this command again; if a \\, $ or quote comes out wrong, use abso run -- <program> <args...>, which passes each word as typed.\n",
329 );
330 }
331 // What the run log and --detach call it: the commands, not the script that runs them.
332 const named = bool(args, "parallel") ? `--parallel ${args.positionals.map(shellWord).join(" ")}` : command;
333 const fetchGlobs = (str(args, "fetch") ?? "")
334 .split(",")
335 .map((g) => g.trim())
336 .filter((g) => g !== "");
337 if (fetchGlobs.length > 0 && bool(args, "detach"))
338 throw new UsageError(
339 "--fetch waits for the run to end; with --detach, fetch later: abso logs <id>, then abso fetch <glob>",
340 );
341 const rawAt = str(args, "at");
342 const filesGlob = str(args, "files");
343 if (filesGlob !== undefined && rawAt === undefined)
344 throw new UsageError("--files takes old copies from a version: give it with --at <version>");
345 if (rawAt !== undefined && !/^\d+$/.test(rawAt))
346 throw new UsageError(`--at is a version number (got ${JSON.stringify(rawAt)})`);
347 const at = rawAt === undefined ? undefined : Number(rawAt);
348 const { root, config, api } = open(env);
349 api.box = boxOf(args, env);
350 // Stamp the run with what it runs: the draft as recorded, on which version of which space.
351 await recordFolder(root, api);
352 let stamp = await runStamp(root, config.agent, api);
353 let entries: TarEntry[] = [];
354 const knownModes = readKnownModes(root);
355 // --at without --files sends the version alone; the folder isn't read.
356 const folderFiles = at === undefined || filesGlob !== undefined ? walk(root, loadIgnore(root)) : [];
357 const toLf: string[] = [];
358 for (const rel of folderFiles) {
359 const path = absolute(root, rel);
360 const d = onDisk(path, knownModes.get(rel) ?? PLAIN);
361 if (d === undefined) continue;
362 if (d.link !== null) {
363 entries.push({ path: rel, data: new Uint8Array(0), link: d.link });
364 continue;
365 }
366 // Text goes as abso records it, with LF line endings: a CRLF script fails in the box's sh (#37).
367 const lf = d.text !== undefined && d.text.includes("\r") ? Buffer.from(d.text.replace(/\r\n?/g, "\n")) : undefined;
368 if (lf !== undefined) toLf.push(rel);
369 const data = lf ?? readFileSync(path);
370 // The bit from the disk, or (on Windows) from the server; a script with "#!" runs either way.
371 const script = data[0] === 0x23 && data[1] === 0x21;
372 entries.push({ path: rel, data, ...(d.exec || script ? { mode: 0o755 } : {}) });
373 }
374 if (toLf.length > 0) {
375 const named =
376 toLf.length <= LISTED ? toLf.join(", ") : `${toLf.slice(0, LISTED).join(", ")}, and ${toLf.length - LISTED} more`;
377 notice(
378 `abso: sent ${plural(toLf.length, "file")} with LF line endings, as abso records them; your folder has CRLF: ${named}.\n`,
379 );
380 }
381 if (at !== undefined) {
382 // A past version in the box; the folder's files stay as they are (Backtracker's bisect).
383 const snap = await snapshotAt(root, api, at);
384 const space = stamp.ABSO_SPACE === "shared" ? "shared" : `draft ${stamp.ABSO_SPACE}`;
385 if (filesGlob === undefined) {
386 entries = await snapshotEntries(api, snap);
387 stamp = { ...stamp, ABSO_VERSION: String(at), ABSO_DRAFT: "0", ABSO_DRAFT_HASH: "", ABSO_AT: String(at) };
388 notice(
389 `abso: running version ${at} of ${space} in the box (${plural(entries.length, "file")}); your folder is untouched.\n`,
390 );
391 } else {
392 const pick = globTest(filesGlob);
393 const old = await snapshotEntries(api, snap, pick);
394 const gone = entries.filter((e) => pick(e.path) && !old.some((o) => o.path === e.path)).map((e) => e.path);
395 entries = [...entries.filter((e) => !pick(e.path)), ...old].sort((a, b) => a.path.localeCompare(b.path));
396 stamp = { ...stamp, ABSO_AT: `${at} files ${filesGlob}` };
397 const said =
398 old.length === 0 && gone.length === 0
399 ? `no file matches ${filesGlob} in your folder or at version ${at}`
400 : `${plural(old.length, "file")} as at version ${at}: ${old.map((e) => e.path).join(", ")}${gone.length > 0 ? `; left out, not there at version ${at}: ${gone.join(", ")}` : ""}`;
401 notice(`abso: running your folder with ${said}. Your folder is untouched.\n`);
402 }
403 }
404 const withSpec = str(args, "with");
405 if (withSpec !== undefined) {
406 const extra = withEntries(withSpec, env.cwd);
407 const paths = new Set(extra.map((e) => e.path));
408 entries = [...entries.filter((e) => !paths.has(e.path)), ...extra].sort((a, b) => a.path.localeCompare(b.path));
409 const named =
410 extra.length <= LISTED
411 ? extra.map((e) => e.path).join(", ")
412 : `${extra
413 .slice(0, LISTED)
414 .map((e) => e.path)
415 .join(", ")}, and ${extra.length - LISTED} more`;
416 notice(
417 `abso: adding ${plural(extra.length, "file")} for this run only: ${named}. They are not in your folder and are not recorded.\n`,
418 );
419 }
420 if (as === "prep") {
421 // The box keeps what the command leaves (node_modules, ~/.cache, /tmp) as what it starts from (#37).
422 notice(
423 "abso: preparing the box from a fresh image: this takes as long as the command, then a few seconds to save.\n",
424 );
425 const p = await api.prep(command, tarGz(entries));
426 if (p.saved !== true) {
427 return {
428 text: `Prep failed (exit ${p.exitCode ?? "?"}); the box is as it was. Its output ends:\n${String(p.output ?? p.error ?? "").trimEnd()}`,
429 json: { ...p },
430 exit: 1,
431 };
432 }
433 rememberPrep(root, api.box, "used");
434 return {
435 text: [
436 `Prepared the box in ${p.seconds} s: ${named}`,
437 ...String(p.output ?? "")
438 .trimEnd()
439 .split("\n")
440 .slice(-5)
441 .map((l) => ` | ${l}`),
442 "From now on it starts from this, so a fresh box already has what the command left (node_modules, ~/.cache, /tmp).",
443 "abso run says when the prep is set aside (a new box image) or out of date (package-lock.json changed): run abso prep again then. abso run --fresh skips it once; abso prep --forget drops it.",
444 ].join("\n"),
445 json: { ...p },
446 };
447 }
448 // A broken stream reconnects to the run quietly; .abso/run.log says when and why.
449 // (Tests shorten the waits with these.)
450 const delays = (name: string) =>
451 fromEnv(env.env, name)
452 ?.split(",")
453 .map(Number)
454 .filter((n) => Number.isFinite(n) && n >= 0);
455 const reconnect = delays("RUN_RECONNECT_MS");
456 const retry = delays("RUN_RETRY_MS");
457 const runner =
458 reconnect?.length || retry?.length
459 ? new Api(api.config, api.timeoutMs, reconnect?.length ? reconnect : undefined, retry?.length ? retry : undefined)
460 : api;
461 runner.runKind = env.runKind ?? "run";
462 runner.box = api.box;
463 const log = (what: string, why: string): void => {
464 try {
465 appendFileSync(join(stateDir(root), "run.log"), `${new Date().toISOString()}\t${what}: ${named}\t${why}\n`);
466 } catch {
467 // The log is a convenience.
468 }
469 };
470 const onRetry = (why: string, attempt: number) => log(`starting again (try ${attempt + 1}), no answer came`, why);
471 if (bool(args, "detach")) {
472 const id = await runner.startRun(`${stampPrefix(stamp)}${command}`, tarGz(entries), onRetry, bool(args, "replace"));
473 return {
474 text: [
475 `Started run ${id} in the box: ${named}`,
476 `It goes on without this connection. abso logs ${id} prints its output from the start and waits for it to finish, with its exit code.`,
477 "While it runs, a later abso run from this folder is refused (409), since it would replace the files under it; abso run --replace stops it first.",
478 ].join("\n"),
479 json: { id, stamp },
480 };
481 }
482 const exit = await runner.run(`${stampPrefix(stamp)}${command}`, tarGz(entries), {
483 out: env.write,
484 err: env.writeErr ?? env.write,
485 onReconnect: (why, attempt) => log(`reconnecting (try ${attempt}) to`, why),
486 onRetry,
487 replace: bool(args, "replace"),
488 fresh: bool(args, "fresh"),
489 onBox: (cold, prep) => {
490 prepState = prep ?? null;
491 rememberPrep(root, api.box, prepState);
492 const say = notice;
493 if (cold && prep === "used")
494 say(
495 "abso: fresh box, started from your prep (abso prep): node_modules, ~/.cache and /tmp are as the prep left them.\n",
496 );
497 else if (cold)
498 say(
499 "abso: fresh box: it started for this run (first run, a deploy, a new image, or 30 idle minutes), so nothing earlier runs left outside the folder (/tmp, ~/.cache, node_modules) is in it. abso prep keeps them for every fresh box.\n",
500 );
501 if (prep !== undefined && prep !== "used") say(`abso: prep ${prep}.\n`);
502 },
503 });
504 if (fetchGlobs.length > 0) {
505 // On stderr: stdout is the command's, and may be going to a file.
506 const fetched = await fetchFromBox(root, api, fetchGlobs);
507 notice(`${fetchedText(fetched).join("\n")}\n`);
508 return { text: "", json: { exit, stamp, fetched, prep: prepState }, exit };
509 }
510 return { text: "", json: { exit, stamp, prep: prepState }, exit };
513/** abso fetch <glob...>: files the box made, written into the folder where abso ignores them. */
514/**
515 * Which of the agent's boxes run, logs and fetch use (#37): --box <name>, else
516 * ABSO_BOX (or the older AVCS_BOX), else the agent's own. A lead can give each subagent its own box
517 * (ABSO_BOX=2 in its environment), so their runs don't wait on each other.
518 */
519/**
520 * What this folder last heard about a box's prep: a run's X-Abso-Prep, or
521 * abso prep and prep --forget. null means no prep; undefined, never heard. So
522 * publish --check can refuse before running a check that can't be trusted
523 * (#37: a 40 s suite ran, then was refused).
524 */
525function prepFile(root: string): string {
526 return join(stateDir(root), "box-prep.json");
528export function knownPrep(root: string, box: string | undefined): string | null | undefined {
529 try {
530 const all = JSON.parse(readFileSync(prepFile(root), "utf8")) as Record<string, string | null>;
531 const key = box ?? "";
532 return key in all ? all[key] : undefined;
533 } catch {
534 return undefined;
535 }
537function rememberPrep(root: string, box: string | undefined, state: string | null): void {
538 let all: Record<string, string | null> = {};
539 try {
540 all = JSON.parse(readFileSync(prepFile(root), "utf8")) as Record<string, string | null>;
541 } catch {
542 // First time.
543 }
544 all[box ?? ""] = state;
545 try {
546 writeFileAtomic(prepFile(root), `${JSON.stringify(all)}\n`);
547 } catch {
548 // A convenience.
549 }
552export function boxOf(args: Parsed, env: Env): string | undefined {
553 const box = str(args, "box") ?? fromEnv(env.env, "BOX");
554 if (box !== undefined && !/^[A-Za-z0-9_-]{1,24}$/.test(box))
555 throw new UsageError(`a box name is 1-24 letters, digits, - or _ (got ${JSON.stringify(box)})`);
556 return box;
559/** abso logs <id>: a run's output (a detached one's, or one whose connection was lost) from the start, until it ends. */
560export async function runLogs(args: Parsed, env: Env): Promise<Output> {
561 const id = args.positionals[0];
562 if (args.positionals.length !== 1 || !/^[A-Za-z0-9_-]{1,64}$/.test(id!))
563 throw new UsageError("logs takes one run id: abso logs <id> (abso run --detach prints it)");
564 const { root, api } = open(env);
565 api.box = boxOf(args, env);
566 const exit = await api.logs(id!, {
567 out: env.write,
568 err: env.writeErr ?? env.write,
569 onReconnect: (why, attempt) => {
570 try {
571 appendFileSync(
572 join(stateDir(root), "run.log"),
573 `${new Date().toISOString()}\treconnecting (try ${attempt}) to run ${id}\t${why}\n`,
574 );
575 } catch {
576 // The log is a convenience.
577 }
578 },
579 });
580 return { text: "", json: { id, exit }, exit };
583/** What `abso run` tells the command about the code it runs, as environment variables. */
584export interface RunStamp {
585 readonly ABSO_AGENT: string;
586 /** shared, or the named draft. */
587 readonly ABSO_SPACE: string;
588 /** The version of that space the draft builds on. */
589 readonly ABSO_VERSION: string;
590 /** How many unpublished changes the draft holds (0: the run is exactly that version). */
591 readonly ABSO_DRAFT: string;
592 /** A short hash of the draft's files as they are, "" when the draft is empty. */
593 readonly ABSO_DRAFT_HASH: string;
594 /** With abso run --at: the version run ("12"), or the files taken from it ("12 files src/*.ts"). */
595 readonly ABSO_AT?: string;
598async function runStamp(root: string, agent: string, api: Api): Promise<RunStamp> {
599 const status = await api.status();
600 const me = status.agents.find((a) => a.agent === agent);
601 const files = Array.isArray(me?.files) ? [...(me.files as readonly string[])].sort() : [];
602 let hash = "";
603 if ((me?.draftChanges ?? 0) > 0) {
604 const h = createHash("sha256");
605 for (const rel of files) h.update(`${rel}\0${readText(absolute(root, rel)) ?? ""}\0`);
606 hash = h.digest("hex").slice(0, 12);
607 }
608 return {
609 ABSO_AGENT: agent,
610 ABSO_SPACE: me?.draft ?? "shared",
611 ABSO_VERSION: String(me?.base ?? status.version),
612 ABSO_DRAFT: String(me?.draftChanges ?? 0),
613 ABSO_DRAFT_HASH: hash,
614 };
617/** `export A='x' B='y'; `: on every part of a compound command, unlike a bare assignment prefix. */
618function stampPrefix(stamp: RunStamp): string {
619 const quote = (v: string) => `'${v.replace(/'/g, `'''`)}'`;
620 return `export ${Object.entries(withOldNames({ ...stamp }))
621 .filter((e): e is [string, string] => e[1] !== undefined)
622 .map(([k, v]) => `${k}=${quote(v)}`)
623 .join(" ")}; `;