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/test/fake-server.ts?draft=login-wait&format=json
759 linesFirst import 97% · pinch 3% · review 1%0 versions changed it
1// A local stand-in for the avcs Worker, for testing the client. The project
2// logic is the real engine (worker/project/project.ts, in memory) with the
3// Worker's own blame, why and where; only the HTTP routing (as in
4// worker/project/http.ts) and the box are local. `run` unpacks the folder into a
5// temp folder and runs the command there.
6//
7// Run it on its own to point a real folder at it:
8// node client/test/fake-server.ts [port]
9
10import { spawn, spawnSync } from "node:child_process";
11import { createHash } from "node:crypto";
12import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
13import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
14import type { AddressInfo } from "node:net";
15import { tmpdir } from "node:os";
16import { dirname, join } from "node:path";
17import { gunzipSync } from "node:zlib";
18import { blame, why } from "../../worker/project/blame.ts";
19import { readerAnswer, statusWithReaders } from "../../worker/project/http.ts";
20import { MemoryStore, Project } from "../../worker/project/project.ts";
21import { type Candidate, type CheckResult, queueRound } from "../../worker/project/queue-driver.ts";
22import { where } from "../../worker/project/where.ts";
23import { globTest } from "../src/at.ts";
24import { tarGz } from "../src/tar.ts";
26/** Exit codes from 0xC0000000 up are Windows exceptions (0xC0000005: an access violation): the process crashed. */
27const WINDOWS_CRASH = 0xc0000000;
29interface Hosted {
30 readonly project: Project;
31 readonly store: MemoryStore;
32 /** Every edit and record body, by agent, for tests. */
33 readonly calls: Map<string, { action: string; body: unknown }[]>;
34 box: string | undefined;
35 /** Runs by id: their output so far, the exit line once known, and who is listening. */
36 readonly runs: Map<string, Run>;
37 /** Binary files' bytes by sha256, as the Worker's blob store keeps them. */
38 readonly blobs: Map<string, Buffer>;
39 /** Agents that read and never record (#37), kept outside the log as the Worker keeps them. */
40 readers?: Set<string>;
41 /** CI (#39), as a test sets it: status's ci, each shared version's log mark, and the jobs GET /ci?version=N answers. */
42 ci?: FakeCi;
43 /** The merge queue (#39): the last round, and whether one is running. */
44 queueLast?: Record<string, unknown> | null;
45 queueBusy?: boolean;
48export interface FakeCi {
49 status: Record<string, unknown>;
50 marks: Map<number, string>;
51 jobs: Map<number, Record<string, unknown>>;
54interface Run {
55 /** The output so far; `at` offsets count its bytes, as the Worker's do. */
56 out: Buffer;
57 /** The stderr so far, when the run keeps it apart (?stderr=split); `errAt` counts its bytes. */
58 err: Buffer;
59 readonly split: boolean;
60 end: string | undefined;
61 readonly listeners: Set<(line: string) => void>;
64export interface Fake {
65 readonly url: string;
66 readonly projects: Map<string, Hosted>;
67 /** The token every request must carry, as the Worker's AVCS_TOKEN. */
68 readonly token: string;
69 /** Added to every answer, to stand in for the network. */
70 delayMs: number;
71 /** How many of the next run streams (the POST or a reattach) to cut after their first output line, as a dropped connection. */
72 cutRunStreams: number;
73 /** How a cut stream ends: dropped, or with the Worker's {"error", "retry": true} (as a deploy ends one). */
74 cutRunAs: "drop" | "retry";
75 /** How many of the next run POSTs to drop before answering (ECONNRESET / "other side closed"); no run starts. */
76 dropRunStarts: number;
77 /** How the dropped ones end: the connection cut, or a 502 with no run id (as Cloudflare answers when the Worker fails). */
78 dropRunAs: "reset" | 502;
79 /**
80 * Paths the next sync answer carries on top of the engine's, as a server
81 * that lets anything through would (the engine refuses them since 03a44da).
82 */
83 injectSync:
84 | { files?: Record<string, string | null>; modes?: Record<string, { exec?: boolean; link?: string | null }> }
85 | undefined;
86 /** Entries box-files adds to its answer, as a box holding hostile paths or links would. */
87 boxExtra: { path: string; data: Uint8Array; link?: string }[] | undefined;
88 /** While true, the merge queue runs no rounds (a test holds a publish in the queue). */
89 queueHold: boolean;
90 /** The next publish: commit it and answer 500 ('after'), or answer 500 without it ('before'), as a storage reset does. */
91 failPublish: "after" | "before" | undefined;
92 /** Run the merge queue's rounds now (after queueHold is let go). */
93 kickQueue(name: string): Promise<void>;
94 /** Each run POST's X-Abso-Run-Key, and whether a run started for it. */
95 runStarts: { key: string | undefined; started: boolean; cmd: string; kind?: string }[];
96 close(): Promise<void>;
99const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/;
101function isLocal(path: string): boolean {
102 return [".abso", ".avcs"].some((d) => path === d || path.startsWith(`${d}/`) || path.startsWith(`./${d}/`));
105async function readBody(req: IncomingMessage): Promise<Buffer> {
106 const chunks: Buffer[] = [];
107 for await (const chunk of req) chunks.push(chunk as Buffer);
108 return Buffer.concat(chunks);
111function send(res: ServerResponse, status: number, body: unknown): void {
112 res.writeHead(status, { "content-type": "application/json" });
113 res.end(JSON.stringify(body));
116/** Read a ustar archive (with pax path records) into path -> bytes. */
117export function untar(data: Uint8Array): Map<string, Uint8Array> {
118 const out = new Map<string, Uint8Array>();
119 const text = (from: number, len: number): string =>
120 new TextDecoder().decode(data.subarray(from, from + len)).replace(/\0.*$/s, "");
121 let at = 0;
122 let paxPath: string | undefined;
123 while (at + 512 <= data.length) {
124 if (data.subarray(at, at + 512).every((b) => b === 0)) break;
125 const name = text(at, 100);
126 const size = parseInt(text(at + 124, 12).trim() || "0", 8);
127 const type = text(at + 156, 1);
128 const prefix = text(at + 345, 155);
129 const body = data.subarray(at + 512, at + 512 + size);
130 at += 512 + Math.ceil(size / 512) * 512;
131 if (type === "x") {
132 const m = /\d+ path=([^\n]*)\n/.exec(new TextDecoder().decode(body));
133 paxPath = m?.[1];
134 continue;
135 }
136 if (type === "0" || type === "") out.set(paxPath ?? (prefix ? `${prefix}/${name}` : name), body);
137 paxPath = undefined;
138 }
139 return out;
142export async function startFake(port = 0, token = "fake-token"): Promise<Fake> {
143 const projects = new Map<string, Hosted>();
144 const fake: Fake = {
145 url: "",
146 projects,
147 token,
148 delayMs: 0,
149 cutRunStreams: 0,
150 cutRunAs: "drop",
151 dropRunStarts: 0,
152 dropRunAs: "reset",
153 runStarts: [],
154 injectSync: undefined,
155 boxExtra: undefined,
156 queueHold: false,
157 failPublish: undefined,
158 kickQueue: async () => {},
159 close: async () => {},
160 };
162 /** The queue's check, as the Worker's CI box runs it: the candidate's avcs.json build and check, in a folder of its files. */
163 const queueCheck = async (c: Candidate): Promise<CheckResult> => {
164 const dir = mkdtempSync(join(tmpdir(), "avcs-fake-queue-"));
165 try {
166 for (const [path, text] of Object.entries(c.files)) {
167 mkdirSync(dirname(join(dir, path)), { recursive: true });
168 writeFileSync(join(dir, path), text);
169 }
170 const cfg = JSON.parse(c.files["avcs.json"] ?? "{}") as { build?: string; check?: string };
171 const cmd = [cfg.build, cfg.check].filter((s) => typeof s === "string" && s !== "").join(" && ");
172 if (cmd === "") return { kind: "fail", output: "the merge queue needs a check (or a build) in avcs.json" };
173 let r = spawnSync(cmd, { cwd: dir, shell: true, encoding: "utf8" });
174 // As for box runs: a Windows crash at start, with nothing printed, runs once more.
175 if ((r.status ?? 0) >= WINDOWS_CRASH && `${r.stdout ?? ""}${r.stderr ?? ""}` === "")
176 r = spawnSync(cmd, { cwd: dir, shell: true, encoding: "utf8" });
177 return r.status === 0 ? { kind: "pass" } : { kind: "fail", output: `${r.stdout ?? ""}${r.stderr ?? ""}` };
178 } finally {
179 rmSync(dir, { recursive: true, force: true });
180 }
181 };
182 /** Rounds until the queue is empty, one at a time, as the Worker's object runs them. */
183 fake.kickQueue = async (name: string): Promise<void> => {
184 const hosted = projects.get(name);
185 if (!hosted || hosted.queueBusy || fake.queueHold) return;
186 hosted.queueBusy = true;
187 try {
188 while (hosted.project.queue().items.length > 0 && !fake.queueHold) {
189 const round = await queueRound(hosted.project, { check: queueCheck });
190 hosted.queueLast = { ...round, at: new Date().toISOString() };
191 if (round.kind !== "landed" && round.kind !== "pulled") break;
192 }
193 } finally {
194 hosted.queueBusy = false;
195 }
196 };
197 const queueState = (hosted: Hosted) => ({
198 items: hosted.project.queue().items,
199 checking: hosted.queueBusy ?? false,
200 paused: null,
201 last: hosted.queueLast ?? null,
202 });
203 let runs = 0;
204 // Blobs come before init (init names them), so they wait here until the project exists.
205 const waiting = new Map<string, Map<string, Buffer>>();
206 const pendingBlobs = (name: string): Map<string, Buffer> => {
207 let m = waiting.get(name);
208 if (!m) waiting.set(name, (m = new Map()));
209 return m;
210 };
212 const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
213 const url = new URL(req.url ?? "/", "http://fake");
214 if (req.headers.authorization !== `Bearer ${token}`) return send(res, 401, { error: "missing or wrong token" });
215 const blob = /^\/p\/([^/]+)\/blobs\/([0-9a-f]{64})$/.exec(url.pathname);
216 if (blob) {
217 const store = projects.get(decodeURIComponent(blob[1]!))?.blobs ?? pendingBlobs(decodeURIComponent(blob[1]!));
218 const sha = blob[2]!;
219 if (req.method === "PUT") {
220 const bytes = await readBody(req);
221 if (createHash("sha256").update(bytes).digest("hex") !== sha)
222 return send(res, 400, { error: "the bytes do not match the hash" });
223 const stored = !store.has(sha);
224 store.set(sha, bytes);
225 return send(res, 200, { sha, stored });
226 }
227 const bytes = store.get(sha);
228 if (!bytes) return send(res, 404, { error: "no such blob" });
229 res.writeHead(200, { "content-type": "application/octet-stream" });
230 res.end(bytes);
231 return;
232 }
233 const boxFiles = /^\/p\/([^/]+)\/a\/([^/]+)\/box-files$/.exec(url.pathname);
234 if (boxFiles) {
235 // As the Worker answers it, from the fake box: a tar.gz of the matching files under it.
236 const box = projects.get(decodeURIComponent(boxFiles[1]!))?.box;
237 const glob = url.searchParams.get("glob") ?? "";
238 if (glob.split("/").includes("..") || glob.startsWith("/"))
239 return send(res, 400, { error: "no .. or absolute paths" });
240 const pick = globTest(glob);
241 const list = (dir: string, prefix: string): string[] =>
242 readdirSync(join(box!, dir), { withFileTypes: true }).flatMap((e) => {
243 const rel = prefix === "" ? e.name : `${prefix}/${e.name}`;
244 return e.isDirectory() ? list(join(dir, e.name), rel) : [rel];
245 });
246 const files = box === undefined ? [] : list("", "").filter(pick);
247 if (files.length === 0) return send(res, 404, { error: `nothing in the box matches ${glob}` });
248 const extra = fake.boxExtra ?? [];
249 const gz = tarGz([
250 ...files.map((rel) => ({ path: rel, data: readFileSync(join(box!, ...rel.split("/"))) })),
251 ...extra,
252 ]);
253 res.writeHead(200, { "content-type": "application/gzip", "x-abso-files": String(files.length) });
254 res.end(Buffer.from(gz));
255 return;
256 }
257 const reattach = /^\/p\/([^/]+)\/a\/([^/]+)\/run\/([^/]+)$/.exec(url.pathname);
258 if (reattach) {
259 const run = projects.get(decodeURIComponent(reattach[1]!))?.runs.get(decodeURIComponent(reattach[3]!));
260 if (!run) return send(res, 404, { error: "no such run; it ended long ago, or another run replaced it" });
261 res.writeHead(200, { "content-type": "application/x-ndjson" });
262 const from = Number(url.searchParams.get("from") ?? 0);
263 const errFrom = Number(url.searchParams.get("errFrom") ?? 0);
264 res.write(`${JSON.stringify({ run: reattach[3], ...(run.split ? { stderr: "split" } : {}) })}\n`);
265 const listen = streamRun(res, run);
266 if (run.out.length > from)
267 listen(`${JSON.stringify({ out: run.out.subarray(from).toString("utf8"), at: run.out.length })}\n`);
268 if (run.split && run.err.length > errFrom)
269 listen(`${JSON.stringify({ err: run.err.subarray(errFrom).toString("utf8"), errAt: run.err.length })}\n`);
270 if (run.end !== undefined) listen(run.end);
271 return;
272 }
273 const m =
274 /^\/p\/([^/]+)\/(init|status|queue|change\/\d+|changes|notes|ci\/revoke|ci|blame|why|where|labels|files|diff|log|show|file|compare|a\/([^/]+)\/(edit|record|publish|sync|run|draft|land|draft-sync|diff|restore|announce|news|starting|reader|drop|pluck|amend|label|files|unqueue|note|note-close|move))$/.exec(
275 url.pathname,
276 );
277 if (!m) return send(res, 404, { error: "no such route; see docs/v2-slice1.md" });
278 const name = decodeURIComponent(m[1]!);
279 const agent = m[3] === undefined ? undefined : decodeURIComponent(m[3]);
280 const op = m[4] ?? m[2]!;
281 const raw = await readBody(req);
282 if (fake.delayMs > 0) await new Promise((r) => setTimeout(r, fake.delayMs));
284 let hosted = projects.get(name);
285 if (op === "init") {
286 const {
287 files,
288 modes,
289 blobs: initBlobs,
290 } = JSON.parse(raw.toString("utf8") || "{}") as {
291 files?: Record<string, string>;
292 modes?: Parameters<Project["init"]>[2];
293 blobs?: Record<string, string>;
294 };
295 if (!files || typeof files !== "object") return send(res, 400, { error: "init needs {files: {path: text}}" });
296 if (hosted) return send(res, 409, { error: "the project already exists" });
297 const bad = Object.keys(files).find(isLocal);
298 if (bad) return send(res, 400, { error: `${bad} is under .abso/, which stays in the agent's folder` });
299 const store = new MemoryStore();
300 const blobs = pendingBlobs(name);
301 waiting.delete(name);
302 // Files kept whole (#46) go to the blob store, as the Worker's do.
303 const whole = {
304 keep: (text: string): string => {
305 const bytes = Buffer.from(text, "utf8");
306 const sha = createHash("sha256").update(bytes).digest("hex");
307 blobs.set(sha, bytes);
308 return sha;
309 },
310 read: (sha: string): string | null => blobs.get(sha)?.toString("utf8") ?? null,
311 };
312 hosted = {
313 project: new Project(store, { hasBlob: (sha) => blobs.has(sha), whole }),
314 store,
315 calls: new Map(),
316 box: undefined,
317 runs: new Map(),
318 blobs,
319 };
320 // As the Worker with a checker: "queue": true in avcs.json turns the merge queue on (#39).
321 hosted.project.checkerReady = true;
322 projects.set(name, hosted);
323 return send(res, 200, hosted.project.init(files, Date.now(), modes, initBlobs ?? {}));
324 }
325 if (!hosted) return send(res, 404, { error: "no such project; run init first" });
326 // Readers (#37), with the Worker's rules; like the Worker, kept outside the log.
327 const readerList = (hosted.readers ??= new Set<string>());
328 const readers = {
329 has: (a: string) => readerList.has(a),
330 set: (a: string, on: boolean) => void (on ? readerList.add(a) : readerList.delete(a)),
331 list: () => [...readerList].sort(),
332 };
333 if (op === "status") {
334 const queue = hosted.project.queue().items.length > 0 ? { queue: queueState(hosted) } : {};
335 return send(res, 200, {
336 ...(statusWithReaders(hosted.project.status(), readers) as object),
337 ...(hosted.ci ? { ci: hosted.ci.status } : {}),
338 ...queue,
339 });
340 }
341 if (op === "queue") return send(res, 200, queueState(hosted));
342 // Changes and notes (#44), as the Worker routes them.
343 if (op === "changes" || op.startsWith("change/") || op === "notes") {
344 const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
345 try {
346 if (op === "changes")
347 return send(
348 res,
349 200,
350 hosted.project.changes(
351 q.since ? Number(q.since) : 0,
352 q.limit ? Number(q.limit) : 50,
353 q.before ? Number(q.before) : undefined,
354 ),
355 );
356 if (op === "notes")
357 return send(
358 res,
359 200,
360 hosted.project.notes({
361 ...(q.file ? { file: q.file } : {}),
362 ...(q.change ? { change: Number(q.change) } : {}),
363 ...(q.open ? { open: true } : {}),
364 }),
365 );
366 return send(res, 200, hosted.project.change(Number(op.slice("change/".length))));
367 } catch (e) {
368 const code = (e as { code?: string }).code;
369 return send(res, code === "not-found" ? 404 : 400, { error: e instanceof Error ? e.message : String(e) });
370 }
371 }
372 if (op === "ci" || op === "ci/revoke") {
373 if (!hosted.ci) return send(res, 404, { error: "no such route; see docs/v2-slice1.md" });
374 if (op === "ci/revoke") {
375 const latest = hosted.ci.status.latest as { version: number; url?: string } | null;
376 if (latest?.url)
377 hosted.ci.status = {
378 ...hosted.ci.status,
379 latest: { ...latest, url: `${latest.url.replace(/\/g\d+\/$/, "")}/g${Date.now()}/` },
380 };
381 return send(res, 200, hosted.ci.status);
382 }
383 const v = url.searchParams.get("version");
384 if (v === null) return send(res, 200, hosted.ci.status);
385 // As the Worker: a version without a job of its own is running, waiting, or not checked.
386 const mark = hosted.ci.marks.get(Number(v));
387 return send(
388 res,
389 200,
390 hosted.ci.jobs.get(Number(v)) ?? {
391 version: Number(v),
392 result: mark === "running" || mark === "waiting" ? mark : "not checked",
393 },
394 );
395 }
396 if (agent !== undefined) {
397 const gated = readerAnswer(
398 hosted.project,
399 op,
400 agent,
401 op === "reader" ? JSON.parse(raw.toString("utf8") || "{}") : undefined,
402 readers,
403 );
404 if (gated) return send(res, gated.status, gated.body);
405 }
406 if (op === "where") return send(res, 200, where(hosted.project));
407 if (op === "labels") return send(res, 200, hosted.project.labels());
408 if (op === "diff" && agent === undefined) {
409 // Another agent's draft, read only (abso diff --agent), as the Worker answers GET /p/:project/diff?agent=.
410 const of = url.searchParams.get("agent");
411 if (!of) return send(res, 400, { error: "diff needs ?agent=<name>" });
412 try {
413 return send(res, 200, hosted.project.diffOf(of));
414 } catch (e) {
415 const code = (e as { code?: string }).code;
416 return send(res, code === "not-found" ? 404 : 500, { error: e instanceof Error ? e.message : String(e) });
417 }
418 }
419 if (op === "files" && agent === undefined) {
420 const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
421 try {
422 return send(res, 200, hosted.project.pathsAt(q.version ? Number(q.version) : undefined, q.draft || null));
423 } catch (e) {
424 return send(res, 400, { error: e instanceof Error ? e.message : String(e) });
425 }
426 }
427 if (op === "blame" || op === "why") {
428 const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
429 if (!q.file) return send(res, 400, { error: `${op} needs ?file=<path>` });
430 const num = (s: string | undefined) => (s === undefined || s === "" ? undefined : Number(s));
431 try {
432 const view = { draft: q.draft || undefined, agent: q.agent || undefined };
433 if (op === "blame")
434 return send(res, 200, blame(hosted.project, q.file, num(q.from), num(q.to), num(q.version), view));
435 const line = num(q.line);
436 if (!line || !Number.isInteger(line)) return send(res, 400, { error: "why needs ?line=<number>" });
437 return send(res, 200, why(hosted.project, q.file, line, view));
438 } catch (e) {
439 const code = (e as { code?: string }).code;
440 return send(res, code === "bad-request" ? 400 : 500, { error: e instanceof Error ? e.message : String(e) });
441 }
442 }
443 if (op === "log" || op === "show" || op === "file" || op === "compare") {
444 // As the Worker routes them: ?draft=<name>, shared when absent.
445 const q = Object.fromEntries(url.searchParams) as Record<string, string | undefined>;
446 const draft = q.draft ? q.draft : null;
447 const agentSpace = q.agent ? { agent: q.agent } : {};
448 const int = (s: string | undefined): number | undefined =>
449 s !== undefined && s !== "" && Number.isInteger(Number(s)) ? Number(s) : undefined;
450 try {
451 if (op === "log") {
452 const log = hosted.project.log({ draft, ...agentSpace, limit: int(q.limit), path: q.path || undefined });
453 // Shared's versions only, by what the answer is (an agent may be in a named draft).
454 const ci = hosted.ci;
455 if (!ci || log.draft !== null) return send(res, 200, log);
456 return send(res, 200, {
457 ...log,
458 versions: log.versions.map((v) => ({ ...v, ci: ci.marks.get(v.version) ?? "not checked" })),
459 });
460 }
461 if (op === "file") {
462 const version = int(q.version);
463 if (!q.path || version === undefined)
464 return send(res, 400, { error: "file needs ?path=<path>&version=<number>" });
465 return send(res, 200, hosted.project.fileAt(q.path, version, { draft, ...agentSpace }));
466 }
467 if (op === "compare") {
468 const from = int(q.from);
469 const to = int(q.to);
470 if (from === undefined || to === undefined)
471 return send(res, 400, { error: "compare needs ?from=<number>&to=<number>" });
472 return send(res, 200, hosted.project.compare(from, to, { draft, ...agentSpace }));
473 }
474 const version = int(q.version);
475 if (version === undefined) return send(res, 400, { error: "show needs ?version=<number>" });
476 return send(res, 200, hosted.project.show(version, { draft, ...agentSpace }));
477 } catch (e) {
478 const code = (e as { code?: string }).code;
479 return send(res, code === "bad-request" ? 400 : 500, { error: e instanceof Error ? e.message : String(e) });
480 }
481 }
482 if (agent === undefined || !NAME.test(agent))
483 return send(res, 400, { error: "agent names use letters, digits, '.', '_' and '-'" });
484 if (op === "run") {
485 const key = req.headers["x-abso-run-key"];
486 const dropped = fake.dropRunStarts > 0;
487 fake.runStarts.push({
488 key: typeof key === "string" ? key : undefined,
489 started: !dropped,
490 cmd: url.searchParams.get("cmd") ?? "",
491 kind: String(req.headers["x-abso-kind"] ?? ""),
492 });
493 if (dropped) {
494 fake.dropRunStarts--;
495 if (fake.dropRunAs === 502) return send(res, 502, { error: "bad gateway" });
496 res.socket?.destroy();
497 return;
498 }
499 return runInBox(hosted, url.searchParams.get("cmd") ?? "", raw, res, url.searchParams.get("stderr") === "split");
500 }
502 const body = JSON.parse(raw.toString("utf8") || "{}") as Record<string, unknown>;
503 const calls = hosted.calls.get(agent) ?? [];
504 hosted.calls.set(agent, calls);
505 calls.push({ action: op, body });
506 const project = hosted.project;
507 try {
508 if (op === "edit") {
509 if (typeof body.file !== "string")
510 return send(res, 400, { error: "edit needs {file, old, new}, {file, content} or {file, edits}" });
511 if (isLocal(body.file))
512 return send(res, 400, { error: `${body.file} is under .abso/, which stays in the agent's folder` });
513 return send(res, 200, project.edit(agent, body as unknown as Parameters<Project["edit"]>[1], Date.now()));
514 }
515 if (op === "record") {
516 const files = body.files as Record<string, string | null> | undefined;
517 if (!files || typeof files !== "object")
518 return send(res, 400, { error: "record needs {files: {path: text or null}}" });
519 const bad = Object.keys(files).find(isLocal);
520 if (bad) return send(res, 400, { error: `${bad} is under .abso/, which stays in the agent's folder` });
521 const meta = {
522 ...(typeof body.session === "string" ? { session: body.session } : {}),
523 ...(typeof body.subagent === "string" ? { subagent: body.subagent } : {}),
524 };
525 return send(
526 res,
527 200,
528 project.record(
529 agent,
530 files,
531 Date.now(),
532 body.modes as Parameters<Project["record"]>[3],
533 body.blobs as Record<string, string> | undefined,
534 meta,
535 ),
536 );
537 }
538 if (op === "publish") {
539 const message = body.message;
540 if (typeof message !== "string" || !message.trim())
541 return send(res, 400, { error: "publish needs {message} saying why" });
542 const fail = fake.failPublish;
543 fake.failPublish = undefined;
544 const storageReset = { error: "Internal error in Durable Object storage caused object to be reset." };
545 if (fail === "before") return send(res, 500, storageReset);
546 const answer = project.publish(agent, message, Date.now(), { asIs: body.asIs === true });
547 if (fail === "after") return send(res, 500, storageReset);
548 // A queued publish wakes the queue, as the Worker's object does.
549 if ((answer as { queued?: number }).queued !== undefined) setTimeout(() => void fake.kickQueue(name), 0);
550 return send(res, 200, answer);
551 }
552 if (op === "note") return send(res, 200, project.note(agent, body, Date.now()));
553 if (op === "move") return send(res, 200, project.move(agent, body.from as string, body.to as string, Date.now()));
554 if (op === "note-close") return send(res, 200, project.closeNote(agent, body.id as number, body.how, Date.now()));
555 if (op === "unqueue") {
556 return send(res, 200, project.unqueue(agent, Date.now()));
557 }
558 if (op === "draft") {
559 const name = body.name;
560 if (name !== null && typeof name !== "string")
561 return send(res, 400, { error: "draft needs {name}, or {name: null} for shared" });
562 return send(res, 200, project.switchTo(agent, name, Date.now(), { carry: body.carry === true }));
563 }
564 if (op === "land") {
565 const message = body.message;
566 if (typeof message !== "string" || !message.trim())
567 return send(res, 400, { error: "land needs {message} saying why" });
568 return send(res, 200, project.land(agent, message, Date.now()));
569 }
570 if (op === "draft-sync") return send(res, 200, project.syncDraft(agent, Date.now()));
571 if (op === "files") return send(res, 200, project.agentPaths(agent));
572 if (op === "diff") return send(res, 200, project.diff(agent));
573 if (op === "starting")
574 return send(
575 res,
576 200,
577 project.starting(agent, body.text as string | null, body.files as string[] | undefined, Date.now()),
578 );
579 if (op === "announce")
580 return send(
581 res,
582 200,
583 project.announce(agent, body.text as string, body.to as string[] | undefined, Date.now()),
584 );
585 if (op === "news") return send(res, 200, project.news(agent));
586 if (op === "restore") {
587 if (body.all === true) return send(res, 200, project.restore(agent, null, Date.now()));
588 if (!Array.isArray(body.files) || !body.files.every((f) => typeof f === "string"))
589 return send(res, 400, { error: "restore needs {files: [path]} or {all: true}" });
590 return send(res, 200, project.restore(agent, body.files as string[], Date.now()));
591 }
592 if (op === "drop")
593 return send(
594 res,
595 200,
596 project.drop(agent, body.versions as number[], body.message as string, Date.now(), {
597 withDependents: body.withDependents === true,
598 }),
599 );
600 if (op === "pluck")
601 return send(
602 res,
603 200,
604 project.pluck(agent, body.draft as string, body.versions as number[], body.message as string, Date.now(), {
605 withDependencies: body.withDependencies === true,
606 }),
607 );
608 if (op === "amend") return send(res, 200, project.amend(agent, body.message as string, Date.now()));
609 if (op === "label")
610 return send(
611 res,
612 200,
613 project.label(agent, body.name as string, body.version as number | undefined, Date.now(), {
614 remove: body.remove === true,
615 }),
616 );
617 const synced = project.sync(agent, {
618 ...(typeof body.label === "string" ? { label: body.label } : {}),
619 ...(body.full === true ? { full: true } : {}),
620 });
621 const extra = fake.injectSync;
622 fake.injectSync = undefined;
623 if (extra === undefined) return send(res, 200, synced);
624 return send(res, 200, {
625 ...synced,
626 files: { ...synced.files, ...extra.files },
627 modes: { ...synced.modes, ...extra.modes },
628 });
629 } catch (e) {
630 const code = (e as { code?: string }).code;
631 const status =
632 code === "not-initialized" || code === "not-found"
633 ? 404
634 : code === "already-initialized" || code === "conflict"
635 ? 409
636 : code === "bad-request" || code === "bad-agent"
637 ? 400
638 : 500;
639 return send(res, status, { error: e instanceof Error ? e.message : String(e) });
640 }
641 };
643 /** Unpack the folder into a temp box (keeping node_modules), run the command, stream ndjson. */
644 const runInBox = (hosted: Hosted, cmd: string, raw: Buffer, res: ServerResponse, split: boolean): void => {
645 if (hosted.box === undefined) hosted.box = mkdtempSync(join(tmpdir(), "avcs-fake-box-"));
646 const box = hosted.box;
647 for (const entry of readdirSync(box))
648 if (entry !== "node_modules") rmSync(join(box, entry), { recursive: true, force: true });
649 for (const [path, data] of untar(gunzipSync(raw))) {
650 const full = join(box, ...path.split("/"));
651 mkdirSync(dirname(full), { recursive: true });
652 writeFileSync(full, data);
653 }
654 // The run lives on without its connection; a reattach streams from where the client got to.
655 const id = `run${++runs}`;
656 const run: Run = { out: Buffer.alloc(0), err: Buffer.alloc(0), split, end: undefined, listeners: new Set() };
657 hosted.runs.clear();
658 hosted.runs.set(id, run);
659 res.writeHead(200, { "content-type": "application/x-ndjson", "x-abso-box": "warm", "x-abso-run": id });
660 res.write(`${JSON.stringify({ run: id, ...(split ? { stderr: "split" } : {}) })}\n`);
661 streamRun(res, run);
662 const emit = (line: string): void => {
663 for (const listen of [...run.listeners]) listen(line);
664 };
665 const out = (chunk: Buffer): void => {
666 run.out = Buffer.concat([run.out, chunk]);
667 emit(`${JSON.stringify({ out: chunk.toString("utf8"), at: run.out.length })}\n`);
668 };
669 const err = (chunk: Buffer): void => {
670 if (!split) return out(chunk);
671 run.err = Buffer.concat([run.err, chunk]);
672 emit(`${JSON.stringify({ err: chunk.toString("utf8"), errAt: run.err.length })}\n`);
673 };
674 child(cmd, box, out, err, (end) => {
675 run.end = end;
676 emit(end);
677 });
678 };
680 const child = (
681 cmd: string,
682 box: string,
683 out: (chunk: Buffer) => void,
684 err: (chunk: Buffer) => void,
685 done: (end: string) => void,
686 ): void => {
687 // The box's sh reads `export A='x'; command`; the shell here may be cmd.exe, so take the stamp into the environment.
688 const stamped = /^export ((?:[A-Z_]+='[^']*' ?)+); ([\s\S]*)$/.exec(cmd);
689 const env = { ...process.env };
690 if (stamped) for (const [, k, v] of stamped[1]!.matchAll(/([A-Z_]+)='([^']*)'/g)) env[k!] = v!;
691 // Node on Windows sometimes crashes as it starts (0xC0000005, about 1 start in 200 on the dev machine,
692 // more when many start at once), which made the box tests flaky. The real box is Linux; a run that
693 // crashed before printing anything is started once more, as a fresh box would run it.
694 const start = (tries: number): void => {
695 let printed = false;
696 const p = spawn(stamped ? stamped[2]! : cmd, { cwd: box, shell: true, env });
697 p.stdout.on("data", (chunk: Buffer) => ((printed = true), out(chunk)));
698 p.stderr.on("data", (chunk: Buffer) => ((printed = true), err(chunk)));
699 p.on("error", (e) => done(`${JSON.stringify({ error: e.message })}\n`));
700 p.on("close", (code) => {
701 if (code !== null && code >= WINDOWS_CRASH && !printed && tries < 2) return start(tries + 1);
702 done(`${JSON.stringify({ exit: code ?? 1 })}\n`);
703 });
704 };
705 start(0);
706 };
708 /** Send a run's lines to one connection until its end line; cut it after its first output when the test asks. */
709 const streamRun = (res: ServerResponse, run: Run): ((line: string) => void) => {
710 const cut = fake.cutRunStreams > 0;
711 if (cut) fake.cutRunStreams--;
712 const listen = (line: string): void => {
713 if (res.destroyed) return;
714 if (line.startsWith('{"out"') || line.startsWith('{"err"')) {
715 if (cut) {
716 // Drop the connection once this line has gone out, as a network that breaks mid-run.
717 run.listeners.delete(listen);
718 if (fake.cutRunAs === "retry")
719 res.end(`${line}${JSON.stringify({ error: "the Worker is restarting (a deploy)", retry: true })}\n`);
720 else res.write(line, () => res.destroy());
721 return;
722 }
723 res.write(line);
724 return;
725 }
726 run.listeners.delete(listen);
727 res.end(line);
728 };
729 run.listeners.add(listen);
730 res.on("close", () => run.listeners.delete(listen));
731 return listen;
732 };
734 const server: Server = createServer((req, res) => {
735 handle(req, res).catch((err: Error) => {
736 if (!res.headersSent) send(res, 500, { error: err.message });
737 else res.end();
738 });
739 });
740 // Never close an idle kept-alive connection: on Windows, under load, the client could reuse one in the moment
741 // the server closed it, and the next call failed with ECONNRESET. close() below drops every connection.
742 server.keepAliveTimeout = 0;
743 await new Promise<void>((ok) => server.listen(port, "127.0.0.1", ok));
744 const address = server.address() as AddressInfo;
745 return Object.assign(fake, {
746 url: `http://127.0.0.1:${address.port}`,
747 close: () =>
748 new Promise<void>((ok) => {
749 server.closeAllConnections();
750 server.close(() => ok());
751 for (const p of projects.values()) if (p.box) rmSync(p.box, { recursive: true, force: true, maxRetries: 5 });
752 }),
753 });
756if (import.meta.main) {
757 const fake = await startFake(Number(process.argv[2] ?? 0), process.env.AVCS_TOKEN ?? "fake-token");
758 console.log(`fake abso server at ${fake.url} (the real engine in memory; token from AVCS_TOKEN, else "fake-token")`);