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