Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/client/src/api.ts?version=285&format=json
1,088 linesFirst import 65% · pinch 21% · groups 7% · autosettle 2% · devops 2% · codex-prose-authorship-1 1% · Last change box-grants in version 285, 29 versions changed it

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

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