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=23&format=json
849 linesFirst import 87% · pinch 10% · devops 2% · infra-split 1%Last change pinch in version 23, 6 versions changed it

You're reading version 23. The newest is 318, and 24 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/** A query string from the values that are set (null and undefined are left out). */
89function query(values: Record<string, string | number | null | undefined>): URLSearchParams {
90 const q = new URLSearchParams();
91 for (const [k, v] of Object.entries(values)) if (v !== null && v !== undefined) q.set(k, String(v));
92 return q;
95export function newsLines(news: News): string[] {
96 if (news === undefined || news === null) return [];
97 return (typeof news === "string" ? [news] : [...news]).filter((s) => typeof s === "string" && s.trim() !== "");
100/** An issue copy's request: the source, and any texts given cleaned, by their source ids. */
101export interface CopyBody {
102 from: string;
103 issue: number;
104 title?: string;
105 description?: string;
106 comments?: { id: number; text?: string }[];
107 asks?: { id: number; question?: string; answer?: string }[];
110/** What a copy writes, as a dry run answers it. */
111export interface CopyPlan {
112 from: { project: string; issue: number };
113 title: string;
114 edited: ("title" | "description")[];
115 labels: string[];
116 closed: { how: "done" | "dropped" } | null;
117 comments: { edited: boolean }[];
118 asks: { edited: boolean }[];
119 skipped: { comments: number[]; asks: number[] };
122export type CopyAnswer =
123 | { dryRun: true; plan: CopyPlan }
124 | { ok: true; id: number; from: { project: string; issue: number }; skipped: { comments: number[]; asks: number[] } };
126export class Api {
127 readonly config: Config;
128 readonly timeoutMs: number;
130 /** Waits between tries when a run's stream breaks; tests shorten them. */
131 readonly reconnectDelaysMs: readonly number[];
132 readonly startRetryDelaysMs: readonly number[];
133 /** Another box of this agent for run, logs and fetch (--box or AVCS_BOX, #37); undefined is its own box. */
134 box: string | undefined;
136 constructor(
137 config: Config,
138 timeoutMs = 30_000,
139 reconnectDelaysMs: readonly number[] = RECONNECT_DELAYS_MS,
140 startRetryDelaysMs: readonly number[] = RUN_START_RETRY_MS,
141 ) {
142 this.config = config;
143 this.timeoutMs = timeoutMs;
144 this.reconnectDelaysMs = reconnectDelaysMs;
145 this.startRetryDelaysMs = startRetryDelaysMs;
146 }
148 /** What a box run is for, for the server's box-run records (#39): X-Avcs-Kind on POST /run. */
149 runKind: RunKind = "run";
151 /** The Issues Worker (#54) this folder's issues calls go to; set by the issues commands (issues.ts). */
152 issuesServer: string | undefined;
154 url(path: string, server = this.config.server): string {
155 return `${server.replace(/\/+$/, "")}/p/${encodeURIComponent(this.config.project)}${path}`;
156 }
158 agentPath(action: string): string {
159 return `/a/${encodeURIComponent(this.config.agent)}/${action}`;
160 }
162 headers(contentType?: string): Record<string, string> {
163 return {
164 // Which client made the call (#29); the mods send theirs too.
165 "x-avcs-client": `abso-cli/${clientVersion()}`,
166 ...(this.config.token ? { authorization: `Bearer ${this.config.token}` } : {}),
167 ...(contentType ? { "content-type": contentType } : {}),
168 };
169 }
171 async json<T>(method: "GET" | "POST", path: string, body?: unknown, server = this.config.server): Promise<T> {
172 let res: Response | undefined;
173 const sent = body === undefined ? undefined : JSON.stringify(body);
174 const timeoutMs = timeoutFor(this.timeoutMs, sent);
175 // A connection that never opened is tried once more, IPv4 first (#37, GAME - UI/UX: one IPv6
176 // address timed out, and the same command went through seconds later). Nothing went out, so
177 // a POST is as safe to send again as a GET.
178 for (let attempt = 0; res === undefined; attempt++) {
179 try {
180 res = await fetch(this.url(path, server), {
181 method,
182 headers: this.headers(sent === undefined ? undefined : "application/json"),
183 ...(sent === undefined ? {} : { body: sent }),
184 signal: AbortSignal.timeout(timeoutMs),
185 });
186 } catch (err) {
187 const e = err as Error;
188 const why =
189 e.name === "TimeoutError"
190 ? `no answer within ${timeoutMs} ms`
191 : ((e.cause as Error | undefined)?.message ?? e.message);
192 if (!neverSent(err)) throw new ApiError(`could not reach ${server}: ${why}`);
193 if (attempt >= 1) {
194 throw new ApiError(
195 `could not reach ${server}: ${why}. Tried twice, the second time IPv4 first; the connection never opened, so nothing reached the server`,
196 undefined,
197 true,
198 );
199 }
200 setDefaultResultOrder("ipv4first");
201 await new Promise((ok) => setTimeout(ok, 500));
202 }
203 }
204 const text = await res.text();
205 // 409 is a refusal that says what to do (a drop took out lines your work builds on): print it as it is.
206 if (!res.ok)
207 throw new ApiError(
208 res.status === 409
209 ? `refused: ${errorSentence(text)}`
210 : `${method} ${path} answered ${res.status}: ${errorSentence(text)}`,
211 res.status,
212 );
213 try {
214 return JSON.parse(text) as T;
215 } catch {
216 throw new ApiError(
217 `${method} ${path} answered with something that isn't JSON: ${text.slice(0, 300)}`,
218 res.status,
219 );
220 }
221 }
223 init(
224 files: Record<string, string>,
225 modes: Modes = {},
226 blobs: Readonly<Record<string, string>> = {},
227 ): Promise<{ version: number; skipped?: readonly string[] }> {
228 return this.json("POST", "/init", {
229 files,
230 ...(Object.keys(modes).length > 0 ? { modes } : {}),
231 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
232 });
233 }
235 edit(body: EditBody): Promise<EditAnswer> {
236 return this.json("POST", this.agentPath("edit"), body);
237 }
239 record(
240 files: Record<string, string | null>,
241 extra: { session?: string; subagent?: string } = {},
242 modes: Modes = {},
243 blobs: Readonly<Record<string, string>> = {},
244 ): Promise<RecordAnswer> {
245 return this.json("POST", this.agentPath("record"), {
246 files,
247 ...(Object.keys(modes).length > 0 ? { modes } : {}),
248 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
249 ...extra,
250 });
251 }
253 /** Move a file in the draft (#49): its lines keep their ids. The way to change a file's case. */
254 move(from: string, to: string): Promise<{ ok: boolean; from: string; to: string; news?: News }> {
255 return this.json("POST", this.agentPath("move"), { from, to });
256 }
258 /** Upload a binary file's bytes under their sha256 (the server checks the hash). */
259 async putBlob(sha: string, bytes: Uint8Array): Promise<void> {
260 await this.bytes("PUT", `/blobs/${sha}`, bytes);
261 }
263 /** A preview of one version of shared at a stable URL (abso serve, #37); a build answers 422 with its output. */
264 async serve(version?: number, cmd?: string, out?: string): Promise<ServeAnswer> {
265 const q = new URLSearchParams({
266 ...(version !== undefined ? { version: String(version) } : {}),
267 ...(cmd ? { cmd } : {}),
268 ...(out ? { out } : {}),
269 });
270 let res: Response;
271 try {
272 res = await fetch(`${this.url("/serve")}?${q}`, {
273 method: "POST",
274 headers: this.headers(),
275 signal: AbortSignal.timeout(20 * 60_000),
276 });
277 } catch (err) {
278 const e = err as Error;
279 throw new ApiError(
280 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
281 );
282 }
283 const text = await res.text();
284 if (!res.ok && res.status !== 422)
285 throw new ApiError(`serve answered ${res.status}: ${errorSentence(text)}`, res.status);
286 return JSON.parse(text) as ServeAnswer;
287 }
289 /** Runs a setup command on the folder in a fresh box and keeps the box as what it starts from (abso prep, #37). */
290 async prep(command: string, tarGz: Uint8Array<ArrayBuffer>): Promise<PrepAnswer> {
291 let res: Response;
292 try {
293 res = await fetch(`${this.url(this.agentPath("prep"))}?cmd=${encodeURIComponent(command)}${boxQuery(this.box)}`, {
294 method: "POST",
295 headers: this.headers("application/gzip"),
296 body: tarGz,
297 // A setup command can take minutes (npm ci, a browser download).
298 signal: AbortSignal.timeout(30 * 60_000),
299 });
300 } catch (err) {
301 const e = err as Error;
302 throw new ApiError(
303 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
304 );
305 }
306 const text = await res.text();
307 if (!res.ok) throw new ApiError(`prep answered ${res.status}: ${errorSentence(text)}`, res.status);
308 return JSON.parse(text) as PrepAnswer;
309 }
311 /** Forgets the box's prep: it starts from the plain image again. Answers whether it had one. */
312 async unprep(): Promise<boolean> {
313 let res: Response;
314 try {
315 res = await fetch(
316 `${this.url(this.agentPath("prep"))}${this.box ? `?box=${encodeURIComponent(this.box)}` : ""}`,
317 { method: "DELETE", headers: this.headers(), signal: AbortSignal.timeout(this.timeoutMs) },
318 );
319 } catch (err) {
320 const e = err as Error;
321 throw new ApiError(
322 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
323 );
324 }
325 const text = await res.text();
326 if (!res.ok) throw new ApiError(`prep answered ${res.status}: ${errorSentence(text)}`, res.status);
327 return (JSON.parse(text) as { forgot: boolean }).forgot;
328 }
330 /** A binary file's bytes by their sha256. */
331 /** 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. */
332 async boxFiles(glob: string): Promise<Uint8Array | null> {
333 try {
334 return await this.bytes(
335 "GET",
336 `${this.agentPath("box-files")}?${new URLSearchParams({ glob, ...(this.box ? { box: this.box } : {}) })}`,
337 );
338 } catch (err) {
339 if (err instanceof ApiError && err.status === 404) return null;
340 throw err;
341 }
342 }
344 getBlob(sha: string): Promise<Uint8Array> {
345 return this.bytes("GET", `/blobs/${sha}`);
346 }
348 async bytes(method: "GET" | "PUT", path: string, body?: Uint8Array): Promise<Uint8Array> {
349 let res: Response;
350 try {
351 res = await fetch(this.url(path), {
352 method,
353 headers: this.headers(body === undefined ? undefined : "application/octet-stream"),
354 ...(body === undefined ? {} : { body: body as Uint8Array<ArrayBuffer> }),
355 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
356 });
357 } catch (err) {
358 const e = err as Error;
359 throw new ApiError(
360 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
361 );
362 }
363 const data = new Uint8Array(await res.arrayBuffer());
364 if (!res.ok)
365 throw new ApiError(
366 `${method} ${path} answered ${res.status}: ${errorSentence(new TextDecoder().decode(data))}`,
367 res.status,
368 );
369 return data;
370 }
372 /** Make this agent a reader, or not (#37): a reader's edits, records and publishes are refused. */
373 reader(on: boolean): Promise<{ agent: string; reader: boolean }> {
374 return this.json("POST", this.agentPath("reader"), { reader: on });
375 }
377 publish(message: string, asIs = false): Promise<PublishAnswer> {
378 return this.json("POST", this.agentPath("publish"), { message, ...(asIs ? { asIs: true } : {}) });
379 }
381 /** One change (#44). */
382 change(id: number): Promise<ChangeAnswer> {
383 return this.json("GET", `/change/${id}`);
384 }
386 /** The changes with anything new at or after log position `since`, newest first (#44). */
387 /** Changes active since a log position, newest first; `older` is set when more come before the page (ask again with `before`). */
388 changes(
389 since: number,
390 limit = 50,
391 before?: number,
392 ): Promise<{ since: number; next: number; changes: readonly ChangeAnswer[]; older?: number }> {
393 return this.json("GET", `/changes?${query({ since, limit, before })}`);
394 }
396 /** A call to the Issues Worker (#54), with the same token. */
397 #issues<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> {
398 if (this.issuesServer === undefined)
399 throw new ApiError(`${this.config.server} has no Issues Worker beside it; AVCS_ISSUES_SERVER names one`);
400 return this.json(method, path, body, this.issuesServer);
401 }
403 /** Issues, most recently updated first. */
404 issues(
405 q: { status?: string; agent?: string; parent?: number; open?: boolean; labels?: readonly string[] } = {},
406 ): Promise<{ issues: readonly IssueRow[] }> {
407 return this.#issues(
408 "GET",
409 `/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 })}`,
410 );
411 }
413 /**
414 * The project's issues matching q, best first: by its words and, where
415 * the server has it on, by what it means.
416 */
417 issueSearch(q: string, limit?: number): Promise<{ hits: readonly IssueSearchHit[] }> {
418 return this.#issues("GET", `/search?${query({ q, limit })}`);
419 }
421 /** Every label in use, with how many issues have it and how many of those are open. */
422 issueLabels(): Promise<{ labels: readonly { label: string; open: number; total: number }[] }> {
423 return this.#issues("GET", "/labels");
424 }
426 issue(id: number): Promise<IssuePage> {
427 return this.#issues("GET", `/issue/${id}`);
428 }
430 /** Open asks of someone (an agent, or person:<id>), soonest due first; every open ask without `of`. */
431 waiting(of?: string): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
432 return this.#issues("GET", `/waiting?${query({ of })}`);
433 }
435 /** This agent's open asks; the Worker marks each it lists for the first time as seen (abso issue 124). */
436 async waitingMine(): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
437 try {
438 return await this.#issues("GET", this.agentPath("waiting"));
439 } catch (err) {
440 // An Issues Worker from before 124 has no /a/:agent/ reads.
441 if (err instanceof ApiError && err.status === 404) return this.waiting(this.config.agent);
442 throw err;
443 }
444 }
446 issueOpen(body: DraftBody & { title: string; attachments?: string[] }): Promise<{ id: number; news?: IssueNews }> {
447 return this.#issues("POST", this.agentPath("issue"), body);
448 }
450 /** Uploads an image to the Issues Worker (abso issue 171): it checks the type by the bytes, strips metadata and answers its id. */
451 async attachmentUpload(bytes: Uint8Array, name: string): Promise<Attachment> {
452 if (this.issuesServer === undefined)
453 throw new ApiError(`${this.config.server} has no Issues Worker beside it; AVCS_ISSUES_SERVER names one`);
454 const path = this.agentPath("attachments");
455 let res: Response;
456 try {
457 res = await fetch(this.url(path, this.issuesServer), {
458 method: "POST",
459 headers: { ...this.headers("application/octet-stream"), "x-avcs-name": encodeURIComponent(name) },
460 body: bytes as Uint8Array<ArrayBuffer>,
461 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
462 });
463 } catch (err) {
464 const e = err as Error;
465 throw new ApiError(
466 `could not reach ${this.issuesServer}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
467 );
468 }
469 const text = await res.text();
470 // A server from before attachments has no upload route: it answers 404, or 400 because the body isn't JSON;
471 // one with the route but nowhere to keep files answers 501. Say so plainly, and that nothing was sent.
472 if (res.status === 404 || res.status === 501 || (res.status === 400 && /the body is JSON/.test(text)))
473 throw new ApiError(
474 `${this.issuesServer} doesn't take attachments yet, so ${name} wasn't sent and nothing was written. Leave --attach off, or link the image instead.`,
475 res.status,
476 );
477 if (!res.ok) throw new ApiError(`uploading ${name} answered ${res.status}: ${errorSentence(text)}`, res.status);
478 return JSON.parse(text) as Attachment;
479 }
481 /**
482 * Copies issue `body.issue` of this project into project `to`, keeping
483 * authors and times: the Issues server reads the source itself, and only
484 * texts may be given cleaned. A dry run answers the plan and writes nothing.
485 */
486 issueCopy(to: string, body: CopyBody & { dryRun?: boolean }): Promise<CopyAnswer> {
487 const there = new Api({ ...this.config, project: to }, this.timeoutMs);
488 there.issuesServer = this.issuesServer;
489 return there.#issues("POST", there.agentPath("copy"), body);
490 }
492 /** Where an attachment is served. */
493 attachmentUrl(id: string): string {
494 return this.url(`/attachments/${id}`, this.issuesServer);
495 }
497 /** An edit (abso issue 3): it tells the issue's watchers, and `also`, unless `notify` is false. null clears a parent or Agent. */
498 issueEdit(
499 id: number,
500 body: {
501 title?: string;
502 description?: string;
503 parent?: number | null;
504 agent?: string | null;
505 blockedBy?: number[];
506 notify?: boolean;
507 also?: string[];
508 addLabels?: string[];
509 removeLabels?: string[];
510 },
511 ): Promise<{ edit: number; notified: readonly string[]; news?: IssueNews }> {
512 return this.#issues("POST", this.agentPath(`issue/${id}/edit`), body);
513 }
515 issueComment(
516 id: number,
517 text: string,
518 objection = false,
519 attachments: readonly string[] = [],
520 ): Promise<{ id: number; news?: IssueNews }> {
521 return this.#issues("POST", this.agentPath(`issue/${id}/comment`), {
522 text,
523 ...(objection ? { objection } : {}),
524 ...(attachments.length > 0 ? { attachments } : {}),
525 });
526 }
528 issueDrop(id: number): Promise<{ news?: IssueNews }> {
529 return this.#issues("POST", this.agentPath(`issue/${id}/drop`), {});
530 }
532 /** Opens a dropped issue again (abso issue 104). */
533 issueReopen(id: number): Promise<{ news?: IssueNews }> {
534 return this.#issues("POST", this.agentPath(`issue/${id}/reopen`), {});
535 }
537 /** Marks an issue done by hand (abso issue 38). `version` is the publish that did it, when there is one. */
538 issueDone(id: number, version: number | null): Promise<{ news?: IssueNews }> {
539 return this.#issues("POST", this.agentPath(`issue/${id}/done`), { ...(version !== null ? { version } : {}) });
540 }
542 /** This agent's drafts (abso issue 3): its own, with no number and no news, newest first. */
543 drafts(): Promise<{ drafts: readonly Draft[] }> {
544 return this.#issues("GET", this.agentPath("drafts"));
545 }
547 /** Saves a draft, new or (with id) over one of this agent's: the body replaces the draft's. */
548 saveDraft(body: DraftBody & { id?: number }): Promise<{ id: number }> {
549 return this.#issues("POST", this.agentPath("draft"), body);
550 }
552 /** Opens a draft as an issue, `body`'s fields over the draft's, and deletes the draft. */
553 openDraft(id: number, body: DraftBody = {}): Promise<{ id: number; news?: IssueNews }> {
554 return this.#issues("POST", this.agentPath(`draft/${id}/open`), body);
555 }
557 deleteDraft(id: number): Promise<{ ok: boolean }> {
558 return this.#issues("POST", this.agentPath(`draft/${id}/delete`), {});
559 }
561 ask(body: {
562 issue?: number;
563 of: string;
564 question: string;
565 review?: boolean;
566 kind?: "question" | "task";
567 due?: string;
568 blocks?: number[];
569 options?: string[];
570 }): Promise<{ id: number; news?: IssueNews }> {
571 return this.#issues("POST", this.agentPath("ask"), body);
572 }
574 answer(
575 id: number,
576 body: { words?: string; option?: number | string; note?: string; done?: boolean },
577 ): Promise<{ ask: Ask; news?: IssueNews }> {
578 return this.#issues("POST", this.agentPath(`answer/${id}`), body);
579 }
581 /** Takes back an ask this agent made, with a note on why; the one asked hears it. */
582 withdraw(id: number, body: { note?: string }): Promise<{ ask: Ask; news?: IssueNews }> {
583 return this.#issues("POST", this.agentPath(`withdraw/${id}`), body);
584 }
586 /** Notes on lines (#44), by file or change; open ones only with `open`. */
587 notes(q: { file?: string; change?: number; open?: boolean } = {}): Promise<{ notes: readonly NoteAnswer[] }> {
588 return this.json("GET", `/notes?${query({ file: q.file, change: q.change, open: q.open ? 1 : undefined })}`);
589 }
591 note(body: NoteBody): Promise<{ id: number; change: number | null; lines: readonly [number, number] }> {
592 return this.json("POST", this.agentPath("note"), body);
593 }
595 noteClose(id: number, how: "resolved" | "withdrawn"): Promise<unknown> {
596 return this.json("POST", this.agentPath("note-close"), { id, how });
597 }
599 /** The merge queue now (#39). */
600 queueState(): Promise<QueueState> {
601 return this.json("GET", "/queue");
602 }
604 /** The project's visibility (abso issue 152): public or private. */
605 visibility(): Promise<{ project: string; visibility: "public" | "private" }> {
606 return this.json("GET", "/visibility");
607 }
609 /** Switch the project's visibility (abso issue 140): an owner's key, or the shared token on staging. */
610 setVisibility(v: "public" | "private"): Promise<{ project: string; visibility: "public" | "private" }> {
611 return this.json("POST", `/visibility?visibility=${v}`, {});
612 }
614 /** Take back this agent's queued publishes (#39); refused while one is being checked. */
615 unqueue(): Promise<{ pulled: readonly number[] }> {
616 return this.json("POST", this.agentPath("unqueue"), {});
617 }
619 /**
620 * Sync; a folder following a label goes to the newest version with that label.
621 * With `full`, the answer holds every file in the agent's view, as a first sync's does,
622 * not only what changed since its last sync (#37: a join for an agent the server knew).
623 */
624 sync(options: { full?: boolean } = {}): Promise<SyncAnswer> {
625 return this.json("POST", this.agentPath("sync"), {
626 ...(this.config.follow ? { label: this.config.follow } : {}),
627 ...(options.full ? { full: true } : {}),
628 });
629 }
631 /** Take published versions back out of shared (with the versions that build on them, when asked). */
632 drop(versions: readonly number[], message: string, withDependents = false): Promise<DropAnswer> {
633 return this.json("POST", this.agentPath("drop"), {
634 versions,
635 message,
636 ...(withDependents ? { withDependents: true } : {}),
637 });
638 }
640 /** Take some versions of a named draft into shared, as one version. */
641 pluck(draft: string, versions: readonly number[], message: string, withDependencies = false): Promise<PluckAnswer> {
642 return this.json("POST", this.agentPath("pluck"), {
643 draft,
644 versions,
645 message,
646 ...(withDependencies ? { withDependencies: true } : {}),
647 });
648 }
650 /** Correct the message of this agent's newest publish in its space. */
651 amend(message: string): Promise<{ version: number; draft: string | null; message: string; was: string }> {
652 return this.json("POST", this.agentPath("amend"), { message });
653 }
655 /** Put a label on a version of shared (the newest by default), or take it off. */
656 label(
657 name: string,
658 version?: number,
659 remove = false,
660 ): Promise<{ name: string; version: number; versions: readonly number[] }> {
661 return this.json("POST", this.agentPath("label"), {
662 name,
663 ...(version === undefined ? {} : { version }),
664 ...(remove ? { remove: true } : {}),
665 });
666 }
668 labels(): Promise<{ labels: Readonly<Record<string, readonly number[]>> }> {
669 return this.json("GET", "/labels");
670 }
672 status(): Promise<StatusAnswer> {
673 return this.json("GET", "/status");
674 }
676 /** The status and the paths in the agent's view, in one trip (abso issue 80). */
677 async statusAndFiles(): Promise<StatusAnswer & { files: FilesAnswer | undefined }> {
678 try {
679 return await this.json("GET", this.agentPath("status"));
680 } catch (err) {
681 // A server from before it has no /a/:agent/status; the listing itself is from #37.
682 if (!(err instanceof ApiError && err.status === 404)) throw err;
683 }
684 const status = await this.status();
685 return { ...status, files: await this.viewFiles().catch(() => undefined) };
686 }
688 /** CI's state (#39), or one version's job. */
689 ci(): Promise<CiStatus>;
690 ci(version: number): Promise<CiJob>;
691 ci(version?: number): Promise<CiStatus | CiJob> {
692 return this.json("GET", version === undefined ? "/ci" : `/ci?${query({ version })}`);
693 }
695 /** Ends every /latest link handed out so far; answers CI's state with the new link. */
696 ciRevoke(): Promise<CiStatus> {
697 return this.json("POST", "/ci/revoke", {});
698 }
700 /** Count versions up to `through` as seen by CI and end any red or bisect, so an import's history isn't checked (#56). */
701 ciSkip(through: number): Promise<unknown> {
702 return this.json("POST", "/ci/skip", { through });
703 }
705 /** Move to a named draft (null: shared). With carry, the current unpublished changes start a new draft. */
706 switchDraft(name: string | null, carry = false): Promise<SwitchAnswer> {
707 return this.json("POST", this.agentPath("draft"), { name, ...(carry ? { carry: true } : {}) });
708 }
710 /** Land never queues: with the merge queue on, the server refuses it (#39). */
711 land(message: string): Promise<Exclude<PublishAnswer, { queued: number }>> {
712 return this.json("POST", this.agentPath("land"), { message });
713 }
715 draftSync(): Promise<DraftSyncAnswer> {
716 return this.json("POST", this.agentPath("draft-sync"), {});
717 }
719 blame(file: string, from?: number, to?: number, version?: number, view: View = {}): Promise<BlameAnswer> {
720 return this.json("GET", `/blame?${query({ file, from, to, version, ...view })}`);
721 }
723 /** The paths in the agent's view: what its folder should hold (#37). */
724 viewFiles(): Promise<FilesAnswer> {
725 return this.json("GET", this.agentPath("files"));
726 }
728 /** The paths in shared, or a named draft, at a version (the newest by default). */
729 filesAt(draft: string | null, version?: number): Promise<FilesAnswer> {
730 return this.json("GET", `/files?${query({ draft, version })}`);
731 }
733 /** The versions of a space, newest first; with `path`, only those that changed it. */
734 log(where: Where, limit?: number, path?: string): Promise<LogAnswer> {
735 return this.json("GET", `/log?${query({ ...where, limit, path })}`);
736 }
738 show(version: number, where: Where): Promise<ShowAnswer> {
739 return this.json("GET", `/show?${query({ version, ...where })}`);
740 }
742 fileAt(path: string, version: number, where: Where): Promise<{ path: string; version: number; text: string | null }> {
743 return this.json("GET", `/file?${query({ path, version, ...where })}`);
744 }
746 compare(from: number, to: number, where: Where): Promise<{ from: number; to: number; files: readonly FileChange[] }> {
747 return this.json("GET", `/compare?${query({ from, to, ...where })}`);
748 }
750 /** A message to the project's other agents (or those named), delivered once as news. */
751 starting(
752 text: string | null,
753 files?: readonly string[],
754 options: { issue?: number; done?: boolean } = {},
755 ): Promise<{
756 starting: { text: string; files: readonly string[]; time: number; issue?: number } | null;
757 overlaps: readonly Overlap[];
758 }> {
759 return this.json("POST", this.agentPath("starting"), {
760 text,
761 ...(files && files.length > 0 ? { files } : {}),
762 ...(options.issue !== undefined ? { issue: options.issue } : {}),
763 ...(options.done ? { done: true } : {}),
764 });
765 }
767 announce(text: string, to?: readonly string[]): Promise<{ id: number; to: readonly string[] }> {
768 return this.json("POST", this.agentPath("announce"), { text, ...(to ? { to } : {}) });
769 }
771 /** The news waiting for this agent, handed over once. */
772 news(): Promise<{ news: News; items?: readonly { readonly text: string; readonly at: number | null }[] }> {
773 return this.json("POST", this.agentPath("news"), {});
774 }
776 /** This agent's unpublished changes, file by file. */
777 diff(): Promise<DiffAnswer> {
778 return this.json("POST", this.agentPath("diff"), {});
779 }
781 /** Discard this agent's unpublished changes to `files` (null: all of them). */
782 restore(files: readonly string[] | null): Promise<RestoreAnswer> {
783 return this.json("POST", this.agentPath("restore"), files === null ? { all: true } : { files });
784 }
786 why(file: string, line: number, view: View = {}): Promise<WhyAnswer> {
787 return this.json("GET", `/why?${query({ file, line, ...view })}`);
788 }
790 where(): Promise<WhereAnswer> {
791 return this.json("GET", "/where");
792 }
794 /**
795 * Send the folder as a tar.gz and run a command in the agent's box. Output
796 * goes to `io.out` as it arrives, and the box's stderr to `io.err` (the
797 * server keeps them apart when asked; an older one sends both as out).
798 * Answers the command's exit code.
799 *
800 * When the stream breaks before the exit line and the server gave the run
801 * an id, the run goes on in the box: this reconnects to it and carries on
802 * from the last output printed, so nothing is lost or printed twice. The
803 * command itself is never sent twice.
804 */
805 async run(command: string, tarGz: Uint8Array<ArrayBuffer>, io: RunIO): Promise<number> {
806 const res = await postRun(this, command, tarGz, io.onRetry, io.replace, io.fresh);
807 // X-Avcs-Box: cold means the box started for this run; X-Avcs-Prep says whether it started from the prep (#37).
808 io.onBox?.(res.headers.get("x-avcs-box") === "cold", res.headers.get("x-avcs-prep") ?? undefined);
809 return follow(this, res, res.headers.get("x-avcs-run"), { at: 0, errAt: 0 }, io);
810 }
812 /**
813 * Start a run and answer its id without waiting: the job goes on in the box
814 * after this connection closes (abso run --detach; abso logs <id> follows it).
815 */
816 async startRun(
817 command: string,
818 tarGz: Uint8Array<ArrayBuffer>,
819 onRetry?: (why: string, attempt: number) => void,
820 replace = false,
821 ): Promise<string> {
822 const res = await postRun(this, command, tarGz, onRetry, replace);
823 const id = res.headers.get("x-avcs-run");
824 if (id === null) {
825 // No id: the box failed before the job started ({"error"} in the body), or the server can't detach.
826 await consumeRun(res, { out: () => {} }, { at: 0, errAt: 0 });
827 throw new ApiError("this server gives runs no id, so a run can't be detached");
828 }
829 await res.body?.cancel();
830 return id;
831 }
833 /** A run's output from its start, for as long as the box keeps it, until it ends (abso logs). Answers its exit code. */
834 async logs(id: string, io: RunIO): Promise<number> {
835 let res: Response;
836 try {
837 res = await fetch(followUrl(this, id, { at: 0, errAt: 0 }), { headers: this.headers() });
838 } catch (err) {
839 const e = err as Error;
840 throw new ApiError(
841 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
842 );
843 }
844 if (res.status === 404) throw new ApiError(`no run ${id} in this box: ${errorSentence(await res.text())}`, 404);
845 if (!res.ok || res.body === null)
846 throw new ApiError(`logs answered ${res.status}: ${errorSentence(await res.text())}`, res.status);
847 return follow(this, res, id, { at: 0, errAt: 0 }, io);
848 }