- 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=166&format=json
985 linesFirst import 72% · pinch 23% · devops 2% · codex-prose-authorship-1 1% · codex-capacity-chair 1% · infra-pipeline 1% · Last change codex-capacity-chair in version 162, 21 versions changed it
You're reading version 166. The newest is 318, and 9 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 { randomUUID } from "node:crypto";
6import { setDefaultResultOrder } from "node:dns";
7import type {
8 ChangeAnswer,
9 DraftSyncAnswer,
10 EditAnswer,
11 EditBody,
12 News,
13 NoteAnswer,
14 NoteBody,
15 PublishAnswer,
16 RecordAnswer,
17 StatusAnswer,
18 SwitchAnswer,
19 SyncAnswer,
20} from "./api-answers.ts";
21import { ApiError, errorSentence, neverSent } from "./api-error.ts";
22import {
23 boxQuery,
24 consumeRun,
25 follow,
26 followUrl,
27 type PrepAnswer,
28 postRun,
29 RECONNECT_DELAYS_MS,
30 RUN_START_RETRY_MS,
31 type RunIO,
32 type RunKind,
33 type ServeAnswer,
34} from "./box-run.ts";
35import type { CiJob, CiStatus, QueueState } from "./ci-answers.ts";
36import { clientVersion } from "./client-version.ts";
37import type { Config } from "./config.ts";
38import type {
39 BlameAnswer,
40 DiffAnswer,
41 DropAnswer,
42 FileChange,
43 FilesAnswer,
44 LogAnswer,
45 Overlap,
46 PluckAnswer,
47 RestoreAnswer,
48 ShowAnswer,
49 View,
50 Where,
51 WhereAnswer,
52 WhyAnswer,
53} from "./history-answers.ts";
54import type {
55 Ask,
56 Attachment,
57 Draft,
58 DraftBody,
59 News as IssueNews,
60 IssuePage,
61 IssueRow,
62 IssueSearchHit,
63} from "./issues-wire.ts";
64import type { Modes } from "./modes.ts";
66export * from "./api-answers.ts";
67export { ApiError, neverSent } from "./api-error.ts";
68export {
69 type PrepAnswer,
70 RECONNECT_DELAYS_MS,
71 RUN_START_RETRY_MS,
72 type RunIO,
73 type RunKind,
74 type ServeAnswer,
75} from "./box-run.ts";
76export * from "./ci-answers.ts";
77export * from "./history-answers.ts";
78export type { Ask, Attachment, Draft, DraftBody, IssueNews, IssuePage, IssueRow, IssueSearchHit };
80/**
81 * How long a call may take: the base, plus 1 s for each 100 KB it sends
82 * (abso issue 34: a sync that recorded 191 reformatted files first ran out of
83 * its 30 s while the server was still taking them in).
84 */
85export function timeoutFor(baseMs: number, sent: string | undefined): number {
86 return sent === undefined ? baseMs : baseMs + Math.floor(Buffer.byteLength(sent) / 100_000) * 1000;
87}
89/**
90 * How long a publish or a land may take before the client stops waiting: the
91 * server gives one request up to 2 minutes of work, so a small body can still
92 * take that long (a large merge). Waiting less reported publishes as failed
93 * that went on to land.
94 */
95export const PUBLISH_TIMEOUT_MS = 150_000;
97/** The most versions the server's log sends at once. */
98export const LOG_PAGE = 200;
100/** A query string from the values that are set (null and undefined are left out). */
101function query(values: Record<string, string | number | null | undefined>): URLSearchParams {
102 const q = new URLSearchParams();
103 for (const [k, v] of Object.entries(values)) if (v !== null && v !== undefined) q.set(k, String(v));
104 return q;
105}
107export function newsLines(news: News): string[] {
108 if (news === undefined || news === null) return [];
109 return (typeof news === "string" ? [news] : [...news]).filter((s) => typeof s === "string" && s.trim() !== "");
110}
112/** An issue copy's request: the source, and any texts given cleaned, by their source ids. */
113export interface CopyBody {
114 from: string;
115 issue: number;
116 title?: string;
117 description?: string;
118 comments?: { id: number; text?: string }[];
119 asks?: { id: number; question?: string; answer?: string }[];
120}
122/** What a copy writes, as a dry run answers it. */
123export interface CopyPlan {
124 from: { project: string; issue: number };
125 title: string;
126 edited: ("title" | "description")[];
127 labels: string[];
128 closed: { how: "done" | "dropped" } | null;
129 comments: { edited: boolean }[];
130 asks: { edited: boolean }[];
131 skipped: { comments: number[]; asks: number[] };
132}
134export type CopyAnswer =
135 | { dryRun: true; plan: CopyPlan }
136 | { ok: true; id: number; from: { project: string; issue: number }; skipped: { comments: number[]; asks: number[] } };
138export class Api {
139 readonly config: Config;
140 readonly timeoutMs: number;
142 /** Waits between tries when a run's stream breaks; tests shorten them. */
143 readonly reconnectDelaysMs: readonly number[];
144 readonly startRetryDelaysMs: readonly number[];
145 /** Another box of this agent for run, logs and fetch (--box or ABSO_BOX, #37); undefined is its own box. */
146 box: string | undefined;
148 constructor(
149 config: Config,
150 timeoutMs = 30_000,
151 reconnectDelaysMs: readonly number[] = RECONNECT_DELAYS_MS,
152 startRetryDelaysMs: readonly number[] = RUN_START_RETRY_MS,
153 ) {
154 this.config = config;
155 this.timeoutMs = timeoutMs;
156 this.reconnectDelaysMs = reconnectDelaysMs;
157 this.startRetryDelaysMs = startRetryDelaysMs;
158 }
160 /** What a box run is for, for the server's box-run records (#39): X-Abso-Kind on POST /run. */
161 runKind: RunKind = "run";
163 /** The Issues Worker (#54) this folder's issues calls go to; set by the issues commands (issues.ts). */
164 issuesServer: string | undefined;
166 url(path: string, server = this.config.server): string {
167 return `${server.replace(/\/+$/, "")}/p/${encodeURIComponent(this.config.project)}${path}`;
168 }
170 agentPath(action: string): string {
171 return `/a/${encodeURIComponent(this.config.agent)}/${action}`;
172 }
174 headers(contentType?: string): Record<string, string> {
175 return {
176 // Which client made the call (#29); the mods send theirs too.
177 "x-abso-client": `abso-cli/${clientVersion()}`,
178 ...(this.config.token && !this.config.visitor ? { authorization: `Bearer ${this.config.token}` } : {}),
179 ...(contentType ? { "content-type": contentType } : {}),
180 };
181 }
183 /**
184 * Every request this Api makes goes through here. In a visitor folder it never sends anything but a GET,
185 * and follows no redirect, so nothing it sends goes anywhere it didn't name (headers() adds no sign-in).
186 */
187 send(url: string, init: RequestInit = {}): Promise<Response> {
188 if (!this.config.visitor) return fetch(url, init);
189 if ((init.method ?? "GET") !== "GET")
190 return Promise.reject(new ApiError("a folder that reads signed out sends only reads"));
191 return fetch(url, { ...init, redirect: "error" });
192 }
194 async json<T>(
195 method: "GET" | "POST",
196 path: string,
197 body?: unknown,
198 server = this.config.server,
199 atLeastMs = 0,
200 ): Promise<T> {
201 let res: Response | undefined;
202 if (this.config.visitor && method !== "GET")
203 throw new ApiError(`${path}: a folder that reads signed out sends only reads`);
204 const sent = body === undefined ? undefined : JSON.stringify(body);
205 const requestId = method === "POST" ? randomUUID() : undefined;
206 const timeoutMs = Math.max(atLeastMs, timeoutFor(this.timeoutMs, sent));
207 // A connection that never opened is tried once more, IPv4 first (#37, GAME - UI/UX: one IPv6
208 // address timed out, and the same command went through seconds later). Nothing went out, so
209 // a POST is as safe to send again as a GET.
210 for (let attempt = 0; res === undefined; attempt++) {
211 try {
212 res = await this.send(this.url(path, server), {
213 method,
214 headers: {
215 ...this.headers(sent === undefined ? undefined : "application/json"),
216 ...(requestId ? { "Idempotency-Key": requestId } : {}),
217 },
218 ...(sent === undefined ? {} : { body: sent }),
219 signal: AbortSignal.timeout(timeoutMs),
220 });
221 } catch (err) {
222 const e = err as Error;
223 const why =
224 e.name === "TimeoutError"
225 ? `no answer within ${timeoutMs} ms`
226 : ((e.cause as Error | undefined)?.message ?? e.message);
227 if (!neverSent(err)) throw new ApiError(`could not reach ${server}: ${why}`);
228 if (attempt >= 1) {
229 throw new ApiError(
230 `could not reach ${server}: ${why}. Tried twice, the second time IPv4 first; the connection never opened, so nothing reached the server`,
231 undefined,
232 true,
233 );
234 }
235 setDefaultResultOrder("ipv4first");
236 await new Promise((ok) => setTimeout(ok, 500));
237 }
238 }
239 let text: string;
240 try {
241 text = await res.text();
242 } catch (err) {
243 const reason = err instanceof Error ? err.message : String(err);
244 throw new ApiError(`${method} ${path} response body ended unexpectedly: ${reason}`, res.status);
245 }
246 // 409 is a refusal that says what to do (a drop took out lines your work builds on): print it as it is.
247 if (!res.ok)
248 throw new ApiError(
249 res.status === 409
250 ? `refused: ${errorSentence(text)}`
251 : `${method} ${path} answered ${res.status}: ${errorSentence(text)}`,
252 res.status,
253 );
254 try {
255 return JSON.parse(text) as T;
256 } catch {
257 throw new ApiError(
258 `${method} ${path} answered with something that isn't JSON: ${text.slice(0, 300)}`,
259 res.status,
260 );
261 }
262 }
264 init(
265 files: Record<string, string>,
266 modes: Modes = {},
267 blobs: Readonly<Record<string, string>> = {},
268 ): Promise<{ version: number; skipped?: readonly string[] }> {
269 return this.json("POST", "/init", {
270 files,
271 ...(Object.keys(modes).length > 0 ? { modes } : {}),
272 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
273 });
274 }
276 edit(body: EditBody): Promise<EditAnswer> {
277 return this.json("POST", this.agentPath("edit"), body);
278 }
280 record(
281 files: Record<string, string | null>,
282 extra: { session?: string; subagent?: string } = {},
283 modes: Modes = {},
284 blobs: Readonly<Record<string, string>> = {},
285 ): Promise<RecordAnswer> {
286 return this.json("POST", this.agentPath("record"), {
287 files,
288 ...(Object.keys(modes).length > 0 ? { modes } : {}),
289 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
290 ...extra,
291 });
292 }
294 /** Move a file in the draft (#49): its lines keep their ids. The way to change a file's case. */
295 move(from: string, to: string): Promise<{ ok: boolean; from: string; to: string; news?: News }> {
296 return this.json("POST", this.agentPath("move"), { from, to });
297 }
299 /** Upload a binary file's bytes under their sha256 (the server checks the hash). */
300 async putBlob(sha: string, bytes: Uint8Array): Promise<void> {
301 await this.bytes("PUT", `/blobs/${sha}`, bytes);
302 }
304 /** A preview of one version of shared at a stable URL (abso serve, #37); a build answers 422 with its output. */
305 async serve(version?: number, cmd?: string, out?: string): Promise<ServeAnswer> {
306 const q = new URLSearchParams({
307 ...(version !== undefined ? { version: String(version) } : {}),
308 ...(cmd ? { cmd } : {}),
309 ...(out ? { out } : {}),
310 });
311 let res: Response;
312 try {
313 res = await this.send(`${this.url("/serve")}?${q}`, {
314 method: "POST",
315 headers: this.headers(),
316 signal: AbortSignal.timeout(20 * 60_000),
317 });
318 } catch (err) {
319 const e = err as Error;
320 throw new ApiError(
321 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
322 );
323 }
324 const text = await res.text();
325 if (!res.ok && res.status !== 422)
326 throw new ApiError(`serve answered ${res.status}: ${errorSentence(text)}`, res.status);
327 return JSON.parse(text) as ServeAnswer;
328 }
330 /** Runs a setup command on the folder in a fresh box and keeps the box as what it starts from (abso prep, #37). */
331 async prep(command: string, tarGz: Uint8Array<ArrayBuffer>): Promise<PrepAnswer> {
332 let res: Response;
333 try {
334 res = await this.send(
335 `${this.url(this.agentPath("prep"))}?cmd=${encodeURIComponent(command)}${boxQuery(this.box)}`,
336 {
337 method: "POST",
338 headers: this.headers("application/gzip"),
339 body: tarGz,
340 // A setup command can take minutes (npm ci, a browser download).
341 signal: AbortSignal.timeout(30 * 60_000),
342 },
343 );
344 } catch (err) {
345 const e = err as Error;
346 throw new ApiError(
347 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
348 );
349 }
350 const text = await res.text();
351 if (!res.ok) throw new ApiError(`prep answered ${res.status}: ${errorSentence(text)}`, res.status);
352 return JSON.parse(text) as PrepAnswer;
353 }
355 /** Forgets the box's prep: it starts from the plain image again. Answers whether it had one. */
356 async unprep(): Promise<boolean> {
357 let res: Response;
358 try {
359 res = await this.send(
360 `${this.url(this.agentPath("prep"))}${this.box ? `?box=${encodeURIComponent(this.box)}` : ""}`,
361 { method: "DELETE", headers: this.headers(), signal: AbortSignal.timeout(this.timeoutMs) },
362 );
363 } catch (err) {
364 const e = err as Error;
365 throw new ApiError(
366 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
367 );
368 }
369 const text = await res.text();
370 if (!res.ok) throw new ApiError(`prep answered ${res.status}: ${errorSentence(text)}`, res.status);
371 return (JSON.parse(text) as { forgot: boolean }).forgot;
372 }
374 /** A binary file's bytes by their sha256. */
375 /** 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. */
376 async boxFiles(glob: string): Promise<Uint8Array | null> {
377 try {
378 return await this.bytes(
379 "GET",
380 `${this.agentPath("box-files")}?${new URLSearchParams({ glob, ...(this.box ? { box: this.box } : {}) })}`,
381 );
382 } catch (err) {
383 if (err instanceof ApiError && err.status === 404) return null;
384 throw err;
385 }
386 }
388 getBlob(sha: string): Promise<Uint8Array> {
389 return this.bytes("GET", `/blobs/${sha}`);
390 }
392 async bytes(method: "GET" | "PUT", path: string, body?: Uint8Array): Promise<Uint8Array> {
393 let res: Response;
394 try {
395 res = await this.send(this.url(path), {
396 method,
397 headers: this.headers(body === undefined ? undefined : "application/octet-stream"),
398 ...(body === undefined ? {} : { body: body as Uint8Array<ArrayBuffer> }),
399 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
400 });
401 } catch (err) {
402 const e = err as Error;
403 throw new ApiError(
404 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
405 );
406 }
407 const data = new Uint8Array(await res.arrayBuffer());
408 if (!res.ok)
409 throw new ApiError(
410 `${method} ${path} answered ${res.status}: ${errorSentence(new TextDecoder().decode(data))}`,
411 res.status,
412 );
413 return data;
414 }
416 /** Make this agent a reader, or not (#37): a reader's edits, records and publishes are refused. */
417 reader(on: boolean): Promise<{ agent: string; reader: boolean }> {
418 return this.json("POST", this.agentPath("reader"), { reader: on });
419 }
421 publish(message: string, asIs = false): Promise<PublishAnswer> {
422 return this.json(
423 "POST",
424 this.agentPath("publish"),
425 { message, ...(asIs ? { asIs: true } : {}) },
426 undefined,
427 PUBLISH_TIMEOUT_MS,
428 );
429 }
431 /** One change (#44). */
432 change(id: number): Promise<ChangeAnswer> {
433 return this.json("GET", `/change/${id}`);
434 }
436 /** The changes with anything new at or after log position `since`, newest first (#44). */
437 /** Changes active since a log position, newest first; `older` is set when more come before the page (ask again with `before`). */
438 changes(
439 since: number,
440 limit = 50,
441 before?: number,
442 ): Promise<{ since: number; next: number; changes: readonly ChangeAnswer[]; older?: number }> {
443 return this.json("GET", `/changes?${query({ since, limit, before })}`);
444 }
446 /** A call to the Issues Worker (#54), with the same token. */
447 #issues<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> {
448 if (this.issuesServer === undefined)
449 throw new ApiError(`${this.config.server} has no Issues Worker beside it; ABSO_ISSUES_SERVER names one`);
450 return this.json(method, path, body, this.issuesServer);
451 }
453 /** An ask-thread call, with a server from before ask threads named as that rather than a bare 404. */
454 async #threads<T>(call: Promise<T>): Promise<T> {
455 try {
456 return await call;
457 } catch (err) {
458 if (err instanceof ApiError && err.status === 404 && /no such issues route/.test(err.message))
459 throw new ApiError(`${this.config.server} doesn't have ask threads yet`, 404);
460 throw err;
461 }
462 }
464 /** Issues, most recently updated first. */
465 issues(
466 q: { status?: string; agent?: string; parent?: number; open?: boolean; labels?: readonly string[] } = {},
467 ): Promise<{ issues: readonly IssueRow[] }> {
468 return this.#issues(
469 "GET",
470 `/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 })}`,
471 );
472 }
474 /**
475 * The project's issues matching q, best first: by its words and, where
476 * the server has it on, by what it means.
477 */
478 issueSearch(q: string, limit?: number): Promise<{ hits: readonly IssueSearchHit[] }> {
479 return this.#issues("GET", `/search?${query({ q, limit })}`);
480 }
482 /** Every label in use, with how many issues have it and how many of those are open. */
483 issueLabels(): Promise<{ labels: readonly { label: string; open: number; total: number }[] }> {
484 return this.#issues("GET", "/labels");
485 }
487 issue(id: number): Promise<IssuePage> {
488 return this.#issues("GET", `/issue/${id}`);
489 }
491 /** The asks this agent sent: the open ones, then the latest answered, each with its thread. */
492 asked(): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
493 return this.#threads(this.#issues("GET", this.agentPath("asked")));
494 }
496 /** One ask, open or closed, with its thread and who it waits on. */
497 askThread(id: number): Promise<{ ask: Ask & { title: string | null } }> {
498 return this.#threads(this.#issues("GET", `/ask/${id}`));
499 }
501 /** Open asks of someone (an agent, or person:<id>), soonest due first; every open ask without `of`. */
502 waiting(of?: string): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
503 return this.#issues("GET", `/waiting?${query({ of })}`);
504 }
506 /** This agent's open asks; the Worker marks each it lists for the first time as seen (abso issue 124). */
507 async waitingMine(): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
508 try {
509 return await this.#issues("GET", this.agentPath("waiting"));
510 } catch (err) {
511 // An Issues Worker from before 124 has no /a/:agent/ reads.
512 if (err instanceof ApiError && err.status === 404) return this.waiting(this.config.agent);
513 throw err;
514 }
515 }
517 issueOpen(body: DraftBody & { title: string; attachments?: string[] }): Promise<{ id: number; news?: IssueNews }> {
518 return this.#issues("POST", this.agentPath("issue"), body);
519 }
521 /** Uploads an image to the Issues Worker (abso issue 171): it checks the type by the bytes, strips metadata and answers its id. */
522 async attachmentUpload(bytes: Uint8Array, name: string): Promise<Attachment> {
523 if (this.issuesServer === undefined)
524 throw new ApiError(`${this.config.server} has no Issues Worker beside it; ABSO_ISSUES_SERVER names one`);
525 const path = this.agentPath("attachments");
526 let res: Response;
527 try {
528 res = await this.send(this.url(path, this.issuesServer), {
529 method: "POST",
530 headers: { ...this.headers("application/octet-stream"), "x-abso-name": encodeURIComponent(name) },
531 body: bytes as Uint8Array<ArrayBuffer>,
532 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
533 });
534 } catch (err) {
535 const e = err as Error;
536 throw new ApiError(
537 `could not reach ${this.issuesServer}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
538 );
539 }
540 const text = await res.text();
541 // A server from before attachments has no upload route: it answers 404, or 400 because the body isn't JSON;
542 // one with the route but nowhere to keep files answers 501. Say so plainly, and that nothing was sent.
543 if (res.status === 404 || res.status === 501 || (res.status === 400 && /the body is JSON/.test(text)))
544 throw new ApiError(
545 `${this.issuesServer} doesn't take attachments yet, so ${name} wasn't sent and nothing was written. Leave --attach off, or link the image instead.`,
546 res.status,
547 );
548 if (!res.ok) throw new ApiError(`uploading ${name} answered ${res.status}: ${errorSentence(text)}`, res.status);
549 return JSON.parse(text) as Attachment;
550 }
552 /**
553 * Copies issue `body.issue` of this project into project `to`, keeping
554 * authors and times: the Issues server reads the source itself, and only
555 * texts may be given cleaned. A dry run answers the plan and writes nothing.
556 */
557 issueCopy(to: string, body: CopyBody & { dryRun?: boolean }): Promise<CopyAnswer> {
558 const there = new Api({ ...this.config, project: to }, this.timeoutMs);
559 there.issuesServer = this.issuesServer;
560 return there.#issues("POST", there.agentPath("copy"), body);
561 }
563 /** Where an attachment is served. */
564 attachmentUrl(id: string): string {
565 return this.url(`/attachments/${id}`, this.issuesServer);
566 }
568 /** An attachment's bytes, or with `source` the svg it was drawn from; refused past `max` bytes. */
569 async attachmentBytes(id: string, source: boolean, max: number): Promise<Uint8Array> {
570 if (this.issuesServer === undefined)
571 throw new ApiError(`${this.config.server} has no Issues Worker beside it; ABSO_ISSUES_SERVER names one`);
572 const url = `${this.attachmentUrl(id)}${source ? "/source" : ""}`;
573 let res: Response;
574 try {
575 res = await this.send(url, {
576 headers: this.headers(),
577 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
578 });
579 } catch (err) {
580 const e = err as Error;
581 throw new ApiError(
582 `could not reach ${this.issuesServer}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
583 );
584 }
585 if (!res.ok) throw new ApiError(`${url} answered ${res.status}: ${errorSentence(await res.text())}`, res.status);
586 const bytes = new Uint8Array(await res.arrayBuffer());
587 if (bytes.length > max) throw new ApiError(`${url} sent ${bytes.length} bytes, more than an attachment may be`);
588 return bytes;
589 }
591 /** An edit (abso issue 3): it tells the issue's watchers, and `also`, unless `notify` is false. null clears a parent or Agent. */
592 issueEdit(
593 id: number,
594 body: {
595 title?: string;
596 description?: string;
597 parent?: number | null;
598 agent?: string | null;
599 blockedBy?: number[];
600 notify?: boolean;
601 also?: string[];
602 addLabels?: string[];
603 removeLabels?: string[];
604 },
605 ): Promise<{ edit: number; notified: readonly string[]; news?: IssueNews }> {
606 return this.#issues("POST", this.agentPath(`issue/${id}/edit`), body);
607 }
609 issueComment(
610 id: number,
611 text: string,
612 objection = false,
613 attachments: readonly string[] = [],
614 ): Promise<{ id: number; news?: IssueNews }> {
615 return this.#issues("POST", this.agentPath(`issue/${id}/comment`), {
616 text,
617 ...(objection ? { objection } : {}),
618 ...(attachments.length > 0 ? { attachments } : {}),
619 });
620 }
622 issueDrop(id: number): Promise<{ news?: IssueNews }> {
623 return this.#issues("POST", this.agentPath(`issue/${id}/drop`), {});
624 }
626 /** Opens a dropped issue again (abso issue 104). */
627 issueReopen(id: number): Promise<{ news?: IssueNews }> {
628 return this.#issues("POST", this.agentPath(`issue/${id}/reopen`), {});
629 }
631 /** Marks an issue done by hand (abso issue 38). `version` is the publish that did it, when there is one. */
632 issueDone(id: number, version: number | null): Promise<{ news?: IssueNews }> {
633 return this.#issues("POST", this.agentPath(`issue/${id}/done`), { ...(version !== null ? { version } : {}) });
634 }
636 /** This agent's drafts (abso issue 3): its own, with no number and no news, newest first. */
637 drafts(): Promise<{ drafts: readonly Draft[] }> {
638 return this.#issues("GET", this.agentPath("drafts"));
639 }
641 /** Saves a draft, new or (with id) over one of this agent's: the body replaces the draft's. */
642 saveDraft(body: DraftBody & { id?: number }): Promise<{ id: number }> {
643 return this.#issues("POST", this.agentPath("draft"), body);
644 }
646 /** Opens a draft as an issue, `body`'s fields over the draft's, and deletes the draft. */
647 openDraft(id: number, body: DraftBody = {}): Promise<{ id: number; news?: IssueNews }> {
648 return this.#issues("POST", this.agentPath(`draft/${id}/open`), body);
649 }
651 deleteDraft(id: number): Promise<{ ok: boolean }> {
652 return this.#issues("POST", this.agentPath(`draft/${id}/delete`), {});
653 }
655 ask(body: {
656 issue?: number;
657 of: string;
658 question: string;
659 review?: boolean;
660 kind?: "question" | "task";
661 due?: string;
662 blocks?: number[];
663 options?: string[];
664 attachments?: string[];
665 }): Promise<{ id: number; news?: IssueNews; attachments?: string[] }> {
666 return this.#issues("POST", this.agentPath("ask"), body);
667 }
669 answer(
670 id: number,
671 body: { words?: string; option?: number | string; note?: string; done?: boolean; attachments?: string[] },
672 ): Promise<{ ask: Ask; news?: IssueNews }> {
673 return this.#issues("POST", this.agentPath(`answer/${id}`), body);
674 }
676 /** Acknowledges an ask of this agent without answering it: the asker hears it, and the ask stays open. */
677 ack(id: number, body: { note?: string }): Promise<{ ask: Ask; news?: IssueNews }> {
678 return this.#issues("POST", this.agentPath(`ack/${id}`), body);
679 }
681 /** Adds to an ask's thread, as its asker or the one asked; the other side hears it, and the ask stays as it is. */
682 reply(id: number, body: { text: string; question?: boolean }): Promise<{ ask: Ask; news?: IssueNews }> {
683 return this.#threads(this.#issues("POST", this.agentPath(`reply/${id}`), body));
684 }
686 /** Takes back an ask this agent made, with a note on why; the one asked hears it. */
687 withdraw(id: number, body: { note?: string }): Promise<{ ask: Ask; news?: IssueNews }> {
688 return this.#issues("POST", this.agentPath(`withdraw/${id}`), body);
689 }
691 /** Notes on lines (#44), by file or change; open ones only with `open`. */
692 notes(q: { file?: string; change?: number; open?: boolean } = {}): Promise<{ notes: readonly NoteAnswer[] }> {
693 return this.json("GET", `/notes?${query({ file: q.file, change: q.change, open: q.open ? 1 : undefined })}`);
694 }
696 note(body: NoteBody): Promise<{ id: number; change: number | null; lines: readonly [number, number] }> {
697 return this.json("POST", this.agentPath("note"), body);
698 }
700 noteClose(id: number, how: "resolved" | "withdrawn"): Promise<unknown> {
701 return this.json("POST", this.agentPath("note-close"), { id, how });
702 }
704 /** The merge queue now (#39). */
705 queueState(): Promise<QueueState> {
706 return this.json("GET", "/queue");
707 }
709 /** The project's visibility (abso issue 152): public or private. */
710 visibility(): Promise<{ project: string; visibility: "public" | "private" }> {
711 return this.json("GET", "/visibility");
712 }
714 /** Switch the project's visibility (abso issue 140): an owner's key, or the shared token on staging. */
715 setVisibility(v: "public" | "private"): Promise<{ project: string; visibility: "public" | "private" }> {
716 return this.json("POST", `/visibility?visibility=${v}`, {});
717 }
719 /** Take back this agent's queued publishes (#39); refused while one is being checked. */
720 unqueue(): Promise<{ pulled: readonly number[] }> {
721 return this.json("POST", this.agentPath("unqueue"), {});
722 }
724 /**
725 * Sync; a folder following a label goes to the newest version with that label.
726 * With `full`, the answer holds every file in the agent's view, as a first sync's does,
727 * not only what changed since its last sync (#37: a join for an agent the server knew).
728 */
729 sync(options: { full?: boolean } = {}): Promise<SyncAnswer> {
730 return this.json("POST", this.agentPath("sync"), {
731 ...(this.config.follow ? { label: this.config.follow } : {}),
732 ...(options.full ? { full: true } : {}),
733 });
734 }
736 /** Take published versions back out of shared (with the versions that build on them, when asked). */
737 drop(versions: readonly number[], message: string, withDependents = false): Promise<DropAnswer> {
738 return this.json("POST", this.agentPath("drop"), {
739 versions,
740 message,
741 ...(withDependents ? { withDependents: true } : {}),
742 });
743 }
745 /** Take some versions of a named draft into shared, as one version. */
746 pluck(draft: string, versions: readonly number[], message: string, withDependencies = false): Promise<PluckAnswer> {
747 return this.json("POST", this.agentPath("pluck"), {
748 draft,
749 versions,
750 message,
751 ...(withDependencies ? { withDependencies: true } : {}),
752 });
753 }
755 /** Correct the message of this agent's newest publish in its space. */
756 amend(message: string): Promise<{ version: number; draft: string | null; message: string; was: string }> {
757 return this.json("POST", this.agentPath("amend"), { message });
758 }
760 /** Put a label on a version of shared (the newest by default), or take it off. */
761 label(
762 name: string,
763 version?: number,
764 remove = false,
765 ): Promise<{ name: string; version: number; versions: readonly number[] }> {
766 return this.json("POST", this.agentPath("label"), {
767 name,
768 ...(version === undefined ? {} : { version }),
769 ...(remove ? { remove: true } : {}),
770 });
771 }
773 labels(): Promise<{ labels: Readonly<Record<string, readonly number[]>> }> {
774 return this.json("GET", "/labels");
775 }
777 status(): Promise<StatusAnswer> {
778 return this.json("GET", "/status");
779 }
781 /** The status and the paths in the agent's view, in one trip (abso issue 80). */
782 async statusAndFiles(): Promise<StatusAnswer & { files: FilesAnswer | undefined }> {
783 try {
784 return await this.json("GET", this.agentPath("status"));
785 } catch (err) {
786 // A server from before it has no /a/:agent/status; the listing itself is from #37.
787 if (!(err instanceof ApiError && err.status === 404)) throw err;
788 }
789 const status = await this.status();
790 return { ...status, files: await this.viewFiles().catch(() => undefined) };
791 }
793 /** CI's state (#39), or one version's job. */
794 ci(): Promise<CiStatus>;
795 ci(version: number): Promise<CiJob>;
796 ci(version?: number): Promise<CiStatus | CiJob> {
797 return this.json("GET", version === undefined ? "/ci" : `/ci?${query({ version })}`);
798 }
800 /** The project's pipeline runs, newest first; one run with its jobs; or one job's log (`log` is pipeline.job). */
801 pipelineRuns(run?: number, log?: string): Promise<unknown> {
802 return this.json("GET", run === undefined ? "/pipelines" : `/pipelines?${query({ run, log })}`);
803 }
805 /** Ends every /latest link handed out so far; answers CI's state with the new link. */
806 ciRevoke(): Promise<CiStatus> {
807 return this.json("POST", "/ci/revoke", {});
808 }
810 /** Count versions up to `through` as seen by CI and end any red or bisect, so an import's history isn't checked (#56). */
811 ciSkip(through: number): Promise<unknown> {
812 return this.json("POST", "/ci/skip", { through });
813 }
815 /** Move to a named draft (null: shared). With carry, the current unpublished changes start a new draft. */
816 switchDraft(name: string | null, carry = false): Promise<SwitchAnswer> {
817 return this.json("POST", this.agentPath("draft"), { name, ...(carry ? { carry: true } : {}) });
818 }
820 /** Land never queues: with the merge queue on, the server refuses it (#39). */
821 land(message: string): Promise<Exclude<PublishAnswer, { queued: number }>> {
822 return this.json("POST", this.agentPath("land"), { message }, undefined, PUBLISH_TIMEOUT_MS);
823 }
825 draftSync(): Promise<DraftSyncAnswer> {
826 return this.json("POST", this.agentPath("draft-sync"), {});
827 }
829 blame(file: string, from?: number, to?: number, version?: number, view: View = {}): Promise<BlameAnswer> {
830 return this.json("GET", `/blame?${query({ file, from, to, version, ...view })}`);
831 }
833 /** The paths in the agent's view: what its folder should hold (#37). */
834 viewFiles(): Promise<FilesAnswer> {
835 return this.json("GET", this.agentPath("files"));
836 }
838 /** The paths in shared, or a named draft, at a version (the newest by default). */
839 filesAt(draft: string | null, version?: number): Promise<FilesAnswer> {
840 return this.json("GET", `/files?${query({ draft, version })}`);
841 }
843 /** The versions of a space, newest first; with `path`, only those that changed it. */
844 /**
845 * The versions newest first, below `before` when it's given. The server
846 * sends at most LOG_PAGE at a time, so a longer log is read page by page,
847 * following each page's next. `next` on the answer says older ones are left.
848 */
849 async log(where: Where, limit?: number, path?: string, before?: number): Promise<LogAnswer> {
850 let page = await this.#logPage(where, limit === undefined ? undefined : Math.min(limit, LOG_PAGE), path, before);
851 const versions = [...page.versions];
852 while (limit !== undefined && versions.length < limit && page.next !== undefined) {
853 page = await this.#logPage(where, Math.min(limit - versions.length, LOG_PAGE), path, page.next);
854 versions.push(...page.versions);
855 }
856 const { next, ...rest } = page;
857 return { ...rest, versions, ...(next !== undefined ? { next } : {}) };
858 }
860 #logPage(
861 where: Where,
862 limit: number | undefined,
863 path: string | undefined,
864 before: number | undefined,
865 ): Promise<LogAnswer> {
866 return this.json("GET", `/log?${query({ ...where, limit, path, before })}`);
867 }
869 show(version: number, where: Where): Promise<ShowAnswer> {
870 return this.json("GET", `/show?${query({ version, ...where })}`);
871 }
873 fileAt(path: string, version: number, where: Where): Promise<{ path: string; version: number; text: string | null }> {
874 return this.json("GET", `/file?${query({ path, version, ...where })}`);
875 }
877 compare(from: number, to: number, where: Where): Promise<{ from: number; to: number; files: readonly FileChange[] }> {
878 return this.json("GET", `/compare?${query({ from, to, ...where })}`);
879 }
881 /** A message to the project's other agents (or those named), delivered once as news. */
882 starting(
883 text: string | null,
884 files?: readonly string[],
885 options: { issue?: number; done?: boolean } = {},
886 ): Promise<{
887 starting: { text: string; files: readonly string[]; time: number; issue?: number } | null;
888 overlaps: readonly Overlap[];
889 }> {
890 return this.json("POST", this.agentPath("starting"), {
891 text,
892 ...(files && files.length > 0 ? { files } : {}),
893 ...(options.issue !== undefined ? { issue: options.issue } : {}),
894 ...(options.done ? { done: true } : {}),
895 });
896 }
898 announce(text: string, to?: readonly string[]): Promise<{ id: number; to: readonly string[] }> {
899 return this.json("POST", this.agentPath("announce"), { text, ...(to ? { to } : {}) });
900 }
902 /** The news waiting for this agent, handed over once. */
903 news(): Promise<{ news: News; items?: readonly { readonly text: string; readonly at: number | null }[] }> {
904 return this.json("POST", this.agentPath("news"), {});
905 }
907 /** This agent's unpublished changes, file by file. */
908 diff(): Promise<DiffAnswer> {
909 return this.json("POST", this.agentPath("diff"), {});
910 }
912 /** Another agent's recorded, unpublished changes, file by file: read only, as the website's drafts show them. */
913 diffOf(agent: string): Promise<DiffAnswer> {
914 return this.json("GET", `/diff?${query({ agent })}`);
915 }
917 /** Discard this agent's unpublished changes to `files` (null: all of them). */
918 restore(files: readonly string[] | null): Promise<RestoreAnswer> {
919 return this.json("POST", this.agentPath("restore"), files === null ? { all: true } : { files });
920 }
922 why(file: string, line: number, view: View = {}): Promise<WhyAnswer> {
923 return this.json("GET", `/why?${query({ file, line, ...view })}`);
924 }
926 where(): Promise<WhereAnswer> {
927 return this.json("GET", "/where");
928 }
930 /**
931 * Send the folder as a tar.gz and run a command in the agent's box. Output
932 * goes to `io.out` as it arrives, and the box's stderr to `io.err` (the
933 * server keeps them apart when asked; an older one sends both as out).
934 * Answers the command's exit code.
935 *
936 * When the stream breaks before the exit line and the server gave the run
937 * an id, the run goes on in the box: this reconnects to it and carries on
938 * from the last output printed, so nothing is lost or printed twice. The
939 * command itself is never sent twice.
940 */
941 async run(command: string, tarGz: Uint8Array<ArrayBuffer>, io: RunIO): Promise<number> {
942 const res = await postRun(this, command, tarGz, io.onRetry, io.replace, io.fresh);
943 // X-Abso-Box: cold means the box started for this run; X-Abso-Prep says whether it started from the prep (#37).
944 io.onBox?.(res.headers.get("x-abso-box") === "cold", res.headers.get("x-abso-prep") ?? undefined);
945 return follow(this, res, res.headers.get("x-abso-run"), { at: 0, errAt: 0 }, io);
946 }
948 /**
949 * Start a run and answer its id without waiting: the job goes on in the box
950 * after this connection closes (abso run --detach; abso logs <id> follows it).
951 */
952 async startRun(
953 command: string,
954 tarGz: Uint8Array<ArrayBuffer>,
955 onRetry?: (why: string, attempt: number) => void,
956 replace = false,
957 ): Promise<string> {
958 const res = await postRun(this, command, tarGz, onRetry, replace);
959 const id = res.headers.get("x-abso-run");
960 if (id === null) {
961 // No id: the box failed before the job started ({"error"} in the body), or the server can't detach.
962 await consumeRun(res, { out: () => {} }, { at: 0, errAt: 0 });
963 throw new ApiError("this server gives runs no id, so a run can't be detached");
964 }
965 await res.body?.cancel();
966 return id;
967 }
969 /** A run's output from its start, for as long as the box keeps it, until it ends (abso logs). Answers its exit code. */
970 async logs(id: string, io: RunIO): Promise<number> {
971 let res: Response;
972 try {
973 res = await this.send(followUrl(this, id, { at: 0, errAt: 0 }), { headers: this.headers() });
974 } catch (err) {
975 const e = err as Error;
976 throw new ApiError(
977 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
978 );
979 }
980 if (res.status === 404) throw new ApiError(`no run ${id} in this box: ${errorSentence(await res.text())}`, 404);
981 if (!res.ok || res.body === null)
982 throw new ApiError(`logs answered ${res.status}: ${errorSentence(await res.text())}`, res.status);
983 return follow(this, res, id, { at: 0, errAt: 0 }, io);
984 }
985}