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 75 to 76

Compare

+316 −0 in 1 place
new file, 316 lines
1+// abso whoami and abso doctor: who and where this box and folder are signed in, and a check of each thing
2+// a command needs (Node, the server, the box's sign-in, the folder's key), one line each, with the next step
3+// when one fails. Neither prints a credential. plainError words the commonest failures the same way.
4+
5+import { ApiError } from "./api-error.ts";
6+import { type Answer, type BoxRecord, boxGet, boxText, originOf, readBox } from "./box.ts";
7+import { builtCopy } from "./client-version.ts";
8+import { type Config, credentialLabel, findRoot, readConfig } from "./config.ts";
9+
10+/** The lowest Node major each kind of copy runs on: the npm package is built for 20, a checkout runs its .ts as is. */
11+export function nodeNeeded(built: boolean): number {
12+ return built ? 20 : 24;
13+}
15+/** What whoami and doctor read from outside: the network, the clock, Node's version and the home folder. Tests give their own. */
16+export interface Probe {
17+ readonly fetcher: typeof fetch;
18+ readonly now: number;
19+ readonly node: string;
20+ readonly built: boolean;
21+ readonly home?: string;
22+}
24+export function realProbe(): Probe {
25+ return { fetcher: fetch, now: Date.now(), node: process.versions.node, built: builtCopy() };
26+}
28+/** This folder's settings, or why they can't be read; undefined outside a folder. */
29+function folderOf(
30+ cwd: string,
31+ env: Readonly<Record<string, string | undefined>>,
32+): { root: string; config?: Config; problem?: string } | undefined {
33+ const root = findRoot(cwd);
34+ if (root === undefined) return undefined;
35+ try {
36+ return { root, config: readConfig(root, env) };
37+ } catch (err) {
38+ return { root, problem: err instanceof Error ? err.message : String(err) };
39+ }
40+}
42+const day = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace("T", " ");
44+/** The server's view of this box: GET /box, as the box. */
45+async function serverBox(record: BoxRecord, probe: Probe): Promise<Answer | { unreachable: string }> {
46+ try {
47+ return await boxGet(record, "/box", timed(probe.fetcher, 10_000));
48+ } catch (err) {
49+ return { unreachable: err instanceof Error ? err.message : String(err) };
50+ }
51+}
53+/** fetch with its own, shorter limit: a check that hangs says so rather than waiting out the command's. */
54+function timed(fetcher: typeof fetch, ms: number): typeof fetch {
55+ return ((input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) =>
56+ fetcher(input, { ...init, signal: AbortSignal.timeout(ms) })) as typeof fetch;
57+}
59+function credentialWords(root: string, server: string, env: Readonly<Record<string, string | undefined>>): string {
60+ const c = credentialLabel(root, server, env);
61+ return c.kind === "agent key" ? `the agent key ${c.id}` : c.kind === "shared token" ? "the shared token" : "no key";
62+}
64+export async function whoami(
65+ server: string,
66+ cwd: string,
67+ env: Readonly<Record<string, string | undefined>>,
68+ probe: Probe,
69+): Promise<{ text: string; json: Record<string, unknown> }> {
70+ const lines: string[] = [];
71+ const record = readBox(server, probe.home);
72+ let box: Record<string, unknown> | null = null;
73+ if (!record) {
74+ lines.push(`This box isn't signed in to ${originOf(server)}. Run abso login.`);
75+ } else {
76+ const answer = await serverBox(record, probe);
77+ const [first, ...rest] = boxText(record, server, probe.now).split("\n");
78+ box = {
79+ server: record.server,
80+ id: record.id,
81+ grant: record.grant,
82+ expiresAt: new Date(record.expiresAt).toISOString(),
83+ };
84+ if ("unreachable" in answer) {
85+ lines.push(first!, ...rest, `${originOf(server)} couldn't be reached to confirm it: ${answer.unreachable}`);
86+ box.confirmed = null;
87+ } else if (answer.status === 200 && answer.body.revoked_at == null) {
88+ const by = typeof answer.body.approved_by === "string" ? `, approved by ${answer.body.approved_by}` : "";
89+ lines.push(`${first!.replace(/\.$/, "")}${by}.`, ...rest);
90+ box.confirmed = true;
91+ if (by) box.approvedBy = answer.body.approved_by;
92+ } else {
93+ lines.push(`${originOf(server)} no longer accepts this box's sign-in (signed out or revoked). Run abso login.`);
94+ box.confirmed = false;
95+ }
96+ }
97+ const folder = folderOf(cwd, env);
98+ let here: Record<string, unknown> | null = null;
99+ if (folder?.config) {
100+ const c = folder.config;
101+ const credential = credentialWords(folder.root, c.server, env);
102+ lines.push(
103+ `This folder is agent ${c.agent} in project ${c.project} on ${originOf(c.server)}, with ${credential}${c.reader ? ", as a reader" : ""}.`,
104+ );
105+ here = { root: folder.root, project: c.project, agent: c.agent, server: c.server, credential };
106+ } else if (folder) {
107+ lines.push(`This folder's settings can't be read: ${folder.problem}`);
108+ here = { root: folder.root, problem: folder.problem };
109+ } else {
110+ lines.push("You're not in an abso folder. abso join <project> makes one.");
111+ }
112+ return { text: lines.join("\n"), json: { server: originOf(server), box, folder: here } };
113+}
115+export interface Check {
116+ readonly check: "node" | "server" | "box" | "folder";
117+ /** ok passes, fail needs the next step it gives, skip doesn't apply here. */
118+ readonly result: "ok" | "fail" | "skip";
119+ readonly text: string;
120+}
122+export async function doctor(
123+ server: string,
124+ cwd: string,
125+ env: Readonly<Record<string, string | undefined>>,
126+ probe: Probe,
127+): Promise<Check[]> {
128+ const checks: Check[] = [];
129+ const need = nodeNeeded(probe.built);
130+ const major = Number(probe.node.split(".")[0]);
131+ checks.push(
132+ major >= need
133+ ? { check: "node", result: "ok", text: `Node ${probe.node} (abso needs ${need} or later).` }
134+ : {
135+ check: "node",
136+ result: "fail",
137+ text: `Node ${probe.node} is too old: abso needs ${need} or later. Install a newer Node from nodejs.org.`,
138+ },
139+ );
141+ const folder = folderOf(cwd, env);
142+ // The folder's own server when there is one: it's the one its commands talk to.
143+ const target = folder?.config?.server ?? server;
144+ const origin = originOf(target);
145+ let reachable = false;
146+ const started = Date.now();
147+ try {
148+ const res = await timed(probe.fetcher, 10_000)(`${origin}/version`);
149+ const body = (await res.json().catch(() => ({}))) as { commit?: unknown };
150+ reachable = res.ok;
151+ checks.push(
152+ res.ok
153+ ? {
154+ check: "server",
155+ result: "ok",
156+ text: `${origin} answers${typeof body.commit === "string" ? ` (version ${body.commit.slice(0, 7)})` : ""} in ${Date.now() - started} ms.`,
157+ }
158+ : {
159+ check: "server",
160+ result: "fail",
161+ text: `${origin} answered ${res.status}. It may be down for a moment: try again shortly.`,
162+ },
163+ );
164+ } catch (err) {
165+ const why = err instanceof Error && err.name === "TimeoutError" ? "no answer within 10 s" : plainCause(err);
166+ checks.push({
167+ check: "server",
168+ result: "fail",
169+ text: `Can't reach ${origin}: ${why}. Check your connection${folder?.config ? ", and the server in .abso/config.json" : ""}.`,
170+ });
171+ }
173+ const record = readBox(target, probe.home);
174+ if (!record) {
175+ checks.push({
176+ check: "box",
177+ result: folder?.config ? "skip" : "fail",
178+ text: `This box isn't signed in to ${origin}. ${folder?.config ? "Only abso join needs it; abso login signs it in." : "Run abso login."}`,
179+ });
180+ } else if (record.expiresAt <= probe.now) {
181+ checks.push({
182+ check: "box",
183+ result: "fail",
184+ text: `This box's sign-in expired ${day(record.expiresAt)} UTC. Run abso login.`,
185+ });
186+ } else if (!reachable) {
187+ checks.push({
188+ check: "box",
189+ result: "skip",
190+ text: `Signed in as box ${record.id}; the server can't confirm it now.`,
191+ });
192+ } else {
193+ const answer = await serverBox(record, probe);
194+ checks.push(
195+ "unreachable" in answer
196+ ? { check: "box", result: "skip", text: `Signed in as box ${record.id}; the server can't confirm it now.` }
197+ : answer.status === 200 && answer.body.revoked_at == null
198+ ? {
199+ check: "box",
200+ result: "ok",
201+ text: `Signed in as box ${record.id}, which ${origin} accepts, until ${day(record.expiresAt)} UTC.`,
202+ }
203+ : {
204+ check: "box",
205+ result: "fail",
206+ text: `${origin} no longer accepts this box's sign-in (signed out or revoked). Run abso login.`,
207+ },
208+ );
209+ }
211+ if (!folder) {
212+ checks.push({
213+ check: "folder",
214+ result: "skip",
215+ text: "You're not in an abso folder. abso join <project> makes one.",
216+ });
217+ } else if (!folder.config) {
218+ checks.push({ check: "folder", result: "fail", text: `This folder's settings can't be read: ${folder.problem}` });
219+ } else {
220+ checks.push(await folderCheck(folder.root, folder.config, env, reachable, probe));
221+ }
222+ return checks;
223+}
225+/** The folder's key against its project: GET head, which the server answers only after it has checked the key. */
226+async function folderCheck(
227+ root: string,
228+ c: Config,
229+ env: Readonly<Record<string, string | undefined>>,
230+ reachable: boolean,
231+ probe: Probe,
232+): Promise<Check> {
233+ const who = `agent ${c.agent} in ${c.project}`;
234+ if (!c.token)
235+ return {
236+ check: "folder",
237+ result: "fail",
238+ text: `This folder (${who}) has no key, and there's no shared token. Run abso login, then abso join ${c.project}.`,
239+ };
240+ const credential = credentialWords(root, c.server, env);
241+ if (!reachable)
242+ return {
243+ check: "folder",
244+ result: "skip",
245+ text: `This folder is ${who}, with ${credential}; the server can't check it now.`,
246+ };
247+ let status: number;
248+ try {
249+ const res = await timed(probe.fetcher, 10_000)(
250+ `${c.server.replace(/\/+$/, "")}/p/${encodeURIComponent(c.project)}/head`,
251+ { headers: { authorization: `Bearer ${c.token}` } },
252+ );
253+ status = res.status;
254+ await res.body?.cancel();
255+ } catch {
256+ return {
257+ check: "folder",
258+ result: "skip",
259+ text: `This folder is ${who}, with ${credential}; the server can't check it now.`,
260+ };
261+ }
262+ if (status === 200)
263+ return {
264+ check: "folder",
265+ result: "ok",
266+ text: `This folder is ${who}, with ${credential}, which the server accepts.`,
267+ };
268+ if (status === 404)
269+ return {
270+ check: "folder",
271+ result: "fail",
272+ text: `${originOf(c.server)} has no project ${c.project}. Check the name in .abso/config.json, or abso init makes it.`,
273+ };
274+ if (status === 401 || status === 403)
275+ return {
276+ check: "folder",
277+ result: "fail",
278+ text: `${originOf(c.server)} didn't accept ${credential} for ${c.project}: it may be revoked or expired. Ask the project's owner, or run abso join ${c.project} again from a signed-in box.`,
279+ };
280+ return {
281+ check: "folder",
282+ result: "fail",
283+ text: `${originOf(c.server)} answered ${status} for ${c.project}. Try again shortly.`,
284+ };
285+}
287+export function doctorText(checks: readonly Check[]): string {
288+ return checks.map((c) => `${c.result.padEnd(4)} ${c.text}`).join("\n");
289+}
291+function plainCause(err: unknown): string {
292+ const cause = (err as { cause?: { code?: string; message?: string } }).cause;
293+ if (cause?.code === "ENOTFOUND" || cause?.code === "EAI_AGAIN") return "the address doesn't resolve";
294+ if (cause?.code === "ECONNREFUSED") return "the connection was refused";
295+ return cause?.message ?? (err instanceof Error ? err.message : String(err));
296+}
298+/**
299+ * The commonest failures in plain words, with the next step: no credential, a credential the server refuses, and a
300+ * server that can't be reached. Anything else is left as it was. `signedIn` is whether the call carried a key or token.
301+ */
302+export function plainError(err: unknown, signedIn: boolean): string | undefined {
303+ if (!(err instanceof ApiError)) return undefined;
304+ if (err.status === 401)
305+ return signedIn
306+ ? `The server didn't accept this folder's key: it may be revoked or expired. abso doctor checks it. (${err.message})`
307+ : "You're not signed in. Run abso login, then abso join <project>.";
308+ if (err.status === undefined && err.message.startsWith("could not reach ")) {
309+ const said = err.message.replace(/^could not reach /, "Can't reach ");
310+ // A message that already gives its next step (publish's "Run the same command again.") keeps it as the last word.
311+ return /\bRun\b[^.]*\.$/.test(said)
312+ ? said
313+ : `${said.replace(/\.$/, "")}. Check your connection; abso doctor checks the rest.`;
314+ }
315+ return undefined;
316+}
MCP
compare on this site's /mcp
CLI
abso diff 75 76 client/src/doctor.ts --json
JSON
/christopher/abso-core/compare/75..76?file=client%2Fsrc%2Fdoctor.ts&format=json