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