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=79&format=json
231 linesFirst import 56% · trials 26% · pinch 11% · review 7% · infra-split 1%Last change pinch in version 70, 11 versions changed it

You're reading version 79. The newest is 318, and 12 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 * Why a join failed signed out. The client reads only as an agent, which needs a
132 * sign-in; a public project is read signed out on the website. Whether the
133 * project is public is asked of the server with no credentials.
134 */
135async function signedOut(server: string, project: string): Promise<string> {
136 let open = false;
137 try {
138 const response = await fetch(new URL(`/p/${project}/status`, server), { signal: AbortSignal.timeout(3000) });
139 open = response.ok;
140 } catch {}
141 return open
142 ? `${project} is public: read it at ${siteOf(server)}/${SITE_OWNER}/${project} (every page is also JSON). The client needs a sign-in, even to read: abso login.`
143 : `This box isn't signed in to ${server}. abso login signs it in.`;
146export async function runJoin(args: Parsed, env: Env): Promise<Output> {
147 if (args.positionals.length !== 1) throw new UsageError("join takes the project name: abso join <project>");
148 const project = args.positionals[0]!;
149 if (!NAME.test(project))
150 throw new UsageError(
151 `project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`,
152 );
153 const root = joinFolder(args, env, project);
154 mkdirSync(root, { recursive: true });
155 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
156 const reader = bool(args, "reader");
157 const server = serverFrom(args, env);
158 const box = readBox(server);
159 const hasKey = existsSync(join(stateDir(root), "key"));
160 let agent: string;
161 let minted: { key: string; id: string } | undefined;
162 if (str(args, "agent") !== undefined) {
163 agent = agentFrom(args);
164 minted = box && !hasKey ? await mintKey(box, project, agent) : undefined;
165 } else {
166 // No --agent: the box's name, or the next free -2, -3.
167 if (!box)
168 throw new UsageError(
169 `${await signedOut(server, project)} (A folder that already has a key joins with --agent <name>.)`,
170 );
171 if (hasKey) throw new UsageError(`${root} already has a key: give its agent's name with --agent <name>`);
172 const free = await mintFreeName(box, project, defaultAgentName());
173 agent = free.agent;
174 minted = { key: free.key, id: free.id };
175 }
176 const config = { server, project, agent, ...(reader ? { reader: true } : {}) };
177 writeConfig(root, config);
178 clearKnown(root);
179 if (minted) installKey(root, JSON.stringify(minted));
180 const settings = readConfig(root, env.env);
181 const api = new Api(settings);
182 let synced: Awaited<ReturnType<typeof syncFolder>>;
183 try {
184 // Before the sync, so the server never takes a record from this folder.
185 if (reader) await api.reader(true);
186 // Every file, even when the server has seen this agent sync before: its plain sync answer would hold only what changed since (#37).
187 synced = await syncFolder(root, api, true);
188 } catch (error) {
189 if (!(error instanceof ApiError && error.status === 401 && !box && !settings.token)) throw error;
190 rmSync(stateDir(root), { recursive: true, force: true });
191 throw new UsageError(await signedOut(config.server, project));
192 }
193 return {
194 text: [
195 `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.` : ""}`,
196 ...refusedText(synced.refused),
197 ...(synced.kept.length > 0
198 ? [
199 `These files were already here and differ from shared, so they were left alone: ${synced.kept.join(", ")}. abso record sends them as your changes.`,
200 ]
201 : []),
202 ...setupHint(root),
203 hookHint(env.env),
204 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),
205 ].join("\n"),
206 json: {
207 project,
208 agent: config.agent,
209 version: synced.version,
210 written: synced.written,
211 kept: synced.kept,
212 refused: synced.refused,
213 root,
214 },
215 };
218/** What to run before building or testing here (#43): a joined folder has the project's files, not what avcs.json's setup installs. */
219function setupHint(root: string): string[] {
220 const read = readProjectFile(root);
221 const setup = read !== null && "file" in read ? read.file.setup : "";
222 return setup === ""
223 ? []
224 : [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`];
227function hookHint(env: Readonly<Record<string, string | undefined>>): string {
228 return modInstalled(env)
229 ? "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record."
230 : `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.`;