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/box.ts --version 147 --json
JSON
/christopher/abso-core/blame/client/src/box.ts?version=147&format=json
398 linesFirst import 57% · trials 18% · codex-mac-1 11% · pinch 11% · review 3% · speed 1%Last change codex-mac-1 in version 102,

398 lines from 10 changes in 9 versions.

init0Start the project1// Signing in once per box (abso issue 108). `abso login` asks the server for a
2// code, a person approves it on the website, and the box gets a credential
3// with a grant: projects, a role cap, an agent limit and an expiry. Agents on
4// the box then mint their own keys from it at `abso join`.
5//
6// The box credential lives in the user's config folder, one file per server,
7// never in a project folder. It is never printed, never an argument, and only
pinch34Client: abso orgs and abso org <name>, reading as the person who approved this box's sign-in (abso login): your organizations and roles, invitations waiting for you, and an org's projects, people (by name, never id), settings and open invites. Changes (--invite, --role, --remove, --leave, --members, --projects-by), abso org new and abso init --org are made on the website for now; each says where and sends nothing. One change at a time. MCP serves orgs and org. Client tests 283/283, tsc and biome clean.Compare8// 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.
init0Start the project10
11import { createHash } from "node:crypto";
trials61abso join and abso init no longer need --server (abso issue 349): --server, then ABSO_SERVER, then the server this box signed in to with abso login, then https://api.abso.dev. A box signed in to more than one server is asked to say which. Usage, about text and the README's join line updated; box.test.ts covers the order.Compare12import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
init0Start the project13import { homedir, hostname } from "node:os";
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare14import { dirname, join } from "node:path";
codex-mac-1102Let login request projects, roles, agent limits and durationCompare15import { type Parsed, str, UsageError } from "./args.ts";
trials61abso join and abso init no longer need --server (abso issue 349): --server, then ABSO_SERVER, then the server this box signed in to with abso login, then https://api.abso.dev. A box signed in to more than one server is asked to say which. Usage, about text and the README's join line updated; box.test.ts covers the order.Compare16import { homeFile, homeWritePath, OLD_STATE_DIR, STATE_DIR } from "./state-dir.ts";
init0Start the project17
18/** What the person who approved the code allowed: each project with the highest role its agents get there, and how many agents. */
19export interface Grant {
20 readonly projects: readonly { readonly project: string; readonly role: string }[];
21 readonly max_agents: number;
codex-mac-1102Let login request projects, roles, agent limits and durationCompare24/** Requested access is a suggestion for the person approving, never an authorization. */
25export interface LoginRequest {
26 readonly projects?: readonly { readonly project: string; readonly role: "reader" | "writer" | "owner" }[];
27 readonly max_agents?: number;
28 readonly days?: number;
31export function loginRequest(args: Parsed): LoginRequest | undefined {
32 const projects = str(args, "projects");
33 const role = str(args, "role");
34 const maxAgents = str(args, "max-agents");
35 const days = str(args, "days");
36 if (projects === undefined && role === undefined && maxAgents === undefined && days === undefined) return undefined;
37 if (role !== undefined && projects === undefined) throw new UsageError("--role needs --projects");
38 const requestedRole = role ?? "writer";
39 if (requestedRole !== "reader" && requestedRole !== "writer" && requestedRole !== "owner")
40 throw new UsageError("--role is reader, writer or owner");
41 const names = projects?.split(",").map((name) => name.trim());
42 if (names && (names.length > 100 || names.some((name) => !/^[A-Za-z0-9._-]+$/.test(name))))
43 throw new UsageError(
44 "--projects is a comma-separated list of up to 100 project names (letters, digits, dot, dash and underscore)",
45 );
46 const integer = (value: string, name: string, max: number): number => {
47 if (!/^[0-9]+$/.test(value) || !Number.isInteger(Number(value)) || Number(value) < 1 || Number(value) > max)
48 throw new UsageError(`--${name} is from 1 to ${max}`);
49 return Number(value);
50 };
51 return {
52 ...(names ? { projects: [...new Set(names)].map((project) => ({ project, role: requestedRole })) } : {}),
53 ...(maxAgents === undefined ? {} : { max_agents: integer(maxAgents, "max-agents", 50) }),
54 ...(days === undefined ? {} : { days: integer(days, "days", 90) }),
55 };
init0Start the project58export interface BoxRecord {
59 readonly server: string;
60 readonly id: string;
61 readonly credential: string;
62 readonly grant: Grant;
63 readonly expiresAt: number;
66export function originOf(server: string): string {
67 try {
68 return new URL(server).origin;
69 } catch {
70 return server;
71 }
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare74function boxFile(server: string): string {
75 return `${createHash("sha256").update(originOf(server)).digest("hex").slice(0, 16)}.json`;
init0Start the project76}
78export function readBox(server: string, home = homedir()): BoxRecord | undefined {
79 try {
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare80 const raw = JSON.parse(readFileSync(homeFile(home, "boxes", boxFile(server)), "utf8")) as Partial<BoxRecord>;
init0Start the project81 if (
82 typeof raw.server !== "string" ||
83 originOf(raw.server) !== originOf(server) ||
84 typeof raw.credential !== "string" ||
85 typeof raw.id !== "string" ||
86 typeof raw.expiresAt !== "number" ||
87 !isGrant(raw.grant)
88 )
89 return undefined;
90 return raw as BoxRecord;
91 } catch {
92 return undefined;
93 }
trials61abso join and abso init no longer need --server (abso issue 349): --server, then ABSO_SERVER, then the server this box signed in to with abso login, then https://api.abso.dev. A box signed in to more than one server is asked to say which. Usage, about text and the README's join line updated; box.test.ts covers the order.Compare94}
96/** The servers this box is signed in to and whose sign-in hasn't expired, from ~/.abso/boxes (and an older ~/.avcs/boxes). */
97export function signedInServers(home = homedir(), now = Date.now()): string[] {
98 const servers = new Set<string>();
99 for (const dir of [STATE_DIR, OLD_STATE_DIR]) {
100 let names: string[];
101 try {
102 names = readdirSync(join(home, dir, "boxes"));
103 } catch {
104 continue;
105 }
106 for (const name of names) {
107 try {
108 const server = (JSON.parse(readFileSync(join(home, dir, "boxes", name), "utf8")) as { server?: unknown })
109 .server;
110 if (typeof server !== "string") continue;
111 const record = readBox(server, home);
112 if (record && record.expiresAt > now) servers.add(originOf(record.server));
113 } catch {
114 // Not a sign-in this client wrote: left alone.
115 }
116 }
117 }
118 return [...servers].sort();
init0Start the project119}
121export function writeBox(record: BoxRecord, home = homedir()): void {
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare122 const path = homeWritePath(home, "boxes", boxFile(record.server));
123 mkdirSync(dirname(path), { recursive: true });
init0Start the project124 writeFileSync(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
125 try {
126 chmodSync(path, 0o600);
127 } catch {
128 // Windows has no owner-only mode; the file is still outside every project folder.
129 }
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare132/** Logout ends the sign-in everywhere on this machine: the credential under ~/.abso and any older copy under ~/.avcs. */
init0Start the project133export function forgetBox(server: string, home = homedir()): boolean {
review17New folders keep their state in .abso/, and the machine's sign-in, servers and admin token are read from ~/.abso/ first, then ~/.avcs/. A folder made before, with only .avcs/, is untouched: it keeps working, is never half-moved, and no older client or mod loses it. stateDir(root) and homeFile/homeWritePath are in the new client/src/state-dir.ts and replace the old AVCS_DIR constant everywhere. abso login writes only to ~/.abso/ and leaves ~/.avcs/ alone; logout removes both copies. The edit mod and the view mod read either folder. .abso is skipped like .avcs (including its odd spellings), the git exclude names whichever folder is in use, and the messages name .abso. Not changed: avcs.json (the server reads that name, so abso.json needs the server to learn it first), .avcsignore, env var names and wire headers. Tests: 709 run, 708 pass (one is skipped), including new ones for the folder choice, the home-file order and box sign-in; biome ci has no errors.Compare134 const paths = [homeWritePath(home, "boxes", boxFile(server)), join(home, OLD_STATE_DIR, "boxes", boxFile(server))];
135 const had = paths.filter((path) => existsSync(path));
136 for (const path of had) rmSync(path, { force: true });
137 return had.length > 0;
init0Start the project138}
140/** Error text with the credential (and anything shaped like a key) taken out. */
141function scrub(text: string, secrets: readonly string[]): string {
142 let out = text.replace(/abso_(sk|bx)_[A-Za-z0-9_-]+/g, "[redacted]");
143 for (const s of secrets) if (s.length > 0) out = out.split(s).join("[redacted]");
144 return out;
pinch34Client: abso orgs and abso org <name>, reading as the person who approved this box's sign-in (abso login): your organizations and roles, invitations waiting for you, and an org's projects, people (by name, never id), settings and open invites. Changes (--invite, --role, --remove, --leave, --members, --projects-by), abso org new and abso init --org are made on the website for now; each says where and sends nothing. One change at a time. MCP serves orgs and org. Client tests 283/283, tsc and biome clean.Compare147export interface Answer {
init0Start the project148 readonly status: number;
149 readonly body: Record<string, unknown>;
152async function call(
153 server: string,
154 path: string,
155 body: unknown,
156 credential: string | undefined,
157 fetcher: typeof fetch,
158): Promise<Answer> {
159 const secrets = credential ? [credential] : [];
160 let response: Response;
161 try {
162 response = await fetcher(`${originOf(server)}${path}`, {
163 method: "POST",
164 headers: {
165 "content-type": "application/json",
166 ...(credential ? { authorization: `Box ${credential}` } : {}),
167 },
168 body: JSON.stringify(body),
169 signal: AbortSignal.timeout(30_000),
170 });
171 } catch (err) {
172 throw new UsageError(
173 `couldn't reach ${originOf(server)}: ${scrub(err instanceof Error ? err.message : String(err), secrets)}`,
174 );
175 }
176 const text = await response.text();
177 let parsed: Record<string, unknown> = {};
178 try {
179 parsed = JSON.parse(text) as Record<string, unknown>;
180 } catch {
181 if (response.ok) throw new UsageError(`${originOf(server)}${path} didn't answer JSON`);
182 }
183 if (!response.ok && !(response.status === 400 && path === "/login/token")) {
184 const said = typeof parsed.error === "string" ? parsed.error : text.slice(0, 300);
185 throw new UsageError(scrub(`${originOf(server)} refused (${response.status}): ${said}`, secrets));
186 }
187 return { status: response.status, body: parsed };
pinch34Client: abso orgs and abso org <name>, reading as the person who approved this box's sign-in (abso login): your organizations and roles, invitations waiting for you, and an org's projects, people (by name, never id), settings and open invites. Changes (--invite, --role, --remove, --leave, --members, --projects-by), abso org new and abso init --org are made on the website for now; each says where and sends nothing. One change at a time. MCP serves orgs and org. Client tests 283/283, tsc and biome clean.Compare190/**
191 * A read that answers as the person who approved this box: the org reads (GET /orgs, /orgs/<name>). Answers the
192 * status and body as they came, refusals included, so the caller can say what each means; never the credential.
193 */
194export async function boxGet(record: BoxRecord, path: string, fetcher: typeof fetch = fetch): Promise<Answer> {
195 const secrets = [record.credential];
196 let response: Response;
197 try {
198 response = await fetcher(`${originOf(record.server)}${path}`, {
199 headers: { authorization: `Box ${record.credential}` },
200 signal: AbortSignal.timeout(30_000),
201 });
202 } catch (err) {
203 throw new UsageError(
204 `couldn't reach ${originOf(record.server)}: ${scrub(err instanceof Error ? err.message : String(err), secrets)}`,
205 );
206 }
207 const text = await response.text();
208 try {
209 const body = JSON.parse(text) as unknown;
210 if (typeof body === "object" && body !== null && !Array.isArray(body))
211 return { status: response.status, body: body as Record<string, unknown> };
212 } catch {}
213 return { status: response.status, body: { error: scrub(text.slice(0, 300), secrets) } };
init0Start the project216/** This machine's name, as the server takes a box's name: 1-64 letters, digits, '.', '_' or '-'. */
217function boxName(): string {
218 const name = hostname()
219 .replace(/[^A-Za-z0-9._-]/g, "-")
220 .replace(/^[^A-Za-z0-9]+/, "")
221 .slice(0, 64);
222 return name || "box";
225function isGrant(g: unknown): g is Grant {
226 const x = g as Partial<Grant> | null;
227 return (
228 typeof x === "object" &&
229 x !== null &&
230 Array.isArray(x.projects) &&
231 x.projects.every((p) => typeof p?.project === "string" && typeof p.role === "string") &&
232 typeof x.max_agents === "number"
233 );
pinch58abso login says it is waiting for approval, and that Ctrl-C stops it, then says it is still waiting about once a minute. It stops by itself when the code runs out, and never waits past 30 minutes whatever the server's expires_in says. A login that said nothing for 15 minutes looked like a hang.Compare236/** The longest login waits for approval, whatever the server says. */
237const MAX_LOGIN_WAIT_S = 30 * 60;
238/** How often login says it's still waiting. */
239const STILL_WAITING_MS = 60_000;
init0Start the project241export interface LoginIo {
codex-mac-1102Let login request projects, roles, agent limits and durationCompare242 readonly request?: LoginRequest;
init0Start the project243 readonly fetch?: typeof fetch;
244 readonly sleep?: (ms: number) => Promise<void>;
245 readonly now?: () => number;
246 /** Where the code and link go while login waits: stderr, so stdout stays quiet. */
247 readonly say: (line: string) => void;
speed60abso login opens the approve page in the browser Like gh auth login and wrangler login: abso login opens the approve page in the default browser with the code already in it, so nobody copies a link by hand. It still prints the link and the code, which stand when the open fails or is skipped. - Windows opens with rundll32 url.dll,FileProtocolHandler, macOS with open, Linux with xdg-open. There's no shell, so a link with & in it arrives whole (cmd's start would cut it). - No browser with --no-browser or ABSO_NO_BROWSER, over SSH (SSH_CONNECTION or SSH_TTY), under CI, or on Linux and other Unixes with neither DISPLAY nor WAYLAND_DISPLAY. - Only http and https links are opened, so a link from a server is never handed to the desktop as a file or a program. - The opener starts detached and isn't waited on; a failure is silent. Tests: open-browser.test.ts (each skip, each platform's command, web links only, a failing opener is silent), and two login tests with an injected opener.Compare248 /** Opens the approve page in a browser, answering whether it tried. None where it shouldn't (--no-browser, SSH, CI). */
249 readonly open?: (url: string) => boolean;
init0Start the project250}
252/**
253 * Asks `server` for a code, shows it with its link, and waits for a person to
254 * approve it. Answers the box's record, already written to the config folder.
255 */
256export async function login(server: string, io: LoginIo, home = homedir()): Promise<BoxRecord> {
257 const fetcher = io.fetch ?? fetch;
258 const sleep = io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
259 const now = io.now ?? Date.now;
codex-mac-1102Let login request projects, roles, agent limits and durationCompare260 const start = await call(
261 server,
262 "/login/device",
263 { name: boxName(), client: "abso", ...(io.request ? { requested_grant: io.request } : {}) },
264 undefined,
265 fetcher,
266 );
init0Start the project267 const { device_code: device, user_code: code, verification_uri_complete: link } = start.body;
268 let interval = Number(start.body.interval) || 5;
pinch58abso login says it is waiting for approval, and that Ctrl-C stops it, then says it is still waiting about once a minute. It stops by itself when the code runs out, and never waits past 30 minutes whatever the server's expires_in says. A login that said nothing for 15 minutes looked like a hang.Compare269 // The server says when its code runs out; a server that says never still gets an end.
270 const expiresIn = Math.min(Number(start.body.expires_in) || 900, MAX_LOGIN_WAIT_S);
init0Start the project271 if (typeof code !== "string" || typeof link !== "string" || typeof device !== "string")
272 throw new UsageError(`${originOf(server)} didn't give a code to approve`);
speed60abso login opens the approve page in the browser Like gh auth login and wrangler login: abso login opens the approve page in the default browser with the code already in it, so nobody copies a link by hand. It still prints the link and the code, which stand when the open fails or is skipped. - Windows opens with rundll32 url.dll,FileProtocolHandler, macOS with open, Linux with xdg-open. There's no shell, so a link with & in it arrives whole (cmd's start would cut it). - No browser with --no-browser or ABSO_NO_BROWSER, over SSH (SSH_CONNECTION or SSH_TTY), under CI, or on Linux and other Unixes with neither DISPLAY nor WAYLAND_DISPLAY. - Only http and https links are opened, so a link from a server is never handed to the desktop as a file or a program. - The opener starts detached and isn't waited on; a failure is silent. Tests: open-browser.test.ts (each skip, each platform's command, web links only, a failing opener is silent), and two login tests with an injected opener.Compare273 // The page opens with the code in it, so nobody copies a link by hand. The link and code are printed all the same.
274 if (io.open?.(link)) io.say("Opening the approve page in your browser.");
init0Start the project275 io.say(`To sign this box in, open ${link} and approve the code ${code}.`);
pinch58abso login says it is waiting for approval, and that Ctrl-C stops it, then says it is still waiting about once a minute. It stops by itself when the code runs out, and never waits past 30 minutes whatever the server's expires_in says. A login that said nothing for 15 minutes looked like a hang.Compare276 io.say("Waiting for approval. Ctrl-C stops waiting, and abso stops by itself when the code runs out.");
init0Start the project277 const until = now() + expiresIn * 1000;
pinch58abso login says it is waiting for approval, and that Ctrl-C stops it, then says it is still waiting about once a minute. It stops by itself when the code runs out, and never waits past 30 minutes whatever the server's expires_in says. A login that said nothing for 15 minutes looked like a hang.Compare278 let toldAt = now();
init0Start the project279 while (now() < until) {
280 await sleep(interval * 1000);
pinch58abso login says it is waiting for approval, and that Ctrl-C stops it, then says it is still waiting about once a minute. It stops by itself when the code runs out, and never waits past 30 minutes whatever the server's expires_in says. A login that said nothing for 15 minutes looked like a hang.Compare281 // A wait with no word looks like a hang, so say it's still waiting now and then.
282 if (now() - toldAt >= STILL_WAITING_MS) {
283 io.say(`Still waiting for the code ${code} to be approved.`);
284 toldAt = now();
285 }
init0Start the project286 const a = await call(server, "/login/token", { device_code: device }, undefined, fetcher);
287 if (a.status === 400) {
288 if (a.body.error === "authorization_pending") continue;
289 if (a.body.error === "slow_down") {
290 interval += 5;
291 continue;
292 }
293 if (a.body.error === "access_denied") throw new UsageError(`the code ${code} was turned down.`);
294 throw new UsageError(`the code ${code} ran out. Run abso login again.`);
295 }
296 const { box_token: credential, box_id: id, grant, expires_at } = a.body;
297 const expiresAt = typeof expires_at === "string" ? Date.parse(expires_at) : Number.NaN;
298 if (typeof credential !== "string" || typeof id !== "string" || !isGrant(grant) || Number.isNaN(expiresAt))
299 throw new UsageError(`${originOf(server)} approved the code but sent no credential`);
300 const record: BoxRecord = { server: originOf(server), id, credential, grant, expiresAt };
301 writeBox(record, home);
302 return record;
303 }
304 throw new UsageError(`nobody approved the code ${code} in time. Run abso login again.`);
307/** An agent's own key, minted from the box's credential: `{key, id}`, as `abso key install` takes it. */
308export async function mintKey(
309 record: BoxRecord,
310 project: string,
311 agent: string,
312 fetcher: typeof fetch = fetch,
313): Promise<{ key: string; id: string }> {
314 const a = await call(record.server, "/box/agent-key", { project, agent }, record.credential, fetcher);
315 const { key, id } = a.body;
316 if (typeof key !== "string" || typeof id !== "string")
317 throw new UsageError(`${record.server} didn't send a key for ${agent}`);
318 return { key, id };
trials64join: a folder prepared with abso key install --server is joined where it is again (Pinch's catch on 63). - --agent keeps 'here' as the default, as before 63, so scripts that join into a prepared folder still do. The ./<project> rule is only for a join with no --agent. - A folder holding only abso's own state folder (.abso, or the older .avcs) counts as empty. - New tests: joinFolder's rule (empty, only .abso, files here, --agent, --dir, a taken ./<project>), and a runJoin test that installs a key with --server and joins with --agent and no --dir: it joins here and sends that key (the shared token is wrong, so only the key gets through). The git line-endings test is back to joining without --dir. - Issue numbers taken out of the new code comments and test names.Compare321/** The agent name abso join takes when none is given: the box's name, lower-cased. */
trials63abso join <project> works with no --agent and no --dir (abso issue 351), so the project page can show npx abso-cli join <project>. - Agent: the box's name (the hostname abso login sends), lower-cased; if taken, <name>-2, -3, up to 20 tries. Names this box already holds in the project (GET /box) are skipped without minting, since minting one again replaces that agent's key and would cut off its folder. A 409 for a taken name moves on; the agent-limit 409 says the limit and where to revoke. No box sign-in: abso login first, or --agent. - Folder: --dir, else here when empty, else ./<project>, which must be new or empty; it prints cd <folder> when it isn't here. - --agent, --dir and --server still win. Project names are checked before use as a folder. Tests: box.test.ts (mintFreeName: held name skipped, 409 moves on, agent limit), client.test.ts (empty folder, ./<project>, refusing a non-empty one); the git line-endings test now joins with --dir . since its folder has files.Compare322export function defaultAgentName(): string {
323 return boxName().toLowerCase();
326/**
trials64join: a folder prepared with abso key install --server is joined where it is again (Pinch's catch on 63). - --agent keeps 'here' as the default, as before 63, so scripts that join into a prepared folder still do. The ./<project> rule is only for a join with no --agent. - A folder holding only abso's own state folder (.abso, or the older .avcs) counts as empty. - New tests: joinFolder's rule (empty, only .abso, files here, --agent, --dir, a taken ./<project>), and a runJoin test that installs a key with --server and joins with --agent and no --dir: it joins here and sends that key (the shared token is wrong, so only the key gets through). The git line-endings test is back to joining without --dir. - Issue numbers taken out of the new code comments and test names.Compare327 * abso join with no --agent: mints a key under `base`, else `base`-2, -3 and so on. Names this
trials63abso join <project> works with no --agent and no --dir (abso issue 351), so the project page can show npx abso-cli join <project>. - Agent: the box's name (the hostname abso login sends), lower-cased; if taken, <name>-2, -3, up to 20 tries. Names this box already holds in the project (GET /box) are skipped without minting, since minting one again replaces that agent's key and would cut off its folder. A 409 for a taken name moves on; the agent-limit 409 says the limit and where to revoke. No box sign-in: abso login first, or --agent. - Folder: --dir, else here when empty, else ./<project>, which must be new or empty; it prints cd <folder> when it isn't here. - --agent, --dir and --server still win. Project names are checked before use as a folder. Tests: box.test.ts (mintFreeName: held name skipped, 409 moves on, agent limit), client.test.ts (empty folder, ./<project>, refusing a non-empty one); the git line-endings test now joins with --dir . since its folder has files.Compare328 * box already holds in the project are skipped without asking, since minting one again would replace that agent's
329 * key and cut off its folder. A name the server says is taken (409) moves on to the next; any other refusal, the
330 * box's agent limit among them, is said as it is.
331 */
332export async function mintFreeName(
333 record: BoxRecord,
334 project: string,
335 base: string,
336 fetcher: typeof fetch = fetch,
337 tries = 20,
338): Promise<{ key: string; id: string; agent: string }> {
339 const box = await boxGet(record, "/box", fetcher);
340 if (box.status !== 200)
341 throw new UsageError(
342 `${originOf(record.server)} refused (${box.status}): ${String(box.body.error ?? "no reason given")}`,
343 );
344 const agents = Array.isArray(box.body.agents) ? (box.body.agents as { project?: unknown; agent?: unknown }[]) : [];
345 const held = new Set(agents.filter((a) => a.project === project).map((a) => String(a.agent)));
346 for (let n = 1; n <= tries; n++) {
347 const agent = n === 1 ? base : `${base}-${n}`;
348 if (held.has(agent)) continue;
349 try {
350 return { ...(await mintKey(record, project, agent, fetcher)), agent };
351 } catch (err) {
352 if (err instanceof UsageError && /refused \(409\): that agent name/.test(err.message)) continue;
353 if (err instanceof UsageError && /refused \(409\): this box is at its agent limit/.test(err.message))
354 throw new UsageError(
355 `this box is at its agent limit (${record.grant.max_agents}): abso box shows its grant, and an agent can be revoked on the website's Boxes page`,
356 );
357 throw err;
358 }
359 }
360 throw new UsageError(
361 `${base} through ${base}-${tries} are all taken in ${project}: give this agent a name with --agent <name>`,
362 );
init0Start the project365/** Ends the box on the server, then forgets it here. Forgets it even when the server can't be reached. */
366export async function logout(record: BoxRecord, fetcher: typeof fetch = fetch, home = homedir()): Promise<boolean> {
367 let ended = true;
368 try {
369 await call(record.server, "/box/logout", {}, record.credential, fetcher);
370 } catch {
371 ended = false;
372 }
373 forgetBox(record.server, home);
374 return ended;
377const day = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " ");
379/** What `abso box` prints: the grant, never the credential. */
380export function boxText(record: BoxRecord | undefined, server: string, now = Date.now()): string {
381 if (!record) return `This box isn't signed in to ${originOf(server)}. abso login signs it in.`;
382 const g = record.grant;
383 const expired = record.expiresAt <= now;
384 return [
385 `Signed in to ${record.server} as box ${record.id}${expired ? ", but the sign-in has expired. abso login renews it." : "."}`,
386 `Projects: ${g.projects.map((p) => `${p.project} (${p.role})`).join(", ")}. Up to ${g.max_agents} agents.`,
387 `${expired ? "Expired" : "Expires"} ${day(record.expiresAt)} UTC.`,
388 ].join("\n");
391/** What `abso box --json` answers: the record without its credential. */
392export function boxPublic(
393 record: BoxRecord | undefined,
394): { server: string; id: string; grant: Grant; expiresAt: string } | null {
395 return record
396 ? { server: record.server, id: record.id, grant: record.grant, expiresAt: new Date(record.expiresAt).toISOString() }
397 : null;