- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/main.ts?version=201&format=json
1,025 linesFirst import 67% · pinch 14% · speed 9% · rename 5% · box-grants 1% · infra-split 1% · Last change whytrail in version 193, 45 versions changed it
You're reading version 201. The newest is 318, and 14 versions since then changed this file.
1// The command table and the dispatcher. main() returns what to print and the
2// exit code instead of printing, so tests can call it directly.
4import { readFileSync } from "node:fs";
5import { resolve } from "node:path";
6import { runAnnounce, runNews, runStart } from "./announce.ts";
7import { ApiError } from "./api.ts";
8import { bool, type FlagSpec, type Parsed, parseArgs, str, UsageError } from "./args.ts";
9import { bodyFilesHelp, readBodyFiles, withBodyFiles } from "./body-files.ts";
10import { boxPublic, boxText, login, loginRequest, logout, readBox } from "./box.ts";
11import { runDiff, runFiles, runLog, runRestore, runShow } from "./changes.ts";
12import { runCheckIgnore } from "./check-ignore.ts";
13import { runCi } from "./ci.ts";
14import { clientVersion } from "./client-version.ts";
15import {
16 type Env,
17 EXIT,
18 type Output,
19 runBisect,
20 runFetch,
21 runFixEol,
22 runInit,
23 runJoin,
24 runLogs,
25 runMv,
26 runPause,
27 runPrep,
28 runPublish,
29 runReader,
30 runRecord,
31 runResume,
32 runRun,
33 runServe,
34 runSettle,
35 runShot,
36 runStatus,
37 runSync,
38 takeNews,
39} from "./commands.ts";
40import { configPath, findRoot, installKey, isVisitor, readConfig, readToken } from "./config.ts";
41import { newsBlockLines, newsShown } from "./core.ts";
42import { doctor, doctorText, plainError, realProbe, whoami } from "./doctor.ts";
43import { runDraftSync, runLand, runSwitch } from "./drafts.ts";
44import { runExport } from "./export.ts";
45import { runBlame, runWhere, runWho, runWhy } from "./history.ts";
46import { runAck, runAnswer, runAsk, runIssue, runIssues, runReply, runSearch, runWaiting } from "./issues.ts";
47import { adminToken, issuedPublic, keyList, keyListText, keyNew, keyRevoke } from "./key-admin.ts";
48import { browserSkip, openInBrowser } from "./open-browser.ts";
49import { runOrg, runOrgs } from "./orgs.ts";
50import { runUnqueue } from "./queue.ts";
51import { runNote, runNotes, runReview } from "./review.ts";
52import {
53 checkFolderServer,
54 chooseServer,
55 localRefusal,
56 SERVER_ORDER,
57 serverFlag,
58 serverHelp,
59 serverUse,
60} from "./server-choice.ts";
61import { installSkill, SKILL, skillPath } from "./skill.ts";
62import { colorsPass, terminalText } from "./terminal-text.ts";
63import { runAmend, runDrop, runFollow, runLabel, runLabels, runPluck } from "./versions.ts";
64import { runVisibility } from "./visibility-commands.ts";
65import { checkVisitor } from "./visitor.ts";
67interface CommandDef {
68 readonly flags: FlagSpec;
69 readonly usage: string;
70 readonly about: string;
71 /** Stop reading options at the first word (for `run <command...>`). */
72 readonly rest?: boolean;
73 readonly run: (args: Parsed, env: Env) => Promise<Output>;
74}
76/** The server login, box, logout, orgs, org, whoami and doctor act on, in the order every command picks one (server-choice.ts). */
77export function boxServer(args: Parsed, env: Pick<Env, "cwd" | "env">): string {
78 return chooseServer(serverFlag(args), env.cwd, env.env);
79}
81async function runKeyInstall(args: Parsed, env: Env): Promise<Output> {
82 // With --server, the folder is the one named (or here), before it is joined: findRoot
83 // could find a parent agent's folder and pin the key there.
84 const server = str(args, "server");
85 const root = server ? resolve(env.cwd, str(args, "dir") ?? ".") : findRoot(env.cwd);
86 if (!root)
87 throw new UsageError("abso key install runs inside an agent's folder, or takes --server <url> before abso join");
88 const stdin = await new Promise<string>((done, reject) => {
89 const chunks: Buffer[] = [];
90 process.stdin.on("data", (c) => chunks.push(c as Buffer));
91 process.stdin.on("end", () => done(Buffer.concat(chunks).toString("utf8")));
92 process.stdin.on("error", reject);
93 });
94 const { id } = installKey(root, stdin, server);
95 return { text: `Installed agent key ${id}.`, json: { installed: id } };
96}
98const COMMANDS: Readonly<Record<string, CommandDef>> = {
99 init: {
100 flags: {
101 server: "string",
102 project: "string",
103 agent: "string",
104 "as-is": "boolean",
105 org: "string",
106 public: "boolean",
107 private: "boolean",
108 },
109 usage: "abso init [folder] --project <name> [--agent <name>] [--as-is] [--org <org>] [--public|--private]",
110 about:
111 "Create a project on the server from a folder's text files The folder becomes that agent's folder. It writes a starting .absoignore, and, when the folder has no avcs.json and package.json gives a check or a build to guess, an avcs.json (setup, check, build and out): what the server's CI runs on each new version of shared. Without one, CI runs what it can guess itself, or nothing. --as-is writes neither: the folder goes up exactly as it is (an import). On a server this box is signed in to (abso login, approving all your projects), the project is made as you, the way the website's New project makes it: you own it, it's private unless you say --public, and the folder joins it at once with its own key (--agent names it; else the box's name). --org <org> makes it that organization's project. Elsewhere it needs --agent and the server's token.",
112 run: (args, env) => runInit(args, env),
113 },
114 key: {
115 flags: {
116 server: "string",
117 dir: "string",
118 project: "string",
119 agent: "string",
120 expires: "string",
121 role: "string",
122 print: "boolean",
123 },
124 usage:
125 "abso key install [--server <url> [--dir <folder>]] | abso key new <agent> [--server <url> [--dir <folder>]] [--project <name>] [--expires <Nd>] [--role owner|writer|reader] [--print] | abso key list [--agent <name>] [--project <name>] | abso key revoke <id> [--project <name>]",
126 about:
127 "install reads {key, id} from stdin into .abso/key. With --server, it writes it into a folder not joined yet, so abso join there signs in with the key. new writes the key into that folder and prints only the id; its role is writer unless --role says otherwise (a reader only reads; a writer writes on its own agent's routes; an owner also skips or revokes CI, resumes the queue, syncs git and exports); --print writes the key to stdout instead. list and revoke never print a key. These three read the admin token from AVCS_ADMIN_TOKEN or ~/.abso/admin-token and send it only to a server named in AVCS_ADMIN_SERVERS. An agent does not run them unless a person on the project says so.",
128 run: async (args, env) => {
129 const sub = args.positionals[0];
130 if (sub === "install" && args.positionals.length === 1) return runKeyInstall(args, env);
131 const serverFlag = str(args, "server");
132 const root = serverFlag ? resolve(env.cwd, str(args, "dir") ?? ".") : findRoot(env.cwd);
133 if (!root) throw new UsageError("abso key runs inside an agent's folder, or takes --server <url>");
134 let config: ReturnType<typeof readConfig>;
135 try {
136 config = readConfig(root, env.env);
137 } catch {
138 config = {
139 server: serverFlag ?? "",
140 project: str(args, "project") ?? "",
141 agent: "admin",
142 token: readToken(env.env),
143 };
144 }
145 if (serverFlag) config = { ...config, server: serverFlag };
146 const admin = adminToken(env.env);
147 if (sub === "new" && args.positionals.length === 2) {
148 const server = str(args, "server") ?? config.server;
149 const project = str(args, "project") ?? config.project;
150 const expires = str(args, "expires");
151 const role = str(args, "role");
152 if (role !== undefined && role !== "owner" && role !== "writer" && role !== "reader")
153 throw new UsageError("--role is owner, writer or reader");
154 const issued = await keyNew({ ...config, server }, admin, args.positionals[1]!, project, expires, role);
155 const print = bool(args, "print");
156 const shown = issuedPublic(issued, print);
157 if (!print) {
158 const dir = str(args, "server") ? resolve(env.cwd, str(args, "dir") ?? ".") : root;
159 installKey(dir, JSON.stringify({ key: issued.key, id: issued.id }), server);
160 }
161 return {
162 text: print ? `${JSON.stringify({ key: issued.key, id: issued.id })}\n` : `Made ${issued.id}.\n`,
163 json: shown,
164 };
165 }
166 if (sub === "list" && args.positionals.length === 1) {
167 const agent = str(args, "agent");
168 const project = str(args, "project") ?? config.project;
169 const keys = await keyList({ ...config, server: str(args, "server") ?? config.server }, admin, agent, project);
170 return { text: `${keyListText(keys)}\n`, json: { keys } };
171 }
172 if (sub === "revoke" && args.positionals.length === 2) {
173 const project = str(args, "project") ?? config.project;
174 const id = args.positionals[1]!;
175 const revoked = await keyRevoke(
176 { ...config, server: str(args, "server") ?? config.server },
177 admin,
178 id,
179 project,
180 );
181 return { text: revoked ? `Revoked ${id}.\n` : `No key ${id}.\n`, json: { id, revoked } };
182 }
183 throw new UsageError("abso key install | abso key new <agent> | abso key list | abso key revoke <id>");
184 },
185 },
186 login: {
187 flags: {
188 server: "string",
189 "no-browser": "boolean",
190 projects: "string",
191 role: "string",
192 days: "string",
193 },
194 usage: "abso login [--no-browser] [--projects <name,name>] [--role <reader|writer|owner>] [--days <1-90>]",
195 about:
196 "Sign this box in once: it opens the approve page in your browser with the code filled in, prints the link and the code too, and waits while a person approves the code on the website, choosing the projects, the highest role and how long. Then abso join in any of those projects gives each agent its own key, with no approval. The box's sign-in is kept in your user folder, never in a project folder, and is never printed. No browser opens with --no-browser or ABSO_NO_BROWSER, over SSH, under CI, or on Linux without a display.",
197 run: async (args, env) => {
198 const server = boxServer(args, env);
199 const open =
200 bool(args, "no-browser") || browserSkip(env.env, process.platform) !== null
201 ? undefined
202 : (url: string) => openInBrowser(url);
203 const record = await login(server, {
204 request: loginRequest(args),
205 say: (line) => process.stderr.write(terminalText(`${line}\n`, colorsPass(process.stderr, env.env))),
206 open,
207 });
208 return {
209 text: `This box is signed in. ${boxText(record, server).split("\n").slice(1).join(" ")}`,
210 json: { box: boxPublic(record) },
211 };
212 },
213 },
214 box: {
215 flags: { server: "string" },
216 usage: "abso box",
217 about:
218 "What this box's sign-in allows: its projects, the highest role its agents may have, how many agents it has made and may make, and when it expires. Never the credential.",
219 run: async (args, env) => {
220 const server = boxServer(args, env);
221 const record = readBox(server);
222 return { text: boxText(record, server), json: { box: boxPublic(record) } };
223 },
224 },
225 whoami: {
226 flags: { server: "string" },
227 usage: "abso whoami",
228 about:
229 "Who and where you're signed in: this box's sign-in, as the server sees it (so a revoked one shows), its projects, roles and expiry, and this folder's project, agent and kind of key. Never a credential.",
230 run: async (args, env) => {
231 const out = await whoami(boxServer(args, env), env.cwd, env.env, realProbe());
232 return { text: out.text, json: out.json };
233 },
234 },
235 doctor: {
236 flags: { server: "string" },
237 usage: "abso doctor",
238 about:
239 "Checks what commands need, one line each: Node's version, that the server answers, this box's sign-in (present, unexpired, accepted), and this folder's key against its project. A failed check says what to do next, and the exit is 1. Never prints a credential.",
240 run: async (args, env) => {
241 const checks = await doctor(boxServer(args, env), env.cwd, env.env, realProbe());
242 const failed = checks.some((c) => c.result === "fail");
243 return { text: doctorText(checks), json: { checks }, ...(failed ? { exit: EXIT.error } : {}) };
244 },
245 },
246 logout: {
247 flags: { server: "string" },
248 usage: "abso logout",
249 about:
250 "End this box's sign-in on the server and forget it here. Keys its agents already have stop working with it.",
251 run: async (args, env) => {
252 const server = boxServer(args, env);
253 const record = readBox(server);
254 if (!record) return { text: `This box isn't signed in to ${server}.`, json: { loggedOut: false } };
255 const ended = await logout(record);
256 return {
257 text: ended
258 ? `Signed this box out of ${record.server}.`
259 : `Forgot this box's sign-in here, but ${record.server} couldn't be reached to end it. Revoke the box on the website.`,
260 json: { loggedOut: true, ended },
261 };
262 },
263 },
264 orgs: {
265 flags: { server: "string" },
266 usage: "abso orgs",
267 about:
268 "Your organizations and your role in each, and invitations waiting for you. It reads as the person who approved this box's sign-in (abso login).",
269 run: (args, env) => runOrgs(boxServer(args, env)),
270 },
271 org: {
272 flags: {
273 server: "string",
274 name: "string",
275 invite: "string",
276 as: "string",
277 role: "string",
278 remove: "string",
279 leave: "boolean",
280 members: "string",
281 "projects-by": "string",
282 },
283 usage:
284 "abso org <name> [--invite <person>|link [--as owner] | --role <person>=owner|member | --remove <person> | --leave | --members read|write | --projects-by members|owners] | abso org new <name> [--name <shown name>]",
285 about:
286 "An organization: its projects, people, open invites and settings, as the person who approved this box's sign-in sees them (people and settings only to members). One change at a time. abso org new makes one as that person, from a box approved for all their projects; other changes are made on the website, and abso says where.",
287 run: (args, env) => runOrg(args, boxServer(args, env)),
288 },
289 skill: {
290 flags: { dir: "string" },
291 usage: "abso skill install [--dir <skills folder>] | abso skill show",
292 about:
293 "The abso skill for Claude Code: how to work in an abso folder, and what never to share. install writes it to ~/.claude/skills/abso/SKILL.md (--dir names another skills folder) and changes no settings; run it again after updating abso. show prints it.",
294 run: async (args, env) => {
295 const [verb, ...more] = args.positionals;
296 if (verb === "show" && more.length === 0) return { text: SKILL, json: { skill: SKILL } };
297 if (verb !== "install" || more.length > 0)
298 throw new UsageError("abso skill install [--dir <skills folder>] | abso skill show");
299 const path = skillPath(str(args, "dir"), env.cwd);
300 const done = installSkill(path);
301 const said = { installed: "Installed", updated: "Updated", current: "Already current:" }[done];
302 return {
303 text: `${said} the abso skill at ${path}. New Claude Code sessions load it.`,
304 json: { path, done },
305 };
306 },
307 },
308 join: {
309 flags: { server: "string", agent: "string", dir: "string", reader: "boolean" },
310 usage: "abso join <project> [--agent <name>] [--dir <folder>] [--reader]",
311 about:
312 "Join a project as a new agent and write its shared files into a folder: --dir, else here when this folder is empty, else ./<project> (which has to be new or empty). Without --agent the agent is named after this box (the name abso login gave it, lower-cased), or the next free <name>-2, <name>-3; that needs the box signed in with abso login. --reader joins as a reader: it reads everything and records nothing, and the server refuses its edits, records and pushes. With --reader and no sign-in, a public project is joined to read signed out: the folder holds only its settings, sends no sign-in, and runs status, log, show, files, blame, why, where, issues, issue and search; every other command is refused.",
313 run: runJoin,
314 },
315 record: {
316 flags: { all: "boolean", binary: "string" },
317 usage: "abso record [--all]",
318 about:
319 "Send every file that changed since the server last heard about it (--all: every file). For edits the hook did not see.",
320 run: runRecord,
321 },
322 push: {
323 flags: {
324 message: "string",
325 binary: "string",
326 "as-is": "boolean",
327 check: "optional",
328 box: "string",
329 wait: "string",
330 "no-wait": "boolean",
331 done: "boolean",
332 },
333 usage: 'abso push -m "<why>" [--as-is] [--check ["<command>"]] [--wait <seconds> | --no-wait] [--done]',
334 about:
335 'Record, then add your draft to shared. Refused when it collides with work pushed since your last pull, or when lines a pull showed changed on both sides are still untouched (--as-is pushes both sides\' lines anyway). --check "<command>" (e.g. --check "npm run typecheck") first pulls, then runs the command in your box on your draft with newest shared, and pushes only if it exits 0, so two changes that each pass alone can\'t turn shared red. --check alone runs the "build" and then the "check" in the project\'s avcs.json (your draft\'s copy), as the server does on each new version. With the merge queue on ("queue": true in avcs.json), a push to shared is queued and lands only once the project\'s check passes on shared with it on top: push waits up to 100 s for that (--wait <seconds> changes it, --no-wait returns at once), then says it landed (exit 0), was turned back with the check\'s output (exit 2, its changes still in your draft), or is still queued (exit 3; the outcome comes as news). --check alone is skipped then, since the queue runs the check. --done takes your start note back once it\'s pushed: this push finishes that work.',
336 run: runPublish,
337 },
338 bisect: {
339 flags: { good: "string", bad: "string", box: "string" },
340 usage: "abso bisect [--good <version>] [--bad <version>] -- <program> <arg...>",
341 about:
342 "The first version where a check fails: runs it in your box at versions of your folder's space (as abso run --at does) and prints that version, its author and message. --bad is the newest by default; without --good it steps back in doubling steps until one passes, then halves the gap. A run that exits 0 passes; exit 125 means it can't be tested (as in git bisect run), so that version is skipped, and if skips leave the answer open it names the range. About log2(versions) runs; your folder is never touched.",
343 rest: true,
344 run: runBisect,
345 },
346 reader: {
347 flags: {},
348 usage: "abso reader on|off",
349 about:
350 "Make this folder's agent a reader, which reads everything and records nothing (the server refuses its edits, records and pushes), or a writer again. Refused while it has unpushed or parked work.",
351 run: runReader,
352 },
353 settle: {
354 flags: { yours: "boolean", theirs: "boolean", both: "boolean" },
355 usage: "abso settle <file...> --yours|--theirs|--both",
356 about:
357 "Settle the collisions a pull marked in these files: each marker block becomes your lines, theirs, or both (yours first), then it records. abso status lists the files with markers.",
358 run: runSettle,
359 },
360 pull: {
361 flags: { verbose: "boolean", full: "boolean" },
362 usage: "abso pull [--full]",
363 about:
364 "Record, then bring shared's new work into the folder. Lines changed on both sides are listed as collisions to settle. --full writes any file of yours the folder is missing, not only what changed since your last pull.",
365 run: runSync,
366 },
367 run: {
368 flags: {
369 detach: "boolean",
370 replace: "boolean",
371 fresh: "boolean",
372 parallel: "boolean",
373 at: "string",
374 files: "string",
375 fetch: "string",
376 box: "string",
377 with: "string",
378 quiet: "boolean",
379 },
380 usage:
381 'abso run [--detach] [--replace] [--fresh] [--box <name>] [--at <version> [--files <glob>]] <command...> | abso run ... -- <program> <arg...> | abso run --parallel "<command>" "<command>"...',
382 about:
383 "Send the folder to this agent's box, run the command there, and stream its output back. Exits with the command's code. After --, each word goes to the program exactly as typed (quotes, backslashes, regex text); without --, the words are one shell command. The box's stderr comes out on stderr. --detach starts it and prints its id without waiting. While a run is still going in the box, a new one is refused (409, naming it), since it would replace the files under it; --replace stops the old one first. --parallel runs each quoted command at once in the box (one upload), labels each line [1], [2], ..., ends with each one's exit code, and exits with the worst. --at <version> runs that version of the folder's space instead of the folder (for bisecting); with --files <glob>, only the matching files are taken from that version. The folder is never touched. --fetch <glob>[,<glob>...] brings matching files from the box's /w back after the run (see abso fetch); several globs go in one argument, comma-separated (--fetch 'shots/*.png,out/*.json'), as for --files and --with. The box's /w is replaced by your folder on every run; the rest of the box (/tmp, ~/.cache, /w/node_modules) lasts between runs until the box stops (idle 30 minutes, or restarted). abso's own notices go to stderr, apart from the command's output; --quiet drops them (the command's own stderr still comes through). --with <box path>=<local path>[,...] adds files (or a folder's files) for this run only: they go to the box and are never written to your folder or recorded, for an A/B run that leaves the project alone. --box <name> (or AVCS_BOX=<name>) runs in another box of yours, with its own /w and state, so a subagent's runs and yours don't wait on each other; logs and fetch take --box too. After abso prep, a fresh box starts from the prep; --fresh starts this run from the plain image instead.",
384 rest: true,
385 run: runRun,
386 },
387 serve: {
388 flags: { version: "string", build: "string", out: "string" },
389 usage: 'abso serve [--version <n>] [--build "<command>"] [--out <folder>]',
390 about:
391 "A preview of one version of shared (the newest by default) at a stable URL that needs no token, for playing a fixed build in a browser with no local server and no sound on this machine. The server builds it once per version (npm ci, then vite build --base ./ into dist; --build and --out change that) and keeps the newest 10 builds. Asking again for a built version answers at once.",
392 run: runServe,
393 },
394 mv: {
395 flags: {},
396 usage: "abso mv <from> <to>",
397 about:
398 "Move a file in your draft, its lines keeping their history (as git mv), recorded as a move rather than guessed from the folder. The way to change a file's case: README.md and readme.md are one file in abso, and a write under another spelling goes to the existing one, with a warning that names abso mv. It reaches shared with your next push.",
399 run: runMv,
400 },
401 review: {
402 flags: { since: "string" },
403 usage: "abso review [<id> | v<version> | <agent>] [--since <position|2h>]",
404 about:
405 "Review is reading what landed. With no change: the changes with anything new since you last looked, newest first (a change is one start note's work, a named draft's, or a lone push), and the mark moves on; --since 2h (or a log position) looks further back without moving it. With a change id, v<version> (the change holding that version of shared) or an agent (its newest change): that change's page, with what it set out to do, its versions, what it settled, its reviewers and its notes.",
406 run: runReview,
407 },
408 note: {
409 flags: {
410 object: "boolean",
411 read: "boolean",
412 draft: "string",
413 at: "string",
414 reply: "string",
415 close: "string",
416 resolved: "boolean",
417 withdrawn: "boolean",
418 },
419 usage:
420 'abso note <file>:<line>[-<line>] "<text>" [--object | --read] [--draft <agent> | --at <version>] | abso note --reply <id> "<text>" | abso note --close <id> --resolved|--withdrawn',
421 about:
422 "A note on lines: it sits on those lines and follows them as the file changes. The lines' authors and the change's agent hear it as news. The line numbers are as your folder shows the file (it records first); --draft <agent> notes their unpushed work as their draft shows it, --at <version> a version of shared. --object asks for a fix (it shows as addressed once all its lines change); --read says you read it, telling nobody. --reply answers a note; --close closes one of yours.",
423 run: runNote,
424 },
425 notes: {
426 flags: { change: "string", all: "boolean" },
427 usage: "abso notes [file] [--change <id>] [--all]",
428 about:
429 "The open notes, on a file or a change, with their replies and where their lines are now. --all includes closed, addressed and outdated ones.",
430 run: runNotes,
431 },
432 issues: {
433 flags: {
434 open: "boolean",
435 status: "string",
436 agent: "string",
437 parent: "string",
438 label: "string",
439 labels: "boolean",
440 drafts: "boolean",
441 },
442 usage:
443 "abso issues [--open] [--status <status>] [--agent <agent>] [--parent <N>] [--label <l,l>] | abso issues --labels",
444 about:
445 "The project's issues, most recently updated first, each with its status, agents, labels, versions and who it waits on. --label keeps the issues with every label named (friction, say); --labels lists the labels in use, with how many issues are open under each; --drafts lists your drafts. A status comes from the work: abso start --issue N puts an issue In progress, an open ask makes it Blocked (or In review, for a review), and push --done closes it.",
446 run: runIssues,
447 },
448 issue: {
449 flags: {
450 comment: "string",
451 object: "string",
452 drop: "boolean",
453 reopen: "boolean",
454 done: "boolean",
455 "done-by": "string",
456 title: "string",
457 description: "string",
458 parent: "string",
459 lines: "string",
460 agent: "string",
461 "blocked-by": "string",
462 notify: "string",
463 quiet: "boolean",
464 label: "string",
465 unlabel: "string",
466 open: "boolean",
467 delete: "boolean",
468 attach: "string",
469 "copy-to": "string",
470 clean: "string",
471 "dry-run": "boolean",
472 "save-attachments": "string",
473 },
474 usage:
475 'abso issue <N> --save-attachments <folder> | abso issue <N> --copy-to <project> [--clean <file>] [--dry-run] | abso issue <N> [--comment "..." [--attach <file,file>] | --object "..." | --drop | --reopen | --done [--done-by <version>]] | abso issue <N> [--title "..."] [--description "..."] [--parent <N|none>] [--agent <agent|none>] [--blocked-by <N,N|none>] [--label <l,l>] [--unlabel <l,l>] [--notify <who,who> | --quiet] | abso issue new "<title>" [--description "..."] [--parent <N>] [--lines <file>:<from>-<to>@<version>] [--agent <agent>] [--blocked-by <N,N>] [--notify <who,who>] [--label <l,l>] [--attach <file,file>]',
476 about:
477 "One issue: its description, Agent, Blocked by, labels, asks, comments, edits, sub-issues and watchers. --comment comments on it and --object objects; its agents hear either. A comment holds up to 4000 characters: a longer --comment (or --comment-file) goes up in parts, split at paragraph breaks and each starting (1/3), (2/3) and so on, and a longer --object is refused before anything is sent. --drop drops it. --reopen opens a dropped issue again. --done marks it done by hand, and --done-by <version> names the pushed version that did it. push --done still marks it done too. --title, --description, --parent, --agent and --blocked-by edit it, and the edit tells its watchers (who opened it, its Agent and agents, its Reviewer, whoever was named in Notify, and whoever commented); --notify tells more people, --quiet tells nobody. --label adds labels and --unlabel takes them off (friction, area:client: lower-case letters, digits and - _ . :); a label-only edit tells nobody unless --notify names people. An issue is Blocked until each issue it's blocked by is Done. abso issue new opens one; --lines ties it to lines at a version of shared, --agent says who it's for, --notify tells people now, and --label labels it. --attach shot.png,after.png puts images on a new issue or a comment (png, jpeg, gif or webp, 10 MB each; the server checks the type by the bytes and takes out metadata such as where a photo was taken. An svg, up to 1 MB, is drawn as a png, and its own file is kept as a download, on servers that take svg), and prints each one's id for the text to point at; the issue's page lists them with a link, and --save-attachments <folder> saves every one on the issue and its comments there as <id>-<name> (an svg's own file too), outside the abso folder or where abso leaves files out. --copy-to <project> copies the issue into another project, with its comments, answered asks and labels, each keeping its author and time; --dry-run shows what would go and writes nothing, and --clean <file> gives cleaned texts by source id as JSON ({title, description, comments: [{id, text}], asks: [{id, question, answer}]}; a comment left out of a given list isn't copied). Copying out of a project on a live server takes an owner of that project. abso issue draft \"<title>\" [the same fields] saves a draft instead: yours alone, with no number and no news; abso issue draft <D> [fields] changes it, --open opens it as an issue, --delete deletes it.",
478 run: runIssue,
479 },
480 ask: {
481 flags: {
482 issue: "string",
483 review: "boolean",
484 task: "boolean",
485 due: "string",
486 blocks: "string",
487 options: "string",
488 withdraw: "string",
489 note: "string",
490 attach: "string",
491 },
492 usage:
493 'abso ask <who> "<question>" [--issue <N>] [--review | --task] [--due <YYYY-MM-DD>] [--blocks <N,N>] [--options "A|B|C"] [--attach <file,file>] | abso ask <N> | abso ask --withdraw <ask> [--note "why"]',
494 about:
495 "Ask an agent, or a person (person:<id>), something; they hear it. Who must be one of the project's agents or members; a name that isn't is refused, with the closest one suggested. abso ask <N> shows ask N, open or closed, with its whole thread, its answer and whose turn it is. On an issue, it holds the issue at Blocked (In review for --review) until answered. --task asks for something done instead of an answer; --options gives the choices; --blocks names the issues waiting on it. --attach sends files with the question, as on an issue. --withdraw takes back an ask you made that no longer needs an answer: it leaves their waiting list, stops holding the issue, keeps your --note as why, and they hear it.",
496 run: runAsk,
497 },
498 search: {
499 flags: { limit: "string" },
500 usage: 'abso search "<words>" [--limit <N>]',
501 about:
502 "The project's issues that match, best first: by their words, and by what they mean where the server has meaning search on, so an issue worded differently from your search still turns up. #N or N puts issue N first. Each hit says where it matched; one only meaning search found says by meaning.",
503 run: runSearch,
504 },
505 waiting: {
506 flags: { of: "string", mine: "boolean", asked: "boolean" },
507 usage: "abso waiting [--of <agent or person:id>] [--mine] [--asked]",
508 about:
509 "The open asks, soonest due first: every one, those waiting on someone (--of), or those waiting on you (--mine), each with its newest reply. An ask waits on the one asked until they answer, or on the asker after a reply with --question, until the asker replies. --mine also lists your pushes still in the merge queue and where each stands; the outcome comes as news. --asked lists the asks you sent instead, open ones first, then the latest answered.",
510 run: runWaiting,
511 },
512 answer: {
513 flags: { option: "string", note: "string", done: "boolean", attach: "string" },
514 usage:
515 'abso answer <ask> "<words>" | abso answer <ask> --option <N> [--note "..."] | abso answer <ask> --done [--note "..."], each with [--attach <file,file>]',
516 about:
517 "Answer an ask of you, in your own words, by picking an option (by number or text), or, for a task, with --done. --attach sends files with the answer. The asker hears it.",
518 run: runAnswer,
519 },
520 ack: {
521 flags: {},
522 usage: 'abso ack <ask> ["<note>"]',
523 about:
524 "Acknowledge an ask of you without answering it yet: it's the first reply in its thread. The asker hears it, with your note, and the ask stays open. abso reply adds more; abso answer closes it later.",
525 run: runAck,
526 },
527 reply: {
528 flags: { question: "boolean" },
529 usage: 'abso reply <ask> "<words>" [--question]',
530 about:
531 'Add to an ask\'s thread, as its asker or the one asked, open or closed: "ok, let me check", what you found, a follow-up. The other side hears it, and the ask stays as it is; abso answer still closes it. --question, from the one asked, asks the asker something back: the ask waits on them until they reply. On a public project, anyone can read the thread.',
532 run: runReply,
533 },
534 unqueue: {
535 flags: {},
536 usage: "abso unqueue",
537 about:
538 "Take back your pushes still waiting in the merge queue: their changes stay in your draft, unpushed. Refused while one is being checked; it lands or is turned back within a few minutes (abso drop takes it back after it lands).",
539 run: runUnqueue,
540 },
541 visibility: {
542 flags: { yes: "boolean" },
543 usage: "abso visibility [public|private] [--yes]",
544 about:
545 "Whether the project is public. With no word, says which. public, with --yes, lets anyone read it, signed in or not: files, versions, drafts, notes, Issues, people's names, CI as pass or fail; never keys, CI logs, preview links or boxes. private makes it members-only again. Switching takes the project owner's key (on staging, the shared token works too).",
546 run: runVisibility,
547 },
548 ci: {
549 flags: { version: "string", revoke: "boolean" },
550 usage: "abso ci [<version>] | abso ci --revoke",
551 about:
552 "The project's CI: the server runs avcs.json's setup, build and check on each new version of shared, one job at a time on the newest. abso ci says whether shared is green or red (and since which version, by whom, once a bisect finds it), what is being checked, and the preview link of the newest passing build, which needs no token. abso ci <version> shows that version's job: which step failed, its exit code, and the end of its output. status says the same in a line, and log marks each version of shared. --revoke ends every preview link handed out so far and makes a new one.",
553 run: runCi,
554 },
555 shot: {
556 flags: {
557 out: "string",
558 wait: "string",
559 size: "string",
560 box: "string",
561 eval: "string",
562 click: "string",
563 mouse: "string",
564 at: "string",
565 scale: "string",
566 region: "string",
567 text: "boolean",
568 tree: "boolean",
569 interactive: "boolean",
570 depth: "string",
571 find: "string",
572 "max-chars": "string",
573 image: "boolean",
574 },
575 usage:
576 'abso shot ["/<path>?<query>"] [--scale 0.1-1] [--region x0,y0,x1,y1] [--text] [--tree [--interactive] [--depth N]] [--find "<text>"] [--max-chars N] [--image] [--at <version>] [--eval "<js>"] [--click "x,y[@ms];ref_N[@ms]"] [--mouse x,y|ref_N] [--out <file.png>] [--wait <ms>] [--size <w>x<h>]',
577 about:
578 "A look at your folder's game, taken in your box: it runs the project's vite dev server and Playwright on that page (default /, a 1280x720 page). Images cost tokens, so read without one when you can: --text prints the page's visible text, --tree its elements (role, name, a ref like ref_12, and its box in page pixels; --interactive only what can be clicked or typed in; --depth N levels), and --find \"<text>\" the elements matching some text; each is capped at --max-chars (default 5000). With none of those, or with --image, it writes a PNG to .avcs/shots/ (never recorded) or --out, and prints its pixel size and about how many tokens reading it costs (width x height / 750). --scale 0.5 halves the width and height (a quarter of the tokens); --region x0,y0,x1,y1 takes part of the page at full detail; they combine. Coordinates are always the page's, whatever the scale or region. To set up a state first, --eval runs JavaScript in the page and --click clicks points (x,y or ref_N; several separated by ;; @ms waits first), in that order, a second after load and two frames after the eval; --mouse x,y or ref_N leaves the pointer there (for hover cards); then it waits --wait ms (default 3000) and looks. It prints --eval's result, page errors and the first 30 console messages. Refs come from --tree or --find on the same page in the same state. --at <version> looks at that version of your folder's space instead of the folder (as abso run --at). Needs vite and playwright in the project's devDependencies; abso prep with npx --no-install playwright install chromium makes it fast.",
579 run: runShot,
580 },
581 prep: {
582 flags: { forget: "boolean", box: "string" },
583 usage: 'abso prep [--box <name>] "<setup command>" | abso prep --forget',
584 about:
585 "Set up your box once and keep it: sends the folder, runs the setup command (npm ci, npx playwright install chromium, a build) in a fresh box of the current image, and saves the box. From then on every fresh box (after a deploy, 30 idle minutes, or a new run's restart) starts from it, with node_modules, ~/.cache and /tmp as the setup left them; /w is still replaced by your folder on each run, apart from node_modules. abso run says when the prep is set aside (a newer box image) or out of date (package-lock.json changed): run abso prep again then. --forget drops it.",
586 rest: true,
587 run: runPrep,
588 },
589 fetch: {
590 flags: { box: "string" },
591 usage: "abso fetch [--box <name>] <glob...>",
592 about:
593 "Files the last run left in the box's /w (bash globs: out/*.png, **/*.log), written into the folder, but only where abso ignores them, so a fetched file never becomes an edit; the rest are named and left alone. /w is replaced on the next run, and everything goes when the box stops.",
594 run: runFetch,
595 },
596 pause: {
597 flags: {},
598 usage: "abso pause",
599 about:
600 "Send nothing from this folder until abso resume: the edit hook skips, abso record refuses, other commands don't record first. For swapping files in by hand (abso run --at usually does it better).",
601 run: runPause,
602 },
603 resume: {
604 flags: {},
605 usage: "abso resume",
606 about: "End abso pause. Changes made while paused go at the next record.",
607 run: runResume,
608 },
609 logs: {
610 flags: { box: "string" },
611 usage: "abso logs [--box <name>] <run id>",
612 about:
613 "A run's output from its start (stdout and stderr apart), for as long as the box keeps it, waiting until it ends. Exits with its code. For abso run --detach, or a run whose connection was lost.",
614 run: runLogs,
615 },
616 status: {
617 flags: { short: "boolean" },
618 usage: "abso status [--short]",
619 about:
620 "The shared version, whether shared is green or red by the project's CI (abso ci has more), who waits in the merge queue, every agent's base and draft, and what in this folder is not yet recorded. --short prints one word for stamping a build: the version this folder is on (214), with the named draft (coast@3), +unpushed when it holds changes not yet pushed, and +queued when a push of yours waits in the merge queue.",
621 run: runStatus,
622 },
623 switch: {
624 flags: { carry: "boolean", verbose: "boolean" },
625 usage: "abso switch <draft> | abso switch -c <new draft> | abso switch shared",
626 about:
627 "Move this folder to a named draft, or back to shared. Your unpushed changes are parked where you leave and come back when you return; -c carries them into a new draft instead.",
628 run: runSwitch,
629 },
630 land: {
631 flags: { message: "string" },
632 usage: 'abso land -m "<why>"',
633 about:
634 "Land your named draft in shared, as one unit. Refused only on a collision with work that landed in shared since the draft began.",
635 run: runLand,
636 },
637 "draft-pull": {
638 flags: {},
639 usage: "abso draft-pull",
640 about: "Move your named draft onto shared's newest version, then bring that into this folder.",
641 run: runDraftSync,
642 },
643 diff: {
644 flags: { draft: "string", agent: "string" },
645 usage: "abso diff [file...] [--agent <name>] | abso diff <from> <to> [file...] [--draft <name>]",
646 about:
647 "Your unpushed changes, line by line, as git prints them (records first). --agent <name>: that agent's recorded, unpushed changes instead, to review them; it changes nothing. With two versions: what changed between them in this space.",
648 run: runDiff,
649 },
650 restore: {
651 flags: { all: "boolean" },
652 usage: "abso restore <file...> | abso restore <file>:<line>[-<line>] | abso restore --all",
653 about:
654 "Discard your unpushed changes to those files (--all: to every file), like git restore. The files go back to how your space has them. <file>:<lines> puts back only the changes that touch those lines (numbered as abso diff shows the file now) and keeps your other changes to it.",
655 run: runRestore,
656 },
657 export: {
658 flags: { version: "string", keep: "string", without: "string" },
659 usage: "abso export <dir> [--version <N>] [--without <version,...>] [--keep <glob>]",
660 about:
661 "Write one pushed version of this folder's space (the newest unless --version) into a folder of its own, for a build that doesn't move. The folder must be empty, an earlier export (which it replaces, keeping node_modules and what --keep names), or one .absoignore leaves out; .avcs-export.json there names the version. --without 37,38 writes the version of shared with those earlier versions left out, and names them there too; shared doesn't change, and it is refused, naming the chain, when a version it keeps builds on one left out.",
662 run: runExport,
663 },
664 files: {
665 flags: { draft: "string", version: "string" },
666 usage: "abso files [glob...] [--draft <name>] [--version <N>]",
667 about:
668 "The files your folder should hold (your view), marking any it's missing. With --draft or --version: that space's files at that version (--draft shared for shared).",
669 run: runFiles,
670 },
671 log: {
672 flags: { limit: "string", before: "string", draft: "string", since: "string", by: "string", count: "boolean" },
673 usage:
674 "abso log [file] [-n <count>] [--before <version>] [--draft <name>] [--since <version|30m|2h|1d|date>] [--by <agent,...>] [--count]",
675 about:
676 "The pushed versions of this folder's space (shared or a named draft), newest first: who, when, why and which files, and for shared, whether the version passed CI's check (abso ci). With a file: only the versions that changed it. --before <version> starts below that version, so any stretch of history can be listed; the end of the list names the --before for the next older ones. --since takes a version (the versions after it), a span back from now (30m, 2h, 1d), a clock time today (20:00) or a date and time; --by keeps one agent's versions (or several, comma-separated); --count prints versions and files per agent instead of the list.",
677 run: runLog,
678 },
679 show: {
680 flags: { draft: "string", without: "string" },
681 usage: "abso show <version> | abso show <version>:<file> [--draft <name>] [--without <version,...>]",
682 about:
683 "One version: who pushed it, why, and its diff. With :<file>, that file's text as it was then. --without 37,38 shows the version of shared with those earlier versions left out: what differs, and with :<file> that file. Shared doesn't change. Refused, naming the chain, when a version it keeps builds on one left out.",
684 run: runShow,
685 },
686 announce: {
687 flags: { to: "string" },
688 usage: "abso announce [--to <agent,agent>] <text>",
689 about:
690 "Tell the project's other agents (or those named) something. Each gets it once, as news on their next edit or the mod's next check.",
691 run: runAnnounce,
692 },
693 start: {
694 flags: { done: "boolean", issue: "string" },
695 usage: 'abso start "<what>" [files...] [--issue <n>] | abso start --done',
696 about:
697 "Say what you are starting on, before your first edit, so abso where shows it to everyone. Names who already has unpushed changes in those files, and tells them. Nothing is locked; pushing ends the note.",
698 run: runStart,
699 },
700 news: {
701 flags: {},
702 usage: "abso news",
703 about:
704 "The news waiting for you: collisions, changed definitions, moved lines and announcements. Each item comes once.",
705 run: runNews,
706 },
707 "fix-eol": {
708 flags: {},
709 usage: "abso fix-eol",
710 about:
711 "Rewrite the files that differ from what abso recorded only in line endings (CRLF here) with LF, as recorded. Their text is unchanged, so nothing is recorded; abso status stops listing them.",
712 run: runFixEol,
713 },
714 who: {
715 flags: {},
716 usage: "abso who <file...>",
717 about:
718 "For each file: who last changed it, who has unpushed changes in it (and where), and whose abso start note names it. Ask before you start in someone's file.",
719 run: runWho,
720 },
721 where: {
722 flags: {},
723 usage: "abso where",
724 about: "Who is working where: each file with unpushed changes, whose they are, and which lines.",
725 run: runWhere,
726 },
727 blame: {
728 flags: { from: "string", to: "string", version: "string", draft: "string", mine: "boolean" },
729 usage: "abso blame <file> [--from <n>] [--to <n>] [--version <n>] [--draft <name> | --mine]",
730 about:
731 "Who wrote each line of the file as shared has it (or had it at --version), and the push that brought it in. --draft reads a named draft; --mine reads your own view, marking your unpushed lines with *.",
732 run: runBlame,
733 },
734 why: {
735 flags: { draft: "string", mine: "boolean", at: "string", all: "boolean" },
736 usage: "abso why <file>:<line> [--at <version>] [--all] [--draft <name> | --mine]",
737 about:
738 "Why one line of shared (or of a named draft, or your own view) is the way it is: the newest change to what it does, its push, its reasons, any collision it settled, and the line's earlier changes, newest first. Changes that only touched formatting (whitespace, line wrapping, quotes, trailing commas) are skipped, and why says which; --all shows them too. A line imported from git names its commit, and #N in it names the old repository's issue when abso.json's \"gitIssues\" says where those are. --at <version> reads the line as shared (or the draft) had it then, as blame --version does.",
739 run: runWhy,
740 },
741 drop: {
742 flags: { message: "string", "with-dependents": "boolean" },
743 usage: 'abso drop <version...> -m "<why>" [--with-dependents]',
744 about:
745 "Take pushed versions back out of shared, as a new version: like git revert. History keeps them. Refused when later versions build on them, unless --with-dependents drops those too.",
746 run: runDrop,
747 },
748 pluck: {
749 flags: { message: "string", "with-dependencies": "boolean" },
750 usage: 'abso pluck <draft> <version...> -m "<why>" [--with-dependencies]',
751 about:
752 "Take some versions of a named draft into shared, as one version, leaving the draft as it is: like git cherry-pick. Refused when they build on other versions of the draft, unless --with-dependencies takes those too.",
753 run: runPluck,
754 },
755 amend: {
756 flags: { message: "string" },
757 usage: 'abso amend -m "<new message>"',
758 about:
759 "Correct the message of your newest push in this space. Only the message changes; the log keeps the original.",
760 run: runAmend,
761 },
762 label: {
763 flags: { version: "string", remove: "boolean" },
764 usage: "abso label <name> [--version <n>] [--remove]",
765 about:
766 "Put a label on a version of shared (the newest by default), or take it off: like a git tag. A label can mark more than one version.",
767 run: runLabel,
768 },
769 labels: {
770 flags: {},
771 usage: "abso labels",
772 about: "Every label and the versions it marks.",
773 run: runLabels,
774 },
775 follow: {
776 flags: { none: "boolean" },
777 usage: "abso follow <label> | abso follow --none",
778 about:
779 "Make this folder follow a label: every pull takes it to the newest version of shared with that label, not the newest version. --none goes back to following shared.",
780 run: runFollow,
781 },
782 "check-ignore": {
783 flags: {},
784 usage: "abso check-ignore <path...>",
785 about:
786 "Whether abso leaves each path out, and which line of which ignore file decided (git's rules, for .gitignore and .absoignore).",
787 run: runCheckIgnore,
788 },
789 pipeline: {
790 flags: { on: "string", space: "string", pipeline: "string", every: "string", log: "string" },
791 usage:
792 "abso pipeline check [file] [--on push|draft|green|land|hand|schedule [--space <name>] [--pipeline <name>] [--every <when>]] | abso pipeline runs [<run>] [--log <pipeline.job>]",
793 about:
794 "Read the folder's pipeline file (abso.yml, abso.yaml or avcs.json, or the file named) and say what's wrong with it, place by place: a cycle in needs, a job that doesn't exist, secrets a draft could reach, a key it doesn't know. Exits 1 when it has problems. With --on, it says which pipelines that event starts (in shared, or --space), with their jobs in waves that can run side by side, and why each other pipeline doesn't start. It reads only the file. abso pipeline runs asks the server what the project's pipelines did: the runs, newest first; with a run's number, its jobs (state, why, exit, time, an npm or deploy job's phase); with --log <pipeline.job>, that job's output.",
795 // Loaded only here, so the yaml package it needs can't stop every other command
796 // when a checkout lacks it (abso issue 168).
797 run: async (args, env) => {
798 let mod: typeof import("./pipeline-commands.ts");
799 try {
800 mod = await import("./pipeline-commands.ts");
801 } catch (e) {
802 if ((e as { code?: string }).code === "ERR_MODULE_NOT_FOUND")
803 throw new UsageError(
804 `abso pipeline needs a package this copy of abso doesn't have installed (${(e as Error).message.split("\n")[0]}); run npm install where abso is installed`,
805 );
806 throw e;
807 }
808 return mod.runPipeline(args, env);
809 },
810 },
811};
813const HELP_INTRO = "abso: version control for agents. This is its command-line client.";
814const HELP_NOTE =
815 "Every command takes --json. Settings live in .abso/config.json (.avcs/config.json in a folder from before the rename). The token comes from ABSO_TOKEN, or else ~/.abso/token (or ~/.avcs/token from before). " +
816 "Every command that talks to a server takes --server <url>; one that works only on this machine (skill, check-ignore, pause, resume, fix-eol) doesn't. In a joined folder --server must be the folder's own server: another is refused, never swapped in. An explicit --server is used as given, and no setting redirects it. The server is " +
817 SERVER_ORDER +
818 ": which servers this box is signed in to plays no part.";
820/** A command's flags: its own, and --server for every command that talks to a server (server-choice.ts). */
821function flagsOf(name: string, def: CommandDef): FlagSpec {
822 return serverUse(name) === "local" ? def.flags : { ...def.flags, server: "string" };
823}
825/** Every command as help shows it, in order: the table's, then the three it doesn't hold. */
826function helpEntries(): { name: string; usage: string; about: string; flags: FlagSpec; server?: string }[] {
827 return [
828 ...Object.entries(COMMANDS).map(([name, c]) => {
829 const server = serverHelp(name);
830 return { name, usage: c.usage, about: c.about, flags: flagsOf(name, c), ...(server ? { server } : {}) };
831 }),
832 {
833 name: "hook",
834 usage: "abso hook",
835 about: "The Claude Code PostToolUse hook. Reads the hook JSON on stdin; never fails.",
836 flags: {},
837 },
838 {
839 name: "mcp",
840 usage: "abso mcp",
841 about:
842 "An MCP server on stdin and stdout: the reading commands and the everyday writing ones as tools, answering with the same text as here. Add it with claude mcp add abso -- abso mcp (on Windows, claude mcp add abso -- cmd /c abso mcp).",
843 flags: {},
844 },
845 {
846 name: "--version",
847 usage: "abso --version",
848 about: "This client's version and commit, and the abso mods installed on this machine.",
849 flags: {},
850 },
851 ];
852}
854function help(): string {
855 const entries = helpEntries().flatMap((c) => [
856 ` ${c.usage}`,
857 ` ${c.about}`,
858 ...(c.server ? [` ${c.server}`] : []),
859 ]);
860 return [HELP_INTRO, "", ...entries, "", HELP_NOTE].join("\n");
861}
863/**
864 * help --json: the same entries as data, for a command reference built from the client itself. A flag is
865 * "string" (takes a value), "boolean" (stands alone) or "optional" (a value that may be left off); every
866 * command also takes --json and --help.
867 */
868function helpJson(): Record<string, unknown> {
869 return {
870 ok: true,
871 command: "help",
872 version: clientVersion(),
873 intro: HELP_INTRO,
874 note: HELP_NOTE,
875 commands: helpEntries(),
876 };
877}
879export interface MainResult {
880 readonly stdout: string;
881 readonly stderr: string;
882 readonly exit: number;
883 /** What --json prints, whether or not it was asked for (abso mcp answers with both). */
884 readonly data?: Record<string, unknown>;
885}
887/** The commands, for abso mcp: each tool is one of them. */
888export function commandTable(): Readonly<
889 Record<string, { readonly flags: FlagSpec; readonly usage: string; readonly about: string }>
890> {
891 return Object.fromEntries(Object.entries(COMMANDS).map(([name, c]) => [name, { ...c, flags: flagsOf(name, c) }]));
892}
894function newsBlock(news: readonly string[]): string[] {
895 return newsBlockLines(news.map((n) => newsShown(n)));
896}
898/** Whether this folder's calls carry a key or token, for how a refusal is worded. False when that can't be told. */
899function carriesCredential(env: Env): boolean {
900 try {
901 const root = findRoot(env.cwd);
902 return root ? readConfig(root, env.env).token !== undefined : readToken(env.env) !== undefined;
903 } catch {
904 return false;
905 }
906}
908/** git's forms of push and pull that abso doesn't have (#427): one plain line naming the abso way. */
909function gitOnlyForm(command: string, words: readonly string[]): string | undefined {
910 const has = (...forms: string[]) => words.some((w) => forms.some((f) => w === f || w.startsWith(`${f}=`)));
911 if (command === "push" && has("-f", "--force", "--force-with-lease", "--force-if-includes"))
912 return "abso push has no --force: nothing overwrites shared. When a push is refused, abso pull brings in the other side and abso settle keeps yours, theirs or both.";
913 if (command === "push" && has("-u", "--set-upstream", "--all", "--tags"))
914 return "abso push has no upstreams, branches or tags: it adds your draft to shared. A named draft is abso switch <name>; a label is abso label.";
915 if (command === "pull" && has("--rebase", "-r", "--no-rebase", "--ff-only", "--ff", "--no-ff", "--squash"))
916 return "abso pull has no --rebase or merge modes: it always brings shared under your draft, and lines changed on both sides are listed for abso settle.";
917 return undefined;
918}
920export async function main(argv: readonly string[], env: Env): Promise<MainResult> {
921 const command = argv[0];
922 const json = argv.includes("--json") && command !== "run" && command !== "logs";
923 if (command === undefined || command === "help" || command === "--help" || command === "-h") {
924 if (json) {
925 const data = helpJson();
926 return { stdout: `${JSON.stringify(data, null, 2)}\n`, stderr: "", exit: EXIT.ok, data };
927 }
928 return { stdout: `${help()}\n`, stderr: "", exit: EXIT.ok };
929 }
930 try {
931 if (command === "--version") {
932 // Loaded only here: it runs git, and no other command needs it.
933 const { versionReport } = await import("./install.ts");
934 const { newerClientNote } = await import("./client-version.ts");
935 const report = versionReport(env.env);
936 const root = findRoot(env.cwd);
937 let behind: string | undefined;
938 if (root) {
939 try {
940 const server = (JSON.parse(readFileSync(configPath(root), "utf8")) as { server?: string }).server;
941 if (server) behind = await newerClientNote(server);
942 } catch {}
943 }
944 return {
945 stdout: json
946 ? `${JSON.stringify({ ok: true, command: "version", ...report.json, ...(behind ? { serverBehind: behind } : {}) }, null, 2)}\n`
947 : `${report.text}${behind ? `\n${behind}` : ""}\n`,
948 stderr: "",
949 exit: EXIT.ok,
950 };
951 }
952 const def = COMMANDS[command];
953 if (!def)
954 throw new UsageError(
955 `unknown command ${JSON.stringify(command)}; the commands are ${Object.keys(COMMANDS).join(", ")}, hook, mcp`,
956 );
957 const gitOnly = gitOnlyForm(command, argv.slice(1));
958 if (gitOnly) throw new UsageError(gitOnly);
959 const use = serverUse(command);
960 const words = argv.includes("--") ? argv.slice(1, argv.indexOf("--")) : argv.slice(1);
961 if (use === "local" && words.some((w) => w === "--server" || w.startsWith("--server=")))
962 throw new UsageError(localRefusal(command));
963 const parsed = parseArgs(command, argv.slice(1), withBodyFiles(command, flagsOf(command, def)), def.rest);
964 if ((command === "push" || command === "pull") && parsed.positionals.length > 0)
965 throw new UsageError(
966 `abso ${command} takes no remote or branch: it ${command === "push" ? "adds your draft to shared" : "brings shared into this folder"}. A named draft is abso switch <name>.`,
967 );
968 if (bool(parsed, "help")) {
969 const files = bodyFilesHelp(command, def.flags);
970 const server = serverHelp(command);
971 return {
972 stdout: `${def.usage}\n ${def.about}\n${server ? ` ${server}\n` : ""}${files ? ` ${files}\n` : ""}`,
973 stderr: "",
974 exit: EXIT.ok,
975 };
976 }
977 // --server is checked before anything is read or sent: a bad value, or (for a command on a joined folder)
978 // a server that isn't the folder's own, is refused here.
979 const named = use === "local" ? undefined : serverFlag(parsed);
980 if (named !== undefined && use === "folder") checkFolderServer(command, named, env.cwd);
981 // A folder that reads signed out runs its reads and nothing else, refused before any call.
982 const root = findRoot(env.cwd);
983 if (root !== undefined && isVisitor(root)) checkVisitor(command, parsed, readConfig(root, env.env).project);
984 const args = readBodyFiles(command, parsed, env.cwd, env.readStdin);
985 takeNews(); // what an earlier call in this process left (tests run many)
986 const out = await def.run(args, named === undefined ? env : { ...env, server: named });
987 const exit = out.exit ?? EXIT.ok;
988 // Every command that took news while recording prints it (#37, News Report).
989 const news = takeNews();
990 const data = {
991 ok: exit === EXIT.ok,
992 command,
993 ...out.json,
994 ...(news.length > 0 && !("news" in out.json) ? { news } : {}),
995 };
996 if (json || bool(args, "json")) return { stdout: `${JSON.stringify(data, null, 2)}\n`, stderr: "", exit, data };
997 // run, logs and bisect: stdout is the box command's, and may be piped; news goes to stderr there (#37).
998 const boxOut = command === "run" || command === "logs" || command === "bisect";
999 const text = [...(out.text === "" ? [] : [out.text.replace(/\n$/, "")]), ...(boxOut ? [] : newsBlock(news))].join(
1000 "\n",
1001 );
1002 const errText = boxOut && news.length > 0 ? `${newsBlock(news).join("\n")}\n` : "";
1003 return { stdout: text === "" ? "" : `${text}\n`, stderr: errText, exit, data };
1004 } catch (err) {
1005 const e = err as Error;
1006 const code = err instanceof UsageError ? "usage" : err instanceof ApiError ? "server" : "error";
1007 const message =
1008 plainError(err, carriesCredential(env)) ??
1009 (err instanceof UsageError || err instanceof ApiError
1010 ? e.message
1011 : `${e.message}${e.stack ? `\n${e.stack}` : ""}`);
1012 // The server refusing (409) is like a collision: exit 2, not a failure.
1013 const exit = err instanceof ApiError && err.status === 409 ? EXIT.refused : EXIT.error;
1014 // News taken before the failure still shows.
1015 const news = takeNews();
1016 const data = { ok: false, command, error: { code, message }, ...(news.length > 0 ? { news } : {}) };
1017 if (json) return { stdout: `${JSON.stringify(data, null, 2)}\n`, stderr: "", exit, data };
1018 return {
1019 stdout: news.length > 0 ? `${newsBlock(news).join("\n")}\n` : "",
1020 stderr: `abso ${command}: ${message}\n`,
1021 exit,
1022 data,
1023 };
1024 }
1025}