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=57&format=json
927 linesFirst import 78% · pinch 19% · devops 2% · infra-split 1% · review 1%Last change pinch in version 54, 13 versions changed it

You're reading version 57. The newest is 318, and 17 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 ? { authorization: `Bearer ${this.config.token}` } : {}),
178 ...(contentType ? { "content-type": contentType } : {}),
179 };
180 }
182 async json<T>(
183 method: "GET" | "POST",
184 path: string,
185 body?: unknown,
186 server = this.config.server,
187 atLeastMs = 0,
188 ): Promise<T> {
189 let res: Response | undefined;
190 const sent = body === undefined ? undefined : JSON.stringify(body);
191 const timeoutMs = Math.max(atLeastMs, timeoutFor(this.timeoutMs, sent));
192 // A connection that never opened is tried once more, IPv4 first (#37, GAME - UI/UX: one IPv6
193 // address timed out, and the same command went through seconds later). Nothing went out, so
194 // a POST is as safe to send again as a GET.
195 for (let attempt = 0; res === undefined; attempt++) {
196 try {
197 res = await fetch(this.url(path, server), {
198 method,
199 headers: this.headers(sent === undefined ? undefined : "application/json"),
200 ...(sent === undefined ? {} : { body: sent }),
201 signal: AbortSignal.timeout(timeoutMs),
202 });
203 } catch (err) {
204 const e = err as Error;
205 const why =
206 e.name === "TimeoutError"
207 ? `no answer within ${timeoutMs} ms`
208 : ((e.cause as Error | undefined)?.message ?? e.message);
209 if (!neverSent(err)) throw new ApiError(`could not reach ${server}: ${why}`);
210 if (attempt >= 1) {
211 throw new ApiError(
212 `could not reach ${server}: ${why}. Tried twice, the second time IPv4 first; the connection never opened, so nothing reached the server`,
213 undefined,
214 true,
215 );
216 }
217 setDefaultResultOrder("ipv4first");
218 await new Promise((ok) => setTimeout(ok, 500));
219 }
220 }
221 const text = await res.text();
222 // 409 is a refusal that says what to do (a drop took out lines your work builds on): print it as it is.
223 if (!res.ok)
224 throw new ApiError(
225 res.status === 409
226 ? `refused: ${errorSentence(text)}`
227 : `${method} ${path} answered ${res.status}: ${errorSentence(text)}`,
228 res.status,
229 );
230 try {
231 return JSON.parse(text) as T;
232 } catch {
233 throw new ApiError(
234 `${method} ${path} answered with something that isn't JSON: ${text.slice(0, 300)}`,
235 res.status,
236 );
237 }
238 }
240 init(
241 files: Record<string, string>,
242 modes: Modes = {},
243 blobs: Readonly<Record<string, string>> = {},
244 ): Promise<{ version: number; skipped?: readonly string[] }> {
245 return this.json("POST", "/init", {
246 files,
247 ...(Object.keys(modes).length > 0 ? { modes } : {}),
248 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
249 });
250 }
252 edit(body: EditBody): Promise<EditAnswer> {
253 return this.json("POST", this.agentPath("edit"), body);
254 }
256 record(
257 files: Record<string, string | null>,
258 extra: { session?: string; subagent?: string } = {},
259 modes: Modes = {},
260 blobs: Readonly<Record<string, string>> = {},
261 ): Promise<RecordAnswer> {
262 return this.json("POST", this.agentPath("record"), {
263 files,
264 ...(Object.keys(modes).length > 0 ? { modes } : {}),
265 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
266 ...extra,
267 });
268 }
270 /** Move a file in the draft (#49): its lines keep their ids. The way to change a file's case. */
271 move(from: string, to: string): Promise<{ ok: boolean; from: string; to: string; news?: News }> {
272 return this.json("POST", this.agentPath("move"), { from, to });
273 }
275 /** Upload a binary file's bytes under their sha256 (the server checks the hash). */
276 async putBlob(sha: string, bytes: Uint8Array): Promise<void> {
277 await this.bytes("PUT", `/blobs/${sha}`, bytes);
278 }
280 /** A preview of one version of shared at a stable URL (abso serve, #37); a build answers 422 with its output. */
281 async serve(version?: number, cmd?: string, out?: string): Promise<ServeAnswer> {
282 const q = new URLSearchParams({
283 ...(version !== undefined ? { version: String(version) } : {}),
284 ...(cmd ? { cmd } : {}),
285 ...(out ? { out } : {}),
286 });
287 let res: Response;
288 try {
289 res = await fetch(`${this.url("/serve")}?${q}`, {
290 method: "POST",
291 headers: this.headers(),
292 signal: AbortSignal.timeout(20 * 60_000),
293 });
294 } catch (err) {
295 const e = err as Error;
296 throw new ApiError(
297 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
298 );
299 }
300 const text = await res.text();
301 if (!res.ok && res.status !== 422)
302 throw new ApiError(`serve answered ${res.status}: ${errorSentence(text)}`, res.status);
303 return JSON.parse(text) as ServeAnswer;
304 }
306 /** Runs a setup command on the folder in a fresh box and keeps the box as what it starts from (abso prep, #37). */
307 async prep(command: string, tarGz: Uint8Array<ArrayBuffer>): Promise<PrepAnswer> {
308 let res: Response;
309 try {
310 res = await fetch(`${this.url(this.agentPath("prep"))}?cmd=${encodeURIComponent(command)}${boxQuery(this.box)}`, {
311 method: "POST",
312 headers: this.headers("application/gzip"),
313 body: tarGz,
314 // A setup command can take minutes (npm ci, a browser download).
315 signal: AbortSignal.timeout(30 * 60_000),
316 });
317 } catch (err) {
318 const e = err as Error;
319 throw new ApiError(
320 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
321 );
322 }
323 const text = await res.text();
324 if (!res.ok) throw new ApiError(`prep answered ${res.status}: ${errorSentence(text)}`, res.status);
325 return JSON.parse(text) as PrepAnswer;
326 }
328 /** Forgets the box's prep: it starts from the plain image again. Answers whether it had one. */
329 async unprep(): Promise<boolean> {
330 let res: Response;
331 try {
332 res = await fetch(
333 `${this.url(this.agentPath("prep"))}${this.box ? `?box=${encodeURIComponent(this.box)}` : ""}`,
334 { method: "DELETE", headers: this.headers(), signal: AbortSignal.timeout(this.timeoutMs) },
335 );
336 } catch (err) {
337 const e = err as Error;
338 throw new ApiError(
339 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
340 );
341 }
342 const text = await res.text();
343 if (!res.ok) throw new ApiError(`prep answered ${res.status}: ${errorSentence(text)}`, res.status);
344 return (JSON.parse(text) as { forgot: boolean }).forgot;
345 }
347 /** A binary file's bytes by their sha256. */
348 /** 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. */
349 async boxFiles(glob: string): Promise<Uint8Array | null> {
350 try {
351 return await this.bytes(
352 "GET",
353 `${this.agentPath("box-files")}?${new URLSearchParams({ glob, ...(this.box ? { box: this.box } : {}) })}`,
354 );
355 } catch (err) {
356 if (err instanceof ApiError && err.status === 404) return null;
357 throw err;
358 }
359 }
361 getBlob(sha: string): Promise<Uint8Array> {
362 return this.bytes("GET", `/blobs/${sha}`);
363 }
365 async bytes(method: "GET" | "PUT", path: string, body?: Uint8Array): Promise<Uint8Array> {
366 let res: Response;
367 try {
368 res = await fetch(this.url(path), {
369 method,
370 headers: this.headers(body === undefined ? undefined : "application/octet-stream"),
371 ...(body === undefined ? {} : { body: body as Uint8Array<ArrayBuffer> }),
372 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
373 });
374 } catch (err) {
375 const e = err as Error;
376 throw new ApiError(
377 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
378 );
379 }
380 const data = new Uint8Array(await res.arrayBuffer());
381 if (!res.ok)
382 throw new ApiError(
383 `${method} ${path} answered ${res.status}: ${errorSentence(new TextDecoder().decode(data))}`,
384 res.status,
385 );
386 return data;
387 }
389 /** Make this agent a reader, or not (#37): a reader's edits, records and publishes are refused. */
390 reader(on: boolean): Promise<{ agent: string; reader: boolean }> {
391 return this.json("POST", this.agentPath("reader"), { reader: on });
392 }
394 publish(message: string, asIs = false): Promise<PublishAnswer> {
395 return this.json(
396 "POST",
397 this.agentPath("publish"),
398 { message, ...(asIs ? { asIs: true } : {}) },
399 undefined,
400 PUBLISH_TIMEOUT_MS,
401 );
402 }
404 /** One change (#44). */
405 change(id: number): Promise<ChangeAnswer> {
406 return this.json("GET", `/change/${id}`);
407 }
409 /** The changes with anything new at or after log position `since`, newest first (#44). */
410 /** Changes active since a log position, newest first; `older` is set when more come before the page (ask again with `before`). */
411 changes(
412 since: number,
413 limit = 50,
414 before?: number,
415 ): Promise<{ since: number; next: number; changes: readonly ChangeAnswer[]; older?: number }> {
416 return this.json("GET", `/changes?${query({ since, limit, before })}`);
417 }
419 /** A call to the Issues Worker (#54), with the same token. */
420 #issues<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> {
421 if (this.issuesServer === undefined)
422 throw new ApiError(`${this.config.server} has no Issues Worker beside it; ABSO_ISSUES_SERVER names one`);
423 return this.json(method, path, body, this.issuesServer);
424 }
426 /** Issues, most recently updated first. */
427 issues(
428 q: { status?: string; agent?: string; parent?: number; open?: boolean; labels?: readonly string[] } = {},
429 ): Promise<{ issues: readonly IssueRow[] }> {
430 return this.#issues(
431 "GET",
432 `/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 })}`,
433 );
434 }
436 /**
437 * The project's issues matching q, best first: by its words and, where
438 * the server has it on, by what it means.
439 */
440 issueSearch(q: string, limit?: number): Promise<{ hits: readonly IssueSearchHit[] }> {
441 return this.#issues("GET", `/search?${query({ q, limit })}`);
442 }
444 /** Every label in use, with how many issues have it and how many of those are open. */
445 issueLabels(): Promise<{ labels: readonly { label: string; open: number; total: number }[] }> {
446 return this.#issues("GET", "/labels");
447 }
449 issue(id: number): Promise<IssuePage> {
450 return this.#issues("GET", `/issue/${id}`);
451 }
453 /** Open asks of someone (an agent, or person:<id>), soonest due first; every open ask without `of`. */
454 waiting(of?: string): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
455 return this.#issues("GET", `/waiting?${query({ of })}`);
456 }
458 /** This agent's open asks; the Worker marks each it lists for the first time as seen (abso issue 124). */
459 async waitingMine(): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
460 try {
461 return await this.#issues("GET", this.agentPath("waiting"));
462 } catch (err) {
463 // An Issues Worker from before 124 has no /a/:agent/ reads.
464 if (err instanceof ApiError && err.status === 404) return this.waiting(this.config.agent);
465 throw err;
466 }
467 }
469 issueOpen(body: DraftBody & { title: string; attachments?: string[] }): Promise<{ id: number; news?: IssueNews }> {
470 return this.#issues("POST", this.agentPath("issue"), body);
471 }
473 /** Uploads an image to the Issues Worker (abso issue 171): it checks the type by the bytes, strips metadata and answers its id. */
474 async attachmentUpload(bytes: Uint8Array, name: string): Promise<Attachment> {
475 if (this.issuesServer === undefined)
476 throw new ApiError(`${this.config.server} has no Issues Worker beside it; ABSO_ISSUES_SERVER names one`);
477 const path = this.agentPath("attachments");
478 let res: Response;
479 try {
480 res = await fetch(this.url(path, this.issuesServer), {
481 method: "POST",
482 headers: { ...this.headers("application/octet-stream"), "x-abso-name": encodeURIComponent(name) },
483 body: bytes as Uint8Array<ArrayBuffer>,
484 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
485 });
486 } catch (err) {
487 const e = err as Error;
488 throw new ApiError(
489 `could not reach ${this.issuesServer}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
490 );
491 }
492 const text = await res.text();
493 // A server from before attachments has no upload route: it answers 404, or 400 because the body isn't JSON;
494 // one with the route but nowhere to keep files answers 501. Say so plainly, and that nothing was sent.
495 if (res.status === 404 || res.status === 501 || (res.status === 400 && /the body is JSON/.test(text)))
496 throw new ApiError(
497 `${this.issuesServer} doesn't take attachments yet, so ${name} wasn't sent and nothing was written. Leave --attach off, or link the image instead.`,
498 res.status,
499 );
500 if (!res.ok) throw new ApiError(`uploading ${name} answered ${res.status}: ${errorSentence(text)}`, res.status);
501 return JSON.parse(text) as Attachment;
502 }
504 /**
505 * Copies issue `body.issue` of this project into project `to`, keeping
506 * authors and times: the Issues server reads the source itself, and only
507 * texts may be given cleaned. A dry run answers the plan and writes nothing.
508 */
509 issueCopy(to: string, body: CopyBody & { dryRun?: boolean }): Promise<CopyAnswer> {
510 const there = new Api({ ...this.config, project: to }, this.timeoutMs);
511 there.issuesServer = this.issuesServer;
512 return there.#issues("POST", there.agentPath("copy"), body);
513 }
515 /** Where an attachment is served. */
516 attachmentUrl(id: string): string {
517 return this.url(`/attachments/${id}`, this.issuesServer);
518 }
520 /** An attachment's bytes, or with `source` the svg it was drawn from; refused past `max` bytes. */
521 async attachmentBytes(id: string, source: boolean, max: number): Promise<Uint8Array> {
522 if (this.issuesServer === undefined)
523 throw new ApiError(`${this.config.server} has no Issues Worker beside it; ABSO_ISSUES_SERVER names one`);
524 const url = `${this.attachmentUrl(id)}${source ? "/source" : ""}`;
525 let res: Response;
526 try {
527 res = await fetch(url, {
528 headers: this.headers(),
529 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
530 });
531 } catch (err) {
532 const e = err as Error;
533 throw new ApiError(
534 `could not reach ${this.issuesServer}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
535 );
536 }
537 if (!res.ok) throw new ApiError(`${url} answered ${res.status}: ${errorSentence(await res.text())}`, res.status);
538 const bytes = new Uint8Array(await res.arrayBuffer());
539 if (bytes.length > max) throw new ApiError(`${url} sent ${bytes.length} bytes, more than an attachment may be`);
540 return bytes;
541 }
543 /** An edit (abso issue 3): it tells the issue's watchers, and `also`, unless `notify` is false. null clears a parent or Agent. */
544 issueEdit(
545 id: number,
546 body: {
547 title?: string;
548 description?: string;
549 parent?: number | null;
550 agent?: string | null;
551 blockedBy?: number[];
552 notify?: boolean;
553 also?: string[];
554 addLabels?: string[];
555 removeLabels?: string[];
556 },
557 ): Promise<{ edit: number; notified: readonly string[]; news?: IssueNews }> {
558 return this.#issues("POST", this.agentPath(`issue/${id}/edit`), body);
559 }
561 issueComment(
562 id: number,
563 text: string,
564 objection = false,
565 attachments: readonly string[] = [],
566 ): Promise<{ id: number; news?: IssueNews }> {
567 return this.#issues("POST", this.agentPath(`issue/${id}/comment`), {
568 text,
569 ...(objection ? { objection } : {}),
570 ...(attachments.length > 0 ? { attachments } : {}),
571 });
572 }
574 issueDrop(id: number): Promise<{ news?: IssueNews }> {
575 return this.#issues("POST", this.agentPath(`issue/${id}/drop`), {});
576 }
578 /** Opens a dropped issue again (abso issue 104). */
579 issueReopen(id: number): Promise<{ news?: IssueNews }> {
580 return this.#issues("POST", this.agentPath(`issue/${id}/reopen`), {});
581 }
583 /** Marks an issue done by hand (abso issue 38). `version` is the publish that did it, when there is one. */
584 issueDone(id: number, version: number | null): Promise<{ news?: IssueNews }> {
585 return this.#issues("POST", this.agentPath(`issue/${id}/done`), { ...(version !== null ? { version } : {}) });
586 }
588 /** This agent's drafts (abso issue 3): its own, with no number and no news, newest first. */
589 drafts(): Promise<{ drafts: readonly Draft[] }> {
590 return this.#issues("GET", this.agentPath("drafts"));
591 }
593 /** Saves a draft, new or (with id) over one of this agent's: the body replaces the draft's. */
594 saveDraft(body: DraftBody & { id?: number }): Promise<{ id: number }> {
595 return this.#issues("POST", this.agentPath("draft"), body);
596 }
598 /** Opens a draft as an issue, `body`'s fields over the draft's, and deletes the draft. */
599 openDraft(id: number, body: DraftBody = {}): Promise<{ id: number; news?: IssueNews }> {
600 return this.#issues("POST", this.agentPath(`draft/${id}/open`), body);
601 }
603 deleteDraft(id: number): Promise<{ ok: boolean }> {
604 return this.#issues("POST", this.agentPath(`draft/${id}/delete`), {});
605 }
607 ask(body: {
608 issue?: number;
609 of: string;
610 question: string;
611 review?: boolean;
612 kind?: "question" | "task";
613 due?: string;
614 blocks?: number[];
615 options?: string[];
616 attachments?: string[];
617 }): Promise<{ id: number; news?: IssueNews; attachments?: string[] }> {
618 return this.#issues("POST", this.agentPath("ask"), body);
619 }
621 answer(
622 id: number,
623 body: { words?: string; option?: number | string; note?: string; done?: boolean; attachments?: string[] },
624 ): Promise<{ ask: Ask; news?: IssueNews }> {
625 return this.#issues("POST", this.agentPath(`answer/${id}`), body);
626 }
628 /** Acknowledges an ask of this agent without answering it: the asker hears it, and the ask stays open. */
629 ack(id: number, body: { note?: string }): Promise<{ ask: Ask; news?: IssueNews }> {
630 return this.#issues("POST", this.agentPath(`ack/${id}`), body);
631 }
633 /** Takes back an ask this agent made, with a note on why; the one asked hears it. */
634 withdraw(id: number, body: { note?: string }): Promise<{ ask: Ask; news?: IssueNews }> {
635 return this.#issues("POST", this.agentPath(`withdraw/${id}`), body);
636 }
638 /** Notes on lines (#44), by file or change; open ones only with `open`. */
639 notes(q: { file?: string; change?: number; open?: boolean } = {}): Promise<{ notes: readonly NoteAnswer[] }> {
640 return this.json("GET", `/notes?${query({ file: q.file, change: q.change, open: q.open ? 1 : undefined })}`);
641 }
643 note(body: NoteBody): Promise<{ id: number; change: number | null; lines: readonly [number, number] }> {
644 return this.json("POST", this.agentPath("note"), body);
645 }
647 noteClose(id: number, how: "resolved" | "withdrawn"): Promise<unknown> {
648 return this.json("POST", this.agentPath("note-close"), { id, how });
649 }
651 /** The merge queue now (#39). */
652 queueState(): Promise<QueueState> {
653 return this.json("GET", "/queue");
654 }
656 /** The project's visibility (abso issue 152): public or private. */
657 visibility(): Promise<{ project: string; visibility: "public" | "private" }> {
658 return this.json("GET", "/visibility");
659 }
661 /** Switch the project's visibility (abso issue 140): an owner's key, or the shared token on staging. */
662 setVisibility(v: "public" | "private"): Promise<{ project: string; visibility: "public" | "private" }> {
663 return this.json("POST", `/visibility?visibility=${v}`, {});
664 }
666 /** Take back this agent's queued publishes (#39); refused while one is being checked. */
667 unqueue(): Promise<{ pulled: readonly number[] }> {
668 return this.json("POST", this.agentPath("unqueue"), {});
669 }
671 /**
672 * Sync; a folder following a label goes to the newest version with that label.
673 * With `full`, the answer holds every file in the agent's view, as a first sync's does,
674 * not only what changed since its last sync (#37: a join for an agent the server knew).
675 */
676 sync(options: { full?: boolean } = {}): Promise<SyncAnswer> {
677 return this.json("POST", this.agentPath("sync"), {
678 ...(this.config.follow ? { label: this.config.follow } : {}),
679 ...(options.full ? { full: true } : {}),
680 });
681 }
683 /** Take published versions back out of shared (with the versions that build on them, when asked). */
684 drop(versions: readonly number[], message: string, withDependents = false): Promise<DropAnswer> {
685 return this.json("POST", this.agentPath("drop"), {
686 versions,
687 message,
688 ...(withDependents ? { withDependents: true } : {}),
689 });
690 }
692 /** Take some versions of a named draft into shared, as one version. */
693 pluck(draft: string, versions: readonly number[], message: string, withDependencies = false): Promise<PluckAnswer> {
694 return this.json("POST", this.agentPath("pluck"), {
695 draft,
696 versions,
697 message,
698 ...(withDependencies ? { withDependencies: true } : {}),
699 });
700 }
702 /** Correct the message of this agent's newest publish in its space. */
703 amend(message: string): Promise<{ version: number; draft: string | null; message: string; was: string }> {
704 return this.json("POST", this.agentPath("amend"), { message });
705 }
707 /** Put a label on a version of shared (the newest by default), or take it off. */
708 label(
709 name: string,
710 version?: number,
711 remove = false,
712 ): Promise<{ name: string; version: number; versions: readonly number[] }> {
713 return this.json("POST", this.agentPath("label"), {
714 name,
715 ...(version === undefined ? {} : { version }),
716 ...(remove ? { remove: true } : {}),
717 });
718 }
720 labels(): Promise<{ labels: Readonly<Record<string, readonly number[]>> }> {
721 return this.json("GET", "/labels");
722 }
724 status(): Promise<StatusAnswer> {
725 return this.json("GET", "/status");
726 }
728 /** The status and the paths in the agent's view, in one trip (abso issue 80). */
729 async statusAndFiles(): Promise<StatusAnswer & { files: FilesAnswer | undefined }> {
730 try {
731 return await this.json("GET", this.agentPath("status"));
732 } catch (err) {
733 // A server from before it has no /a/:agent/status; the listing itself is from #37.
734 if (!(err instanceof ApiError && err.status === 404)) throw err;
735 }
736 const status = await this.status();
737 return { ...status, files: await this.viewFiles().catch(() => undefined) };
738 }
740 /** CI's state (#39), or one version's job. */
741 ci(): Promise<CiStatus>;
742 ci(version: number): Promise<CiJob>;
743 ci(version?: number): Promise<CiStatus | CiJob> {
744 return this.json("GET", version === undefined ? "/ci" : `/ci?${query({ version })}`);
745 }
747 /** Ends every /latest link handed out so far; answers CI's state with the new link. */
748 ciRevoke(): Promise<CiStatus> {
749 return this.json("POST", "/ci/revoke", {});
750 }
752 /** Count versions up to `through` as seen by CI and end any red or bisect, so an import's history isn't checked (#56). */
753 ciSkip(through: number): Promise<unknown> {
754 return this.json("POST", "/ci/skip", { through });
755 }
757 /** Move to a named draft (null: shared). With carry, the current unpublished changes start a new draft. */
758 switchDraft(name: string | null, carry = false): Promise<SwitchAnswer> {
759 return this.json("POST", this.agentPath("draft"), { name, ...(carry ? { carry: true } : {}) });
760 }
762 /** Land never queues: with the merge queue on, the server refuses it (#39). */
763 land(message: string): Promise<Exclude<PublishAnswer, { queued: number }>> {
764 return this.json("POST", this.agentPath("land"), { message }, undefined, PUBLISH_TIMEOUT_MS);
765 }
767 draftSync(): Promise<DraftSyncAnswer> {
768 return this.json("POST", this.agentPath("draft-sync"), {});
769 }
771 blame(file: string, from?: number, to?: number, version?: number, view: View = {}): Promise<BlameAnswer> {
772 return this.json("GET", `/blame?${query({ file, from, to, version, ...view })}`);
773 }
775 /** The paths in the agent's view: what its folder should hold (#37). */
776 viewFiles(): Promise<FilesAnswer> {
777 return this.json("GET", this.agentPath("files"));
778 }
780 /** The paths in shared, or a named draft, at a version (the newest by default). */
781 filesAt(draft: string | null, version?: number): Promise<FilesAnswer> {
782 return this.json("GET", `/files?${query({ draft, version })}`);
783 }
785 /** The versions of a space, newest first; with `path`, only those that changed it. */
786 /**
787 * The versions newest first, below `before` when it's given. The server
788 * sends at most LOG_PAGE at a time, so a longer log is read page by page,
789 * following each page's next. `next` on the answer says older ones are left.
790 */
791 async log(where: Where, limit?: number, path?: string, before?: number): Promise<LogAnswer> {
792 let page = await this.#logPage(where, limit === undefined ? undefined : Math.min(limit, LOG_PAGE), path, before);
793 const versions = [...page.versions];
794 while (limit !== undefined && versions.length < limit && page.next !== undefined) {
795 page = await this.#logPage(where, Math.min(limit - versions.length, LOG_PAGE), path, page.next);
796 versions.push(...page.versions);
797 }
798 const { next, ...rest } = page;
799 return { ...rest, versions, ...(next !== undefined ? { next } : {}) };
800 }
802 #logPage(
803 where: Where,
804 limit: number | undefined,
805 path: string | undefined,
806 before: number | undefined,
807 ): Promise<LogAnswer> {
808 return this.json("GET", `/log?${query({ ...where, limit, path, before })}`);
809 }
811 show(version: number, where: Where): Promise<ShowAnswer> {
812 return this.json("GET", `/show?${query({ version, ...where })}`);
813 }
815 fileAt(path: string, version: number, where: Where): Promise<{ path: string; version: number; text: string | null }> {
816 return this.json("GET", `/file?${query({ path, version, ...where })}`);
817 }
819 compare(from: number, to: number, where: Where): Promise<{ from: number; to: number; files: readonly FileChange[] }> {
820 return this.json("GET", `/compare?${query({ from, to, ...where })}`);
821 }
823 /** A message to the project's other agents (or those named), delivered once as news. */
824 starting(
825 text: string | null,
826 files?: readonly string[],
827 options: { issue?: number; done?: boolean } = {},
828 ): Promise<{
829 starting: { text: string; files: readonly string[]; time: number; issue?: number } | null;
830 overlaps: readonly Overlap[];
831 }> {
832 return this.json("POST", this.agentPath("starting"), {
833 text,
834 ...(files && files.length > 0 ? { files } : {}),
835 ...(options.issue !== undefined ? { issue: options.issue } : {}),
836 ...(options.done ? { done: true } : {}),
837 });
838 }
840 announce(text: string, to?: readonly string[]): Promise<{ id: number; to: readonly string[] }> {
841 return this.json("POST", this.agentPath("announce"), { text, ...(to ? { to } : {}) });
842 }
844 /** The news waiting for this agent, handed over once. */
845 news(): Promise<{ news: News; items?: readonly { readonly text: string; readonly at: number | null }[] }> {
846 return this.json("POST", this.agentPath("news"), {});
847 }
849 /** This agent's unpublished changes, file by file. */
850 diff(): Promise<DiffAnswer> {
851 return this.json("POST", this.agentPath("diff"), {});
852 }
854 /** Another agent's recorded, unpublished changes, file by file: read only, as the website's drafts show them. */
855 diffOf(agent: string): Promise<DiffAnswer> {
856 return this.json("GET", `/diff?${query({ agent })}`);
857 }
859 /** Discard this agent's unpublished changes to `files` (null: all of them). */
860 restore(files: readonly string[] | null): Promise<RestoreAnswer> {
861 return this.json("POST", this.agentPath("restore"), files === null ? { all: true } : { files });
862 }
864 why(file: string, line: number, view: View = {}): Promise<WhyAnswer> {
865 return this.json("GET", `/why?${query({ file, line, ...view })}`);
866 }
868 where(): Promise<WhereAnswer> {
869 return this.json("GET", "/where");
870 }
872 /**
873 * Send the folder as a tar.gz and run a command in the agent's box. Output
874 * goes to `io.out` as it arrives, and the box's stderr to `io.err` (the
875 * server keeps them apart when asked; an older one sends both as out).
876 * Answers the command's exit code.
877 *
878 * When the stream breaks before the exit line and the server gave the run
879 * an id, the run goes on in the box: this reconnects to it and carries on
880 * from the last output printed, so nothing is lost or printed twice. The
881 * command itself is never sent twice.
882 */
883 async run(command: string, tarGz: Uint8Array<ArrayBuffer>, io: RunIO): Promise<number> {
884 const res = await postRun(this, command, tarGz, io.onRetry, io.replace, io.fresh);
885 // X-Abso-Box: cold means the box started for this run; X-Abso-Prep says whether it started from the prep (#37).
886 io.onBox?.(res.headers.get("x-abso-box") === "cold", res.headers.get("x-abso-prep") ?? undefined);
887 return follow(this, res, res.headers.get("x-abso-run"), { at: 0, errAt: 0 }, io);
888 }
890 /**
891 * Start a run and answer its id without waiting: the job goes on in the box
892 * after this connection closes (abso run --detach; abso logs <id> follows it).
893 */
894 async startRun(
895 command: string,
896 tarGz: Uint8Array<ArrayBuffer>,
897 onRetry?: (why: string, attempt: number) => void,
898 replace = false,
899 ): Promise<string> {
900 const res = await postRun(this, command, tarGz, onRetry, replace);
901 const id = res.headers.get("x-abso-run");
902 if (id === null) {
903 // No id: the box failed before the job started ({"error"} in the body), or the server can't detach.
904 await consumeRun(res, { out: () => {} }, { at: 0, errAt: 0 });
905 throw new ApiError("this server gives runs no id, so a run can't be detached");
906 }
907 await res.body?.cancel();
908 return id;
909 }
911 /** A run's output from its start, for as long as the box keeps it, until it ends (abso logs). Answers its exit code. */
912 async logs(id: string, io: RunIO): Promise<number> {
913 let res: Response;
914 try {
915 res = await fetch(followUrl(this, id, { at: 0, errAt: 0 }), { headers: this.headers() });
916 } catch (err) {
917 const e = err as Error;
918 throw new ApiError(
919 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
920 );
921 }
922 if (res.status === 404) throw new ApiError(`no run ${id} in this box: ${errorSentence(await res.text())}`, 404);
923 if (!res.ok || res.body === null)
924 throw new ApiError(`logs answered ${res.status}: ${errorSentence(await res.text())}`, res.status);
925 return follow(this, res, id, { at: 0, errAt: 0 }, io);
926 }