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
blame on this site's /mcp
CLI
abso blame client/src/api.ts --version 14 --json
JSON
/christopher/abso-core/blame/client/src/api.ts?version=14&format=json
788 linesFirst import 94% · pinch 5% · infra-split 1%Last change infra-split in version 14,

788 lines from 3 changes in 3 versions.

init0Start the project1// 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";
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";
init0Start the project54import type { Modes } from "./modes.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 };
init0Start the project69
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;
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;
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() !== "");
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 }> {
init0Start the project404 return this.#issues("POST", this.agentPath("issue"), body);
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 });
init0Start the project465 }
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 }
infra-split14An asker can take back an ask: abso ask --withdraw <ask> [--note "why"] An ask that later decisions have overtaken used to sit in the asked person's waiting list for good. Only they could answer it, and "none of these" wasn't an option. Now the one who asked can withdraw it. - `abso ask --withdraw <ask> [--note "why"]` sends one call to the server's withdraw route. It's refused before any call when mixed with a question or the other ask flags. `--note-file` reads the note from a file or stdin, like every text flag. - A withdrawn ask closes the way an answered one does: it leaves the waiting list, and it stops holding its issue at Blocked. The ask keeps its question. The asker's note is kept as why, and the one asked hears it. - Ask gains `outcome?: "withdrawn"`. Older servers leave it out. The asks list and an issue's page show "withdrawn by <asker>" and the note, instead of "answered by". - The server side of the route comes with the hosted Issues service. Until it's there, the call answers with that server's error. Tests: the new usage mistakes, and the single POST to the asker's own route. Checked: npx biome ci . and npm run check exit 0 (704 pass, 1 skipped).Compare519
520 /** Takes back an ask this agent made, with a note on why; the one asked hears it. */
521 withdraw(id: number, body: { note?: string }): Promise<{ ask: Ask; news?: IssueNews }> {
522 return this.#issues("POST", this.agentPath(`withdraw/${id}`), body);
523 }
init0Start the project524
525 /** Notes on lines (#44), by file or change; open ones only with `open`. */
526 notes(q: { file?: string; change?: number; open?: boolean } = {}): Promise<{ notes: readonly NoteAnswer[] }> {
527 return this.json("GET", `/notes?${query({ file: q.file, change: q.change, open: q.open ? 1 : undefined })}`);
528 }
530 note(body: NoteBody): Promise<{ id: number; change: number | null; lines: readonly [number, number] }> {
531 return this.json("POST", this.agentPath("note"), body);
532 }
534 noteClose(id: number, how: "resolved" | "withdrawn"): Promise<unknown> {
535 return this.json("POST", this.agentPath("note-close"), { id, how });
536 }
538 /** The merge queue now (#39). */
539 queueState(): Promise<QueueState> {
540 return this.json("GET", "/queue");
541 }
543 /** The project's visibility (abso issue 152): public or private. */
544 visibility(): Promise<{ project: string; visibility: "public" | "private" }> {
545 return this.json("GET", "/visibility");
546 }
548 /** Switch the project's visibility (abso issue 140): an owner's key, or the shared token on staging. */
549 setVisibility(v: "public" | "private"): Promise<{ project: string; visibility: "public" | "private" }> {
550 return this.json("POST", `/visibility?visibility=${v}`, {});
551 }
553 /** Take back this agent's queued publishes (#39); refused while one is being checked. */
554 unqueue(): Promise<{ pulled: readonly number[] }> {
555 return this.json("POST", this.agentPath("unqueue"), {});
556 }
558 /**
559 * Sync; a folder following a label goes to the newest version with that label.
560 * With `full`, the answer holds every file in the agent's view, as a first sync's does,
561 * not only what changed since its last sync (#37: a join for an agent the server knew).
562 */
563 sync(options: { full?: boolean } = {}): Promise<SyncAnswer> {
564 return this.json("POST", this.agentPath("sync"), {
565 ...(this.config.follow ? { label: this.config.follow } : {}),
566 ...(options.full ? { full: true } : {}),
567 });
568 }
570 /** Take published versions back out of shared (with the versions that build on them, when asked). */
571 drop(versions: readonly number[], message: string, withDependents = false): Promise<DropAnswer> {
572 return this.json("POST", this.agentPath("drop"), {
573 versions,
574 message,
575 ...(withDependents ? { withDependents: true } : {}),
576 });
577 }
579 /** Take some versions of a named draft into shared, as one version. */
580 pluck(draft: string, versions: readonly number[], message: string, withDependencies = false): Promise<PluckAnswer> {
581 return this.json("POST", this.agentPath("pluck"), {
582 draft,
583 versions,
584 message,
585 ...(withDependencies ? { withDependencies: true } : {}),
586 });
587 }
589 /** Correct the message of this agent's newest publish in its space. */
590 amend(message: string): Promise<{ version: number; draft: string | null; message: string; was: string }> {
591 return this.json("POST", this.agentPath("amend"), { message });
592 }
594 /** Put a label on a version of shared (the newest by default), or take it off. */
595 label(
596 name: string,
597 version?: number,
598 remove = false,
599 ): Promise<{ name: string; version: number; versions: readonly number[] }> {
600 return this.json("POST", this.agentPath("label"), {
601 name,
602 ...(version === undefined ? {} : { version }),
603 ...(remove ? { remove: true } : {}),
604 });
605 }
607 labels(): Promise<{ labels: Readonly<Record<string, readonly number[]>> }> {
608 return this.json("GET", "/labels");
609 }
611 status(): Promise<StatusAnswer> {
612 return this.json("GET", "/status");
613 }
615 /** The status and the paths in the agent's view, in one trip (abso issue 80). */
616 async statusAndFiles(): Promise<StatusAnswer & { files: FilesAnswer | undefined }> {
617 try {
618 return await this.json("GET", this.agentPath("status"));
619 } catch (err) {
620 // A server from before it has no /a/:agent/status; the listing itself is from #37.
621 if (!(err instanceof ApiError && err.status === 404)) throw err;
622 }
623 const status = await this.status();
624 return { ...status, files: await this.viewFiles().catch(() => undefined) };
625 }
627 /** CI's state (#39), or one version's job. */
628 ci(): Promise<CiStatus>;
629 ci(version: number): Promise<CiJob>;
630 ci(version?: number): Promise<CiStatus | CiJob> {
631 return this.json("GET", version === undefined ? "/ci" : `/ci?${query({ version })}`);
632 }
634 /** Ends every /latest link handed out so far; answers CI's state with the new link. */
635 ciRevoke(): Promise<CiStatus> {
636 return this.json("POST", "/ci/revoke", {});
637 }
639 /** Count versions up to `through` as seen by CI and end any red or bisect, so an import's history isn't checked (#56). */
640 ciSkip(through: number): Promise<unknown> {
641 return this.json("POST", "/ci/skip", { through });
642 }
644 /** Move to a named draft (null: shared). With carry, the current unpublished changes start a new draft. */
645 switchDraft(name: string | null, carry = false): Promise<SwitchAnswer> {
646 return this.json("POST", this.agentPath("draft"), { name, ...(carry ? { carry: true } : {}) });
647 }
649 /** Land never queues: with the merge queue on, the server refuses it (#39). */
650 land(message: string): Promise<Exclude<PublishAnswer, { queued: number }>> {
651 return this.json("POST", this.agentPath("land"), { message });
652 }
654 draftSync(): Promise<DraftSyncAnswer> {
655 return this.json("POST", this.agentPath("draft-sync"), {});
656 }
658 blame(file: string, from?: number, to?: number, version?: number, view: View = {}): Promise<BlameAnswer> {
659 return this.json("GET", `/blame?${query({ file, from, to, version, ...view })}`);
660 }
662 /** The paths in the agent's view: what its folder should hold (#37). */
663 viewFiles(): Promise<FilesAnswer> {
664 return this.json("GET", this.agentPath("files"));
665 }
667 /** The paths in shared, or a named draft, at a version (the newest by default). */
668 filesAt(draft: string | null, version?: number): Promise<FilesAnswer> {
669 return this.json("GET", `/files?${query({ draft, version })}`);
670 }
672 /** The versions of a space, newest first; with `path`, only those that changed it. */
673 log(where: Where, limit?: number, path?: string): Promise<LogAnswer> {
674 return this.json("GET", `/log?${query({ ...where, limit, path })}`);
675 }
677 show(version: number, where: Where): Promise<ShowAnswer> {
678 return this.json("GET", `/show?${query({ version, ...where })}`);
679 }
681 fileAt(path: string, version: number, where: Where): Promise<{ path: string; version: number; text: string | null }> {
682 return this.json("GET", `/file?${query({ path, version, ...where })}`);
683 }
685 compare(from: number, to: number, where: Where): Promise<{ from: number; to: number; files: readonly FileChange[] }> {
686 return this.json("GET", `/compare?${query({ from, to, ...where })}`);
687 }
689 /** A message to the project's other agents (or those named), delivered once as news. */
690 starting(
691 text: string | null,
692 files?: readonly string[],
693 options: { issue?: number; done?: boolean } = {},
694 ): Promise<{
695 starting: { text: string; files: readonly string[]; time: number; issue?: number } | null;
696 overlaps: readonly Overlap[];
697 }> {
698 return this.json("POST", this.agentPath("starting"), {
699 text,
700 ...(files && files.length > 0 ? { files } : {}),
701 ...(options.issue !== undefined ? { issue: options.issue } : {}),
702 ...(options.done ? { done: true } : {}),
703 });
704 }
706 announce(text: string, to?: readonly string[]): Promise<{ id: number; to: readonly string[] }> {
707 return this.json("POST", this.agentPath("announce"), { text, ...(to ? { to } : {}) });
708 }
710 /** The news waiting for this agent, handed over once. */
711 news(): Promise<{ news: News; items?: readonly { readonly text: string; readonly at: number | null }[] }> {
712 return this.json("POST", this.agentPath("news"), {});
713 }
715 /** This agent's unpublished changes, file by file. */
716 diff(): Promise<DiffAnswer> {
717 return this.json("POST", this.agentPath("diff"), {});
718 }
720 /** Discard this agent's unpublished changes to `files` (null: all of them). */
721 restore(files: readonly string[] | null): Promise<RestoreAnswer> {
722 return this.json("POST", this.agentPath("restore"), files === null ? { all: true } : { files });
723 }
725 why(file: string, line: number, view: View = {}): Promise<WhyAnswer> {
726 return this.json("GET", `/why?${query({ file, line, ...view })}`);
727 }
729 where(): Promise<WhereAnswer> {
730 return this.json("GET", "/where");
731 }
733 /**
734 * Send the folder as a tar.gz and run a command in the agent's box. Output
735 * goes to `io.out` as it arrives, and the box's stderr to `io.err` (the
736 * server keeps them apart when asked; an older one sends both as out).
737 * Answers the command's exit code.
738 *
739 * When the stream breaks before the exit line and the server gave the run
740 * an id, the run goes on in the box: this reconnects to it and carries on
741 * from the last output printed, so nothing is lost or printed twice. The
742 * command itself is never sent twice.
743 */
744 async run(command: string, tarGz: Uint8Array<ArrayBuffer>, io: RunIO): Promise<number> {
745 const res = await postRun(this, command, tarGz, io.onRetry, io.replace, io.fresh);
746 // X-Avcs-Box: cold means the box started for this run; X-Avcs-Prep says whether it started from the prep (#37).
747 io.onBox?.(res.headers.get("x-avcs-box") === "cold", res.headers.get("x-avcs-prep") ?? undefined);
748 return follow(this, res, res.headers.get("x-avcs-run"), { at: 0, errAt: 0 }, io);
749 }
751 /**
752 * Start a run and answer its id without waiting: the job goes on in the box
753 * after this connection closes (abso run --detach; abso logs <id> follows it).
754 */
755 async startRun(
756 command: string,
757 tarGz: Uint8Array<ArrayBuffer>,
758 onRetry?: (why: string, attempt: number) => void,
759 replace = false,
760 ): Promise<string> {
761 const res = await postRun(this, command, tarGz, onRetry, replace);
762 const id = res.headers.get("x-avcs-run");
763 if (id === null) {
764 // No id: the box failed before the job started ({"error"} in the body), or the server can't detach.
765 await consumeRun(res, { out: () => {} }, { at: 0, errAt: 0 });
766 throw new ApiError("this server gives runs no id, so a run can't be detached");
767 }
768 await res.body?.cancel();
769 return id;
770 }
772 /** A run's output from its start, for as long as the box keeps it, until it ends (abso logs). Answers its exit code. */
773 async logs(id: string, io: RunIO): Promise<number> {
774 let res: Response;
775 try {
776 res = await fetch(followUrl(this, id, { at: 0, errAt: 0 }), { headers: this.headers() });
777 } catch (err) {
778 const e = err as Error;
779 throw new ApiError(
780 `could not reach ${this.config.server}: ${(e.cause as Error | undefined)?.message ?? e.message}`,
781 );
782 }
783 if (res.status === 404) throw new ApiError(`no run ${id} in this box: ${errorSentence(await res.text())}`, 404);
784 if (!res.ok || res.body === null)
785 throw new ApiError(`logs answered ${res.status}: ${errorSentence(await res.text())}`, res.status);
786 return follow(this, res, id, { at: 0, errAt: 0 }, io);
787 }