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=67&format=json
208 linesFirst import 63% · trials 29% · review 8% · infra-split 1%Last change trials in version 64, 9 versions changed it

You're reading version 67. The newest is 318, and 14 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 { projectFileName, readProjectFile, startingProjectFileText, writeStartingProjectFile } from "./project-file.ts";
20import { refusedText } from "./safety.ts";
21import { OLD_STATE_DIR, STATE_DIR, stateDir } from "./state-dir.ts";
23/**
24 * The server to join or start on: --server, then ABSO_SERVER, then the server this box is signed in
25 * to (abso login wrote it), then https://api.abso.dev. A box signed in to more than one server has to say which.
26 */
27export function serverFrom(args: Parsed, env: Pick<Env, "env">, home?: string): string {
28 const named = str(args, "server") ?? fromEnv(env.env, "SERVER");
29 if (named) return named;
30 const signedIn = signedInServers(home);
31 if (signedIn.length > 1)
32 throw new UsageError(`this box is signed in to ${signedIn.join(" and ")}: say which with --server <url>`);
33 return signedIn[0] ?? TOKEN_SERVERS[0]!;
36const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
38function agentFrom(args: Parsed): string {
39 const agent = str(args, "agent");
40 if (!agent) throw new UsageError("give this folder's agent name with --agent <name>");
41 if (!NAME.test(agent))
42 throw new UsageError(`agent names are letters, digits, dot, dash and underscore (got ${JSON.stringify(agent)})`);
43 return agent;
46function makeSettings(args: Parsed, env: Env, project: string): Settings {
47 return { server: serverFrom(args, env), project, agent: agentFrom(args) };
50export async function runInit(args: Parsed, env: Env): Promise<Output> {
51 if (args.positionals.length > 1) throw new UsageError("init takes one folder");
52 const root = resolve(env.cwd, args.positionals[0] ?? ".");
53 if (!existsSync(root) || !statSync(root).isDirectory()) throw new UsageError(`${root} is not a folder`);
54 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
55 const project = str(args, "project");
56 if (!project) throw new UsageError("give the project a name with --project <name>");
57 const config = makeSettings(args, env, project);
58 const asIs = bool(args, "as-is");
59 const absoignore = join(root, ".absoignore");
60 const wroteIgnore = !asIs && !existsSync(absoignore) && !existsSync(join(root, ".avcsignore"));
61 if (wroteIgnore) writeFileSync(absoignore, STARTING_ABSOIGNORE);
62 // What the server runs on each new version (#39), guessed from package.json; recorded with the rest.
63 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root);
64 const { files, blobs, modes, leftOut } = readFolder(root, loadIgnore(root));
65 const token = tokenFor(config.server, env.env);
66 const api = new Api({ ...config, ...(token ? { token } : {}) });
67 await uploadBlobs(api, blobs);
68 const answer = await api.init(
69 Object.fromEntries(files),
70 modes,
71 Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),
72 );
73 writeConfig(root, config);
74 clearKnown(root);
75 for (const [rel, text] of files) writeKnown(root, rel, text);
76 writeKnownBlobs(root, new Map([...blobs].map(([rel, b]) => [rel, b.sha])));
77 const knownModes = new Map<string, FullMode>();
78 foldModes(knownModes, modes);
79 writeKnownModes(root, knownModes);
80 const synced = await syncFolder(root, api);
81 return {
82 text: [
83 `Created project ${project} at version ${answer.version} from ${plural(files.size, "text file")} in ${root}.`,
84 ...leftOutText(leftOut),
85 ...(wroteIgnore
86 ? ["Wrote a starting .absoignore (Claude Code state and operating system files); edit it like .gitignore."]
87 : []),
88 ...startingProjectFileText(wroteProject),
89 ...(answer.skipped && answer.skipped.length > 0 ? [`The server skipped: ${answer.skipped.join(", ")}.`] : []),
90 `This folder is agent ${config.agent}. Settings are in .abso/config.json.`,
91 ...refusedText(synced.refused),
92 ...(synced.kept.length > 0 ? [`Kept your copy of ${synced.kept.join(", ")}.`] : []),
93 hookHint(env.env),
94 ].join("\n"),
95 json: {
96 project,
97 version: answer.version,
98 files: files.size,
99 root,
100 agent: config.agent,
101 wroteAbsoignore: wroteIgnore,
102 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject,
103 leftOut,
104 },
105 };
108/**
109 * Where abso join writes: --dir, else here when --agent is given (as before, so a folder prepared with
110 * abso key install --server is joined where its key is). With no --agent: here when this folder is empty, else
111 * ./<project>, which has to be new or empty so nobody's files are written over. A folder holding only abso's own
112 * state folder counts as empty.
113 */
114export function joinFolder(args: Parsed, env: Pick<Env, "cwd">, project: string): string {
115 const dir = str(args, "dir");
116 if (dir !== undefined) return resolve(env.cwd, dir);
117 if (str(args, "agent") !== undefined) return resolve(env.cwd);
118 const empty = (path: string) => readdirSync(path).every((name) => name === STATE_DIR || name === OLD_STATE_DIR);
119 if (empty(env.cwd)) return resolve(env.cwd);
120 const sub = resolve(env.cwd, project);
121 if (existsSync(sub) && (!statSync(sub).isDirectory() || !empty(sub)))
122 throw new UsageError(`${sub} already has files in it: say where to join with --dir <folder>`);
123 return sub;
126export async function runJoin(args: Parsed, env: Env): Promise<Output> {
127 if (args.positionals.length !== 1) throw new UsageError("join takes the project name: abso join <project>");
128 const project = args.positionals[0]!;
129 if (!NAME.test(project))
130 throw new UsageError(
131 `project names are letters, digits, dot, dash and underscore (got ${JSON.stringify(project)})`,
132 );
133 const root = joinFolder(args, env, project);
134 mkdirSync(root, { recursive: true });
135 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
136 const reader = bool(args, "reader");
137 const server = serverFrom(args, env);
138 const box = readBox(server);
139 const hasKey = existsSync(join(stateDir(root), "key"));
140 let agent: string;
141 let minted: { key: string; id: string } | undefined;
142 if (str(args, "agent") !== undefined) {
143 agent = agentFrom(args);
144 minted = box && !hasKey ? await mintKey(box, project, agent) : undefined;
145 } else {
146 // No --agent: the box's name, or the next free -2, -3.
147 if (!box) throw new UsageError("abso login signs this box in first (or give --agent <name>)");
148 if (hasKey) throw new UsageError(`${root} already has a key: give its agent's name with --agent <name>`);
149 const free = await mintFreeName(box, project, defaultAgentName());
150 agent = free.agent;
151 minted = { key: free.key, id: free.id };
152 }
153 const config = { server, project, agent, ...(reader ? { reader: true } : {}) };
154 writeConfig(root, config);
155 clearKnown(root);
156 if (minted) installKey(root, JSON.stringify(minted));
157 const settings = readConfig(root, env.env);
158 const api = new Api(settings);
159 let synced: Awaited<ReturnType<typeof syncFolder>>;
160 try {
161 // Before the sync, so the server never takes a record from this folder.
162 if (reader) await api.reader(true);
163 // Every file, even when the server has seen this agent sync before: its plain sync answer would hold only what changed since (#37).
164 synced = await syncFolder(root, api, true);
165 } catch (error) {
166 if (!(error instanceof ApiError && error.status === 401 && !box && !settings.token)) throw error;
167 rmSync(stateDir(root), { recursive: true, force: true });
168 throw new UsageError(`This box isn't signed in to ${config.server}. abso login signs it in.`);
169 }
170 return {
171 text: [
172 `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.` : ""}`,
173 ...refusedText(synced.refused),
174 ...(synced.kept.length > 0
175 ? [
176 `These files were already here and differ from shared, so they were left alone: ${synced.kept.join(", ")}. abso record sends them as your changes.`,
177 ]
178 : []),
179 ...setupHint(root),
180 hookHint(env.env),
181 ...(root === resolve(env.cwd) ? [] : [`cd ${relative(env.cwd, root) || root}`]),
182 ].join("\n"),
183 json: {
184 project,
185 agent: config.agent,
186 version: synced.version,
187 written: synced.written,
188 kept: synced.kept,
189 refused: synced.refused,
190 root,
191 },
192 };
195/** What to run before building or testing here (#43): a joined folder has the project's files, not what avcs.json's setup installs. */
196function setupHint(root: string): string[] {
197 const read = readProjectFile(root);
198 const setup = read !== null && "file" in read ? read.file.setup : "";
199 return setup === ""
200 ? []
201 : [`Nothing is installed yet. Before building or testing here, run ${projectFileName(root)}'s setup: ${setup}`];
204function hookHint(env: Readonly<Record<string, string | undefined>>): string {
205 return modInstalled(env)
206 ? "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record."
207 : `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.`;