- 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=21&format=json
162 linesFirst import 94% · review 6%Last change review in version 17, 3 versions changed it
You're reading version 21. The newest is 318, and 20 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, rmSync, statSync, writeFileSync } from "node:fs";
4import { join, 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 { mintKey, readBox } from "./box.ts";
9import { STARTING_AVCSIGNORE } 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 { clearKnown, loadIgnore, readFolder, writeKnown } from "./folder.ts";
15import { modInstalled } from "./install.ts";
16import { type FullMode, foldModes, writeKnownModes } from "./modes.ts";
17import { PROJECT_FILE, readProjectFile, startingProjectFileText, writeStartingProjectFile } from "./project-file.ts";
18import { refusedText } from "./safety.ts";
19import { stateDir } from "./state-dir.ts";
21function serverFrom(args: Parsed, env: Env): string {
22 const server = str(args, "server") ?? env.env.AVCS_SERVER;
23 if (!server) throw new UsageError("give the server with --server <url> (or AVCS_SERVER)");
24 return server;
25}
27function agentFrom(args: Parsed): string {
28 const agent = str(args, "agent");
29 if (!agent) throw new UsageError("give this folder's agent name with --agent <name>");
30 if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(agent))
31 throw new UsageError(`agent names are letters, digits, dot, dash and underscore (got ${JSON.stringify(agent)})`);
32 return agent;
33}
35function makeSettings(args: Parsed, env: Env, project: string): Settings {
36 return { server: serverFrom(args, env), project, agent: agentFrom(args) };
37}
39export async function runInit(args: Parsed, env: Env): Promise<Output> {
40 if (args.positionals.length > 1) throw new UsageError("init takes one folder");
41 const root = resolve(env.cwd, args.positionals[0] ?? ".");
42 if (!existsSync(root) || !statSync(root).isDirectory()) throw new UsageError(`${root} is not a folder`);
43 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
44 const project = str(args, "project");
45 if (!project) throw new UsageError("give the project a name with --project <name>");
46 const config = makeSettings(args, env, project);
47 const asIs = bool(args, "as-is");
48 const avcsignore = join(root, ".avcsignore");
49 const wroteIgnore = !asIs && !existsSync(avcsignore);
50 if (wroteIgnore) writeFileSync(avcsignore, STARTING_AVCSIGNORE);
51 // What the server runs on each new version (#39), guessed from package.json; recorded with the rest.
52 const wroteProject = asIs ? "exists" : writeStartingProjectFile(root);
53 const { files, blobs, modes, leftOut } = readFolder(root, loadIgnore(root));
54 const token = tokenFor(config.server, env.env);
55 const api = new Api({ ...config, ...(token ? { token } : {}) });
56 await uploadBlobs(api, blobs);
57 const answer = await api.init(
58 Object.fromEntries(files),
59 modes,
60 Object.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),
61 );
62 writeConfig(root, config);
63 clearKnown(root);
64 for (const [rel, text] of files) writeKnown(root, rel, text);
65 writeKnownBlobs(root, new Map([...blobs].map(([rel, b]) => [rel, b.sha])));
66 const knownModes = new Map<string, FullMode>();
67 foldModes(knownModes, modes);
68 writeKnownModes(root, knownModes);
69 const synced = await syncFolder(root, api);
70 return {
71 text: [
72 `Created project ${project} at version ${answer.version} from ${plural(files.size, "text file")} in ${root}.`,
73 ...leftOutText(leftOut),
74 ...(wroteIgnore
75 ? ["Wrote a starting .avcsignore (Claude Code state and operating system files); edit it like .gitignore."]
76 : []),
77 ...startingProjectFileText(wroteProject),
78 ...(answer.skipped && answer.skipped.length > 0 ? [`The server skipped: ${answer.skipped.join(", ")}.`] : []),
79 `This folder is agent ${config.agent}. Settings are in .abso/config.json.`,
80 ...refusedText(synced.refused),
81 ...(synced.kept.length > 0 ? [`Kept your copy of ${synced.kept.join(", ")}.`] : []),
82 hookHint(env.env),
83 ].join("\n"),
84 json: {
85 project,
86 version: answer.version,
87 files: files.size,
88 root,
89 agent: config.agent,
90 wroteAvcsignore: wroteIgnore,
91 wroteProjectFile: typeof wroteProject === "string" ? null : wroteProject,
92 leftOut,
93 },
94 };
95}
97export async function runJoin(args: Parsed, env: Env): Promise<Output> {
98 if (args.positionals.length !== 1)
99 throw new UsageError("join takes the project name: abso join <project> --agent <name>");
100 const project = args.positionals[0]!;
101 const root = resolve(env.cwd, str(args, "dir") ?? ".");
102 mkdirSync(root, { recursive: true });
103 if (findRoot(root) === root) throw new UsageError(`${root} already has .abso/config.json`);
104 const reader = bool(args, "reader");
105 const config = { ...makeSettings(args, env, project), ...(reader ? { reader: true } : {}) };
106 const box = readBox(config.server);
107 const minted =
108 box && !existsSync(join(stateDir(root), "key")) ? await mintKey(box, project, config.agent) : undefined;
109 writeConfig(root, config);
110 clearKnown(root);
111 if (minted) installKey(root, JSON.stringify(minted));
112 const settings = readConfig(root, env.env);
113 const api = new Api(settings);
114 let synced: Awaited<ReturnType<typeof syncFolder>>;
115 try {
116 // Before the sync, so the server never takes a record from this folder.
117 if (reader) await api.reader(true);
118 // Every file, even when the server has seen this agent sync before: its plain sync answer would hold only what changed since (#37).
119 synced = await syncFolder(root, api, true);
120 } catch (error) {
121 if (!(error instanceof ApiError && error.status === 401 && !box && !settings.token)) throw error;
122 rmSync(stateDir(root), { recursive: true, force: true });
123 throw new UsageError(`This box isn't signed in to ${config.server}. abso login signs it in.`);
124 }
125 return {
126 text: [
127 `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.` : ""}`,
128 ...refusedText(synced.refused),
129 ...(synced.kept.length > 0
130 ? [
131 `These files were already here and differ from shared, so they were left alone: ${synced.kept.join(", ")}. abso record sends them as your changes.`,
132 ]
133 : []),
134 ...setupHint(root),
135 hookHint(env.env),
136 ].join("\n"),
137 json: {
138 project,
139 agent: config.agent,
140 version: synced.version,
141 written: synced.written,
142 kept: synced.kept,
143 refused: synced.refused,
144 root,
145 },
146 };
147}
149/** What to run before building or testing here (#43, Engine): a joined folder has the project's files, not what avcs.json's setup installs. */
150function setupHint(root: string): string[] {
151 const read = readProjectFile(root);
152 const setup = read !== null && "file" in read ? read.file.setup : "";
153 return setup === ""
154 ? []
155 : [`Nothing is installed yet. Before building or testing here, run ${PROJECT_FILE}'s setup: ${setup}`];
156}
158function hookHint(env: Readonly<Record<string, string | undefined>>): string {
159 return modInstalled(env)
160 ? "Edits made by Claude Code here are recorded by the abso mod on this machine, signed in as this folder. Anything else: abso record."
161 : `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.`;
162}