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