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 12 to 318

Compare

+294 −31 in 14 places
Lines 5–66 at 318 (were 5–24 at 12)
55//
66// The box credential lives in the user's config folder, one file per server,
77// never in a project folder. It is never printed, never an argument, and only
8−// ever sent to the server that issued it, on /box/ routes.
8+// ever sent to the server that issued it: on /box/ routes, and on the org reads,
9+// which answer as the person who approved the box.
1011import { createHash } from "node:crypto";
11−import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12+import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1213import { homedir, hostname } from "node:os";
13−import { join } from "node:path";
14−import { UsageError } from "./args.ts";
14+import { dirname, join } from "node:path";
15+import { type Parsed, str, UsageError } from "./args.ts";
16+import { homeFile, homeWritePath, OLD_STATE_DIR, STATE_DIR } from "./state-dir.ts";
1517
16−/** What the person who approved the code allowed: each project with the highest role its agents get there, and how many agents. */
18+/**
19+ * What the person who approved the code allowed: each project with the highest role its agents get there. A box lets in any
20+ * number of agents (abso 642; Christopher, 2026-10-14, ask 1947); the server still records a max_agents it doesn't enforce.
21+ */
1722export interface Grant {
1823 readonly projects: readonly { readonly project: string; readonly role: string }[];
19− readonly max_agents: number;
24+ /** Version 2 grants (abso 663): member-all is every project of the approver's, now and later, at most this role. */
25+ readonly scopes?: readonly { readonly kind: string; readonly role: string }[];
2026}
2127
28+/** The role a box has in all its approver's projects, now and later, or null when its grant is a list (abso 663). */
29+export function allProjectsRole(grant: Grant): string | null {
30+ return grant.scopes?.find((scope) => scope.kind === "member-all")?.role ?? null;
31+}
33+/** Requested access is a suggestion for the person approving, never an authorization. */
34+export interface LoginRequest {
35+ readonly projects?: readonly { readonly project: string; readonly role: "reader" | "writer" | "owner" }[];
36+ readonly days?: number;
37+}
39+export function loginRequest(args: Parsed): LoginRequest | undefined {
40+ const projects = str(args, "projects");
41+ const role = str(args, "role");
42+ const days = str(args, "days");
43+ if (projects === undefined && role === undefined && days === undefined) return undefined;
44+ if (role !== undefined && projects === undefined) throw new UsageError("--role needs --projects");
45+ const requestedRole = role ?? "writer";
46+ if (requestedRole !== "reader" && requestedRole !== "writer" && requestedRole !== "owner")
47+ throw new UsageError("--role is reader, writer or owner");
48+ const names = projects?.split(",").map((name) => name.trim());
49+ if (names && (names.length > 100 || names.some((name) => !/^[A-Za-z0-9._-]+$/.test(name))))
50+ throw new UsageError(
51+ "--projects is a comma-separated list of up to 100 project names (letters, digits, dot, dash and underscore)",
52+ );
53+ const integer = (value: string, name: string, max: number): number => {
54+ if (!/^[0-9]+$/.test(value) || !Number.isInteger(Number(value)) || Number(value) < 1 || Number(value) > max)
55+ throw new UsageError(`--${name} is from 1 to ${max}`);
56+ return Number(value);
57+ };
58+ return {
59+ ...(names ? { projects: [...new Set(names)].map((project) => ({ project, role: requestedRole })) } : {}),
60+ ...(days === undefined ? {} : { days: integer(days, "days", 90) }),
61+ };
62+}
2264export interface BoxRecord {
2365 readonly server: string;
2466 readonly id: string;
Lines 77–89 at 318 (were 35–48 at 12)
3577 }
3678}
3779
38−function boxPath(server: string, home: string): string {
39− const name = createHash("sha256").update(originOf(server)).digest("hex").slice(0, 16);
40− return join(home, ".avcs", "boxes", `${name}.json`);
80+function boxFile(server: string): string {
81+ return `${createHash("sha256").update(originOf(server)).digest("hex").slice(0, 16)}.json`;
4182}
4283
4384export function readBox(server: string, home = homedir()): BoxRecord | undefined {
4485 try {
45− const raw = JSON.parse(readFileSync(boxPath(server, home), "utf8")) as Partial<BoxRecord>;
86+ const raw = JSON.parse(readFileSync(homeFile(home, "boxes", boxFile(server)), "utf8")) as Partial<BoxRecord>;
4687 if (
4788 typeof raw.server !== "string" ||
4889 originOf(raw.server) !== originOf(server) ||
Lines 99–132 at 318 (were 58–66 at 12)
5899 }
59100}
60101
102+/** The servers this box is signed in to and whose sign-in hasn't expired, from ~/.abso/boxes (and an older ~/.avcs/boxes). */
103+export function signedInServers(home = homedir(), now = Date.now()): string[] {
104+ const servers = new Set<string>();
105+ for (const dir of [STATE_DIR, OLD_STATE_DIR]) {
106+ let names: string[];
107+ try {
108+ names = readdirSync(join(home, dir, "boxes"));
109+ } catch {
110+ continue;
111+ }
112+ for (const name of names) {
113+ try {
114+ const server = (JSON.parse(readFileSync(join(home, dir, "boxes", name), "utf8")) as { server?: unknown })
115+ .server;
116+ if (typeof server !== "string") continue;
117+ const record = readBox(server, home);
118+ if (record && record.expiresAt > now) servers.add(originOf(record.server));
119+ } catch {
120+ // Not a sign-in this client wrote: left alone.
121+ }
122+ }
123+ }
124+ return [...servers].sort();
125+}
61127export function writeBox(record: BoxRecord, home = homedir()): void {
62− const path = boxPath(record.server, home);
63− mkdirSync(join(home, ".avcs", "boxes"), { recursive: true });
128+ const path = homeWritePath(home, "boxes", boxFile(record.server));
129+ mkdirSync(dirname(path), { recursive: true });
64130 writeFileSync(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
65131 try {
66132 chmodSync(path, 0o600);
Lines 135–146 at 318 (were 69–83 at 12)
69135 }
70136}
71137
138+/** Logout ends the sign-in everywhere on this machine: the credential under ~/.abso and any older copy under ~/.avcs. */
72139export function forgetBox(server: string, home = homedir()): boolean {
73− const path = boxPath(server, home);
74− try {
75− readFileSync(path);
76− } catch {
77− return false;
78− }
79− rmSync(path, { force: true });
80− return true;
140+ const paths = [homeWritePath(home, "boxes", boxFile(server)), join(home, OLD_STATE_DIR, "boxes", boxFile(server))];
141+ const had = paths.filter((path) => existsSync(path));
142+ for (const path of had) rmSync(path, { force: true });
143+ return had.length > 0;
81144}
82145
83146/** Error text with the credential (and anything shaped like a key) taken out. */
Lines 150–156 at 318 (were 87–93 at 12)
87150 return out;
88151}
89152
90−interface Answer {
153+export interface Answer {
91154 readonly status: number;
92155 readonly body: Record<string, unknown>;
93156}
Lines 161–167 at 318 (were 98–103 at 12)
98161 body: unknown,
99162 credential: string | undefined,
100163 fetcher: typeof fetch,
164+ headers: Readonly<Record<string, string>> = {},
101165): Promise<Answer> {
102166 const secrets = credential ? [credential] : [];
103167 let response: Response;
Lines 170–176 at 318 (were 106–111 at 12)
106170 method: "POST",
107171 headers: {
108172 "content-type": "application/json",
173+ ...headers,
109174 ...(credential ? { authorization: `Box ${credential}` } : {}),
110175 },
111176 body: JSON.stringify(body),
Lines 195–228 at 318 (were 130–137 at 12)
130195 return { status: response.status, body: parsed };
131196}
132197
198+/**
199+ * A read that answers as the person who approved this box: the org reads (GET /orgs, /orgs/<name>). Answers the
200+ * status and body as they came, refusals included, so the caller can say what each means; never the credential.
201+ */
202+export async function boxGet(record: BoxRecord, path: string, fetcher: typeof fetch = fetch): Promise<Answer> {
203+ const secrets = [record.credential];
204+ let response: Response;
205+ try {
206+ response = await fetcher(`${originOf(record.server)}${path}`, {
207+ headers: { authorization: `Box ${record.credential}` },
208+ signal: AbortSignal.timeout(30_000),
209+ });
210+ } catch (err) {
211+ throw new UsageError(
212+ `couldn't reach ${originOf(record.server)}: ${scrub(err instanceof Error ? err.message : String(err), secrets)}`,
213+ );
214+ }
215+ const text = await response.text();
216+ try {
217+ const body = JSON.parse(text) as unknown;
218+ if (typeof body === "object" && body !== null && !Array.isArray(body))
219+ return { status: response.status, body: body as Record<string, unknown> };
220+ } catch {}
221+ return { status: response.status, body: { error: scrub(text.slice(0, 300), secrets) } };
222+}
133224/** This machine's name, as the server takes a box's name: 1-64 letters, digits, '.', '_' or '-'. */
134−function boxName(): string {
225+export function boxName(): string {
135226 const name = hostname()
136227 .replace(/[^A-Za-z0-9._-]/g, "-")
137228 .replace(/^[^A-Za-z0-9]+/, "")
Lines 236–282 at 318 (were 145–163 at 12)
145236 typeof x === "object" &&
146237 x !== null &&
147238 Array.isArray(x.projects) &&
148− x.projects.every((p) => typeof p?.project === "string" && typeof p.role === "string") &&
149− typeof x.max_agents === "number"
239+ x.projects.every((p) => typeof p?.project === "string" && typeof p.role === "string")
150240 );
151241}
152242
243+/** The longest login waits for approval, whatever the server says. */
244+const MAX_LOGIN_WAIT_S = 30 * 60;
245+/** How often login says it's still waiting. */
246+const STILL_WAITING_MS = 60_000;
153248export interface LoginIo {
249+ readonly request?: LoginRequest;
154250 readonly fetch?: typeof fetch;
155251 readonly sleep?: (ms: number) => Promise<void>;
156252 readonly now?: () => number;
157253 /** Where the code and link go while login waits: stderr, so stdout stays quiet. */
158254 readonly say: (line: string) => void;
255+ /** Opens the approve page in a browser, answering whether it tried. None where it shouldn't (--no-browser, SSH, CI). */
256+ readonly open?: (url: string) => boolean;
257+ /**
258+ * abso 684: in a joined folder, asks a person in its project to approve this sign-in, through an abso ask, so nobody
259+ * relays the code. Answers who was asked, or null to fall back to the code alone.
260+ */
261+ readonly ask?: (codes: { readonly device: string; readonly user: string }) => Promise<LoginAsked | null>;
159262}
160263
264+/** A sign-in asked of people (abso 684). */
265+export interface LoginAsked {
266+ readonly project: string;
267+ /** "the person who approved this agent's box", or "the owners of <project>". */
268+ readonly who: string;
269+ readonly asks: readonly number[];
270+ /** Milliseconds: when the asked sign-in runs out. */
271+ readonly expiresAt: number;
272+ /** The most the box may be granted: the asking agent's own role. */
273+ readonly role: string;
274+ /** Withdraws the asks once nobody answered in time. */
275+ readonly withdraw: () => Promise<void>;
276+}
278+const CENTRAL = new Intl.DateTimeFormat("en-US", { timeZone: "America/Chicago", hour: "numeric", minute: "2-digit" });
161280/**
162281 * Asks `server` for a code, shows it with its link, and waits for a person to
163282 * approve it. Answers the box's record, already written to the config folder.
Lines 285–337 at 318 (were 166–181 at 12)
166285 const fetcher = io.fetch ?? fetch;
167286 const sleep = io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
168287 const now = io.now ?? Date.now;
169− const start = await call(server, "/login/device", { name: boxName(), client: "abso" }, undefined, fetcher);
288+ const start = await call(
289+ server,
290+ "/login/device",
291+ { name: boxName(), client: "abso", ...(io.request ? { requested_grant: io.request } : {}) },
292+ undefined,
293+ fetcher,
294+ );
170295 const { device_code: device, user_code: code, verification_uri_complete: link } = start.body;
171296 let interval = Number(start.body.interval) || 5;
172− const expiresIn = Number(start.body.expires_in) || 900;
297+ // The server says when its code runs out; a server that says never still gets an end.
298+ const expiresIn = Math.min(Number(start.body.expires_in) || 900, MAX_LOGIN_WAIT_S);
173299 if (typeof code !== "string" || typeof link !== "string" || typeof device !== "string")
174300 throw new UsageError(`${originOf(server)} didn't give a code to approve`);
175− io.say(`To sign this box in, open ${link} and approve the code ${code}.`);
176− const until = now() + expiresIn * 1000;
301+ // The page opens with the code in it, so nobody copies a link by hand. The link and code are printed all the same.
302+ // A failed ask falls back to the code, and says why, so a person can still approve it (abso 684).
303+ const asked = io.ask
304+ ? await io.ask({ device, user: code }).catch((e: unknown) => {
305+ io.say(
306+ `Couldn't ask a person to approve this (${e instanceof Error ? e.message : String(e)}), so here is the code.`,
307+ );
308+ return null;
309+ })
310+ : null;
311+ if (asked) {
312+ const askWord = asked.asks.length === 1 ? `ask ${asked.asks[0]}` : `asks ${asked.asks.join(", ")}`;
313+ io.say(`Asked ${asked.who} (${askWord} in ${asked.project}) to sign this box in, as at most ${asked.role}.`);
314+ io.say(
315+ `Waiting for their answer, until ${CENTRAL.format(new Date(asked.expiresAt))} CT. To approve it yourself instead: ${link}`,
316+ );
317+ } else {
318+ if (io.open?.(link)) io.say("Opening the approve page in your browser.");
319+ io.say(`To sign this box in, open ${link} and approve the code ${code}.`);
320+ io.say("Waiting for approval. Ctrl-C stops waiting, and abso stops by itself when the code runs out.");
321+ }
322+ const until = asked ? Math.min(asked.expiresAt, now() + MAX_LOGIN_WAIT_S * 1000) : now() + expiresIn * 1000;
323+ let toldAt = now();
177324 while (now() < until) {
178325 await sleep(interval * 1000);
326+ // A wait with no word looks like a hang, so say it's still waiting now and then.
327+ if (now() - toldAt >= STILL_WAITING_MS) {
328+ io.say(
329+ asked
330+ ? `Still waiting (${asked.who} hasn't answered yet).`
331+ : `Still waiting for the code ${code} to be approved.`,
332+ );
333+ toldAt = now();
334+ }
179335 const a = await call(server, "/login/token", { device_code: device }, undefined, fetcher);
180336 if (a.status === 400) {
181337 if (a.body.error === "authorization_pending") continue;
Lines 339–352 at 318 (were 183–190 at 12)
183339 interval += 5;
184340 continue;
185341 }
186− if (a.body.error === "access_denied") throw new UsageError(`the code ${code} was turned down.`);
187− throw new UsageError(`the code ${code} ran out. Run abso login again.`);
342+ if (a.body.error === "access_denied")
343+ throw new UsageError(asked ? `${asked.who} turned this sign-in down.` : `the code ${code} was turned down.`);
344+ if (asked) await asked.withdraw().catch(() => undefined);
345+ throw new UsageError(
346+ asked
347+ ? "nobody answered in time, so nothing was granted. Run abso login again."
348+ : `the code ${code} ran out. Run abso login again.`,
349+ );
188350 }
189351 const { box_token: credential, box_id: id, grant, expires_at } = a.body;
190352 const expiresAt = typeof expires_at === "string" ? Date.parse(expires_at) : Number.NaN;
Lines 356–365 at 318 (were 194–199 at 12)
194356 writeBox(record, home);
195357 return record;
196358 }
359+ if (asked) {
360+ await asked.withdraw().catch(() => undefined);
361+ throw new UsageError("nobody answered in time, so nothing was granted. Run abso login again.");
362+ }
197363 throw new UsageError(`nobody approved the code ${code} in time. Run abso login again.`);
198364}
199365
Lines 377–476 at 318 (were 211–216 at 12)
211377 return { key, id };
212378}
213379
380+/** What a new project from this box starts with (abso 663): the website's own create, as the person who approved the box. */
381+export interface NewProject {
382+ readonly name: string;
383+ readonly owner?: string;
384+ readonly visibility?: "public" | "private";
385+ readonly files?: readonly (
386+ | { readonly path: string; readonly text: string }
387+ | { readonly path: string; readonly base64: string }
388+ )[];
389+}
391+/**
392+ * Makes a project as the person who approved this box (abso init, abso 663). One key for every try, so a retry after
393+ * a lost answer or a pending one is the same project, never a second.
394+ */
395+export async function boxCreateProject(
396+ record: BoxRecord,
397+ project: NewProject,
398+ key: string,
399+ fetcher: typeof fetch = fetch,
400+ sleep: (ms: number) => Promise<void> = (ms) => new Promise((done) => setTimeout(done, ms)),
401+): Promise<Record<string, unknown>> {
402+ for (let attempt = 1; ; attempt++) {
403+ const a = await call(record.server, "/box/projects", project, record.credential, fetcher, {
404+ "Idempotency-Key": key,
405+ });
406+ const pending = (a.body.operation as { state?: unknown } | undefined)?.state === "pending";
407+ if (!pending) return a.body;
408+ if (attempt >= 10)
409+ throw new UsageError(
410+ `${originOf(record.server)} is still making ${project.name}. Run the same abso init again in a minute: it picks up where this left off.`,
411+ );
412+ await sleep(1000 * attempt);
413+ }
414+}
416+/** Makes an organization as the person who approved this box (abso org new, abso 663). */
417+export async function boxCreateOrg(
418+ record: BoxRecord,
419+ name: string,
420+ displayName: string | undefined,
421+ fetcher: typeof fetch = fetch,
422+): Promise<Record<string, unknown>> {
423+ return (
424+ await call(
425+ record.server,
426+ "/box/orgs",
427+ { name, ...(displayName === undefined ? {} : { displayName }) },
428+ record.credential,
429+ fetcher,
430+ )
431+ ).body;
432+}
434+/** The agent name abso join takes when none is given: the box's name, lower-cased. */
435+export function defaultAgentName(): string {
436+ return boxName().toLowerCase();
437+}
439+/**
440+ * abso join with no --agent: mints a key under `base`, else `base`-2, -3 and so on. Names this
441+ * box already holds in the project are skipped without asking, since minting one again would replace that agent's
442+ * key and cut off its folder. A name the server says is taken (409) moves on to the next; any other refusal, the
443+ * box's agent limit among them, is said as it is.
444+ */
445+export async function mintFreeName(
446+ record: BoxRecord,
447+ project: string,
448+ base: string,
449+ fetcher: typeof fetch = fetch,
450+ tries = 20,
451+): Promise<{ key: string; id: string; agent: string }> {
452+ const box = await boxGet(record, "/box", fetcher);
453+ if (box.status !== 200)
454+ throw new UsageError(
455+ `${originOf(record.server)} refused (${box.status}): ${String(box.body.error ?? "no reason given")}`,
456+ );
457+ const agents = Array.isArray(box.body.agents) ? (box.body.agents as { project?: unknown; agent?: unknown }[]) : [];
458+ const held = new Set(agents.filter((a) => a.project === project).map((a) => String(a.agent)));
459+ for (let n = 1; n <= tries; n++) {
460+ const agent = n === 1 ? base : `${base}-${n}`;
461+ if (held.has(agent)) continue;
462+ try {
463+ return { ...(await mintKey(record, project, agent, fetcher)), agent };
464+ } catch (err) {
465+ if (err instanceof UsageError && /refused \(409\): that agent name/.test(err.message)) continue;
466+ throw err;
467+ }
468+ }
469+ throw new UsageError(
470+ `${base} through ${base}-${tries} are all taken in ${project}: give this agent a name with --agent <name>`,
471+ );
472+}
214474/** Ends the box on the server, then forgets it here. Forgets it even when the server can't be reached. */
215475export async function logout(record: BoxRecord, fetcher: typeof fetch = fetch, home = homedir()): Promise<boolean> {
216476 let ended = true;
Lines 490–501 at 318 (were 230–238 at 12)
230490 if (!record) return `This box isn't signed in to ${originOf(server)}. abso login signs it in.`;
231491 const g = record.grant;
232492 const expired = record.expiresAt <= now;
493+ const all = allProjectsRole(g);
233494 return [
234495 `Signed in to ${record.server} as box ${record.id}${expired ? ", but the sign-in has expired. abso login renews it." : "."}`,
235− `Projects: ${g.projects.map((p) => `${p.project} (${p.role})`).join(", ")}. Up to ${g.max_agents} agents.`,
496+ all === null
497+ ? `Projects: ${g.projects.map((p) => `${p.project} (${p.role})`).join(", ")}.`
498+ : `Projects: all of yours, now and later (${all} at most). abso init makes a new one; abso org new makes an organization.`,
236499 `${expired ? "Expired" : "Expires"} ${day(record.expiresAt)} UTC.`,
237500 ].join("\n");
238501}
MCP
compare on this site's /mcp
CLI
abso diff 12 318 client/src/box.ts --json
JSON
/christopher/abso-core/compare/12..318?file=client%2Fsrc%2Fbox.ts&format=json