- 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=16&format=json
795 linesFirst import 93% · pinch 6% · infra-split 1%Last change pinch in version 15, 4 versions changed it
You're reading version 16. The newest is 318, and 26 versions since then changed this file.
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).
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, Attachment, 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, Attachment, 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;
77}
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;
84}
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() !== "");
89}
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; attachments?: string[] }): Promise<{ id: number; news?: IssueNews }> {
404 return this.#issues("POST", this.agentPath("issue"), body);
405 }
407 /** Uploads an image to the Issues Worker (abso issue 171): it checks the type by the bytes, strips metadata and answers its id. */
408 async attachmentUpload(bytes: Uint8Array, name: string): Promise<Attachment> {
409 if (this.issuesServer === undefined)
410 throw new ApiError(`${this.config.server} has no Issues Worker beside it; AVCS_ISSUES_SERVER names one`);
411 const path = this.agentPath("attachments");
412 let res: Response;
413 try {
414 res = await fetch(this.url(path, this.issuesServer), {
415 method: "POST",
416 headers: { ...this.headers("application/octet-stream"), "x-avcs-name": encodeURIComponent(name) },
417 body: bytes as Uint8Array<ArrayBuffer>,
418 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
419 });
420 } catch (err) {
421 const e = err as Error;
422 throw new ApiError(
423 `could not reach ${this.issuesServer}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
424 );
425 }
426 const text = await res.text();
427 // A server from before attachments has no upload route: it answers 404, or 400 because the body isn't JSON;
428 // one with the route but nowhere to keep files answers 501. Say so plainly, and that nothing was sent.
429 if (res.status === 404 || res.status === 501 || (res.status === 400 && /the body is JSON/.test(text)))
430 throw new ApiError(
431 `${this.issuesServer} doesn't take attachments yet, so ${name} wasn't sent and nothing was written. Leave --attach off, or link the image instead.`,
432 res.status,
433 );
434 if (!res.ok) throw new ApiError(`uploading ${name} answered ${res.status}: ${errorSentence(text)}`, res.status);
435 return JSON.parse(text) as Attachment;
436 }
438 /** Where an attachment is served. */
439 attachmentUrl(id: string): string {
440 return this.url(`/attachments/${id}`, this.issuesServer);
441 }
443 /** An edit (abso issue 3): it tells the issue's watchers, and `also`, unless `notify` is false. null clears a parent or Agent. */
444 issueEdit(
445 id: number,
446 body: {
447 title?: string;
448 description?: string;
449 parent?: number | null;
450 agent?: string | null;
451 blockedBy?: number[];
452 notify?: boolean;
453 also?: string[];
454 addLabels?: string[];
455 removeLabels?: string[];
456 },
457 ): Promise<{ edit: number; notified: readonly string[]; news?: IssueNews }> {
458 return this.#issues("POST", this.agentPath(`issue/${id}/edit`), body);
459 }
461 issueComment(
462 id: number,
463 text: string,
464 objection = false,
465 attachments: readonly string[] = [],
466 ): Promise<{ id: number; news?: IssueNews }> {
467 return this.#issues("POST", this.agentPath(`issue/${id}/comment`), {
468 text,
469 ...(objection ? { objection } : {}),
470 ...(attachments.length > 0 ? { attachments } : {}),
471 });
472 }
474 issueDrop(id: number): Promise<{ news?: IssueNews }> {
475 return this.#issues("POST", this.agentPath(`issue/${id}/drop`), {});
476 }
478 /** Opens a dropped issue again (abso issue 104). */
479 issueReopen(id: number): Promise<{ news?: IssueNews }> {
480 return this.#issues("POST", this.agentPath(`issue/${id}/reopen`), {});
481 }
483 /** Marks an issue done by hand (abso issue 38). `version` is the publish that did it, when there is one. */
484 issueDone(id: number, version: number | null): Promise<{ news?: IssueNews }> {
485 return this.#issues("POST", this.agentPath(`issue/${id}/done`), { ...(version !== null ? { version } : {}) });
486 }
488 /** This agent's drafts (abso issue 3): its own, with no number and no news, newest first. */
489 drafts(): Promise<{ drafts: readonly Draft[] }> {
490 return this.#issues("GET", this.agentPath("drafts"));
491 }
493 /** Saves a draft, new or (with id) over one of this agent's: the body replaces the draft's. */
494 saveDraft(body: DraftBody & { id?: number }): Promise<{ id: number }> {
495 return this.#issues("POST", this.agentPath("draft"), body);
496 }
498 /** Opens a draft as an issue, `body`'s fields over the draft's, and deletes the draft. */
499 openDraft(id: number, body: DraftBody = {}): Promise<{ id: number; news?: IssueNews }> {
500 return this.#issues("POST", this.agentPath(`draft/${id}/open`), body);
501 }
503 deleteDraft(id: number): Promise<{ ok: boolean }> {
504 return this.#issues("POST", this.agentPath(`draft/${id}/delete`), {});
505 }
507 ask(body: {
508 issue?: number;
509 of: string;
510 question: string;
511 review?: boolean;
512 kind?: "question" | "task";
513 due?: string;
514 blocks?: number[];
515 options?: string[];
516 }): Promise<{ id: number; news?: IssueNews }> {
517 return this.#issues("POST", this.agentPath("ask"), body);
518 }
520 answer(
521 id: number,
522 body: { words?: string; option?: number | string; note?: string; done?: boolean },
523 ): Promise<{ ask: Ask; news?: IssueNews }> {
524 return this.#issues("POST", this.agentPath(`answer/${id}`), body);
525 }
527 /** Takes back an ask this agent made, with a note on why; the one asked hears it. */
528 withdraw(id: number, body: { note?: string }): Promise<{ ask: Ask; news?: IssueNews }> {
529 return this.#issues("POST", this.agentPath(`withdraw/${id}`), body);
530 }
532 /** Notes on lines (#44), by file or change; open ones only with `open`. */
533 notes(q: { file?: string; change?: number; open?: boolean } = {}): Promise<{ notes: readonly NoteAnswer[] }> {
534 return this.json("GET", `/notes?${query({ file: q.file, change: q.change, open: q.open ? 1 : undefined })}`);
535 }
537 note(body: NoteBody): Promise<{ id: number; change: number | null; lines: readonly [number, number] }> {
538 return this.json("POST", this.agentPath("note"), body);
539 }
541 noteClose(id: number, how: "resolved" | "withdrawn"): Promise<unknown> {
542 return this.json("POST", this.agentPath("note-close"), { id, how });
543 }
545 /** The merge queue now (#39). */
546 queueState(): Promise<QueueState> {
547 return this.json("GET", "/queue");
548 }
550 /** The project's visibility (abso issue 152): public or private. */
551 visibility(): Promise<{ project: string; visibility: "public" | "private" }> {
552 return this.json("GET", "/visibility");
553 }
555 /** Switch the project's visibility (abso issue 140): an owner's key, or the shared token on staging. */
556 setVisibility(v: "public" | "private"): Promise<{ project: string; visibility: "public" | "private" }> {
557 return this.json("POST", `/visibility?visibility=${v}`, {});
558 }
560 /** Take back this agent's queued publishes (#39); refused while one is being checked. */
561 unqueue(): Promise<{ pulled: readonly number[] }> {
562 return this.json("POST", this.agentPath("unqueue"), {});
563 }
565 /**
566 * Sync; a folder following a label goes to the newest version with that label.
567 * With `full`, the answer holds every file in the agent's view, as a first sync's does,
568 * not only what changed since its last sync (#37: a join for an agent the server knew).
569 */
570 sync(options: { full?: boolean } = {}): Promise<SyncAnswer> {
571 return this.json("POST", this.agentPath("sync"), {
572 ...(this.config.follow ? { label: this.config.follow } : {}),
573 ...(options.full ? { full: true } : {}),
574 });
575 }
577 /** Take published versions back out of shared (with the versions that build on them, when asked). */
578 drop(versions: readonly number[], message: string, withDependents = false): Promise<DropAnswer> {
579 return this.json("POST", this.agentPath("drop"), {
580 versions,
581 message,
582 ...(withDependents ? { withDependents: true } : {}),
583 });
584 }
586 /** Take some versions of a named draft into shared, as one version. */
587 pluck(draft: string, versions: readonly number[], message: string, withDependencies = false): Promise<PluckAnswer> {
588 return this.json("POST", this.agentPath("pluck"), {
589 draft,
590 versions,
591 message,
592 ...(withDependencies ? { withDependencies: true } : {}),
593 });
594 }
596 /** Correct the message of this agent's newest publish in its space. */
597 amend(message: string): Promise<{ version: number; draft: string | null; message: string; was: string }> {
598 return this.json("POST", this.agentPath("amend"), { message });
599 }
601 /** Put a label on a version of shared (the newest by default), or take it off. */
602 label(
603 name: string,
604 version?: number,
605 remove = false,
606 ): Promise<{ name: string; version: number; versions: readonly number[] }> {
607 return this.json("POST", this.agentPath("label"), {
608 name,
609 ...(version === undefined ? {} : { version }),
610 ...(remove ? { remove: true } : {}),
611 });
612 }
614 labels(): Promise<{ labels: Readonly<Record<string, readonly number[]>> }> {
615 return this.json("GET", "/labels");
616 }
618 status(): Promise<StatusAnswer> {
619 return this.json("GET", "/status");
620 }
622 /** The status and the paths in the agent's view, in one trip (abso issue 80). */
623 async statusAndFiles(): Promise<StatusAnswer & { files: FilesAnswer | undefined }> {
624 try {
625 return await this.json("GET", this.agentPath("status"));
626 } catch (err) {
627 // A server from before it has no /a/:agent/status; the listing itself is from #37.
628 if (!(err instanceof ApiError && err.status === 404)) throw err;
629 }
630 const status = await this.status();
631 return { ...status, files: await this.viewFiles().catch(() => undefined) };
632 }
634 /** CI's state (#39), or one version's job. */
635 ci(): Promise<CiStatus>;
636 ci(version: number): Promise<CiJob>;
637 ci(version?: number): Promise<CiStatus | CiJob> {
638 return this.json("GET", version === undefined ? "/ci" : `/ci?${query({ version })}`);
639 }
641 /** Ends every /latest link handed out so far; answers CI's state with the new link. */
642 ciRevoke(): Promise<CiStatus> {
643 return this.json("POST", "/ci/revoke", {});
644 }
646 /** Count versions up to `through` as seen by CI and end any red or bisect, so an import's history isn't checked (#56). */
647 ciSkip(through: number): Promise<unknown> {
648 return this.json("POST", "/ci/skip", { through });
649 }
651 /** Move to a named draft (null: shared). With carry, the current unpublished changes start a new draft. */
652 switchDraft(name: string | null, carry = false): Promise<SwitchAnswer> {
653 return this.json("POST", this.agentPath("draft"), { name, ...(carry ? { carry: true } : {}) });
654 }
656 /** Land never queues: with the merge queue on, the server refuses it (#39). */
657 land(message: string): Promise<Exclude<PublishAnswer, { queued: number }>> {
658 return this.json("POST", this.agentPath("land"), { message });
659 }
661 draftSync(): Promise<DraftSyncAnswer> {
662 return this.json("POST", this.agentPath("draft-sync"), {});
663 }
665 blame(file: string, from?: number, to?: number, version?: number, view: View = {}): Promise<BlameAnswer> {
666 return this.json("GET", `/blame?${query({ file, from, to, version, ...view })}`);
667 }
669 /** The paths in the agent's view: what its folder should hold (#37). */
670 viewFiles(): Promise<FilesAnswer> {
671 return this.json("GET", this.agentPath("files"));
672 }
674 /** The paths in shared, or a named draft, at a version (the newest by default). */
675 filesAt(draft: string | null, version?: number): Promise<FilesAnswer> {
676 return this.json("GET", `/files?${query({ draft, version })}`);
677 }
679 /** The versions of a space, newest first; with `path`, only those that changed it. */
680 log(where: Where, limit?: number, path?: string): Promise<LogAnswer> {
681 return this.json("GET", `/log?${query({ ...where, limit, path })}`);
682 }
684 show(version: number, where: Where): Promise<ShowAnswer> {
685 return this.json("GET", `/show?${query({ version, ...where })}`);
686 }
688 fileAt(path: string, version: number, where: Where): Promise<{ path: string; version: number; text: string | null }> {
689 return this.json("GET", `/file?${query({ path, version, ...where })}`);
690 }
692 compare(from: number, to: number, where: Where): Promise<{ from: number; to: number; files: readonly FileChange[] }> {
693 return this.json("GET", `/compare?${query({ from, to, ...where })}`);
694 }
696 /** A message to the project's other agents (or those named), delivered once as news. */
697 starting(
698 text: string | null,
699 files?: readonly string[],
700 options: { issue?: number; done?: boolean } = {},
701 ): Promise<{
702 starting: { text: string; files: readonly string[]; time: number; issue?: number } | null;
703 overlaps: readonly Overlap[];
704 }> {
705 return this.json("POST", this.agentPath("starting"), {
706 text,
707 ...(files && files.length > 0 ? { files } : {}),
708 ...(options.issue !== undefined ? { issue: options.issue } : {}),
709 ...(options.done ? { done: true } : {}),
710 });
711 }
713 announce(text: string, to?: readonly string[]): Promise<{ id: number; to: readonly string[] }> {
714 return this.json("POST", this.agentPath("announce"), { text, ...(to ? { to } : {}) });
715 }
717 /** The news waiting for this agent, handed over once. */
718 news(): Promise<{ news: News; items?: readonly { readonly text: string; readonly at: number | null }[] }> {
719 return this.json("POST", this.agentPath("news"), {});
720 }
722 /** This agent's unpublished changes, file by file. */
723 diff(): Promise<DiffAnswer> {
724 return this.json("POST", this.agentPath("diff"), {});
725 }
727 /** Discard this agent's unpublished changes to `files` (null: all of them). */
728 restore(files: readonly string[] | null): Promise<RestoreAnswer> {
729 return this.json("POST", this.agentPath("restore"), files === null ? { all: true } : { files });
730 }
732 why(file: string, line: number, view: View = {}): Promise<WhyAnswer> {
733 return this.json("GET", `/why?${query({ file, line, ...view })}`);
734 }
736 where(): Promise<WhereAnswer> {
737 return this.json("GET", "/where");
738 }
740 /**
741 * Send the folder as a tar.gz and run a command in the agent's box. Output
742 * goes to `io.out` as it arrives, and the box's stderr to `io.err` (the
743 * server keeps them apart when asked; an older one sends both as out).
744 * Answers the command's exit code.
745 *
746 * When the stream breaks before the exit line and the server gave the run
747 * an id, the run goes on in the box: this reconnects to it and carries on
748 * from the last output printed, so nothing is lost or printed twice. The
749 * command itself is never sent twice.
750 */
751 async run(command: string, tarGz: Uint8Array<ArrayBuffer>, io: RunIO): Promise<number> {
752 const res = await postRun(this, command, tarGz, io.onRetry, io.replace, io.fresh);
753 // X-Avcs-Box: cold means the box started for this run; X-Avcs-Prep says whether it started from the prep (#37).
754 io.onBox?.(res.headers.get("x-avcs-box") === "cold", res.headers.get("x-avcs-prep") ?? undefined);
755 return follow(this, res, res.headers.get("x-avcs-run"), { at: 0, errAt: 0 }, io);
756 }
758 /**
759 * Start a run and answer its id without waiting: the job goes on in the box
760 * after this connection closes (abso run --detach; abso logs <id> follows it).
761 */
762 async startRun(
763 command: string,
764 tarGz: Uint8Array<ArrayBuffer>,
765 onRetry?: (why: string, attempt: number) => void,
766 replace = false,
767 ): Promise<string> {
768 const res = await postRun(this, command, tarGz, onRetry, replace);
769 const id = res.headers.get("x-avcs-run");
770 if (id === null) {
771 // No id: the box failed before the job started ({"error"} in the body), or the server can't detach.
772 await consumeRun(res, { out: () => {} }, { at: 0, errAt: 0 });
773 throw new ApiError("this server gives runs no id, so a run can't be detached");
774 }
775 await res.body?.cancel();
776 return id;
777 }
779 /** A run's output from its start, for as long as the box keeps it, until it ends (abso logs). Answers its exit code. */
780 async logs(id: string, io: RunIO): Promise<number> {
781 let res: Response;
782 try {
783 res = await fetch(followUrl(this, id, { at: 0, errAt: 0 }), { headers: this.headers() });
784 } catch (err) {
785 const e = err as Error;
786 throw new ApiError(
787 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
788 );
789 }
790 if (res.status === 404) throw new ApiError(`no run ${id} in this box: ${errorSentence(await res.text())}`, 404);
791 if (!res.ok || res.body === null)
792 throw new ApiError(`logs answered ${res.status}: ${errorSentence(await res.text())}`, res.status);
793 return follow(this, res, id, { at: 0, errAt: 0 }, io);
794 }
795}