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