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

Versions 39 to 318

Compare

+213 −28 in 25 places
Lines 2–10 at 318 (were 2–8 at 39)
22// except `run`, which sends a tar.gz and reads the answer as a stream of JSON
33// lines (box-run.ts).
44
5+import { randomUUID } from "node:crypto";
56import { setDefaultResultOrder } from "node:dns";
7+import { CALLER_HEADER } from "../../src/caller.ts";
68import type {
79 ChangeAnswer,
810 DraftSyncAnswer,
Lines 20–27 at 318 (were 18–23 at 39)
1820 SyncAnswer,
1921} from "./api-answers.ts";
2022import { ApiError, errorSentence, neverSent } from "./api-error.ts";
23+import { UsageError } from "./args.ts";
24+import type { AutosettleAnswer, AutosettleMode } from "./autosettle-commands.ts";
2125import {
2226 boxQuery,
2327 consumeRun,
Lines 53–75 at 318 (were 49–65 at 39)
4953 Where,
5054 WhereAnswer,
5155 WhyAnswer,
56+ WithoutAnswer,
5257} from "./history-answers.ts";
5358import type {
5459 Ask,
5560 Attachment,
5661 Draft,
5762 DraftBody,
63+ GroupEvent,
64+ GroupShown,
65+ GroupSummary,
66+ GroupWrite,
5867 News as IssueNews,
5968 IssuePage,
6069 IssueRow,
6170 IssueSearchHit,
6271} from "./issues-wire.ts";
72+import { isLocal, LOCAL_BASE, localFetch, NO_STORE } from "./local-store.ts";
6373import type { Modes } from "./modes.ts";
6474
6575export * from "./api-answers.ts";
Lines 144–166 at 318 (were 134–139 at 39)
134144 | { dryRun: true; plan: CopyPlan }
135145 | { ok: true; id: number; from: { project: string; issue: number }; skipped: { comments: number[]; asks: number[] } };
136146
147+/**
148+ * The server's line when another chat just used this seat (seatNotice on an answer): kept until main() prints it with
149+ * the news, once however many answers carried it.
150+ */
151+const seatNotices = new Set<string>();
152+function noteSeat(answer: unknown): void {
153+ if (typeof answer !== "object" || answer === null || Array.isArray(answer)) return;
154+ const line = (answer as { seatNotice?: unknown }).seatNotice;
155+ if (typeof line === "string" && line !== "" && line.length <= 300 && !/[\u0000-\u001f]/.test(line))
156+ seatNotices.add(line);
157+}
158+export function takeSeatNotices(): string[] {
159+ const out = [...seatNotices];
160+ seatNotices.clear();
161+ return out;
162+}
137164export class Api {
138165 readonly config: Config;
139166 readonly timeoutMs: number;
Lines 183–205 at 318 (were 156–171 at 39)
156183 this.startRetryDelaysMs = startRetryDelaysMs;
157184 }
158185
159− /** What a box run is for, for the server's box-run records (#39): X-Avcs-Kind on POST /run. */
186+ /** What a box run is for, for the server's box-run records (#39): X-Abso-Kind on POST /run. */
160187 runKind: RunKind = "run";
161188
162189 /** The Issues Worker (#54) this folder's issues calls go to; set by the issues commands (issues.ts). */
163190 issuesServer: string | undefined;
164191
192+ /** Who is calling this seat (src/caller.ts): this chat's session, this computer and this folder. Set by open(). */
193+ caller: string | undefined;
165195 url(path: string, server = this.config.server): string {
166− return `${server.replace(/\/+$/, "")}/p/${encodeURIComponent(this.config.project)}${path}`;
196+ const base = isLocal(server) ? LOCAL_BASE : server;
197+ return `${base.replace(/\/+$/, "")}/p/${encodeURIComponent(this.config.project)}${path}`;
167198 }
168199
200+ /** A local project's calls: answered in this process (local-store.ts). */
201+ private local: ((input: string, init?: RequestInit) => Promise<Response>) | undefined;
169203 agentPath(action: string): string {
170204 return `/a/${encodeURIComponent(this.config.agent)}/${action}`;
171205 }
Lines 207–237 at 318 (were 173–184 at 39)
173207 headers(contentType?: string): Record<string, string> {
174208 return {
175209 // Which client made the call (#29); the mods send theirs too.
176− "x-avcs-client": `abso-cli/${clientVersion()}`,
177− ...(this.config.token ? { authorization: `Bearer ${this.config.token}` } : {}),
210+ "x-abso-client": `abso-cli/${clientVersion()}`,
211+ ...(this.config.token && !this.config.visitor ? { authorization: `Bearer ${this.config.token}` } : {}),
212+ // A visitor says nothing about where it's reading from.
213+ ...(this.caller !== undefined && !this.config.visitor ? { [CALLER_HEADER]: this.caller } : {}),
178214 ...(contentType ? { "content-type": contentType } : {}),
179215 };
180216 }
181217
218+ /**
219+ * Every request this Api makes goes through here. In a visitor folder it never sends anything but a GET,
220+ * and follows no redirect, so nothing it sends goes anywhere it didn't name (headers() adds no sign-in).
221+ */
222+ send(url: string, init: RequestInit = {}): Promise<Response> {
223+ if (isLocal(this.config.server)) {
224+ const dir = this.config.localStore;
225+ if (dir === undefined) return Promise.reject(new UsageError(NO_STORE));
226+ this.local ??= localFetch(dir);
227+ return this.local(url, init);
228+ }
229+ if (!this.config.visitor) return fetch(url, init);
230+ if ((init.method ?? "GET") !== "GET")
231+ return Promise.reject(new ApiError("a folder that reads signed out sends only reads"));
232+ return fetch(url, { ...init, redirect: "error" });
233+ }
182235 async json<T>(
183236 method: "GET" | "POST",
184237 path: string,
Lines 240–267 at 318 (were 187–206 at 39)
187240 atLeastMs = 0,
188241 ): Promise<T> {
189242 let res: Response | undefined;
243+ if (this.config.visitor && method !== "GET")
244+ throw new ApiError(`${path}: a folder that reads signed out sends only reads`);
190245 const sent = body === undefined ? undefined : JSON.stringify(body);
246+ const requestId = method === "POST" ? randomUUID() : undefined;
191247 const timeoutMs = Math.max(atLeastMs, timeoutFor(this.timeoutMs, sent));
192248 // A connection that never opened is tried once more, IPv4 first (#37, GAME - UI/UX: one IPv6
193249 // address timed out, and the same command went through seconds later). Nothing went out, so
194250 // a POST is as safe to send again as a GET.
195251 for (let attempt = 0; res === undefined; attempt++) {
196252 try {
197− res = await fetch(this.url(path, server), {
253+ res = await this.send(this.url(path, server), {
198254 method,
199− headers: this.headers(sent === undefined ? undefined : "application/json"),
255+ headers: {
256+ ...this.headers(sent === undefined ? undefined : "application/json"),
257+ ...(requestId ? { "Idempotency-Key": requestId } : {}),
258+ },
200259 ...(sent === undefined ? {} : { body: sent }),
201260 signal: AbortSignal.timeout(timeoutMs),
202261 });
203262 } catch (err) {
263+ // A local project's refusal (no store, a Node without SQLite) says itself.
264+ if (err instanceof UsageError) throw err;
204265 const e = err as Error;
205266 const why =
206267 e.name === "TimeoutError"
Lines 279–291 at 318 (were 218–224 at 39)
218279 await new Promise((ok) => setTimeout(ok, 500));
219280 }
220281 }
221− const text = await res.text();
282+ let text: string;
283+ try {
284+ text = await res.text();
285+ } catch (err) {
286+ const reason = err instanceof Error ? err.message : String(err);
287+ throw new ApiError(`${method} ${path} response body ended unexpectedly: ${reason}`, res.status);
288+ }
222289 // 409 is a refusal that says what to do (a drop took out lines your work builds on): print it as it is.
223290 if (!res.ok)
224291 throw new ApiError(
Lines 295–303 at 318 (were 228–234 at 39)
228295 res.status,
229296 );
230297 try {
231− return JSON.parse(text) as T;
298+ const parsed = JSON.parse(text) as T;
299+ noteSeat(parsed);
300+ return parsed;
232301 } catch {
233302 throw new ApiError(
234303 `${method} ${path} answered with something that isn't JSON: ${text.slice(0, 300)}`,
Lines 355–361 at 318 (were 286–292 at 39)
286355 });
287356 let res: Response;
288357 try {
289− res = await fetch(`${this.url("/serve")}?${q}`, {
358+ res = await this.send(`${this.url("/serve")}?${q}`, {
290359 method: "POST",
291360 headers: this.headers(),
292361 signal: AbortSignal.timeout(20 * 60_000),
Lines 376–391 at 318 (were 307–319 at 39)
307376 async prep(command: string, tarGz: Uint8Array<ArrayBuffer>): Promise<PrepAnswer> {
308377 let res: Response;
309378 try {
310− res = await fetch(`${this.url(this.agentPath("prep"))}?cmd=${encodeURIComponent(command)}${boxQuery(this.box)}`, {
311− method: "POST",
312− headers: this.headers("application/gzip"),
313− body: tarGz,
314− // A setup command can take minutes (npm ci, a browser download).
315− signal: AbortSignal.timeout(30 * 60_000),
316− });
379+ res = await this.send(
380+ `${this.url(this.agentPath("prep"))}?cmd=${encodeURIComponent(command)}${boxQuery(this.box)}`,
381+ {
382+ method: "POST",
383+ headers: this.headers("application/gzip"),
384+ body: tarGz,
385+ // A setup command can take minutes (npm ci, a browser download).
386+ signal: AbortSignal.timeout(30 * 60_000),
387+ },
388+ );
317389 } catch (err) {
318390 const e = err as Error;
319391 throw new ApiError(
Lines 401–407 at 318 (were 329–335 at 39)
329401 async unprep(): Promise<boolean> {
330402 let res: Response;
331403 try {
332− res = await fetch(
404+ res = await this.send(
333405 `${this.url(this.agentPath("prep"))}${this.box ? `?box=${encodeURIComponent(this.box)}` : ""}`,
334406 { method: "DELETE", headers: this.headers(), signal: AbortSignal.timeout(this.timeoutMs) },
335407 );
Lines 437–443 at 318 (were 365–371 at 39)
365437 async bytes(method: "GET" | "PUT", path: string, body?: Uint8Array): Promise<Uint8Array> {
366438 let res: Response;
367439 try {
368− res = await fetch(this.url(path), {
440+ res = await this.send(this.url(path), {
369441 method,
370442 headers: this.headers(body === undefined ? undefined : "application/octet-stream"),
371443 ...(body === undefined ? {} : { body: body as Uint8Array<ArrayBuffer> }),
Lines 495–511 at 318 (were 423–428 at 39)
423495 return this.json(method, path, body, this.issuesServer);
424496 }
425497
498+ /** An ask-thread call, with a server from before ask threads named as that rather than a bare 404. */
499+ async #threads<T>(call: Promise<T>): Promise<T> {
500+ try {
501+ return await call;
502+ } catch (err) {
503+ if (err instanceof ApiError && err.status === 404 && /no such issues route/.test(err.message))
504+ throw new ApiError(`${this.config.server} doesn't have ask threads yet`, 404);
505+ throw err;
506+ }
507+ }
426509 /** Issues, most recently updated first. */
427510 issues(
428511 q: { status?: string; agent?: string; parent?: number; open?: boolean; labels?: readonly string[] } = {},
Lines 533–548 at 318 (were 450–455 at 39)
450533 return this.#issues("GET", `/issue/${id}`);
451534 }
452535
536+ /** The asks this agent sent: the open ones, then the latest answered, each with its thread. */
537+ asked(): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
538+ return this.#threads(this.#issues("GET", this.agentPath("asked")));
539+ }
541+ /** One ask, open or closed, with its thread and who it waits on. */
542+ askThread(id: number): Promise<{ ask: Ask & { title: string | null } }> {
543+ return this.#threads(this.#issues("GET", `/ask/${id}`));
544+ }
453546 /** Open asks of someone (an agent, or person:<id>), soonest due first; every open ask without `of`. */
454547 waiting(of?: string): Promise<{ asks: readonly (Ask & { title: string | null })[] }> {
455548 return this.#issues("GET", `/waiting?${query({ of })}`);
Lines 570–578 at 318 (were 477–485 at 39)
477570 const path = this.agentPath("attachments");
478571 let res: Response;
479572 try {
480− res = await fetch(this.url(path, this.issuesServer), {
573+ res = await this.send(this.url(path, this.issuesServer), {
481574 method: "POST",
482− headers: { ...this.headers("application/octet-stream"), "x-avcs-name": encodeURIComponent(name) },
575+ headers: { ...this.headers("application/octet-stream"), "x-abso-name": encodeURIComponent(name) },
483576 body: bytes as Uint8Array<ArrayBuffer>,
484577 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
485578 });
Lines 617–623 at 318 (were 524–530 at 39)
524617 const url = `${this.attachmentUrl(id)}${source ? "/source" : ""}`;
525618 let res: Response;
526619 try {
527− res = await fetch(url, {
620+ res = await this.send(url, {
528621 headers: this.headers(),
529622 signal: AbortSignal.timeout(Math.max(this.timeoutMs, 120_000)),
530623 });
Lines 718–775 at 318 (were 625–630 at 39)
625718 return this.#issues("POST", this.agentPath(`answer/${id}`), body);
626719 }
627720
721+ /** Acknowledges an ask of this agent without answering it: the asker hears it, and the ask stays open. */
722+ ack(id: number, body: { note?: string }): Promise<{ ask: Ask; news?: IssueNews }> {
723+ return this.#issues("POST", this.agentPath(`ack/${id}`), body);
724+ }
726+ /** Adds to an ask's thread, as its asker or the one asked; the other side hears it, and the ask stays as it is. */
727+ reply(id: number, body: { text: string; question?: boolean }): Promise<{ ask: Ask; news?: IssueNews }> {
728+ return this.#threads(this.#issues("POST", this.agentPath(`reply/${id}`), body));
729+ }
731+ /** A groups call, with a server from before groups named as that rather than a bare 404. */
732+ async #groups<T>(call: Promise<T>): Promise<T> {
733+ try {
734+ return await call;
735+ } catch (err) {
736+ if (err instanceof ApiError && err.status === 404 && /no such issues route|reads have no/.test(err.message))
737+ throw new ApiError(`${this.config.server} doesn't have groups yet`, 404);
738+ throw err;
739+ }
740+ }
742+ /** The project's groups this agent can see. */
743+ groupList(): Promise<{ groups: readonly GroupSummary[] }> {
744+ return this.#groups(this.#issues("GET", this.agentPath("groups")));
745+ }
747+ /** One group's settings and roster, by name or id. */
748+ group(ref: string): Promise<GroupShown> {
749+ return this.#groups(this.#issues("GET", this.agentPath(`group/${encodeURIComponent(ref)}`)));
750+ }
752+ /** A page of a group's history, newest first, and the `before` that reads further back (null at the start). */
753+ groupEvents(
754+ ref: string,
755+ q: { before?: number; limit?: number; kind?: string } = {},
756+ ): Promise<{ events: readonly GroupEvent[]; before: number | null }> {
757+ const qs = query({ before: q.before, limit: q.limit, kind: q.kind }).toString();
758+ return this.#groups(
759+ this.#issues("GET", this.agentPath(`group/${encodeURIComponent(ref)}/events${qs ? `?${qs}` : ""}`)),
760+ );
761+ }
763+ /** Make a group (ref undefined), or post, join, leave, add, remove or change settings in one. */
764+ groupWrite(
765+ ref: string | undefined,
766+ action: "post" | "join" | "leave" | "add" | "remove" | "settings" | undefined,
767+ body: Record<string, unknown>,
768+ ): Promise<GroupWrite> {
769+ const path = ref === undefined ? "groups" : `group/${encodeURIComponent(ref)}/${action}`;
770+ return this.#groups(this.#issues("POST", this.agentPath(path), body));
771+ }
628773 /** Takes back an ask this agent made, with a note on why; the one asked hears it. */
629774 withdraw(id: number, body: { note?: string }): Promise<{ ask: Ask; news?: IssueNews }> {
630775 return this.#issues("POST", this.agentPath(`withdraw/${id}`), body);
Lines 803–828 at 318 (were 658–663 at 39)
658803 return this.json("POST", `/visibility?visibility=${v}`, {});
659804 }
660805
806+ /** The project's auto-settle choice (abso-core 23): off, advise or settle, and how sure before abso settles. */
807+ autosettle(): Promise<AutosettleAnswer> {
808+ return this.json("GET", "/autosettle");
809+ }
811+ /** Change it (abso-core 23): an owner's key, or the shared token on staging. Without `at`, the server keeps its own. */
812+ setAutosettle(mode: AutosettleMode, at?: number): Promise<AutosettleAnswer> {
813+ return this.json("POST", `/autosettle?mode=${mode}${at === undefined ? "" : `&at=${at}`}`, {});
814+ }
816+ /** Auto-settle's history (abso-core 23): held pushes the model advised on, newest first. */
817+ autosettleHistory(): Promise<unknown> {
818+ return this.json("GET", "/autosettle/history");
819+ }
821+ /** One held push from the history, with each collision's calls to the model. */
822+ autosettleHold(id: number): Promise<unknown> {
823+ return this.json("GET", `/autosettle/history/${id}`);
824+ }
661826 /** Take back this agent's queued publishes (#39); refused while one is being checked. */
662827 unqueue(): Promise<{ pulled: readonly number[] }> {
663828 return this.json("POST", this.agentPath("unqueue"), {});
Lines 904–914 at 318 (were 739–744 at 39)
739904 return this.json("GET", version === undefined ? "/ci" : `/ci?${query({ version })}`);
740905 }
741906
907+ /** The project's pipeline runs, newest first; one run with its jobs; or one job's log (`log` is pipeline.job). */
908+ pipelineRuns(run?: number, log?: string): Promise<unknown> {
909+ return this.json("GET", run === undefined ? "/pipelines" : `/pipelines?${query({ run, log })}`);
910+ }
742912 /** Ends every /latest link handed out so far; answers CI's state with the new link. */
743913 ciRevoke(): Promise<CiStatus> {
744914 return this.json("POST", "/ci/revoke", {});
Lines 985–995 at 318 (were 815–820 at 39)
815985 return this.json("GET", `/compare?${query({ from, to, ...where })}`);
816986 }
817987
988+ /** Version `version` of shared with `versions` left out, or the refusal naming what builds on them. */
989+ without(version: number, versions: readonly number[]): Promise<WithoutAnswer> {
990+ return this.json("GET", `/without?${query({ version, versions: versions.join(",") })}`);
991+ }
818993 /** A message to the project's other agents (or those named), delivered once as news. */
819994 starting(
820995 text: string | null,
Lines 1016–1043 at 318 (were 841–858 at 39)
8411016 return this.json("POST", this.agentPath("news"), {});
8421017 }
8431018
1019+ /** A ticket that opens this agent's news stream once, within a minute (abso 690; news-stream.ts). */
1020+ newsTicket(): Promise<{ url: string; protocols: string[]; expiresAt: number | string }> {
1021+ return this.json("POST", this.agentPath("news/ticket"), {});
1022+ }
8441024 /** This agent's unpublished changes, file by file. */
8451025 diff(): Promise<DiffAnswer> {
8461026 return this.json("POST", this.agentPath("diff"), {});
8471027 }
8481028
1029+ /** Another agent's recorded, unpublished changes, file by file: read only, as the website's drafts show them. */
1030+ diffOf(agent: string): Promise<DiffAnswer> {
1031+ return this.json("GET", `/diff?${query({ agent })}`);
1032+ }
8491034 /** Discard this agent's unpublished changes to `files` (null: all of them). */
8501035 restore(files: readonly string[] | null): Promise<RestoreAnswer> {
8511036 return this.json("POST", this.agentPath("restore"), files === null ? { all: true } : { files });
8521037 }
8531038
854− why(file: string, line: number, view: View = {}): Promise<WhyAnswer> {
855− return this.json("GET", `/why?${query({ file, line, ...view })}`);
1039+ why(file: string, line: number, view: View = {}, version?: number): Promise<WhyAnswer> {
1040+ return this.json("GET", `/why?${query({ file, line, version, ...view })}`);
8561041 }
8571042
8581043 where(): Promise<WhereAnswer> {
Lines 1057–1065 at 318 (were 872–880 at 39)
8721057 */
8731058 async run(command: string, tarGz: Uint8Array<ArrayBuffer>, io: RunIO): Promise<number> {
8741059 const res = await postRun(this, command, tarGz, io.onRetry, io.replace, io.fresh);
875− // X-Avcs-Box: cold means the box started for this run; X-Avcs-Prep says whether it started from the prep (#37).
876− io.onBox?.(res.headers.get("x-avcs-box") === "cold", res.headers.get("x-avcs-prep") ?? undefined);
877− return follow(this, res, res.headers.get("x-avcs-run"), { at: 0, errAt: 0 }, io);
1060+ // X-Abso-Box: cold means the box started for this run; X-Abso-Prep says whether it started from the prep (#37).
1061+ io.onBox?.(res.headers.get("x-abso-box") === "cold", res.headers.get("x-abso-prep") ?? undefined);
1062+ return follow(this, res, res.headers.get("x-abso-run"), { at: 0, errAt: 0 }, io);
8781063 }
8791064
8801065 /**
Lines 1073–1079 at 318 (were 888–894 at 39)
8881073 replace = false,
8891074 ): Promise<string> {
8901075 const res = await postRun(this, command, tarGz, onRetry, replace);
891− const id = res.headers.get("x-avcs-run");
1076+ const id = res.headers.get("x-abso-run");
8921077 if (id === null) {
8931078 // No id: the box failed before the job started ({"error"} in the body), or the server can't detach.
8941079 await consumeRun(res, { out: () => {} }, { at: 0, errAt: 0 });
Lines 1087–1093 at 318 (were 902–908 at 39)
9021087 async logs(id: string, io: RunIO): Promise<number> {
9031088 let res: Response;
9041089 try {
905− res = await fetch(followUrl(this, id, { at: 0, errAt: 0 }), { headers: this.headers() });
1090+ res = await this.send(followUrl(this, id, { at: 0, errAt: 0 }), { headers: this.headers() });
9061091 } catch (err) {
9071092 const e = err as Error;
9081093 throw new ApiError(
MCP
compare on this site's /mcp
CLI
abso diff 39 318 client/src/api.ts --json
JSON
/christopher/abso-core/compare/39..318?file=client%2Fsrc%2Fapi.ts&format=json