- 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=100&format=json
271 linesFirst import 46% · pinch 25% · trials 21% · review 6% · infra-split 1% · rename 1%Last change rename in version 100, 15 versions changed it
You're reading version 100. The newest is 318, and 8 versions since then changed this file.
1// abso init and abso join: start a project from a folder, or join one into a folder.
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]!;
35}
37const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
39function agentFrom(args: Parsed, named?: string): string {
40 const agent = named ?? 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;
45}
47function makeSettings(args: Parsed, env: Env, project: string): Settings {
48 return { server: serverFrom(args, env), project, agent: agentFrom(args) };
49}
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 };
107}
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;
125}
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 }
144}
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.`;
154}
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 };
176}
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 && !fromEnv(env.env, "KEY_FILE") ? await mintKey(box, project, agent) : undefined;
197 } else if (fromEnv(env.env, "KEY_FILE")) {
198 // A pipeline run's key (ABSO_KEY_FILE) belongs to one agent, which the runner names in ABSO_AGENT.
199 const named = fromEnv(env.env, "AGENT");
200 if (!named)
201 throw new UsageError("a pipeline run's key joins as its own agent: give it with --agent <name> or ABSO_AGENT");
202 agent = agentFrom(args, named);
203 } else {
204 // No --agent: the box's name, or the next free -2, -3. Not signed in, --reader reads a public project signed out.
205 if (!box && reader && !hasKey && (await isPublic(server, project)))
206 return joinAsVisitor(root, server, project, env);
207 if (!box)
208 throw new UsageError(
209 `${await signedOut(server, project)} (A folder that already has a key joins with --agent <name>.)`,
210 );
211 if (hasKey) throw new UsageError(`${root} already has a key: give its agent's name with --agent <name>`);
212 const free = await mintFreeName(box, project, defaultAgentName());
213 agent = free.agent;
214 minted = { key: free.key, id: free.id };
215 }
216 const config = { server, project, agent, ...(reader ? { reader: true } : {}) };
217 writeConfig(root, config);
218 clearKnown(root);
219 if (minted) installKey(root, JSON.stringify(minted));
220 const settings = readConfig(root, env.env);
221 const api = new Api(settings);
222 let synced: Awaited<ReturnType<typeof syncFolder>>;
223 try {
224 // Before the sync, so the server never takes a record from this folder.
225 if (reader) await api.reader(true);
226 // Every file, even when the server has seen this agent sync before: its plain sync answer would hold only what changed since (#37).
227 synced = await syncFolder(root, api, true);
228 } catch (error) {
229 if (!(error instanceof ApiError && error.status === 401 && !box && !settings.token)) throw error;
230 rmSync(stateDir(root), { recursive: true, force: true });
231 throw new UsageError(await signedOut(config.server, project));
232 }
233 return {
234 text: [
235 `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.` : ""}`,
236 ...refusedText(synced.refused),
237 ...(synced.kept.length > 0
238 ? [
239 `These files were already here and differ from shared, so they were left alone: ${synced.kept.join(", ")}. abso record sends them as your changes.`,
240 ]
241 : []),
242 ...setupHint(root),
243 hookHint(env.env),
244 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),
245 ].join("\n"),
246 json: {
247 project,
248 agent: config.agent,
249 version: synced.version,
250 written: synced.written,
251 kept: synced.kept,
252 refused: synced.refused,
253 root,
254 },
255 };
256}
258/** What to run before building or testing here (#43): a joined folder has the project's files, not what avcs.json's setup installs. */
259function setupHint(root: string): string[] {
260 const read = readProjectFile(root);
261 const setup = read !== null && "file" in read ? read.file.setup : "";
262 return setup === ""
263 ? []
264 : [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`];
265}
267function hookHint(env: Readonly<Record<string, string | undefined>>): string {
268 return modInstalled(env)
269 ? "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record."
270 : `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.`;
271}