- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/box-run.ts?format=json
236 linesFirst import 97% · pinch 2% · infra-split 1%Last change pinch in version 88, 4 versions changed it
1// Running a command in the agent's box (abso run, logs, serve and prep): what those calls answer,
2// and following a run's stream of JSON lines, reattaching by its id when the stream breaks.
4import type { Api } from "./api.ts";
5import { ApiError, errorSentence } from "./api-error.ts";
7/** What POST /serve answers (abso serve). */
8export interface ServeAnswer {
9 readonly version: number;
10 readonly url?: string;
11 readonly built: boolean;
12 readonly cached?: boolean;
13 readonly files?: number;
14 readonly bytes?: number;
15 readonly seconds?: number;
16 readonly exitCode?: number;
17 readonly output?: string;
18 readonly error?: string;
19}
21/** What abso prep's POST answers. */
22export interface PrepAnswer {
23 readonly error?: string;
24 readonly exitCode?: number;
25 readonly output?: string;
26 readonly saved?: boolean;
27 readonly snapshot?: string;
28 readonly size?: number;
29 readonly seconds?: number;
30}
32/** Where a run's output goes. */
33/** What a box run is for (#39). */
34export type RunKind = "run" | "shot" | "bisect" | "publish-check";
36export interface RunIO {
37 readonly out: (text: string) => void;
38 /** The box's stderr, when the server keeps it apart; without this it goes to `out`. */
39 readonly err?: (text: string) => void;
40 readonly onReconnect?: (why: string, attempt: number) => void;
41 readonly onRetry?: (why: string, attempt: number) => void;
42 /** Stop the runs still going in the box first, instead of a 409 (abso run --replace). */
43 readonly replace?: boolean;
44 /** Called when the run starts: whether the box is fresh, and what X-Abso-Prep says about its prep. */
45 readonly onBox?: (cold: boolean, prep: string | undefined) => void;
46 /** Start from the plain image this once, not the prep (abso run --fresh). */
47 readonly fresh?: boolean;
48}
50/** How far into a run's stdout (`at`) and stderr (`errAt`) the client has printed: the server's opaque offsets. */
51export interface Seen {
52 at: number;
53 errAt: number;
54}
56/** A run stream the server ended early, saying the run goes on: reattach. */
57class RunBroke extends Error {}
59/** Waits before starting a run again when its connection failed before any answer (a trial saw about 1 in 20). */
60export const RUN_START_RETRY_MS: readonly number[] = [500, 1500, 3000];
62/** Waits between reconnect tries: about two minutes in all. */
63export const RECONNECT_DELAYS_MS: readonly number[] = [500, 1000, 2000, 4000, 8000, 15_000, 30_000, 60_000];
65/**
66 * Read one run stream, printing its output. Each out line's `at` is the
67 * server's offset after it (opaque to the client), handed back on a reattach
68 * so the server sends only what came after. Answers the exit code, or
69 * undefined when the stream ended without one. Throws ApiError when the box
70 * reports an error, and RunBroke (or the network's error) when the stream
71 * breaks in a way a reattach recovers.
72 */
73export async function consumeRun(
74 res: Response,
75 io: Pick<RunIO, "out" | "err">,
76 seen: Seen,
77): Promise<number | undefined> {
78 const decoder = new TextDecoder();
79 let pending = "";
80 let exit: number | undefined;
81 const take = (line: string): void => {
82 if (line.trim() === "") return;
83 let msg: {
84 out?: string;
85 at?: number;
86 err?: string;
87 errAt?: number;
88 exit?: number;
89 error?: string;
90 retry?: boolean;
91 };
92 try {
93 msg = JSON.parse(line) as typeof msg;
94 } catch {
95 // Not one of ours: show it as output rather than drop it.
96 io.out(`${line}\n`);
97 return;
98 }
99 if (typeof msg.out === "string") {
100 io.out(msg.out);
101 if (typeof msg.at === "number") seen.at = msg.at;
102 }
103 if (typeof msg.err === "string") {
104 (io.err ?? io.out)(msg.err);
105 if (typeof msg.errAt === "number") seen.errAt = msg.errAt;
106 }
107 if (typeof msg.exit === "number") exit = msg.exit;
108 if (typeof msg.error === "string") {
109 // The server ends a stream it has to drop (a deploy) with retry: the run goes on in the box.
110 if (msg.retry === true) throw new RunBroke(msg.error);
111 throw new ApiError(`the box could not run the command: ${msg.error}`);
112 }
113 // Anything else ({"run"}, {"beat"}) only says the run is alive.
114 };
115 for await (const chunk of res.body!) {
116 pending += decoder.decode(chunk, { stream: true });
117 let nl: number;
118 while ((nl = pending.indexOf("\n")) >= 0) {
119 take(pending.slice(0, nl));
120 pending = pending.slice(nl + 1);
121 }
122 }
123 take(pending + decoder.decode());
124 return exit;
125}
126export function boxQuery(box: string | undefined): string {
127 return box ? `&box=${encodeURIComponent(box)}` : "";
128}
130/** POST the run, starting again (same key) while no run id has come back. */
131export async function postRun(
132 api: Api,
133 command: string,
134 tarGz: Uint8Array<ArrayBuffer>,
135 onRetry?: (why: string, attempt: number) => void,
136 replace = false,
137 fresh = false,
138): Promise<Response> {
139 // One key for every try of this run, so a server can tell a retry from a new run.
140 const key = crypto.randomUUID();
141 let res: Response | undefined;
142 // When no run id came back, start again, a few times: the connection failed before the
143 // server answered (ECONNRESET, "other side closed"), or something in front of the Worker
144 // answered 5xx. The same key makes that safe: a server that did start the run follows it
145 // instead of starting it again (5e34543). Once a run id arrives, the run is never started
146 // again; a broken stream reattaches by its id instead.
147 for (let attempt = 0; res === undefined; attempt++) {
148 let why: string;
149 let status: number | undefined;
150 try {
151 // stderr=split: the box's stderr comes apart from stdout (7a5a111); older servers ignore it.
152 // replace=1: stop the runs still going in the box first; without it the server answers 409 (#25).
153 const answer = await api.send(
154 `${api.url(api.agentPath("run"))}?cmd=${encodeURIComponent(command)}&stderr=split${replace ? "&replace=1" : ""}${fresh ? "&fresh=1" : ""}${boxQuery(api.box)}`,
155 {
156 method: "POST",
157 headers: { ...api.headers("application/gzip"), "x-abso-run-key": key, "x-abso-kind": api.runKind },
158 body: tarGz,
159 },
160 );
161 if (answer.status < 500 || answer.headers.get("x-abso-run") !== null) {
162 res = answer;
163 break;
164 }
165 status = answer.status;
166 why = `run answered ${answer.status}: ${errorSentence(await answer.text())}`;
167 } catch (err) {
168 const e = err as Error;
169 why = `could not reach ${api.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`;
170 }
171 const delay = api.startRetryDelaysMs[attempt];
172 if (delay === undefined) throw new ApiError(`${why}${attempt > 0 ? ` (tried ${attempt + 1} times)` : ""}`, status);
173 onRetry?.(why, attempt + 1);
174 await new Promise((ok) => setTimeout(ok, delay));
175 }
176 if (!res.ok || res.body === null) {
177 throw new ApiError(`run answered ${res.status}: ${errorSentence(await res.text())}`, res.status);
178 }
179 return res;
180}
182export function followUrl(api: Api, id: string, seen: Seen): string {
183 return `${api.url(`${api.agentPath("run")}/${encodeURIComponent(id)}`)}?from=${seen.at}&errFrom=${seen.errAt}${boxQuery(api.box)}`;
184}
186/** Print a run's stream until its exit line, reattaching by id when it breaks. */
187export async function follow(api: Api, first: Response, id: string | null, seen: Seen, io: RunIO): Promise<number> {
188 let res = first;
189 for (let attempt = 0; ; attempt++) {
190 let why: string;
191 try {
192 const exit = await consumeRun(res, io, seen);
193 if (exit !== undefined) return exit;
194 why = "the stream ended without an exit line";
195 } catch (err) {
196 if (err instanceof ApiError) throw err;
197 const e = err as Error;
198 why = (e.cause as Error | undefined)?.message ?? e.message;
199 }
200 if (id === null) throw new ApiError(`the run broke off (${why}), and this server can't reattach to a run`);
201 res = await reattach(api, id, seen, why, attempt, io.onReconnect);
202 }
203}
205/** Wait, then ask for the run's output after what was seen; tries until RECONNECT_DELAYS_MS runs out. */
206async function reattach(
207 api: Api,
208 id: string,
209 seen: Seen,
210 why: string,
211 attempt: number,
212 onReconnect?: (why: string, attempt: number) => void,
213): Promise<Response> {
214 let last = why;
215 for (const delay of api.reconnectDelaysMs) {
216 onReconnect?.(last, attempt + 1);
217 await new Promise((ok) => setTimeout(ok, delay));
218 try {
219 const res = await api.send(followUrl(api, id, seen), { headers: api.headers() });
220 if (res.status === 404)
221 throw new ApiError(
222 `the run broke off (${why}) and is gone from the box: ${errorSentence(await res.text())}`,
223 404,
224 );
225 if (res.ok && res.body !== null) return res;
226 last = `reconnect answered ${res.status}: ${errorSentence(await res.text())}`;
227 } catch (err) {
228 if (err instanceof ApiError) throw err;
229 const e = err as Error;
230 last = (e.cause as Error | undefined)?.message ?? e.message;
231 }
232 }
233 throw new ApiError(
234 `the run broke off (${why}) and reconnecting failed (${last}); it may still be running in the box (abso logs ${id} follows it)`,
235 );
236}