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?version=155&format=json
348 linesspeed 98% · pinch 2%Last change speed in version 155, 4 versions changed it

You're reading version 155. The newest is 318, and 4 versions since then changed this file. Go to the newestCompare with 318

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