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