- MCP
- blame on this site's /mcp
- CLI
- abso blame client/src/api.ts --version 8 --json
- JSON
- /christopher/abso-core/blame/client/src/api.ts?version=8&format=json
783 linesFirst import 95% · pinch 5%Last change pinch in version 5,
783 lines from 2 changes in 2 versions.
2// except `run`, which sends a tar.gz and reads the answer as a stream of JSON
3// lines (box-run.ts).
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";
pinch5abso issue new and abso issue N --comment take --attach <file,file> (abso issue 171). Each file goes up to the Issues Worker first (POST /p/:project/a/:agent/attachments, the bytes as the body and the name URI-encoded in X-Avcs-Name), and the write carries the ids the uploads answered. Nothing is sent if a file is missing or over 10 MB. --attach anywhere else is refused. The issue's page lists each attachment under the issue or comment carrying it: id, name, size and its link. The wire types gain Attachment and attachments?. MCP's issue tool takes attach too, since its parameters come from the flags. The server side is abso 621 (off until Cloud binds the bucket). Tests: client/test/attach.test.ts, against a stand-in Issues server. Checked: biome ci, npm run check (698 pass).Compare53import type { Ask, Attachment, Draft, DraftBody, News as IssueNews, IssuePage, IssueRow } from "./issues-wire.ts";
56export * from "./api-answers.ts";
57export { ApiError, neverSent } from "./api-error.ts";
58export {
59 type PrepAnswer,
60 RECONNECT_DELAYS_MS,
61 RUN_START_RETRY_MS,
62 type RunIO,
63 type RunKind,
64 type ServeAnswer,
65} from "./box-run.ts";
66export * from "./ci-answers.ts";
67export * from "./history-answers.ts";
pinch5abso issue new and abso issue N --comment take --attach <file,file> (abso issue 171). Each file goes up to the Issues Worker first (POST /p/:project/a/:agent/attachments, the bytes as the body and the name URI-encoded in X-Avcs-Name), and the write carries the ids the uploads answered. Nothing is sent if a file is missing or over 10 MB. --attach anywhere else is refused. The issue's page lists each attachment under the issue or comment carrying it: id, name, size and its link. The wire types gain Attachment and attachments?. MCP's issue tool takes attach too, since its parameters come from the flags. The server side is abso 621 (off until Cloud binds the bucket). Tests: client/test/attach.test.ts, against a stand-in Issues server. Checked: biome ci, npm run check (698 pass).Compare68export type { Ask, Attachment, Draft, DraftBody, IssueNews, IssuePage, IssueRow };
70/**
71 * How long a call may take: the base, plus 1 s for each 100 KB it sends
72 * (abso issue 34: a sync that recorded 191 reformatted files first ran out of
73 * its 30 s while the server was still taking them in).
74 */
75export function timeoutFor(baseMs: number, sent: string | undefined): number {
76 return sent === undefined ? baseMs : baseMs + Math.floor(Buffer.byteLength(sent) / 100_000) * 1000;
77}
79/** A query string from the values that are set (null and undefined are left out). */
80function query(values: Record<string, string | number | null | undefined>): URLSearchParams {
81 const q = new URLSearchParams();
82 for (const [k, v] of Object.entries(values)) if (v !== null && v !== undefined) q.set(k, String(v));
83 return q;
84}
86export function newsLines(news: News): string[] {
87 if (news === undefined || news === null) return [];
88 return (typeof news === "string" ? [news] : [...news]).filter((s) => typeof s === "string" && s.trim() !== "");
89}
91export class Api {
92 readonly config: Config;
93 readonly timeoutMs: number;
95 /** Waits between tries when a run's stream breaks; tests shorten them. */
96 readonly reconnectDelaysMs: readonly number[];
97 readonly startRetryDelaysMs: readonly number[];
98 /** Another box of this agent for run, logs and fetch (--box or AVCS_BOX, #37); undefined is its own box. */
99 box: string | undefined;
101 constructor(
102 config: Config,
103 timeoutMs = 30_000,
104 reconnectDelaysMs: readonly number[] = RECONNECT_DELAYS_MS,
105 startRetryDelaysMs: readonly number[] = RUN_START_RETRY_MS,
106 ) {
107 this.config = config;
108 this.timeoutMs = timeoutMs;
109 this.reconnectDelaysMs = reconnectDelaysMs;
110 this.startRetryDelaysMs = startRetryDelaysMs;
111 }
113 /** What a box run is for, for the server's box-run records (#39): X-Avcs-Kind on POST /run. */
114 runKind: RunKind = "run";
116 /** The Issues Worker (#54) this folder's issues calls go to; set by the issues commands (issues.ts). */
117 issuesServer: string | undefined;
119 url(path: string, server = this.config.server): string {
120 return `${server.replace(/\/+$/, "")}/p/${encodeURIComponent(this.config.project)}${path}`;
121 }
123 agentPath(action: string): string {
124 return `/a/${encodeURIComponent(this.config.agent)}/${action}`;
125 }
127 headers(contentType?: string): Record<string, string> {
128 return {
129 // Which client made the call (#29); the mods send theirs too.
130 "x-avcs-client": `abso-cli/${clientVersion()}`,
131 ...(this.config.token ? { authorization: `Bearer ${this.config.token}` } : {}),
132 ...(contentType ? { "content-type": contentType } : {}),
133 };
134 }
136 async json<T>(method: "GET" | "POST", path: string, body?: unknown, server = this.config.server): Promise<T> {
137 let res: Response | undefined;
138 const sent = body === undefined ? undefined : JSON.stringify(body);
139 const timeoutMs = timeoutFor(this.timeoutMs, sent);
140 // A connection that never opened is tried once more, IPv4 first (#37, GAME - UI/UX: one IPv6
141 // address timed out, and the same command went through seconds later). Nothing went out, so
142 // a POST is as safe to send again as a GET.
143 for (let attempt = 0; res === undefined; attempt++) {
144 try {
145 res = await fetch(this.url(path, server), {
146 method,
147 headers: this.headers(sent === undefined ? undefined : "application/json"),
148 ...(sent === undefined ? {} : { body: sent }),
149 signal: AbortSignal.timeout(timeoutMs),
150 });
151 } catch (err) {
152 const e = err as Error;
153 const why =
154 e.name === "TimeoutError"
155 ? `no answer within ${timeoutMs} ms`
156 : ((e.cause as Error | undefined)?.message ?? e.message);
157 if (!neverSent(err)) throw new ApiError(`could not reach ${server}: ${why}`);
158 if (attempt >= 1) {
159 throw new ApiError(
160 `could not reach ${server}: ${why}. Tried twice, the second time IPv4 first; the connection never opened, so nothing reached the server`,
161 undefined,
162 true,
163 );
164 }
165 setDefaultResultOrder("ipv4first");
166 await new Promise((ok) => setTimeout(ok, 500));
167 }
168 }
169 const text = await res.text();
170 // 409 is a refusal that says what to do (a drop took out lines your work builds on): print it as it is.
171 if (!res.ok)
172 throw new ApiError(
173 res.status === 409
174 ? `refused: ${errorSentence(text)}`
175 : `${method} ${path} answered ${res.status}: ${errorSentence(text)}`,
176 res.status,
177 );
178 try {
179 return JSON.parse(text) as T;
180 } catch {
181 throw new ApiError(
182 `${method} ${path} answered with something that isn't JSON: ${text.slice(0, 300)}`,
183 res.status,
184 );
185 }
186 }
188 init(
189 files: Record<string, string>,
190 modes: Modes = {},
191 blobs: Readonly<Record<string, string>> = {},
192 ): Promise<{ version: number; skipped?: readonly string[] }> {
193 return this.json("POST", "/init", {
194 files,
195 ...(Object.keys(modes).length > 0 ? { modes } : {}),
196 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
197 });
198 }
200 edit(body: EditBody): Promise<EditAnswer> {
201 return this.json("POST", this.agentPath("edit"), body);
202 }
204 record(
205 files: Record<string, string | null>,
206 extra: { session?: string; subagent?: string } = {},
207 modes: Modes = {},
208 blobs: Readonly<Record<string, string>> = {},
209 ): Promise<RecordAnswer> {
210 return this.json("POST", this.agentPath("record"), {
211 files,
212 ...(Object.keys(modes).length > 0 ? { modes } : {}),
213 ...(Object.keys(blobs).length > 0 ? { blobs } : {}),
214 ...extra,
215 });
216 }
218 /** Move a file in the draft (#49): its lines keep their ids. The way to change a file's case. */
219 move(from: string, to: string): Promise<{ ok: boolean; from: string; to: string; news?: News }> {
220 return this.json("POST", this.agentPath("move"), { from, to });
221 }
223 /** Upload a binary file's bytes under their sha256 (the server checks the hash). */
224 async putBlob(sha: string, bytes: Uint8Array): Promise<void> {
225 await this.bytes("PUT", `/blobs/${sha}`, bytes);
226 }
228 /** A preview of one version of shared at a stable URL (abso serve, #37); a build answers 422 with its output. */
229 async serve(version?: number, cmd?: string, out?: string): Promise<ServeAnswer> {
230 const q = new URLSearchParams({
231 ...(version !== undefined ? { version: String(version) } : {}),
232 ...(cmd ? { cmd } : {}),
233 ...(out ? { out } : {}),
234 });
235 let res: Response;
236 try {
237 res = await fetch(`${this.url("/serve")}?${q}`, {
238 method: "POST",
239 headers: this.headers(),
240 signal: AbortSignal.timeout(20 * 60_000),
241 });
242 } catch (err) {
243 const e = err as Error;
244 throw new ApiError(
245 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
246 );
247 }
248 const text = await res.text();
249 if (!res.ok && res.status !== 422)
250 throw new ApiError(`serve answered ${res.status}: ${errorSentence(text)}`, res.status);
251 return JSON.parse(text) as ServeAnswer;
252 }
254 /** Runs a setup command on the folder in a fresh box and keeps the box as what it starts from (abso prep, #37). */
255 async prep(command: string, tarGz: Uint8Array<ArrayBuffer>): Promise<PrepAnswer> {
256 let res: Response;
257 try {
258 res = await fetch(`${this.url(this.agentPath("prep"))}?cmd=${encodeURIComponent(command)}${boxQuery(this.box)}`, {
259 method: "POST",
260 headers: this.headers("application/gzip"),
261 body: tarGz,
262 // A setup command can take minutes (npm ci, a browser download).
263 signal: AbortSignal.timeout(30 * 60_000),
264 });
265 } catch (err) {
266 const e = err as Error;
267 throw new ApiError(
268 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
269 );
270 }
271 const text = await res.text();
272 if (!res.ok) throw new ApiError(`prep answered ${res.status}: ${errorSentence(text)}`, res.status);
273 return JSON.parse(text) as PrepAnswer;
274 }
276 /** Forgets the box's prep: it starts from the plain image again. Answers whether it had one. */
277 async unprep(): Promise<boolean> {
278 let res: Response;
279 try {
280 res = await fetch(
281 `${this.url(this.agentPath("prep"))}${this.box ? `?box=${encodeURIComponent(this.box)}` : ""}`,
282 { method: "DELETE", headers: this.headers(), signal: AbortSignal.timeout(this.timeoutMs) },
283 );
284 } catch (err) {
285 const e = err as Error;
286 throw new ApiError(
287 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
288 );
289 }
290 const text = await res.text();
291 if (!res.ok) throw new ApiError(`prep answered ${res.status}: ${errorSentence(text)}`, res.status);
292 return (JSON.parse(text) as { forgot: boolean }).forgot;
293 }
295 /** A binary file's bytes by their sha256. */
296 /** 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. */
297 async boxFiles(glob: string): Promise<Uint8Array | null> {
298 try {
299 return await this.bytes(
300 "GET",
301 `${this.agentPath("box-files")}?${new URLSearchParams({ glob, ...(this.box ? { box: this.box } : {}) })}`,
302 );
303 } catch (err) {
304 if (err instanceof ApiError && err.status === 404) return null;
305 throw err;
306 }
307 }
309 getBlob(sha: string): Promise<Uint8Array> {
310 return this.bytes("GET", `/blobs/${sha}`);
311 }
313 async bytes(method: "GET" | "PUT", path: string, body?: Uint8Array): Promise<Uint8Array> {
314 let res: Response;
315 try {
316 res = await fetch(this.url(path), {
317 method,
318 headers: this.headers(body === undefined ? undefined : "application/octet-stream"),
319 ...(body === undefined ? {} : { body: body as Uint8Array<ArrayBuffer> }),
320 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
321 });
322 } catch (err) {
323 const e = err as Error;
324 throw new ApiError(
325 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
326 );
327 }
328 const data = new Uint8Array(await res.arrayBuffer());
329 if (!res.ok)
330 throw new ApiError(
331 `${method} ${path} answered ${res.status}: ${errorSentence(new TextDecoder().decode(data))}`,
332 res.status,
333 );
334 return data;
335 }
337 /** Make this agent a reader, or not (#37): a reader's edits, records and publishes are refused. */
338 reader(on: boolean): Promise<{ agent: string; reader: boolean }> {
339 return this.json("POST", this.agentPath("reader"), { reader: on });
340 }
342 publish(message: string, asIs = false): Promise<PublishAnswer> {
343 return this.json("POST", this.agentPath("publish"), { message, ...(asIs ? { asIs: true } : {}) });
344 }
346 /** One change (#44). */
347 change(id: number): Promise<ChangeAnswer> {
348 return this.json("GET", `/change/${id}`);
349 }
351 /** The changes with anything new at or after log position `since`, newest first (#44). */
352 /** Changes active since a log position, newest first; `older` is set when more come before the page (ask again with `before`). */
353 changes(
354 since: number,
355 limit = 50,
356 before?: number,
357 ): Promise<{ since: number; next: number; changes: readonly ChangeAnswer[]; older?: number }> {
358 return this.json("GET", `/changes?${query({ since, limit, before })}`);
359 }
361 /** A call to the Issues Worker (#54), with the same token. */
362 #issues<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> {
363 if (this.issuesServer === undefined)
364 throw new ApiError(`${this.config.server} has no Issues Worker beside it; AVCS_ISSUES_SERVER names one`);
365 return this.json(method, path, body, this.issuesServer);
366 }
368 /** Issues, most recently updated first. */
369 issues(
370 q: { status?: string; agent?: string; parent?: number; open?: boolean; labels?: readonly string[] } = {},
371 ): Promise<{ issues: readonly IssueRow[] }> {
372 return this.#issues(
373 "GET",
374 `/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 })}`,
375 );
376 }
378 /** Every label in use, with how many issues have it and how many of those are open. */
379 issueLabels(): Promise<{ labels: readonly { label: string; open: number; total: number }[] }> {
380 return this.#issues("GET", "/labels");
381 }
383 issue(id: number): Promise<IssuePage> {
384 return this.#issues("GET", `/issue/${id}`);
385 }
387 /** Open asks of someone (an agent, or person:<id>), soonest due first; every open ask without `of`. */
388 waiting(of?: string): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
389 return this.#issues("GET", `/waiting?${query({ of })}`);
390 }
392 /** This agent's open asks; the Worker marks each it lists for the first time as seen (abso issue 124). */
393 async waitingMine(): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
394 try {
395 return await this.#issues("GET", this.agentPath("waiting"));
396 } catch (err) {
397 // An Issues Worker from before 124 has no /a/:agent/ reads.
398 if (err instanceof ApiError && err.status === 404) return this.waiting(this.config.agent);
399 throw err;
400 }
401 }
pinch5abso issue new and abso issue N --comment take --attach <file,file> (abso issue 171). Each file goes up to the Issues Worker first (POST /p/:project/a/:agent/attachments, the bytes as the body and the name URI-encoded in X-Avcs-Name), and the write carries the ids the uploads answered. Nothing is sent if a file is missing or over 10 MB. --attach anywhere else is refused. The issue's page lists each attachment under the issue or comment carrying it: id, name, size and its link. The wire types gain Attachment and attachments?. MCP's issue tool takes attach too, since its parameters come from the flags. The server side is abso 621 (off until Cloud binds the bucket). Tests: client/test/attach.test.ts, against a stand-in Issues server. Checked: biome ci, npm run check (698 pass).Compare403 issueOpen(body: DraftBody & { title: string; attachments?: string[] }): Promise<{ id: number; news?: IssueNews }> {
405 }
pinch5abso issue new and abso issue N --comment take --attach <file,file> (abso issue 171). Each file goes up to the Issues Worker first (POST /p/:project/a/:agent/attachments, the bytes as the body and the name URI-encoded in X-Avcs-Name), and the write carries the ids the uploads answered. Nothing is sent if a file is missing or over 10 MB. --attach anywhere else is refused. The issue's page lists each attachment under the issue or comment carrying it: id, name, size and its link. The wire types gain Attachment and attachments?. MCP's issue tool takes attach too, since its parameters come from the flags. The server side is abso 621 (off until Cloud binds the bucket). Tests: client/test/attach.test.ts, against a stand-in Issues server. Checked: biome ci, npm run check (698 pass).Compare407 /** Uploads an image to the Issues Worker (abso issue 171): it checks the type by the bytes, strips metadata and answers its id. */
408 async attachmentUpload(bytes: Uint8Array, name: string): Promise<Attachment> {
409 if (this.issuesServer === undefined)
410 throw new ApiError(`${this.config.server} has no Issues Worker beside it; AVCS_ISSUES_SERVER names one`);
411 const path = this.agentPath("attachments");
412 let res: Response;
413 try {
414 res = await fetch(this.url(path, this.issuesServer), {
415 method: "POST",
416 headers: { ...this.headers("application/octet-stream"), "x-avcs-name": encodeURIComponent(name) },
417 body: bytes as Uint8Array<ArrayBuffer>,
418 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
419 });
420 } catch (err) {
421 const e = err as Error;
422 throw new ApiError(
423 `could not reach ${this.issuesServer}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
424 );
425 }
426 const text = await res.text();
427 if (!res.ok) throw new ApiError(`uploading ${name} answered ${res.status}: ${errorSentence(text)}`, res.status);
428 return JSON.parse(text) as Attachment;
429 }
431 /** Where an attachment is served. */
432 attachmentUrl(id: string): string {
433 return this.url(`/attachments/${id}`, this.issuesServer);
434 }
init0Start the project436 /** An edit (abso issue 3): it tells the issue's watchers, and `also`, unless `notify` is false. null clears a parent or Agent. */
437 issueEdit(
438 id: number,
439 body: {
440 title?: string;
441 description?: string;
442 parent?: number | null;
443 agent?: string | null;
444 blockedBy?: number[];
445 notify?: boolean;
446 also?: string[];
447 addLabels?: string[];
448 removeLabels?: string[];
449 },
450 ): Promise<{ edit: number; notified: readonly string[]; news?: IssueNews }> {
451 return this.#issues("POST", this.agentPath(`issue/${id}/edit`), body);
452 }
pinch5abso issue new and abso issue N --comment take --attach <file,file> (abso issue 171). Each file goes up to the Issues Worker first (POST /p/:project/a/:agent/attachments, the bytes as the body and the name URI-encoded in X-Avcs-Name), and the write carries the ids the uploads answered. Nothing is sent if a file is missing or over 10 MB. --attach anywhere else is refused. The issue's page lists each attachment under the issue or comment carrying it: id, name, size and its link. The wire types gain Attachment and attachments?. MCP's issue tool takes attach too, since its parameters come from the flags. The server side is abso 621 (off until Cloud binds the bucket). Tests: client/test/attach.test.ts, against a stand-in Issues server. Checked: biome ci, npm run check (698 pass).Compare454 issueComment(
455 id: number,
456 text: string,
457 objection = false,
458 attachments: readonly string[] = [],
459 ): Promise<{ id: number; news?: IssueNews }> {
460 return this.#issues("POST", this.agentPath(`issue/${id}/comment`), {
461 text,
462 ...(objection ? { objection } : {}),
463 ...(attachments.length > 0 ? { attachments } : {}),
464 });
467 issueDrop(id: number): Promise<{ news?: IssueNews }> {
468 return this.#issues("POST", this.agentPath(`issue/${id}/drop`), {});
469 }
471 /** Opens a dropped issue again (abso issue 104). */
472 issueReopen(id: number): Promise<{ news?: IssueNews }> {
473 return this.#issues("POST", this.agentPath(`issue/${id}/reopen`), {});
474 }
476 /** Marks an issue done by hand (abso issue 38). `version` is the publish that did it, when there is one. */
477 issueDone(id: number, version: number | null): Promise<{ news?: IssueNews }> {
478 return this.#issues("POST", this.agentPath(`issue/${id}/done`), { ...(version !== null ? { version } : {}) });
479 }
481 /** This agent's drafts (abso issue 3): its own, with no number and no news, newest first. */
482 drafts(): Promise<{ drafts: readonly Draft[] }> {
483 return this.#issues("GET", this.agentPath("drafts"));
484 }
486 /** Saves a draft, new or (with id) over one of this agent's: the body replaces the draft's. */
487 saveDraft(body: DraftBody & { id?: number }): Promise<{ id: number }> {
488 return this.#issues("POST", this.agentPath("draft"), body);
489 }
491 /** Opens a draft as an issue, `body`'s fields over the draft's, and deletes the draft. */
492 openDraft(id: number, body: DraftBody = {}): Promise<{ id: number; news?: IssueNews }> {
493 return this.#issues("POST", this.agentPath(`draft/${id}/open`), body);
494 }
496 deleteDraft(id: number): Promise<{ ok: boolean }> {
497 return this.#issues("POST", this.agentPath(`draft/${id}/delete`), {});
498 }
500 ask(body: {
501 issue?: number;
502 of: string;
503 question: string;
504 review?: boolean;
505 kind?: "question" | "task";
506 due?: string;
507 blocks?: number[];
508 options?: string[];
509 }): Promise<{ id: number; news?: IssueNews }> {
510 return this.#issues("POST", this.agentPath("ask"), body);
511 }
513 answer(
514 id: number,
515 body: { words?: string; option?: number | string; note?: string; done?: boolean },
516 ): Promise<{ ask: Ask; news?: IssueNews }> {
517 return this.#issues("POST", this.agentPath(`answer/${id}`), body);
518 }
520 /** Notes on lines (#44), by file or change; open ones only with `open`. */
521 notes(q: { file?: string; change?: number; open?: boolean } = {}): Promise<{ notes: readonly NoteAnswer[] }> {
522 return this.json("GET", `/notes?${query({ file: q.file, change: q.change, open: q.open ? 1 : undefined })}`);
523 }
525 note(body: NoteBody): Promise<{ id: number; change: number | null; lines: readonly [number, number] }> {
526 return this.json("POST", this.agentPath("note"), body);
527 }
529 noteClose(id: number, how: "resolved" | "withdrawn"): Promise<unknown> {
530 return this.json("POST", this.agentPath("note-close"), { id, how });
531 }
533 /** The merge queue now (#39). */
534 queueState(): Promise<QueueState> {
535 return this.json("GET", "/queue");
536 }
538 /** The project's visibility (abso issue 152): public or private. */
539 visibility(): Promise<{ project: string; visibility: "public" | "private" }> {
540 return this.json("GET", "/visibility");
541 }
543 /** Switch the project's visibility (abso issue 140): an owner's key, or the shared token on staging. */
544 setVisibility(v: "public" | "private"): Promise<{ project: string; visibility: "public" | "private" }> {
545 return this.json("POST", `/visibility?visibility=${v}`, {});
546 }
548 /** Take back this agent's queued publishes (#39); refused while one is being checked. */
549 unqueue(): Promise<{ pulled: readonly number[] }> {
550 return this.json("POST", this.agentPath("unqueue"), {});
551 }
553 /**
554 * Sync; a folder following a label goes to the newest version with that label.
555 * With `full`, the answer holds every file in the agent's view, as a first sync's does,
556 * not only what changed since its last sync (#37: a join for an agent the server knew).
557 */
558 sync(options: { full?: boolean } = {}): Promise<SyncAnswer> {
559 return this.json("POST", this.agentPath("sync"), {
560 ...(this.config.follow ? { label: this.config.follow } : {}),
561 ...(options.full ? { full: true } : {}),
562 });
563 }
565 /** Take published versions back out of shared (with the versions that build on them, when asked). */
566 drop(versions: readonly number[], message: string, withDependents = false): Promise<DropAnswer> {
567 return this.json("POST", this.agentPath("drop"), {
568 versions,
569 message,
570 ...(withDependents ? { withDependents: true } : {}),
571 });
572 }
574 /** Take some versions of a named draft into shared, as one version. */
575 pluck(draft: string, versions: readonly number[], message: string, withDependencies = false): Promise<PluckAnswer> {
576 return this.json("POST", this.agentPath("pluck"), {
577 draft,
578 versions,
579 message,
580 ...(withDependencies ? { withDependencies: true } : {}),
581 });
582 }
584 /** Correct the message of this agent's newest publish in its space. */
585 amend(message: string): Promise<{ version: number; draft: string | null; message: string; was: string }> {
586 return this.json("POST", this.agentPath("amend"), { message });
587 }
589 /** Put a label on a version of shared (the newest by default), or take it off. */
590 label(
591 name: string,
592 version?: number,
593 remove = false,
594 ): Promise<{ name: string; version: number; versions: readonly number[] }> {
595 return this.json("POST", this.agentPath("label"), {
596 name,
597 ...(version === undefined ? {} : { version }),
598 ...(remove ? { remove: true } : {}),
599 });
600 }
602 labels(): Promise<{ labels: Readonly<Record<string, readonly number[]>> }> {
603 return this.json("GET", "/labels");
604 }
606 status(): Promise<StatusAnswer> {
607 return this.json("GET", "/status");
608 }
610 /** The status and the paths in the agent's view, in one trip (abso issue 80). */
611 async statusAndFiles(): Promise<StatusAnswer & { files: FilesAnswer | undefined }> {
612 try {
613 return await this.json("GET", this.agentPath("status"));
614 } catch (err) {
615 // A server from before it has no /a/:agent/status; the listing itself is from #37.
616 if (!(err instanceof ApiError && err.status === 404)) throw err;
617 }
618 const status = await this.status();
619 return { ...status, files: await this.viewFiles().catch(() => undefined) };
620 }
622 /** CI's state (#39), or one version's job. */
623 ci(): Promise<CiStatus>;
624 ci(version: number): Promise<CiJob>;
625 ci(version?: number): Promise<CiStatus | CiJob> {
626 return this.json("GET", version === undefined ? "/ci" : `/ci?${query({ version })}`);
627 }
629 /** Ends every /latest link handed out so far; answers CI's state with the new link. */
630 ciRevoke(): Promise<CiStatus> {
631 return this.json("POST", "/ci/revoke", {});
632 }
634 /** Count versions up to `through` as seen by CI and end any red or bisect, so an import's history isn't checked (#56). */
635 ciSkip(through: number): Promise<unknown> {
636 return this.json("POST", "/ci/skip", { through });
637 }
639 /** Move to a named draft (null: shared). With carry, the current unpublished changes start a new draft. */
640 switchDraft(name: string | null, carry = false): Promise<SwitchAnswer> {
641 return this.json("POST", this.agentPath("draft"), { name, ...(carry ? { carry: true } : {}) });
642 }
644 /** Land never queues: with the merge queue on, the server refuses it (#39). */
645 land(message: string): Promise<Exclude<PublishAnswer, { queued: number }>> {
646 return this.json("POST", this.agentPath("land"), { message });
647 }
649 draftSync(): Promise<DraftSyncAnswer> {
650 return this.json("POST", this.agentPath("draft-sync"), {});
651 }
653 blame(file: string, from?: number, to?: number, version?: number, view: View = {}): Promise<BlameAnswer> {
654 return this.json("GET", `/blame?${query({ file, from, to, version, ...view })}`);
655 }
657 /** The paths in the agent's view: what its folder should hold (#37). */
658 viewFiles(): Promise<FilesAnswer> {
659 return this.json("GET", this.agentPath("files"));
660 }
662 /** The paths in shared, or a named draft, at a version (the newest by default). */
663 filesAt(draft: string | null, version?: number): Promise<FilesAnswer> {
664 return this.json("GET", `/files?${query({ draft, version })}`);
665 }
667 /** The versions of a space, newest first; with `path`, only those that changed it. */
668 log(where: Where, limit?: number, path?: string): Promise<LogAnswer> {
669 return this.json("GET", `/log?${query({ ...where, limit, path })}`);
670 }
672 show(version: number, where: Where): Promise<ShowAnswer> {
673 return this.json("GET", `/show?${query({ version, ...where })}`);
674 }
676 fileAt(path: string, version: number, where: Where): Promise<{ path: string; version: number; text: string | null }> {
677 return this.json("GET", `/file?${query({ path, version, ...where })}`);
678 }
680 compare(from: number, to: number, where: Where): Promise<{ from: number; to: number; files: readonly FileChange[] }> {
681 return this.json("GET", `/compare?${query({ from, to, ...where })}`);
682 }
684 /** A message to the project's other agents (or those named), delivered once as news. */
685 starting(
686 text: string | null,
687 files?: readonly string[],
688 options: { issue?: number; done?: boolean } = {},
689 ): Promise<{
690 starting: { text: string; files: readonly string[]; time: number; issue?: number } | null;
691 overlaps: readonly Overlap[];
692 }> {
693 return this.json("POST", this.agentPath("starting"), {
694 text,
695 ...(files && files.length > 0 ? { files } : {}),
696 ...(options.issue !== undefined ? { issue: options.issue } : {}),
697 ...(options.done ? { done: true } : {}),
698 });
699 }
701 announce(text: string, to?: readonly string[]): Promise<{ id: number; to: readonly string[] }> {
702 return this.json("POST", this.agentPath("announce"), { text, ...(to ? { to } : {}) });
703 }
705 /** The news waiting for this agent, handed over once. */
706 news(): Promise<{ news: News; items?: readonly { readonly text: string; readonly at: number | null }[] }> {
707 return this.json("POST", this.agentPath("news"), {});
708 }
710 /** This agent's unpublished changes, file by file. */
711 diff(): Promise<DiffAnswer> {
712 return this.json("POST", this.agentPath("diff"), {});
713 }
715 /** Discard this agent's unpublished changes to `files` (null: all of them). */
716 restore(files: readonly string[] | null): Promise<RestoreAnswer> {
717 return this.json("POST", this.agentPath("restore"), files === null ? { all: true } : { files });
718 }
720 why(file: string, line: number, view: View = {}): Promise<WhyAnswer> {
721 return this.json("GET", `/why?${query({ file, line, ...view })}`);
722 }
724 where(): Promise<WhereAnswer> {
725 return this.json("GET", "/where");
726 }
728 /**
729 * Send the folder as a tar.gz and run a command in the agent's box. Output
730 * goes to `io.out` as it arrives, and the box's stderr to `io.err` (the
731 * server keeps them apart when asked; an older one sends both as out).
732 * Answers the command's exit code.
733 *
734 * When the stream breaks before the exit line and the server gave the run
735 * an id, the run goes on in the box: this reconnects to it and carries on
736 * from the last output printed, so nothing is lost or printed twice. The
737 * command itself is never sent twice.
738 */
739 async run(command: string, tarGz: Uint8Array<ArrayBuffer>, io: RunIO): Promise<number> {
740 const res = await postRun(this, command, tarGz, io.onRetry, io.replace, io.fresh);
741 // X-Avcs-Box: cold means the box started for this run; X-Avcs-Prep says whether it started from the prep (#37).
742 io.onBox?.(res.headers.get("x-avcs-box") === "cold", res.headers.get("x-avcs-prep") ?? undefined);
743 return follow(this, res, res.headers.get("x-avcs-run"), { at: 0, errAt: 0 }, io);
744 }
746 /**
747 * Start a run and answer its id without waiting: the job goes on in the box
748 * after this connection closes (abso run --detach; abso logs <id> follows it).
749 */
750 async startRun(
751 command: string,
752 tarGz: Uint8Array<ArrayBuffer>,
753 onRetry?: (why: string, attempt: number) => void,
754 replace = false,
755 ): Promise<string> {
756 const res = await postRun(this, command, tarGz, onRetry, replace);
757 const id = res.headers.get("x-avcs-run");
758 if (id === null) {
759 // No id: the box failed before the job started ({"error"} in the body), or the server can't detach.
760 await consumeRun(res, { out: () => {} }, { at: 0, errAt: 0 });
761 throw new ApiError("this server gives runs no id, so a run can't be detached");
762 }
763 await res.body?.cancel();
764 return id;
765 }
767 /** A run's output from its start, for as long as the box keeps it, until it ends (abso logs). Answers its exit code. */
768 async logs(id: string, io: RunIO): Promise<number> {
769 let res: Response;
770 try {
771 res = await fetch(followUrl(this, id, { at: 0, errAt: 0 }), { headers: this.headers() });
772 } catch (err) {
773 const e = err as Error;
774 throw new ApiError(
775 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
776 );
777 }
778 if (res.status === 404) throw new ApiError(`no run ${id} in this box: ${errorSentence(await res.text())}`, 404);
779 if (!res.ok || res.body === null)
780 throw new ApiError(`logs answered ${res.status}: ${errorSentence(await res.text())}`, res.status);
781 return follow(this, res, id, { at: 0, errAt: 0 }, io);
782 }
783}