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=20&format=json
812 linesFirst import 91% · pinch 6% · devops 2% · infra-split 1%Last change devops in version 20, 5 versions changed it

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