Skip to content

abso-core

Public
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=87&format=json
951 linesFirst import 76% · pinch 21% · devops 2% · infra-pipeline 1% · infra-split 1% · review 1%Last change pinch in version 87, 17 versions changed it

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