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/api.ts?version=0&format=json
745 linesFirst import 100%Last change First import in version 0, 1 version changed it

You're reading version 0. The newest is 318, and 29 versions since then changed this file. Go to the newestCompare with 318

1// Calls to the server's HTTP API (docs/v2-slice1.md). Every call is JSON
2// except `run`, which sends a tar.gz and reads the answer as a stream of JSON
3// lines (box-run.ts).
4
5import { setDefaultResultOrder } from "node:dns";
6import type {
7 ChangeAnswer,
8 DraftSyncAnswer,
9 EditAnswer,
10 EditBody,
11 News,
12 NoteAnswer,
13 NoteBody,
14 PublishAnswer,
15 RecordAnswer,
16 StatusAnswer,
17 SwitchAnswer,
18 SyncAnswer,
19} from "./api-answers.ts";
20import { ApiError, errorSentence, neverSent } from "./api-error.ts";
21import {
22 boxQuery,
23 consumeRun,
24 follow,
25 followUrl,
26 type PrepAnswer,
27 postRun,
28 RECONNECT_DELAYS_MS,
29 RUN_START_RETRY_MS,
30 type RunIO,
31 type RunKind,
32 type ServeAnswer,
33} from "./box-run.ts";
34import type { CiJob, CiStatus, QueueState } from "./ci-answers.ts";
35import { clientVersion } from "./client-version.ts";
36import type { Config } from "./config.ts";
37import type {
38 BlameAnswer,
39 DiffAnswer,
40 DropAnswer,
41 FileChange,
42 FilesAnswer,
43 LogAnswer,
44 Overlap,
45 PluckAnswer,
46 RestoreAnswer,
47 ShowAnswer,
48 View,
49 Where,
50 WhereAnswer,
51 WhyAnswer,
52} from "./history-answers.ts";
53import type { Ask, Draft, DraftBody, News as IssueNews, IssuePage, IssueRow } from "./issues-wire.ts";
54import type { Modes } from "./modes.ts";
56export * from "./api-answers.ts";
57export { ApiError, neverSent } from "./api-error.ts";
58export {
59 type PrepAnswer,
60 RECONNECT_DELAYS_MS,
61 RUN_START_RETRY_MS,
62 type RunIO,
63 type RunKind,
64 type ServeAnswer,
65} from "./box-run.ts";
66export * from "./ci-answers.ts";
67export * from "./history-answers.ts";
68export type { Ask, Draft, DraftBody, IssueNews, IssuePage, IssueRow };
70/**
71 * How long a call may take: the base, plus 1 s for each 100 KB it sends
72 * (abso issue 34: a sync that recorded 191 reformatted files first ran out of
73 * its 30 s while the server was still taking them in).
74 */
75export function timeoutFor(baseMs: number, sent: string | undefined): number {
76 return sent === undefined ? baseMs : baseMs + Math.floor(Buffer.byteLength(sent) / 100_000) * 1000;
79/** A query string from the values that are set (null and undefined are left out). */
80function query(values: Record<string, string | number | null | undefined>): URLSearchParams {
81 const q = new URLSearchParams();
82 for (const [k, v] of Object.entries(values)) if (v !== null && v !== undefined) q.set(k, String(v));
83 return q;
86export function newsLines(news: News): string[] {
87 if (news === undefined || news === null) return [];
88 return (typeof news === "string" ? [news] : [...news]).filter((s) => typeof s === "string" && s.trim() !== "");
91export class Api {
92 readonly config: Config;
93 readonly timeoutMs: number;
95 /** Waits between tries when a run's stream breaks; tests shorten them. */
96 readonly reconnectDelaysMs: readonly number[];
97 readonly startRetryDelaysMs: readonly number[];
98 /** Another box of this agent for run, logs and fetch (--box or AVCS_BOX, #37); undefined is its own box. */
99 box: string | undefined;
101 constructor(
102 config: Config,
103 timeoutMs = 30_000,
104 reconnectDelaysMs: readonly number[] = RECONNECT_DELAYS_MS,
105 startRetryDelaysMs: readonly number[] = RUN_START_RETRY_MS,
106 ) {
107 this.config = config;
108 this.timeoutMs = timeoutMs;
109 this.reconnectDelaysMs = reconnectDelaysMs;
110 this.startRetryDelaysMs = startRetryDelaysMs;
111 }
113 /** What a box run is for, for the server's box-run records (#39): X-Avcs-Kind on POST /run. */
114 runKind: RunKind = "run";
116 /** The Issues Worker (#54) this folder's issues calls go to; set by the issues commands (issues.ts). */
117 issuesServer: string | undefined;
119 url(path: string, server = this.config.server): string {
120 return `${server.replace(/\/+$/, "")}/p/${encodeURIComponent(this.config.project)}${path}`;
121 }
123 agentPath(action: string): string {
124 return `/a/${encodeURIComponent(this.config.agent)}/${action}`;
125 }
127 headers(contentType?: string): Record<string, string> {
128 return {
129 // Which client made the call (#29); the mods send theirs too.
130 "x-avcs-client": `abso-cli/${clientVersion()}`,
131 ...(this.config.token ? { authorization: `Bearer ${this.config.token}` } : {}),
132 ...(contentType ? { "content-type": contentType } : {}),
133 };
134 }
136 async json<T>(method: "GET" | "POST", path: string, body?: unknown, server = this.config.server): Promise<T> {
137 let res: Response | undefined;
138 const sent = body === undefined ? undefined : JSON.stringify(body);
139 const timeoutMs = timeoutFor(this.timeoutMs, sent);
140 // A connection that never opened is tried once more, IPv4 first (#37, GAME - UI/UX: one IPv6
141 // address timed out, and the same command went through seconds later). Nothing went out, so
142 // a POST is as safe to send again as a GET.
143 for (let attempt = 0; res === undefined; attempt++) {
144 try {
145 res = await fetch(this.url(path, server), {
146 method,
147 headers: this.headers(sent === undefined ? undefined : "application/json"),
148 ...(sent === undefined ? {} : { body: sent }),
149 signal: AbortSignal.timeout(timeoutMs),
150 });
151 } catch (err) {
152 const e = err as Error;
153 const why =
154 e.name === "TimeoutError"
155 ? `no answer within ${timeoutMs} ms`
156 : ((e.cause as Error | undefined)?.message ?? e.message);
157 if (!neverSent(err)) throw new ApiError(`could not reach ${server}: ${why}`);
158 if (attempt >= 1) {
159 throw new ApiError(
160 `could not reach ${server}: ${why}. Tried twice, the second time IPv4 first; the connection never opened, so nothing reached the server`,
161 undefined,
162 true,
163 );
164 }
165 setDefaultResultOrder("ipv4first");
166 await new Promise((ok) => setTimeout(ok, 500));
167 }
168 }
169 const text = await res.text();
170 // 409 is a refusal that says what to do (a drop took out lines your work builds on): print it as it is.
171 if (!res.ok)
172 throw new ApiError(
173 res.status === 409
174 ? `refused: ${errorSentence(text)}`
175 : `${method} ${path} answered ${res.status}: ${errorSentence(text)}`,
176 res.status,
177 );
178 try {
179 return JSON.parse(text) as T;
180 } catch {
181 throw new ApiError(
182 `${method} ${path} answered with something that isn't JSON: ${text.slice(0, 300)}`,
183 res.status,
184 );
185 }
186 }
188 init(
189 files: Record<string, string>,
190 modes: Modes = {},
191 blobs: Readonly<Record<string, string>> = {},
192 ): Promise<{ version: number; skipped?: readonly string[] }> {
193 return this.json("POST", "/init", {
194 files,
195 ...(Object.keys(modes).length > 0 ? { modes } : {}),
196 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
197 });
198 }
200 edit(body: EditBody): Promise<EditAnswer> {
201 return this.json("POST", this.agentPath("edit"), body);
202 }
204 record(
205 files: Record<string, string | null>,
206 extra: { session?: string; subagent?: string } = {},
207 modes: Modes = {},
208 blobs: Readonly<Record<string, string>> = {},
209 ): Promise<RecordAnswer> {
210 return this.json("POST", this.agentPath("record"), {
211 files,
212 ...(Object.keys(modes).length > 0 ? { modes } : {}),
213 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
214 ...extra,
215 });
216 }
218 /** Move a file in the draft (#49): its lines keep their ids. The way to change a file's case. */
219 move(from: string, to: string): Promise<{ ok: boolean; from: string; to: string; news?: News }> {
220 return this.json("POST", this.agentPath("move"), { from, to });
221 }
223 /** Upload a binary file's bytes under their sha256 (the server checks the hash). */
224 async putBlob(sha: string, bytes: Uint8Array): Promise<void> {
225 await this.bytes("PUT", `/blobs/${sha}`, bytes);
226 }
228 /** A preview of one version of shared at a stable URL (abso serve, #37); a build answers 422 with its output. */
229 async serve(version?: number, cmd?: string, out?: string): Promise<ServeAnswer> {
230 const q = new URLSearchParams({
231 ...(version !== undefined ? { version: String(version) } : {}),
232 ...(cmd ? { cmd } : {}),
233 ...(out ? { out } : {}),
234 });
235 let res: Response;
236 try {
237 res = await fetch(`${this.url("/serve")}?${q}`, {
238 method: "POST",
239 headers: this.headers(),
240 signal: AbortSignal.timeout(20 * 60_000),
241 });
242 } catch (err) {
243 const e = err as Error;
244 throw new ApiError(
245 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
246 );
247 }
248 const text = await res.text();
249 if (!res.ok && res.status !== 422)
250 throw new ApiError(`serve answered ${res.status}: ${errorSentence(text)}`, res.status);
251 return JSON.parse(text) as ServeAnswer;
252 }
254 /** Runs a setup command on the folder in a fresh box and keeps the box as what it starts from (abso prep, #37). */
255 async prep(command: string, tarGz: Uint8Array<ArrayBuffer>): Promise<PrepAnswer> {
256 let res: Response;
257 try {
258 res = await fetch(`${this.url(this.agentPath("prep"))}?cmd=${encodeURIComponent(command)}${boxQuery(this.box)}`, {
259 method: "POST",
260 headers: this.headers("application/gzip"),
261 body: tarGz,
262 // A setup command can take minutes (npm ci, a browser download).
263 signal: AbortSignal.timeout(30 * 60_000),
264 });
265 } catch (err) {
266 const e = err as Error;
267 throw new ApiError(
268 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
269 );
270 }
271 const text = await res.text();
272 if (!res.ok) throw new ApiError(`prep answered ${res.status}: ${errorSentence(text)}`, res.status);
273 return JSON.parse(text) as PrepAnswer;
274 }
276 /** Forgets the box's prep: it starts from the plain image again. Answers whether it had one. */
277 async unprep(): Promise<boolean> {
278 let res: Response;
279 try {
280 res = await fetch(
281 `${this.url(this.agentPath("prep"))}${this.box ? `?box=${encodeURIComponent(this.box)}` : ""}`,
282 { method: "DELETE", headers: this.headers(), signal: AbortSignal.timeout(this.timeoutMs) },
283 );
284 } catch (err) {
285 const e = err as Error;
286 throw new ApiError(
287 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
288 );
289 }
290 const text = await res.text();
291 if (!res.ok) throw new ApiError(`prep answered ${res.status}: ${errorSentence(text)}`, res.status);
292 return (JSON.parse(text) as { forgot: boolean }).forgot;
293 }
295 /** A binary file's bytes by their sha256. */
296 /** A tar.gz of the files under the box's /w that match a glob (bash globstar); null when none match or the box has stopped. */
297 async boxFiles(glob: string): Promise<Uint8Array | null> {
298 try {
299 return await this.bytes(
300 "GET",
301 `${this.agentPath("box-files")}?${new URLSearchParams({ glob, ...(this.box ? { box: this.box } : {}) })}`,
302 );
303 } catch (err) {
304 if (err instanceof ApiError && err.status === 404) return null;
305 throw err;
306 }
307 }
309 getBlob(sha: string): Promise<Uint8Array> {
310 return this.bytes("GET", `/blobs/${sha}`);
311 }
313 async bytes(method: "GET" | "PUT", path: string, body?: Uint8Array): Promise<Uint8Array> {
314 let res: Response;
315 try {
316 res = await fetch(this.url(path), {
317 method,
318 headers: this.headers(body === undefined ? undefined : "application/octet-stream"),
319 ...(body === undefined ? {} : { body: body as Uint8Array<ArrayBuffer> }),
320 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
321 });
322 } catch (err) {
323 const e = err as Error;
324 throw new ApiError(
325 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
326 );
327 }
328 const data = new Uint8Array(await res.arrayBuffer());
329 if (!res.ok)
330 throw new ApiError(
331 `${method} ${path} answered ${res.status}: ${errorSentence(new TextDecoder().decode(data))}`,
332 res.status,
333 );
334 return data;
335 }
337 /** Make this agent a reader, or not (#37): a reader's edits, records and publishes are refused. */
338 reader(on: boolean): Promise<{ agent: string; reader: boolean }> {
339 return this.json("POST", this.agentPath("reader"), { reader: on });
340 }
342 publish(message: string, asIs = false): Promise<PublishAnswer> {
343 return this.json("POST", this.agentPath("publish"), { message, ...(asIs ? { asIs: true } : {}) });
344 }
346 /** One change (#44). */
347 change(id: number): Promise<ChangeAnswer> {
348 return this.json("GET", `/change/${id}`);
349 }
351 /** The changes with anything new at or after log position `since`, newest first (#44). */
352 /** Changes active since a log position, newest first; `older` is set when more come before the page (ask again with `before`). */
353 changes(
354 since: number,
355 limit = 50,
356 before?: number,
357 ): Promise<{ since: number; next: number; changes: readonly ChangeAnswer[]; older?: number }> {
358 return this.json("GET", `/changes?${query({ since, limit, before })}`);
359 }
361 /** A call to the Issues Worker (#54), with the same token. */
362 #issues<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> {
363 if (this.issuesServer === undefined)
364 throw new ApiError(`${this.config.server} has no Issues Worker beside it; AVCS_ISSUES_SERVER names one`);
365 return this.json(method, path, body, this.issuesServer);
366 }
368 /** Issues, most recently updated first. */
369 issues(
370 q: { status?: string; agent?: string; parent?: number; open?: boolean; labels?: readonly string[] } = {},
371 ): Promise<{ issues: readonly IssueRow[] }> {
372 return this.#issues(
373 "GET",
374 `/issues?${query({ status: q.status, agent: q.agent, parent: q.parent, open: q.open ? 1 : undefined, label: q.labels && q.labels.length > 0 ? q.labels.join(",") : undefined })}`,
375 );
376 }
378 /** Every label in use, with how many issues have it and how many of those are open. */
379 issueLabels(): Promise<{ labels: readonly { label: string; open: number; total: number }[] }> {
380 return this.#issues("GET", "/labels");
381 }
383 issue(id: number): Promise<IssuePage> {
384 return this.#issues("GET", `/issue/${id}`);
385 }
387 /** Open asks of someone (an agent, or person:<id>), soonest due first; every open ask without `of`. */
388 waiting(of?: string): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
389 return this.#issues("GET", `/waiting?${query({ of })}`);
390 }
392 /** This agent's open asks; the Worker marks each it lists for the first time as seen (abso issue 124). */
393 async waitingMine(): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
394 try {
395 return await this.#issues("GET", this.agentPath("waiting"));
396 } catch (err) {
397 // An Issues Worker from before 124 has no /a/:agent/ reads.
398 if (err instanceof ApiError && err.status === 404) return this.waiting(this.config.agent);
399 throw err;
400 }
401 }
403 issueOpen(body: DraftBody & { title: string }): Promise<{ id: number; news?: IssueNews }> {
404 return this.#issues("POST", this.agentPath("issue"), body);
405 }
407 /** An edit (abso issue 3): it tells the issue's watchers, and `also`, unless `notify` is false. null clears a parent or Agent. */
408 issueEdit(
409 id: number,
410 body: {
411 title?: string;
412 description?: string;
413 parent?: number | null;
414 agent?: string | null;
415 blockedBy?: number[];
416 notify?: boolean;
417 also?: string[];
418 addLabels?: string[];
419 removeLabels?: string[];
420 },
421 ): Promise<{ edit: number; notified: readonly string[]; news?: IssueNews }> {
422 return this.#issues("POST", this.agentPath(`issue/${id}/edit`), body);
423 }
425 issueComment(id: number, text: string, objection = false): Promise<{ id: number; news?: IssueNews }> {
426 return this.#issues("POST", this.agentPath(`issue/${id}/comment`), { text, ...(objection ? { objection } : {}) });
427 }
429 issueDrop(id: number): Promise<{ news?: IssueNews }> {
430 return this.#issues("POST", this.agentPath(`issue/${id}/drop`), {});
431 }
433 /** Opens a dropped issue again (abso issue 104). */
434 issueReopen(id: number): Promise<{ news?: IssueNews }> {
435 return this.#issues("POST", this.agentPath(`issue/${id}/reopen`), {});
436 }
438 /** Marks an issue done by hand (abso issue 38). `version` is the publish that did it, when there is one. */
439 issueDone(id: number, version: number | null): Promise<{ news?: IssueNews }> {
440 return this.#issues("POST", this.agentPath(`issue/${id}/done`), { ...(version !== null ? { version } : {}) });
441 }
443 /** This agent's drafts (abso issue 3): its own, with no number and no news, newest first. */
444 drafts(): Promise<{ drafts: readonly Draft[] }> {
445 return this.#issues("GET", this.agentPath("drafts"));
446 }
448 /** Saves a draft, new or (with id) over one of this agent's: the body replaces the draft's. */
449 saveDraft(body: DraftBody & { id?: number }): Promise<{ id: number }> {
450 return this.#issues("POST", this.agentPath("draft"), body);
451 }
453 /** Opens a draft as an issue, `body`'s fields over the draft's, and deletes the draft. */
454 openDraft(id: number, body: DraftBody = {}): Promise<{ id: number; news?: IssueNews }> {
455 return this.#issues("POST", this.agentPath(`draft/${id}/open`), body);
456 }
458 deleteDraft(id: number): Promise<{ ok: boolean }> {
459 return this.#issues("POST", this.agentPath(`draft/${id}/delete`), {});
460 }
462 ask(body: {
463 issue?: number;
464 of: string;
465 question: string;
466 review?: boolean;
467 kind?: "question" | "task";
468 due?: string;
469 blocks?: number[];
470 options?: string[];
471 }): Promise<{ id: number; news?: IssueNews }> {
472 return this.#issues("POST", this.agentPath("ask"), body);
473 }
475 answer(
476 id: number,
477 body: { words?: string; option?: number | string; note?: string; done?: boolean },
478 ): Promise<{ ask: Ask; news?: IssueNews }> {
479 return this.#issues("POST", this.agentPath(`answer/${id}`), body);
480 }
482 /** Notes on lines (#44), by file or change; open ones only with `open`. */
483 notes(q: { file?: string; change?: number; open?: boolean } = {}): Promise<{ notes: readonly NoteAnswer[] }> {
484 return this.json("GET", `/notes?${query({ file: q.file, change: q.change, open: q.open ? 1 : undefined })}`);
485 }
487 note(body: NoteBody): Promise<{ id: number; change: number | null; lines: readonly [number, number] }> {
488 return this.json("POST", this.agentPath("note"), body);
489 }
491 noteClose(id: number, how: "resolved" | "withdrawn"): Promise<unknown> {
492 return this.json("POST", this.agentPath("note-close"), { id, how });
493 }
495 /** The merge queue now (#39). */
496 queueState(): Promise<QueueState> {
497 return this.json("GET", "/queue");
498 }
500 /** The project's visibility (abso issue 152): public or private. */
501 visibility(): Promise<{ project: string; visibility: "public" | "private" }> {
502 return this.json("GET", "/visibility");
503 }
505 /** Switch the project's visibility (abso issue 140): an owner's key, or the shared token on staging. */
506 setVisibility(v: "public" | "private"): Promise<{ project: string; visibility: "public" | "private" }> {
507 return this.json("POST", `/visibility?visibility=${v}`, {});
508 }
510 /** Take back this agent's queued publishes (#39); refused while one is being checked. */
511 unqueue(): Promise<{ pulled: readonly number[] }> {
512 return this.json("POST", this.agentPath("unqueue"), {});
513 }
515 /**
516 * Sync; a folder following a label goes to the newest version with that label.
517 * With `full`, the answer holds every file in the agent's view, as a first sync's does,
518 * not only what changed since its last sync (#37: a join for an agent the server knew).
519 */
520 sync(options: { full?: boolean } = {}): Promise<SyncAnswer> {
521 return this.json("POST", this.agentPath("sync"), {
522 ...(this.config.follow ? { label: this.config.follow } : {}),
523 ...(options.full ? { full: true } : {}),
524 });
525 }
527 /** Take published versions back out of shared (with the versions that build on them, when asked). */
528 drop(versions: readonly number[], message: string, withDependents = false): Promise<DropAnswer> {
529 return this.json("POST", this.agentPath("drop"), {
530 versions,
531 message,
532 ...(withDependents ? { withDependents: true } : {}),
533 });
534 }
536 /** Take some versions of a named draft into shared, as one version. */
537 pluck(draft: string, versions: readonly number[], message: string, withDependencies = false): Promise<PluckAnswer> {
538 return this.json("POST", this.agentPath("pluck"), {
539 draft,
540 versions,
541 message,
542 ...(withDependencies ? { withDependencies: true } : {}),
543 });
544 }
546 /** Correct the message of this agent's newest publish in its space. */
547 amend(message: string): Promise<{ version: number; draft: string | null; message: string; was: string }> {
548 return this.json("POST", this.agentPath("amend"), { message });
549 }
551 /** Put a label on a version of shared (the newest by default), or take it off. */
552 label(
553 name: string,
554 version?: number,
555 remove = false,
556 ): Promise<{ name: string; version: number; versions: readonly number[] }> {
557 return this.json("POST", this.agentPath("label"), {
558 name,
559 ...(version === undefined ? {} : { version }),
560 ...(remove ? { remove: true } : {}),
561 });
562 }
564 labels(): Promise<{ labels: Readonly<Record<string, readonly number[]>> }> {
565 return this.json("GET", "/labels");
566 }
568 status(): Promise<StatusAnswer> {
569 return this.json("GET", "/status");
570 }
572 /** The status and the paths in the agent's view, in one trip (abso issue 80). */
573 async statusAndFiles(): Promise<StatusAnswer & { files: FilesAnswer | undefined }> {
574 try {
575 return await this.json("GET", this.agentPath("status"));
576 } catch (err) {
577 // A server from before it has no /a/:agent/status; the listing itself is from #37.
578 if (!(err instanceof ApiError && err.status === 404)) throw err;
579 }
580 const status = await this.status();
581 return { ...status, files: await this.viewFiles().catch(() => undefined) };
582 }
584 /** CI's state (#39), or one version's job. */
585 ci(): Promise<CiStatus>;
586 ci(version: number): Promise<CiJob>;
587 ci(version?: number): Promise<CiStatus | CiJob> {
588 return this.json("GET", version === undefined ? "/ci" : `/ci?${query({ version })}`);
589 }
591 /** Ends every /latest link handed out so far; answers CI's state with the new link. */
592 ciRevoke(): Promise<CiStatus> {
593 return this.json("POST", "/ci/revoke", {});
594 }
596 /** Count versions up to `through` as seen by CI and end any red or bisect, so an import's history isn't checked (#56). */
597 ciSkip(through: number): Promise<unknown> {
598 return this.json("POST", "/ci/skip", { through });
599 }
601 /** Move to a named draft (null: shared). With carry, the current unpublished changes start a new draft. */
602 switchDraft(name: string | null, carry = false): Promise<SwitchAnswer> {
603 return this.json("POST", this.agentPath("draft"), { name, ...(carry ? { carry: true } : {}) });
604 }
606 /** Land never queues: with the merge queue on, the server refuses it (#39). */
607 land(message: string): Promise<Exclude<PublishAnswer, { queued: number }>> {
608 return this.json("POST", this.agentPath("land"), { message });
609 }
611 draftSync(): Promise<DraftSyncAnswer> {
612 return this.json("POST", this.agentPath("draft-sync"), {});
613 }
615 blame(file: string, from?: number, to?: number, version?: number, view: View = {}): Promise<BlameAnswer> {
616 return this.json("GET", `/blame?${query({ file, from, to, version, ...view })}`);
617 }
619 /** The paths in the agent's view: what its folder should hold (#37). */
620 viewFiles(): Promise<FilesAnswer> {
621 return this.json("GET", this.agentPath("files"));
622 }
624 /** The paths in shared, or a named draft, at a version (the newest by default). */
625 filesAt(draft: string | null, version?: number): Promise<FilesAnswer> {
626 return this.json("GET", `/files?${query({ draft, version })}`);
627 }
629 /** The versions of a space, newest first; with `path`, only those that changed it. */
630 log(where: Where, limit?: number, path?: string): Promise<LogAnswer> {
631 return this.json("GET", `/log?${query({ ...where, limit, path })}`);
632 }
634 show(version: number, where: Where): Promise<ShowAnswer> {
635 return this.json("GET", `/show?${query({ version, ...where })}`);
636 }
638 fileAt(path: string, version: number, where: Where): Promise<{ path: string; version: number; text: string | null }> {
639 return this.json("GET", `/file?${query({ path, version, ...where })}`);
640 }
642 compare(from: number, to: number, where: Where): Promise<{ from: number; to: number; files: readonly FileChange[] }> {
643 return this.json("GET", `/compare?${query({ from, to, ...where })}`);
644 }
646 /** A message to the project's other agents (or those named), delivered once as news. */
647 starting(
648 text: string | null,
649 files?: readonly string[],
650 options: { issue?: number; done?: boolean } = {},
651 ): Promise<{
652 starting: { text: string; files: readonly string[]; time: number; issue?: number } | null;
653 overlaps: readonly Overlap[];
654 }> {
655 return this.json("POST", this.agentPath("starting"), {
656 text,
657 ...(files && files.length > 0 ? { files } : {}),
658 ...(options.issue !== undefined ? { issue: options.issue } : {}),
659 ...(options.done ? { done: true } : {}),
660 });
661 }
663 announce(text: string, to?: readonly string[]): Promise<{ id: number; to: readonly string[] }> {
664 return this.json("POST", this.agentPath("announce"), { text, ...(to ? { to } : {}) });
665 }
667 /** The news waiting for this agent, handed over once. */
668 news(): Promise<{ news: News; items?: readonly { readonly text: string; readonly at: number | null }[] }> {
669 return this.json("POST", this.agentPath("news"), {});
670 }
672 /** This agent's unpublished changes, file by file. */
673 diff(): Promise<DiffAnswer> {
674 return this.json("POST", this.agentPath("diff"), {});
675 }
677 /** Discard this agent's unpublished changes to `files` (null: all of them). */
678 restore(files: readonly string[] | null): Promise<RestoreAnswer> {
679 return this.json("POST", this.agentPath("restore"), files === null ? { all: true } : { files });
680 }
682 why(file: string, line: number, view: View = {}): Promise<WhyAnswer> {
683 return this.json("GET", `/why?${query({ file, line, ...view })}`);
684 }
686 where(): Promise<WhereAnswer> {
687 return this.json("GET", "/where");
688 }
690 /**
691 * Send the folder as a tar.gz and run a command in the agent's box. Output
692 * goes to `io.out` as it arrives, and the box's stderr to `io.err` (the
693 * server keeps them apart when asked; an older one sends both as out).
694 * Answers the command's exit code.
695 *
696 * When the stream breaks before the exit line and the server gave the run
697 * an id, the run goes on in the box: this reconnects to it and carries on
698 * from the last output printed, so nothing is lost or printed twice. The
699 * command itself is never sent twice.
700 */
701 async run(command: string, tarGz: Uint8Array<ArrayBuffer>, io: RunIO): Promise<number> {
702 const res = await postRun(this, command, tarGz, io.onRetry, io.replace, io.fresh);
703 // X-Avcs-Box: cold means the box started for this run; X-Avcs-Prep says whether it started from the prep (#37).
704 io.onBox?.(res.headers.get("x-avcs-box") === "cold", res.headers.get("x-avcs-prep") ?? undefined);
705 return follow(this, res, res.headers.get("x-avcs-run"), { at: 0, errAt: 0 }, io);
706 }
708 /**
709 * Start a run and answer its id without waiting: the job goes on in the box
710 * after this connection closes (abso run --detach; abso logs <id> follows it).
711 */
712 async startRun(
713 command: string,
714 tarGz: Uint8Array<ArrayBuffer>,
715 onRetry?: (why: string, attempt: number) => void,
716 replace = false,
717 ): Promise<string> {
718 const res = await postRun(this, command, tarGz, onRetry, replace);
719 const id = res.headers.get("x-avcs-run");
720 if (id === null) {
721 // No id: the box failed before the job started ({"error"} in the body), or the server can't detach.
722 await consumeRun(res, { out: () => {} }, { at: 0, errAt: 0 });
723 throw new ApiError("this server gives runs no id, so a run can't be detached");
724 }
725 await res.body?.cancel();
726 return id;
727 }
729 /** A run's output from its start, for as long as the box keeps it, until it ends (abso logs). Answers its exit code. */
730 async logs(id: string, io: RunIO): Promise<number> {
731 let res: Response;
732 try {
733 res = await fetch(followUrl(this, id, { at: 0, errAt: 0 }), { headers: this.headers() });
734 } catch (err) {
735 const e = err as Error;
736 throw new ApiError(
737 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
738 );
739 }
740 if (res.status === 404) throw new ApiError(`no run ${id} in this box: ${errorSentence(await res.text())}`, 404);
741 if (!res.ok || res.body === null)
742 throw new ApiError(`logs answered ${res.status}: ${errorSentence(await res.text())}`, res.status);
743 return follow(this, res, id, { at: 0, errAt: 0 }, io);
744 }