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=261&format=json
392 linesFirst import 32% · box-grants 31% · pinch 17% · trials 11% · review 4% · onboard 3% · Last change onboard in version 224, 18 versions changed it

You're reading version 261. The newest is 318, and 5 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 { findRoot, installKey, readConfig, type Settings, tokenFor, writeConfig } from "./config.ts";
23import { elsewhereText } from "./doctor.ts";
24import { fromEnv } from "./env-names.ts";
25import { clearKnown, loadIgnore, readFolder, writeKnown } from "./folder.ts";
26import { modInstalled } from "./install.ts";
27import { type FullMode, foldModes, writeKnownModes } from "./modes.ts";
28import { initInOrg, siteOf } from "./orgs.ts";
29import { projectFileName, readProjectFile, startingProjectFileText, writeStartingProjectFile } from "./project-file.ts";
30import { refusedText } from "./safety.ts";
31import { chooseServer, serverFlag } from "./server-choice.ts";
32import { OLD_STATE_DIR, STATE_DIR, stateDir } from "./state-dir.ts";
34/** The server to join or start on, in the order every command picks one (server-choice.ts chooseServer). */
35export function serverFrom(args: Parsed, env: Pick<Env, "env" | "cwd">): string {
36 return chooseServer(serverFlag(args), env.cwd, env.env);
39const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
41function agentFrom(args: Parsed, named?: string): string {
42 const agent = named ?? str(args, "agent");
43 if (!agent) throw new UsageError("give this folder's agent name with --agent <name>");
44 if (!NAME.test(agent))
45 throw new UsageError(`agent names are letters, digits, dot, dash and underscore (got ${JSON.stringify(agent)})`);
46 return agent;
49function makeSettings(args: Parsed, env: Env, project: string): Settings {
50 return { server: serverFrom(args, env), project, agent: agentFrom(args) };
53/**
54 * A new project has nothing in it yet: say what comes next, since the join itself wrote nothing. Not for a reader, which
55 * can't push, or when files were already in the folder (the join's own line names them).
56 */
57export function emptyHint(version: number, written: number, kept: number, reader: boolean): string[] {
58 if (reader || version !== 0 || written > 0 || kept > 0) return [];
59 return ['The project is empty. Put its files in this folder, then abso push -m "why" publishes them.'];
62export async function runInit(args: Parsed, env: Env): Promise<Output> {
63 if (args.positionals.length > 1) throw new UsageError("init takes one folder");
64 const root = resolve(env.cwd, args.positionals[0] ?? ".");
65 if (!existsSync(root) || !statSync(root).isDirectory()) throw new UsageError(`${root} is not a folder`);
66 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
67 const project = str(args, "project");
68 if (!project) throw new UsageError("give the project a name with --project <name>");
69 if (bool(args, "public") && bool(args, "private")) throw new UsageError("--public or --private, not both");
70 // A box signed in here, and no token for this server: the project is made as the person who approved the box,
71 // the way the website makes one (abso 663).
72 const server = serverFrom(args, env);
73 const box = readBox(server);
74 if (box && !tokenFor(server, env.env) && !fromEnv(env.env, "KEY_FILE"))
75 return initFromBox(args, env, root, project, server, box);
76 const org = str(args, "org");
77 if (org !== undefined) return initInOrg(org, server);
78 const config = makeSettings(args, env, project);
79 const asIs = bool(args, "as-is");
80 const absoignore = join(root, ".absoignore");
81 const wroteIgnore = !asIs && !existsSync(absoignore) && !existsSync(join(root, ".avcsignore"));
82 if (wroteIgnore) writeFileSync(absoignore, STARTING_ABSOIGNORE);
83 // What the server runs on each new version (#39), guessed from package.json; recorded with the rest.
84 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root);
85 const { files, blobs, modes, leftOut } = readFolder(root, loadIgnore(root));
86 const token = tokenFor(config.server, env.env);
87 const api = new Api({ ...config, ...(token ? { token } : {}) });
88 await uploadBlobs(api, blobs);
89 const answer = await api.init(
90 Object.fromEntries(files),
91 modes,
92 Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),
93 );
94 writeConfig(root, config);
95 clearKnown(root);
96 for (const [rel, text] of files) writeKnown(root, rel, text);
97 writeKnownBlobs(root, new Map([...blobs].map(([rel, b]) => [rel, b.sha])));
98 const knownModes = new Map<string, FullMode>();
99 foldModes(knownModes, modes);
100 writeKnownModes(root, knownModes);
101 const synced = await syncFolder(root, api);
102 return {
103 text: [
104 `Created project ${project} at version ${answer.version} from ${plural(files.size, "text file")} in ${root}.`,
105 ...leftOutText(leftOut),
106 ...(wroteIgnore
107 ? ["Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore."]
108 : []),
109 ...startingProjectFileText(wroteProject),
110 ...(answer.skipped && answer.skipped.length > 0 ? [`The server skipped: ${answer.skipped.join(", ")}.`] : []),
111 `This folder is agent ${config.agent}. Settings are in .abso/config.json.`,
112 ...refusedText(synced.refused),
113 ...(synced.kept.length > 0 ? [`Kept your copy of ${synced.kept.join(", ")}.`] : []),
114 hookHint(env.env),
115 ].join("\n"),
116 json: {
117 project,
118 version: answer.version,
119 files: files.size,
120 root,
121 agent: config.agent,
122 wroteAbsoignore: wroteIgnore,
123 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject,
124 leftOut,
125 },
126 };
129/** 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. */
130const BOX_INIT_MAX = 24 * 1024 * 1024;
131/** The Idempotency-Key of an abso init that didn't finish, so running it again makes the same project (abso 663). */
132const INIT_KEY = "init-key";
134/**
135 * abso init from a signed-in box (abso 663): the server makes the project as the person who approved the box, the way the
136 * website's New project does (owner, visibility, address), with the folder as its first version. This folder then
137 * joins it like abso join, with its own key from the box, so it works at once with no new approval.
138 */
139async function initFromBox(
140 args: Parsed,
141 env: Env,
142 root: string,
143 project: string,
144 server: string,
145 box: BoxRecord,
146): Promise<Output> {
147 if (!NAME.test(project))
148 throw new UsageError(
149 `project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`,
150 );
151 const named = str(args, "agent");
152 if (named !== undefined) agentFrom(args);
153 const asIs = bool(args, "as-is");
154 const absoignore = join(root, ".absoignore");
155 const wroteIgnore = !asIs && !existsSync(absoignore) && !existsSync(join(root, ".avcsignore"));
156 if (wroteIgnore) writeFileSync(absoignore, STARTING_ABSOIGNORE);
157 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root);
158 const { files, blobs, leftOut } = readFolder(root, loadIgnore(root));
159 const listed: NonNullable<NewProject["files"]>[number][] = [
160 ...[...files].map(([path, text]) => ({ path, text })),
161 ...[...blobs].map(([path, b]) => ({ path, base64: Buffer.from(b.bytes).toString("base64") })),
162 ];
163 const org = str(args, "org");
164 const body: NewProject = {
165 name: project,
166 ...(org === undefined ? {} : { owner: org }),
167 ...(bool(args, "public")
168 ? { visibility: "public" as const }
169 : bool(args, "private")
170 ? { visibility: "private" as const }
171 : {}),
172 ...(listed.length > 0 ? { files: listed } : {}),
173 };
174 if (JSON.stringify(body).length > BOX_INIT_MAX)
175 throw new UsageError(
176 `${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.`,
177 );
178 // One key per folder until it finishes: running the same abso init again is the same project, never a second.
179 const keyPath = join(stateDir(root), INIT_KEY);
180 let key = existsSync(keyPath) ? readFileSync(keyPath, "utf8").trim() : "";
181 if (!/^[0-9a-f-]{36}$/.test(key)) {
182 key = randomUUID();
183 mkdirSync(stateDir(root), { recursive: true });
184 writeFileSync(keyPath, key);
185 }
186 const made = await boxCreateProject(box, body, key);
187 const visibility = typeof made.visibility === "string" ? made.visibility : "private";
188 const minted =
189 named !== undefined
190 ? { ...(await mintKey(box, project, named)), agent: named }
191 : await mintFreeName(box, project, defaultAgentName());
192 const config = { server, project, agent: minted.agent };
193 writeConfig(root, config);
194 clearKnown(root);
195 installKey(root, JSON.stringify({ key: minted.key, id: minted.id }));
196 rmSync(keyPath, { force: true });
197 const synced = await syncFolder(root, new Api(readConfig(root, env.env)), true);
198 const owner = org ?? "you";
199 return {
200 text: [
201 `Created project ${project} (${visibility}, owned by ${owner}) at version ${synced.version} from ${plural(listed.length, "file")} in ${root}.`,
202 ...leftOutText(leftOut),
203 ...(wroteIgnore
204 ? ["Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore."]
205 : []),
206 ...startingProjectFileText(wroteProject),
207 `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.`,
208 ...refusedText(synced.refused),
209 ...(synced.written.length > 0 ? [`Wrote ${plural(synced.written.length, "file")} from shared.`] : []),
210 hookHint(env.env),
211 ].join("\n"),
212 json: {
213 project,
214 id: made.id ?? null,
215 owner: made.owner ?? null,
216 visibility,
217 version: synced.version,
218 files: listed.length,
219 root,
220 agent: minted.agent,
221 key_id: minted.id,
222 wroteAbsoignore: wroteIgnore,
223 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject,
224 leftOut,
225 },
226 };
229/**
230 * Where abso join writes: --dir, else here when --agent is given (as before, so a folder prepared with
231 * abso key install --server is joined where its key is). With no --agent: here when this folder is empty, else
232 * ./<project>, which has to be new or empty so nobody's files are written over. A folder holding only abso's own
233 * state folder counts as empty.
234 */
235export function joinFolder(args: Parsed, env: Pick<Env, "cwd">, project: string): string {
236 const dir = str(args, "dir");
237 if (dir !== undefined) return resolve(env.cwd, dir);
238 if (str(args, "agent") !== undefined) return resolve(env.cwd);
239 const empty = (path: string) => readdirSync(path).every((name) => name === STATE_DIR || name === OLD_STATE_DIR);
240 if (empty(env.cwd)) return resolve(env.cwd);
241 const sub = resolve(env.cwd, project);
242 if (existsSync(sub) && (!statSync(sub).isDirectory() || !empty(sub)))
243 throw new UsageError(`${sub} already has files in it: say where to join with --dir <folder>`);
244 return sub;
247/** Signed out, the server doesn't say who owns a project, and the website puts every project under this one owner for now. */
248const SITE_OWNER = "christopher";
250/**
251 * Whether anyone can read the project: its status answers with no credentials. Only the answer's code
252 * counts, never its body, and no redirect is followed. A private project and a missing one look the same.
253 */
254export async function isPublic(server: string, project: string): Promise<boolean> {
255 try {
256 const response = await fetch(new URL(`/p/${encodeURIComponent(project)}/status`, server), {
257 redirect: "error",
258 signal: AbortSignal.timeout(3000),
259 });
260 return response.status === 200;
261 } catch {
262 return false;
263 }
266/**
267 * Why a join failed signed out. Without --reader, the client reads only as an agent, which needs a
268 * sign-in; a public project is read signed out on the website, or with abso join --reader.
269 */
270async function signedOut(server: string, project: string): Promise<string> {
271 return (await isPublic(server, project))
272 ? `${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.`
273 : `This box isn't signed in to ${server}. abso login signs it in.${elsewhereText(server, `abso join ${project}`)}`;
276/** A folder that reads a public project signed out: no agent, no key, no copy of the files. */
277async function joinAsVisitor(root: string, server: string, project: string, env: Env): Promise<Output> {
278 writeConfig(root, { server, project, agent: "", visitor: true });
279 const api = new Api(readConfig(root, env.env));
280 let version: number;
281 try {
282 version = (await api.status()).version;
283 } catch (error) {
284 rmSync(stateDir(root), { recursive: true, force: true });
285 throw error;
286 }
287 return {
288 text: [
289 `Joined ${project} to read it signed out, at version ${version}, in ${root}. Nothing is sent with a sign-in, and nothing here is recorded.`,
290 `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.`,
291 `To work on ${project}: abso login, then abso join ${project} in a new folder.`,
292 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),
293 ].join("\n"),
294 json: { project, visitor: true, version, root },
295 };
298export async function runJoin(args: Parsed, env: Env): Promise<Output> {
299 if (args.positionals.length !== 1) throw new UsageError("join takes the project name: abso join <project>");
300 const project = args.positionals[0]!;
301 if (!NAME.test(project))
302 throw new UsageError(
303 `project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`,
304 );
305 const root = joinFolder(args, env, project);
306 mkdirSync(root, { recursive: true });
307 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
308 const reader = bool(args, "reader");
309 const server = serverFrom(args, env);
310 const box = readBox(server);
311 const hasKey = existsSync(join(stateDir(root), "key"));
312 let agent: string;
313 let minted: { key: string; id: string } | undefined;
314 if (str(args, "agent") !== undefined) {
315 agent = agentFrom(args);
316 minted = box && !hasKey && !fromEnv(env.env, "KEY_FILE") ? await mintKey(box, project, agent) : undefined;
317 } else if (fromEnv(env.env, "KEY_FILE")) {
318 // A pipeline run's key (ABSO_KEY_FILE) belongs to one agent, which the runner names in ABSO_AGENT.
319 const named = fromEnv(env.env, "AGENT");
320 if (!named)
321 throw new UsageError("a pipeline run's key joins as its own agent: give it with --agent <name> or ABSO_AGENT");
322 agent = agentFrom(args, named);
323 } else {
324 // No --agent: the box's name, or the next free -2, -3. Not signed in, --reader reads a public project signed out.
325 if (!box && reader && !hasKey && (await isPublic(server, project)))
326 return joinAsVisitor(root, server, project, env);
327 if (!box)
328 throw new UsageError(
329 `${await signedOut(server, project)} (A folder that already has a key joins with --agent <name>.)`,
330 );
331 if (hasKey) throw new UsageError(`${root} already has a key: give its agent's name with --agent <name>`);
332 const free = await mintFreeName(box, project, defaultAgentName());
333 agent = free.agent;
334 minted = { key: free.key, id: free.id };
335 }
336 const config = { server, project, agent, ...(reader ? { reader: true } : {}) };
337 writeConfig(root, config);
338 clearKnown(root);
339 if (minted) installKey(root, JSON.stringify(minted));
340 const settings = readConfig(root, env.env);
341 const api = new Api(settings);
342 let synced: Awaited<ReturnType<typeof syncFolder>>;
343 try {
344 // Before the sync, so the server never takes a record from this folder.
345 if (reader) await api.reader(true);
346 // Every file, even when the server has seen this agent sync before: its plain sync answer would hold only what changed since (#37).
347 synced = await syncFolder(root, api, true);
348 } catch (error) {
349 if (!(error instanceof ApiError && error.status === 401 && !box && !settings.token)) throw error;
350 rmSync(stateDir(root), { recursive: true, force: true });
351 throw new UsageError(await signedOut(config.server, project));
352 }
353 return {
354 text: [
355 `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.` : ""}`,
356 ...refusedText(synced.refused),
357 ...(synced.kept.length > 0
358 ? [
359 `These files were already here and differ from shared, so they were left alone: ${synced.kept.join(", ")}. abso record sends them as your changes.`,
360 ]
361 : []),
362 ...emptyHint(synced.version, synced.written.length, synced.kept.length, reader),
363 ...setupHint(root),
364 hookHint(env.env),
365 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),
366 ].join("\n"),
367 json: {
368 project,
369 agent: config.agent,
370 version: synced.version,
371 written: synced.written,
372 kept: synced.kept,
373 refused: synced.refused,
374 root,
375 },
376 };
379/** What to run before building or testing here (#43): a joined folder has the project's files, not what avcs.json's setup installs. */
380function setupHint(root: string): string[] {
381 const read = readProjectFile(root);
382 const setup = read !== null && "file" in read ? read.file.setup : "";
383 return setup === ""
384 ? []
385 : [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`];
388function hookHint(env: Readonly<Record<string, string | undefined>>): string {
389 return modInstalled(env)
390 ? "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record."
391 : `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.`;