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/join-commands.ts?version=279&format=json
460 linesFirst import 27% · box-grants 26% · readspeed 17% · pinch 14% · trials 10% · review 3% · Last change readspeed in version 268, 19 versions changed it

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

1// abso init and abso join: start a project from a folder, or join one into a folder.
2
3import { randomUUID } from "node:crypto";
4import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
5import { join, relative, resolve } from "node:path";
6import { Api, ApiError } from "./api.ts";
7import { bool, type Parsed, str, UsageError } from "./args.ts";
8import { writeKnownBlobs } from "./blobs.ts";
9import {
10 type BoxRecord,
11 boxCreateProject,
12 defaultAgentName,
13 mintFreeName,
14 mintKey,
15 type NewProject,
16 readBox,
17} from "./box.ts";
18import { STARTING_ABSOIGNORE } from "./check-ignore.ts";
19import { CLIENT_DIR } from "./client-version.ts";
20import { type Env, type Output, plural } from "./command-env.ts";
21import { leftOutText, syncFolder, uploadBlobs } from "./commands.ts";
22import {
23 findRoot,
24 installKey,
25 readConfig,
26 runKey,
27 type Settings,
28 tokenFile,
29 trustedToken,
30 writeConfig,
31} from "./config.ts";
32import { elsewhereText } from "./doctor.ts";
33import { fromEnv } from "./env-names.ts";
34import { clearKnown, loadIgnore, readFolder, writeKnown } from "./folder.ts";
35import { modInstalled } from "./install.ts";
36import { type FullMode, foldModes, writeKnownModes } from "./modes.ts";
37import { initInOrg, siteOf } from "./orgs.ts";
38import { projectFileName, readProjectFile, startingProjectFileText, writeStartingProjectFile } from "./project-file.ts";
39import { refusedText } from "./safety.ts";
40import { chooseServer, serverFlag } from "./server-choice.ts";
41import { OLD_STATE_DIR, STATE_DIR, stateDir } from "./state-dir.ts";
43/** The server to join or start on, in the order every command picks one (server-choice.ts chooseServer). */
44export function serverFrom(args: Parsed, env: Pick<Env, "env" | "cwd">): string {
45 return chooseServer(serverFlag(args), env.cwd, env.env);
48const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
50function agentFrom(args: Parsed, named?: string): string {
51 const agent = named ?? str(args, "agent");
52 if (!agent) throw new UsageError("give this folder's agent name with --agent <name>");
53 if (!NAME.test(agent))
54 throw new UsageError(`agent names are letters, digits, dot, dash and underscore (got ${JSON.stringify(agent)})`);
55 return agent;
58function makeSettings(args: Parsed, env: Env, project: string): Settings {
59 return { server: serverFrom(args, env), project, agent: agentFrom(args) };
62/**
63 * A new project has nothing in it yet: say what comes next, since the join itself wrote nothing. Not for a reader, which
64 * can't push, or when files were already in the folder (the join's own line names them).
65 */
66export function emptyHint(version: number, written: number, kept: number, reader: boolean): string[] {
67 if (reader || version !== 0 || written > 0 || kept > 0) return [];
68 return ['The project is empty. Put its files in this folder, then abso push -m "why" publishes them.'];
71/** A credential other than the box's, and how init and join name it when they say what they sign in with. */
72export interface Credential {
73 readonly token: string | undefined;
74 readonly words: string;
77/**
78 * What init and join sign in with when it isn't the box's sign-in. The machine's token file only with --token-file, and
79 * never into a folder that already has a key; else a token the environment names (ABSO_TOKEN, or a pipeline run's
80 * ABSO_KEY_FILE); else none. The token file is never read unasked, so a project is never made or joined with a shared
81 * credential nobody chose.
82 */
83export function tokenCredential(
84 args: Parsed,
85 env: Env["env"],
86 server: string,
87 root: string,
88 file: () => string | undefined = tokenFile,
89): Credential | undefined {
90 if (bool(args, "token-file")) {
91 if (existsSync(join(stateDir(root), "key")))
92 throw new UsageError(`${root} already has a key, so it signs in with that: leave off --token-file`);
93 const token = trustedToken(server, env, file());
94 if (!token) throw new UsageError("--token-file reads ~/.abso/token, and this machine has none");
95 return { token, words: "the token file, ~/.abso/token, as --token-file asks" };
96 }
97 const named = fromEnv(env, "TOKEN")?.trim();
98 if (named) return { token: trustedToken(server, env, named), words: "ABSO_TOKEN" };
99 const run = runKey(env);
100 if (run) return { token: trustedToken(server, env, run), words: "a pipeline run's key (ABSO_KEY_FILE)" };
101 return undefined;
104/** Why a token file is no fallback: said when one is here and nothing else signs in. */
105const TOKEN_FILE_ASKED = "~/.abso/token is used only with --token-file.";
107export async function runInit(args: Parsed, env: Env): Promise<Output> {
108 if (args.positionals.length > 1) throw new UsageError("init takes one folder");
109 const root = resolve(env.cwd, args.positionals[0] ?? ".");
110 if (!existsSync(root) || !statSync(root).isDirectory()) throw new UsageError(`${root} is not a folder`);
111 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
112 const project = str(args, "project");
113 if (!project) throw new UsageError("give the project a name with --project <name>");
114 if (bool(args, "public") && bool(args, "private")) throw new UsageError("--public or --private, not both");
115 // A box signed in here, and no other credential asked for: the project is made as the person who approved the box,
116 // the way the website makes one (abso 663). The token file only with --token-file, never by itself.
117 const server = serverFrom(args, env);
118 const box = readBox(server);
119 const credential = tokenCredential(args, env.env, server, root);
120 const say = env.writeErr ?? env.write;
121 if (box && credential === undefined) {
122 say(`Signing in with this box's sign-in, ${box.id}.
123`);
124 return initFromBox(args, env, root, project, server, box);
125 }
126 if (credential === undefined && tokenFile() !== undefined)
127 throw new UsageError(
128 `abso init signs in with this box's sign-in, and this box isn't signed in to ${server}: abso login signs it in. ${TOKEN_FILE_ASKED}`,
129 );
130 const org = str(args, "org");
131 if (org !== undefined) return initInOrg(org, server);
132 const config = makeSettings(args, env, project);
133 const asIs = bool(args, "as-is");
134 const absoignore = join(root, ".absoignore");
135 const wroteIgnore = !asIs && !existsSync(absoignore) && !existsSync(join(root, ".avcsignore"));
136 if (wroteIgnore) writeFileSync(absoignore, STARTING_ABSOIGNORE);
137 // What the server runs on each new version (#39), guessed from package.json; recorded with the rest.
138 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root);
139 const { files, blobs, modes, leftOut } = readFolder(root, loadIgnore(root));
140 const token = credential?.token;
141 say(`Signing in with ${credential?.words ?? `no credential: nothing here signs in to ${server}`}.
142`);
143 const api = new Api({ ...config, ...(token ? { token } : {}) });
144 await uploadBlobs(api, blobs);
145 const answer = await api.init(
146 Object.fromEntries(files),
147 modes,
148 Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),
149 );
150 writeConfig(root, config);
151 clearKnown(root);
152 for (const [rel, text] of files) writeKnown(root, rel, text);
153 writeKnownBlobs(root, new Map([...blobs].map(([rel, b]) => [rel, b.sha])));
154 const knownModes = new Map<string, FullMode>();
155 foldModes(knownModes, modes);
156 writeKnownModes(root, knownModes);
157 const synced = await syncFolder(root, api);
158 return {
159 text: [
160 `Created project ${project} at version ${answer.version} from ${plural(files.size, "text file")} in ${root}.`,
161 ...leftOutText(leftOut),
162 ...(wroteIgnore
163 ? ["Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore."]
164 : []),
165 ...startingProjectFileText(wroteProject),
166 ...(answer.skipped && answer.skipped.length > 0 ? [`The server skipped: ${answer.skipped.join(", ")}.`] : []),
167 `This folder is agent ${config.agent}. Settings are in .abso/config.json.`,
168 ...refusedText(synced.refused),
169 ...(synced.kept.length > 0 ? [`Kept your copy of ${synced.kept.join(", ")}.`] : []),
170 hookHint(env.env),
171 ].join("\n"),
172 json: {
173 project,
174 version: answer.version,
175 files: files.size,
176 root,
177 agent: config.agent,
178 wroteAbsoignore: wroteIgnore,
179 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject,
180 leftOut,
181 },
182 };
185/** The most a new project's folder may be from a box: the server takes a body up to 25 MB, base64 and JSON included. */
186const BOX_INIT_MAX = 24 * 1024 * 1024;
187/** The Idempotency-Key of an abso init that didn't finish, so running it again makes the same project (abso 663). */
188const INIT_KEY = "init-key";
190/**
191 * abso init from a signed-in box (abso 663): the server makes the project as the person who approved the box, the way the
192 * website's New project does (owner, visibility, address), with the folder as its first version. This folder then
193 * joins it like abso join, with its own key from the box, so it works at once with no new approval.
194 */
195async function initFromBox(
196 args: Parsed,
197 env: Env,
198 root: string,
199 project: string,
200 server: string,
201 box: BoxRecord,
202): Promise<Output> {
203 if (!NAME.test(project))
204 throw new UsageError(
205 `project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`,
206 );
207 const named = str(args, "agent");
208 if (named !== undefined) agentFrom(args);
209 const asIs = bool(args, "as-is");
210 const absoignore = join(root, ".absoignore");
211 const wroteIgnore = !asIs && !existsSync(absoignore) && !existsSync(join(root, ".avcsignore"));
212 if (wroteIgnore) writeFileSync(absoignore, STARTING_ABSOIGNORE);
213 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root);
214 const { files, blobs, leftOut } = readFolder(root, loadIgnore(root));
215 const listed: NonNullable<NewProject["files"]>[number][] = [
216 ...[...files].map(([path, text]) => ({ path, text })),
217 ...[...blobs].map(([path, b]) => ({ path, base64: Buffer.from(b.bytes).toString("base64") })),
218 ];
219 const org = str(args, "org");
220 const body: NewProject = {
221 name: project,
222 ...(org === undefined ? {} : { owner: org }),
223 ...(bool(args, "public")
224 ? { visibility: "public" as const }
225 : bool(args, "private")
226 ? { visibility: "private" as const }
227 : {}),
228 ...(listed.length > 0 ? { files: listed } : {}),
229 };
230 if (JSON.stringify(body).length > BOX_INIT_MAX)
231 throw new UsageError(
232 `${root} is over 24 MB to send. Make ${project} with abso init on a smaller folder (or on the website), then copy the rest in and push.`,
233 );
234 // One key per folder until it finishes: running the same abso init again is the same project, never a second.
235 const keyPath = join(stateDir(root), INIT_KEY);
236 let key = existsSync(keyPath) ? readFileSync(keyPath, "utf8").trim() : "";
237 if (!/^[0-9a-f-]{36}$/.test(key)) {
238 key = randomUUID();
239 mkdirSync(stateDir(root), { recursive: true });
240 writeFileSync(keyPath, key);
241 }
242 const made = await boxCreateProject(box, body, key);
243 const visibility = typeof made.visibility === "string" ? made.visibility : "private";
244 const minted =
245 named !== undefined
246 ? { ...(await mintKey(box, project, named)), agent: named }
247 : await mintFreeName(box, project, defaultAgentName());
248 const config = { server, project, agent: minted.agent };
249 writeConfig(root, config);
250 clearKnown(root);
251 installKey(root, JSON.stringify({ key: minted.key, id: minted.id }));
252 rmSync(keyPath, { force: true });
253 const synced = await syncFolder(root, new Api(readConfig(root, env.env)), true);
254 const owner = org ?? "you";
255 return {
256 text: [
257 `Created project ${project} (${visibility}, owned by ${owner}) at version ${synced.version} from ${plural(listed.length, "file")} in ${root}.`,
258 ...leftOutText(leftOut),
259 ...(wroteIgnore
260 ? ["Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore."]
261 : []),
262 ...startingProjectFileText(wroteProject),
263 `This folder is agent ${minted.agent}, with its own key, ${minted.id}, made from this box's sign-in. Settings are in .abso/config.json.`,
264 ...refusedText(synced.refused),
265 ...(synced.written.length > 0 ? [`Wrote ${plural(synced.written.length, "file")} from shared.`] : []),
266 hookHint(env.env),
267 ].join("\n"),
268 json: {
269 project,
270 id: made.id ?? null,
271 owner: made.owner ?? null,
272 visibility,
273 version: synced.version,
274 files: listed.length,
275 root,
276 agent: minted.agent,
277 key_id: minted.id,
278 wroteAbsoignore: wroteIgnore,
279 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject,
280 leftOut,
281 },
282 };
285/**
286 * Where abso join writes: --dir, else here when --agent is given (as before, so a folder prepared with
287 * abso key install --server is joined where its key is). With no --agent: here when this folder is empty, else
288 * ./<project>, which has to be new or empty so nobody's files are written over. A folder holding only abso's own
289 * state folder counts as empty.
290 */
291export function joinFolder(args: Parsed, env: Pick<Env, "cwd">, project: string): string {
292 const dir = str(args, "dir");
293 if (dir !== undefined) return resolve(env.cwd, dir);
294 if (str(args, "agent") !== undefined) return resolve(env.cwd);
295 const empty = (path: string) => readdirSync(path).every((name) => name === STATE_DIR || name === OLD_STATE_DIR);
296 if (empty(env.cwd)) return resolve(env.cwd);
297 const sub = resolve(env.cwd, project);
298 if (existsSync(sub) && (!statSync(sub).isDirectory() || !empty(sub)))
299 throw new UsageError(`${sub} already has files in it: say where to join with --dir <folder>`);
300 return sub;
303/** Signed out, the server doesn't say who owns a project, and the website puts every project under this one owner for now. */
304const SITE_OWNER = "christopher";
306/**
307 * Whether anyone can read the project: its status answers with no credentials. Only the answer's code
308 * counts, never its body, and no redirect is followed. A private project and a missing one look the same.
309 */
310export async function isPublic(server: string, project: string): Promise<boolean> {
311 try {
312 const response = await fetch(new URL(`/p/${encodeURIComponent(project)}/status`, server), {
313 redirect: "error",
314 signal: AbortSignal.timeout(3000),
315 });
316 return response.status === 200;
317 } catch {
318 return false;
319 }
322/**
323 * Why a join failed signed out. Without --reader, the client reads only as an agent, which needs a
324 * sign-in; a public project is read signed out on the website, or with abso join --reader.
325 */
326async function signedOut(server: string, project: string): Promise<string> {
327 return (await isPublic(server, project))
328 ? `${project} is public: read it at ${siteOf(server)}/${SITE_OWNER}/${project} (every page is also JSON), or here with abso join ${project} --reader. To work on it: abso login.`
329 : `This box isn't signed in to ${server}. abso login signs it in.${elsewhereText(server, `abso join ${project}`)}`;
332/** A folder that reads a public project signed out: no agent, no key, no copy of the files. */
333async function joinAsVisitor(root: string, server: string, project: string, env: Env): Promise<Output> {
334 writeConfig(root, { server, project, agent: "", visitor: true });
335 const api = new Api(readConfig(root, env.env));
336 let version: number;
337 try {
338 version = (await api.status()).version;
339 } catch (error) {
340 rmSync(stateDir(root), { recursive: true, force: true });
341 throw error;
342 }
343 return {
344 text: [
345 `Joined ${project} to read it signed out, at version ${version}, in ${root}. Nothing is sent with a sign-in, and nothing here is recorded.`,
346 `This folder holds no copy of the files: abso files lists them, abso show ${version}:<file> prints one, and status, log, blame, why, where, issues, issue and search read the rest.`,
347 `To work on ${project}: abso login, then abso join ${project} in a new folder.`,
348 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),
349 ].join("\n"),
350 json: { project, visitor: true, version, root },
351 };
354export async function runJoin(args: Parsed, env: Env): Promise<Output> {
355 if (args.positionals.length !== 1) throw new UsageError("join takes the project name: abso join <project>");
356 const project = args.positionals[0]!;
357 if (!NAME.test(project))
358 throw new UsageError(
359 `project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`,
360 );
361 const root = joinFolder(args, env, project);
362 mkdirSync(root, { recursive: true });
363 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
364 const reader = bool(args, "reader");
365 const server = serverFrom(args, env);
366 const box = readBox(server);
367 const hasKey = existsSync(join(stateDir(root), "key"));
368 const credential = tokenCredential(args, env.env, server, root);
369 const tokenFileAsked = bool(args, "token-file");
370 let agent: string;
371 let minted: { key: string; id: string } | undefined;
372 if (str(args, "agent") !== undefined) {
373 agent = agentFrom(args);
374 minted =
375 box && !hasKey && !fromEnv(env.env, "KEY_FILE") && !tokenFileAsked
376 ? await mintKey(box, project, agent)
377 : undefined;
378 } else if (fromEnv(env.env, "KEY_FILE")) {
379 // A pipeline run's key (ABSO_KEY_FILE) belongs to one agent, which the runner names in ABSO_AGENT.
380 const named = fromEnv(env.env, "AGENT");
381 if (!named)
382 throw new UsageError("a pipeline run's key joins as its own agent: give it with --agent <name> or ABSO_AGENT");
383 agent = agentFrom(args, named);
384 } else {
385 // No --agent: the box's name, or the next free -2, -3. Not signed in, --reader reads a public project signed out.
386 if (!box && reader && !hasKey && (await isPublic(server, project)))
387 return joinAsVisitor(root, server, project, env);
388 if (!box)
389 throw new UsageError(
390 `${await signedOut(server, project)} (A folder that already has a key joins with --agent <name>.)`,
391 );
392 if (hasKey) throw new UsageError(`${root} already has a key: give its agent's name with --agent <name>`);
393 const free = await mintFreeName(box, project, defaultAgentName());
394 agent = free.agent;
395 minted = { key: free.key, id: free.id };
396 }
397 const config = { server, project, agent, ...(reader ? { reader: true } : {}) };
398 writeConfig(root, config);
399 clearKnown(root);
400 if (minted) installKey(root, JSON.stringify(minted));
401 // The token file only with --token-file: readConfig reads it otherwise.
402 const read = readConfig(root, env.env, false);
403 const settings = tokenFileAsked ? { ...read, token: credential?.token } : read;
404 (env.writeErr ?? env.write)(
405 `Signing in with ${minted && box ? `a new key from this box's sign-in, ${box.id}` : hasKey ? "this folder's key" : (credential?.words ?? `no credential: nothing here signs in to ${server}`)}.
406`,
407 );
408 const api = new Api(settings);
409 let synced: Awaited<ReturnType<typeof syncFolder>>;
410 try {
411 // Before the sync, so the server never takes a record from this folder.
412 if (reader) await api.reader(true);
413 // Every file, even when the server has seen this agent sync before: its plain sync answer would hold only what changed since (#37).
414 synced = await syncFolder(root, api, true);
415 } catch (error) {
416 if (!(error instanceof ApiError && error.status === 401 && !box && !settings.token)) throw error;
417 rmSync(stateDir(root), { recursive: true, force: true });
418 const why = await signedOut(config.server, project);
419 throw new UsageError(!tokenFileAsked && tokenFile() !== undefined ? `${why} ${TOKEN_FILE_ASKED}` : why);
420 }
421 return {
422 text: [
423 `Joined ${project} as ${config.agent} at version ${synced.version}: wrote ${plural(synced.written.length, "file")} into ${root}.${reader ? " It is a reader: status, pull, log, show, files and export work, and nothing it does is recorded or pushed." : ""}${minted ? ` It signs in with its own key, ${minted.id}, made from this box's sign-in.` : ""}`,
424 ...refusedText(synced.refused),
425 ...(synced.kept.length > 0
426 ? [
427 `These files were already here and differ from shared, so they were left alone: ${synced.kept.join(", ")}. abso record sends them as your changes.`,
428 ]
429 : []),
430 ...emptyHint(synced.version, synced.written.length, synced.kept.length, reader),
431 ...setupHint(root),
432 hookHint(env.env),
433 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),
434 ].join("\n"),
435 json: {
436 project,
437 agent: config.agent,
438 version: synced.version,
439 written: synced.written,
440 kept: synced.kept,
441 refused: synced.refused,
442 root,
443 },
444 };
447/** What to run before building or testing here (#43): a joined folder has the project's files, not what avcs.json's setup installs. */
448function setupHint(root: string): string[] {
449 const read = readProjectFile(root);
450 const setup = read !== null && "file" in read ? read.file.setup : "";
451 return setup === ""
452 ? []
453 : [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`];
456function hookHint(env: Readonly<Record<string, string | undefined>>): string {
457 return modInstalled(env)
458 ? "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record."
459 : `Edits made by Claude Code reach the server through the abso mod, which isn't on this machine yet: node ${join(CLIENT_DIR, "install-mod.ts")} installs it, and new chats load it. Anything else: abso record.`;