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=136&format=json
980 linesFirst import 72% · pinch 24% · devops 2% · codex-prose-authorship-1 1% · infra-pipeline 1% · infra-split 1% · review 1%Last change codex-prose-authorship-1 in version 108, 20 versions changed it

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