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=220&format=json
1,002 linesFirst import 71% · pinch 23% · devops 2% · autosettle 1% · codex-prose-authorship-1 1% · candidates 1% · Last change autosettle in version 220, 24 versions changed it

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

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