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=90&format=json
265 linesFirst import 49% · pinch 23% · trials 22% · review 6% · infra-split 1%Last change pinch in version 87, 13 versions changed it

You're reading version 90. The newest is 318, and 10 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 { existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
4import { join, relative, resolve } from "node:path";
5import { Api, ApiError } from "./api.ts";
6import { bool, type Parsed, str, UsageError } from "./args.ts";
7import { writeKnownBlobs } from "./blobs.ts";
8import { defaultAgentName, mintFreeName, mintKey, readBox, signedInServers } from "./box.ts";
9import { STARTING_ABSOIGNORE } from "./check-ignore.ts";
10import { CLIENT_DIR } from "./client-version.ts";
11import { type Env, type Output, plural } from "./command-env.ts";
12import { leftOutText, syncFolder, uploadBlobs } from "./commands.ts";
13import { findRoot, installKey, readConfig, type Settings, tokenFor, writeConfig } from "./config.ts";
14import { TOKEN_SERVERS } from "./core.ts";
15import { fromEnv } from "./env-names.ts";
16import { clearKnown, loadIgnore, readFolder, writeKnown } from "./folder.ts";
17import { modInstalled } from "./install.ts";
18import { type FullMode, foldModes, writeKnownModes } from "./modes.ts";
19import { siteOf } from "./orgs.ts";
20import { projectFileName, readProjectFile, startingProjectFileText, writeStartingProjectFile } from "./project-file.ts";
21import { refusedText } from "./safety.ts";
22import { OLD_STATE_DIR, STATE_DIR, stateDir } from "./state-dir.ts";
24/**
25 * The server to join or start on: --server, then ABSO_SERVER, then the server this box is signed in
26 * to (abso login wrote it), then https://api.abso.dev. A box signed in to more than one server has to say which.
27 */
28export function serverFrom(args: Parsed, env: Pick<Env, "env">, home?: string): string {
29 const named = str(args, "server") ?? fromEnv(env.env, "SERVER");
30 if (named) return named;
31 const signedIn = signedInServers(home);
32 if (signedIn.length > 1)
33 throw new UsageError(`this box is signed in to ${signedIn.join(" and ")}: say which with --server <url>`);
34 return signedIn[0] ?? TOKEN_SERVERS[0]!;
37const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
39function agentFrom(args: Parsed): string {
40 const agent = str(args, "agent");
41 if (!agent) throw new UsageError("give this folder's agent name with --agent <name>");
42 if (!NAME.test(agent))
43 throw new UsageError(`agent names are letters, digits, dot, dash and underscore (got ${JSON.stringify(agent)})`);
44 return agent;
47function makeSettings(args: Parsed, env: Env, project: string): Settings {
48 return { server: serverFrom(args, env), project, agent: agentFrom(args) };
51export async function runInit(args: Parsed, env: Env): Promise<Output> {
52 if (args.positionals.length > 1) throw new UsageError("init takes one folder");
53 const root = resolve(env.cwd, args.positionals[0] ?? ".");
54 if (!existsSync(root) || !statSync(root).isDirectory()) throw new UsageError(`${root} is not a folder`);
55 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
56 const project = str(args, "project");
57 if (!project) throw new UsageError("give the project a name with --project <name>");
58 const config = makeSettings(args, env, project);
59 const asIs = bool(args, "as-is");
60 const absoignore = join(root, ".absoignore");
61 const wroteIgnore = !asIs && !existsSync(absoignore) && !existsSync(join(root, ".avcsignore"));
62 if (wroteIgnore) writeFileSync(absoignore, STARTING_ABSOIGNORE);
63 // What the server runs on each new version (#39), guessed from package.json; recorded with the rest.
64 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root);
65 const { files, blobs, modes, leftOut } = readFolder(root, loadIgnore(root));
66 const token = tokenFor(config.server, env.env);
67 const api = new Api({ ...config, ...(token ? { token } : {}) });
68 await uploadBlobs(api, blobs);
69 const answer = await api.init(
70 Object.fromEntries(files),
71 modes,
72 Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),
73 );
74 writeConfig(root, config);
75 clearKnown(root);
76 for (const [rel, text] of files) writeKnown(root, rel, text);
77 writeKnownBlobs(root, new Map([...blobs].map(([rel, b]) => [rel, b.sha])));
78 const knownModes = new Map<string, FullMode>();
79 foldModes(knownModes, modes);
80 writeKnownModes(root, knownModes);
81 const synced = await syncFolder(root, api);
82 return {
83 text: [
84 `Created project ${project} at version ${answer.version} from ${plural(files.size, "text file")} in ${root}.`,
85 ...leftOutText(leftOut),
86 ...(wroteIgnore
87 ? ["Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore."]
88 : []),
89 ...startingProjectFileText(wroteProject),
90 ...(answer.skipped && answer.skipped.length > 0 ? [`The server skipped: ${answer.skipped.join(", ")}.`] : []),
91 `This folder is agent ${config.agent}. Settings are in .abso/config.json.`,
92 ...refusedText(synced.refused),
93 ...(synced.kept.length > 0 ? [`Kept your copy of ${synced.kept.join(", ")}.`] : []),
94 hookHint(env.env),
95 ].join("\n"),
96 json: {
97 project,
98 version: answer.version,
99 files: files.size,
100 root,
101 agent: config.agent,
102 wroteAbsoignore: wroteIgnore,
103 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject,
104 leftOut,
105 },
106 };
109/**
110 * Where abso join writes: --dir, else here when --agent is given (as before, so a folder prepared with
111 * abso key install --server is joined where its key is). With no --agent: here when this folder is empty, else
112 * ./<project>, which has to be new or empty so nobody's files are written over. A folder holding only abso's own
113 * state folder counts as empty.
114 */
115export function joinFolder(args: Parsed, env: Pick<Env, "cwd">, project: string): string {
116 const dir = str(args, "dir");
117 if (dir !== undefined) return resolve(env.cwd, dir);
118 if (str(args, "agent") !== undefined) return resolve(env.cwd);
119 const empty = (path: string) => readdirSync(path).every((name) => name === STATE_DIR || name === OLD_STATE_DIR);
120 if (empty(env.cwd)) return resolve(env.cwd);
121 const sub = resolve(env.cwd, project);
122 if (existsSync(sub) && (!statSync(sub).isDirectory() || !empty(sub)))
123 throw new UsageError(`${sub} already has files in it: say where to join with --dir <folder>`);
124 return sub;
127/** Signed out, the server doesn't say who owns a project, and the website puts every project under this one owner for now. */
128const SITE_OWNER = "christopher";
130/**
131 * Whether anyone can read the project: its status answers with no credentials. Only the answer's code
132 * counts, never its body, and no redirect is followed. A private project and a missing one look the same.
133 */
134export async function isPublic(server: string, project: string): Promise<boolean> {
135 try {
136 const response = await fetch(new URL(`/p/${encodeURIComponent(project)}/status`, server), {
137 redirect: "error",
138 signal: AbortSignal.timeout(3000),
139 });
140 return response.status === 200;
141 } catch {
142 return false;
143 }
146/**
147 * Why a join failed signed out. Without --reader, the client reads only as an agent, which needs a
148 * sign-in; a public project is read signed out on the website, or with abso join --reader.
149 */
150async function signedOut(server: string, project: string): Promise<string> {
151 return (await isPublic(server, project))
152 ? `${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.`
153 : `This box isn't signed in to ${server}. abso login signs it in.`;
156/** A folder that reads a public project signed out: no agent, no key, no copy of the files. */
157async function joinAsVisitor(root: string, server: string, project: string, env: Env): Promise<Output> {
158 writeConfig(root, { server, project, agent: "", visitor: true });
159 const api = new Api(readConfig(root, env.env));
160 let version: number;
161 try {
162 version = (await api.status()).version;
163 } catch (error) {
164 rmSync(stateDir(root), { recursive: true, force: true });
165 throw error;
166 }
167 return {
168 text: [
169 `Joined ${project} to read it signed out, at version ${version}, in ${root}. Nothing is sent with a sign-in, and nothing here is recorded.`,
170 `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.`,
171 `To work on ${project}: abso login, then abso join ${project} in a new folder.`,
172 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),
173 ].join("\n"),
174 json: { project, visitor: true, version, root },
175 };
178export async function runJoin(args: Parsed, env: Env): Promise<Output> {
179 if (args.positionals.length !== 1) throw new UsageError("join takes the project name: abso join <project>");
180 const project = args.positionals[0]!;
181 if (!NAME.test(project))
182 throw new UsageError(
183 `project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`,
184 );
185 const root = joinFolder(args, env, project);
186 mkdirSync(root, { recursive: true });
187 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
188 const reader = bool(args, "reader");
189 const server = serverFrom(args, env);
190 const box = readBox(server);
191 const hasKey = existsSync(join(stateDir(root), "key"));
192 let agent: string;
193 let minted: { key: string; id: string } | undefined;
194 if (str(args, "agent") !== undefined) {
195 agent = agentFrom(args);
196 minted = box && !hasKey ? await mintKey(box, project, agent) : undefined;
197 } else {
198 // No --agent: the box's name, or the next free -2, -3. Not signed in, --reader reads a public project signed out.
199 if (!box && reader && !hasKey && (await isPublic(server, project)))
200 return joinAsVisitor(root, server, project, env);
201 if (!box)
202 throw new UsageError(
203 `${await signedOut(server, project)} (A folder that already has a key joins with --agent <name>.)`,
204 );
205 if (hasKey) throw new UsageError(`${root} already has a key: give its agent's name with --agent <name>`);
206 const free = await mintFreeName(box, project, defaultAgentName());
207 agent = free.agent;
208 minted = { key: free.key, id: free.id };
209 }
210 const config = { server, project, agent, ...(reader ? { reader: true } : {}) };
211 writeConfig(root, config);
212 clearKnown(root);
213 if (minted) installKey(root, JSON.stringify(minted));
214 const settings = readConfig(root, env.env);
215 const api = new Api(settings);
216 let synced: Awaited<ReturnType<typeof syncFolder>>;
217 try {
218 // Before the sync, so the server never takes a record from this folder.
219 if (reader) await api.reader(true);
220 // Every file, even when the server has seen this agent sync before: its plain sync answer would hold only what changed since (#37).
221 synced = await syncFolder(root, api, true);
222 } catch (error) {
223 if (!(error instanceof ApiError && error.status === 401 && !box && !settings.token)) throw error;
224 rmSync(stateDir(root), { recursive: true, force: true });
225 throw new UsageError(await signedOut(config.server, project));
226 }
227 return {
228 text: [
229 `Joined ${project} as ${config.agent} at version ${synced.version}: wrote ${plural(synced.written.length, "file")} into ${root}.${reader ? " It is a reader: status, sync, log, show, files and export work, and nothing it does is recorded or published." : ""}${minted ? ` It signs in with its own key, ${minted.id}, made from this box's sign-in.` : ""}`,
230 ...refusedText(synced.refused),
231 ...(synced.kept.length > 0
232 ? [
233 `These files were already here and differ from shared, so they were left alone: ${synced.kept.join(", ")}. abso record sends them as your changes.`,
234 ]
235 : []),
236 ...setupHint(root),
237 hookHint(env.env),
238 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),
239 ].join("\n"),
240 json: {
241 project,
242 agent: config.agent,
243 version: synced.version,
244 written: synced.written,
245 kept: synced.kept,
246 refused: synced.refused,
247 root,
248 },
249 };
252/** What to run before building or testing here (#43): a joined folder has the project's files, not what avcs.json's setup installs. */
253function setupHint(root: string): string[] {
254 const read = readProjectFile(root);
255 const setup = read !== null && "file" in read ? read.file.setup : "";
256 return setup === ""
257 ? []
258 : [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`];
261function hookHint(env: Readonly<Record<string, string | undefined>>): string {
262 return modInstalled(env)
263 ? "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record."
264 : `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.`;