but-axi 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ed Heltzel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,283 @@
1
- # Temporary Holding Version
1
+ ```text
2
+ ██████╗ ██╗ ██╗████████╗ █████╗ ██╗ ██╗██╗
3
+ ██╔══██╗██║ ██║╚══██╔══╝ ██╔══██╗╚██╗██╔╝██║
4
+ ██████╔╝██║ ██║ ██║ ███████║ ╚███╔╝ ██║
5
+ ██╔══██╗██║ ██║ ██║ ██╔══██║ ██╔██╗ ██║
6
+ ██████╔╝╚██████╔╝ ██║ ██║ ██║██╔╝ ██╗██║
7
+ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝
8
+ ```
2
9
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
10
+ <h1 align="center">but-axi</h1>
11
+
12
+ GitButler CLI for agents, designed with [AXI](https://axi.md) (Agent eXperience Interface).
13
+
14
+ `but-axi` wraps the official GitButler [`but`](https://docs.gitbutler.com/cli-overview) CLI. It runs `but ... --json` underneath and returns token-efficient [TOON](https://github.com/toon-format/toon) output with counts up front, explicit empty states, truncated diffs, structured errors, and `help[]` next-step hints.
15
+ Mutations (commit, branch new, push, undo, redo, oplog snapshot, oplog restore) return their result and a compact workspace summary in one call: workspace path, counts, upstream, and applied branches. That summary is not the full `status` payload (no file list, no commit list).
16
+ It is built for agents that drive version control through a shell.
17
+
18
+ ## AXI principles
19
+
20
+ `but-axi` follows the [10 AXI principles](https://axi.md):
21
+
22
+ | # | Principle | How but-axi does it |
23
+ | - | --------- | ------------------- |
24
+ | 1 | Token-efficient output | TOON tables such as `branches[2]{name,commits,state}:` instead of raw JSON |
25
+ | 2 | Minimal default schemas | 3-4 fields per row. `--fields a,b` adds more |
26
+ | 3 | Content truncation | Patches over 3000 chars and commit bodies over 800 chars are cut, with a size hint and `--full` |
27
+ | 4 | Pre-computed aggregates | A `count:` line first: stacks, branches, commits, uncommitted, conflicts |
28
+ | 5 | Definitive empty states | `branches: 0 applied branches`, `hunks: 0 matching hunks`, `pushed 0 branches (already up to date)` |
29
+ | 6 | Structured errors and exit codes | `error:`, `code:`, `help[]` on stdout. Exit 0 ok, 1 runtime error, 2 usage error. Never prompts. Idempotent commit, branch new, push |
30
+ | 7 | Ambient context | `but-axi setup hooks` installs a SessionStart dashboard for Claude Code, Codex, and Cursor |
31
+ | 8 | Content first | Bare `but-axi` shows live workspace state, not help text |
32
+ | 9 | Contextual disclosure | Every output ends with `help[]` command templates. `-C <path>` is carried forward and runtime values stay placeholders like `<branch>` |
33
+ | 10 | Consistent help | `but-axi <command> --help` is short |
34
+
35
+ ## Quick Start
36
+
37
+ Install the but-axi skill in the [Agent Skills](https://agentskills.io) format with [`npx skills`](https://github.com/vercel-labs/skills):
38
+
39
+ ```sh
40
+ npx skills add edheltzel/but-axi --skill but-axi -g
41
+ ```
42
+
43
+ That is the entire setup - no npm install needed.
44
+ The skill is a minimal discovery stub that directs your agent to the always-current `npx -y but-axi` dashboard and help output instead of duplicating command guidance.
45
+ You still need [GitButler](https://gitbutler.com/downloads) with its [`but`](https://docs.gitbutler.com/cli-overview) CLI, Git, and Node.js 22+.
46
+
47
+ The skill is not a user-facing slash command (`user-invocable: false`).
48
+ Just ask for anything that touches GitButler version control - status, diffs, commits, branches, push, undo/redo - and the agent loads the skill on its own when it recognizes the task.
49
+
50
+ `-g` installs the skill for all projects (`~/.agents/skills/` / `~/.claude/skills/`, for example); drop it to install for the current project only.
51
+
52
+ ## Other Ways to Install
53
+
54
+ The skill is the recommended path, but it is not the only one.
55
+
56
+ ### Zero setup
57
+
58
+ but-axi is an AXI, so any capable agent can run the CLI directly with nothing installed at all.
59
+ Just tell your agent:
60
+
61
+ ```
62
+ Execute `npx -y but-axi` to get GitButler tools.
63
+ ```
64
+
65
+ ### Session hook
66
+
67
+ Want ambient GitButler context - the current workspace dashboard - fed into every agent session instead of loading on demand?
68
+ Install the CLI globally and opt into the hook:
69
+
70
+ ```sh
71
+ npm install -g but-axi
72
+ but-axi setup hooks
73
+ ```
74
+
75
+ This installs a `SessionStart` hook for **Claude Code**, **Codex**, **Cursor**, and **omp** that surfaces the current GitButler workspace state at the start of each session.
76
+ **Restart your agent session after running this** so the new hook takes effect.
77
+
78
+ ### Clone (development)
79
+
80
+ ```sh
81
+ git clone https://github.com/edheltzel/but-axi.git
82
+ cd but-axi
83
+ npm install
84
+ npm link
85
+ but-axi
86
+ but-axi setup hooks
87
+ ```
88
+
89
+ ### Session hook
90
+
91
+ ```sh
92
+ but-axi setup hooks # install for every agent found (claude, codex, cursor, omp)
93
+ but-axi setup hooks --agents claude # only some agents
94
+ but-axi setup hooks --dry-run # show what would change
95
+ but-axi setup hooks --status # installed or not, per agent
96
+ but-axi setup hooks --uninstall # remove the managed entries
97
+ ```
98
+
99
+ | Agent | Config file | Hook |
100
+ | ----- | ----------- | ---- |
101
+ | Claude Code | `~/.claude/settings.json` | `hooks.SessionStart` group, plain text output |
102
+ | Codex | `~/.codex/hooks.json` | `hooks.SessionStart` group, plain text output (needs `[features] hooks = true` in `~/.codex/config.toml`) |
103
+ | Cursor | `~/.cursor/hooks.json` | `hooks.sessionStart` entry, output `{"additional_context": "..."}` |
104
+ | omp | `~/.omp/agent/extensions/but-axi.ts` | Auto-discovered TypeScript extension (no config edit), see below |
105
+
106
+ Setup merges into the existing file and never replaces it. Each file it edits is first copied to `<file>.bak-but-axi-<timestamp>`.
107
+ Running setup again changes nothing (`already installed (no change)`), and a stale entry is repaired in place.
108
+ Install and uninstall find the entry by the marker `# but-axi hook session-start` in the command.
109
+ The hook command uses absolute paths to `node` and the script, so it works when an app starts with a short `PATH`.
110
+ The hook reads the session directory from the hook's stdin JSON (`cwd`, or Cursor's `workspace_roots`) and prints nothing outside a GitButler workspace or on any error.
111
+
112
+ omp has no shell hook config, so but-axi writes a small extension instead, rendered from [`omp/but-axi.ts`](omp/but-axi.ts) with the absolute `node` and script paths baked in.
113
+ On `session_start` it runs `but-axi hook session-start --agent omp` in the session directory (5 second timeout, then SIGTERM and SIGKILL; output capped at 64 KB).
114
+ Before the first agent turn it appends the dashboard to the system prompt. Outside a GitButler workspace, on an error, or on a timeout it adds nothing.
115
+ The file carries the marker `but-axi-omp-extension`. Setup only overwrites or removes a `but-axi.ts` that has the marker, and refuses to touch one that does not.
116
+ Before it updates or removes the file, setup copies it to `~/.omp/agent/but-axi.ts.bak-but-axi-<timestamp>`. The copy goes outside `extensions/` so omp does not load it.
117
+
118
+ Not covered: jcode (its `session_start` setting is a single command that is already in use).
119
+ Cursor note: Cursor has a [known issue](https://forum.cursor.com/t/sessionstart-hook-additional-context-is-never-injected-into-agents-initial-system-context/158452) where `sessionStart` `additional_context` can be dropped.
120
+
121
+ ## Usage
122
+
123
+ ```sh
124
+ but-axi # home view: live workspace state + next steps
125
+ but-axi status # uncommitted files, branches, commits, with IDs
126
+ but-axi status --fields sha,author # extra columns
127
+ but-axi diff # all uncommitted hunks + truncated patch
128
+ but-axi diff <id> --full # one file/commit/branch, complete patch
129
+ but-axi diff --query login # only hunks and patch lines that match
130
+ but-axi show <commit-id|branch> # commit details or branch commit list
131
+ but-axi commit -b <branch> -m "<msg>" # commit everything, return compact summary
132
+ but-axi commit -m "<msg>" <id> <id> # commit selected hunks/files
133
+ but-axi branch # applied + unapplied branches
134
+ but-axi branch list --query <text> # filter that list; --above is only for branch new
135
+ but-axi branch new <name> # idempotent create
136
+ but-axi push [<branch>] [--dry-run] # push, return pushed refs + summary
137
+ but-axi undo | but-axi redo # oplog undo/redo, return compact summary
138
+ but-axi oplog [--limit 20] # operation history
139
+ but-axi oplog snapshot -m "<msg>" # snapshot id + compact summary
140
+ but-axi oplog restore <id> # restore, return compact summary
141
+ but-axi -C ~/code/app status # any command against another directory
142
+ ```
143
+
144
+ Home view in a fresh workspace with two uncommitted files:
145
+
146
+ ```text
147
+ $ but-axi -C /tmp/but-axi-demo/app
148
+ bin: /opt/homebrew/bin/but-axi
149
+ description: Agent-ergonomic GitButler CLI that wraps `but --json` with compact TOON views and combined actions
150
+ workspace: /private/tmp/but-axi-demo/app
151
+ count: 0 stacks; 0 branches; 0 commits; 2 uncommitted; 0 conflicts
152
+ upstream: up to date
153
+ branches: 0 applied branches
154
+ help[4]:
155
+ Run `but-axi -C /tmp/but-axi-demo/app diff` to inspect 2 uncommitted
156
+ Run `but-axi -C /tmp/but-axi-demo/app commit -b <branch> -m "<message>"`
157
+ Run `but-axi -C /tmp/but-axi-demo/app status` for IDs, files and commits
158
+ Run `but-axi -C /tmp/but-axi-demo/app --help` for all commands
159
+ ```
160
+
161
+ A commit returns the new commit and a compact workspace summary in one call:
162
+
163
+ ```text
164
+ $ but-axi -C /tmp/but-axi-demo/app commit -b feature/login -m "feat: add login helper"
165
+ committed:
166
+ id: rqk
167
+ sha: fb48aec
168
+ branch: feature/login
169
+ subject: "feat: add login helper"
170
+ workspace: /private/tmp/but-axi-demo/app
171
+ count: 1 stack; 1 branch; 1 commit (1 on unpushed branches); 0 uncommitted; 0 conflicts
172
+ upstream: up to date
173
+ branches[1]{name,commits,state}:
174
+ feature/login,1,unpushed
175
+ help[3]:
176
+ Run `but-axi -C /tmp/but-axi-demo/app push feature/login`
177
+ Run `but-axi -C /tmp/but-axi-demo/app show rqk`
178
+ Run `but-axi -C /tmp/but-axi-demo/app undo` to revert this commit
179
+ ```
180
+
181
+ Push works the same way:
182
+
183
+ ```text
184
+ $ but-axi -C /tmp/but-axi-demo/app push feature/login
185
+ result: pushed 1 branch
186
+ pushed[1]{branch,remote,from,to}:
187
+ feature/login,origin,(new),fb48aec
188
+ workspace: /private/tmp/but-axi-demo/app
189
+ count: 1 stack; 1 branch; 1 commit (0 on unpushed branches); 0 uncommitted; 0 conflicts
190
+ upstream: up to date
191
+ branches[1]{name,commits,state}:
192
+ feature/login,1,pushed
193
+ help[2]:
194
+ Run `but pr new <branch> -m "<title>"` to open a PR (raw but)
195
+ Run `but-axi -C /tmp/but-axi-demo/app status`
196
+ ```
197
+
198
+ Long patches are cut with a size hint:
199
+
200
+ ```text
201
+ patch_note: "(truncated, 24979 chars total — use --full to see complete diff)"
202
+ ```
203
+
204
+ ### Commands
205
+
206
+ | Command | Description |
207
+ | ------- | ----------- |
208
+ | *(none)* | Home view: `bin`, `description`, workspace, counts, branches, `help[]` |
209
+ | `status` | `uncommitted{id,path,change}`, `branches{id,name,commits,state}`, `commits{id,branch,subject}` |
210
+ | `diff [<id>]` | `hunks{id,path,status,lines}` plus a truncated `patch` |
211
+ | `show <id\|branch>` | Commit: id, sha, author, date, subject, body, files. Branch: commits, base, stackedOn |
212
+ | `commit` | `-m` (repeatable), `-b <branch>`, optional change IDs. Never opens an editor. With nothing to commit it prints `skipped` and exits 0 |
213
+ | `branch [list\|new\|show]` | List, create (an existing branch is reported as `already exists (no change)`), show |
214
+ | `push [<branch>]` | `--dry-run`, `--with-force`, `--no-verify`. Already pushed gives `pushed 0 branches` and exit 0 |
215
+ | `undo`, `redo` | Oplog undo or redo plus the compact workspace summary |
216
+ | `oplog [list\|snapshot\|restore]` | list: `--limit <n>`. snapshot: `-m <msg>`, returns the snapshot id and compact summary. restore: `<id>` and that summary. A flag from the wrong subcommand is a usage error |
217
+ | `setup hooks` | `--status`, `--uninstall`, `--agents`, `--dry-run` |
218
+ | `hook session-start` | Hook entrypoint (`--agent claude\|codex\|cursor\|omp`). Any other agent name is a usage error |
219
+ | `version` | Print the version. Extra arguments are a usage error |
220
+
221
+ ### Global flags
222
+
223
+ - `-C <path>` runs against another directory. It is carried forward into `help[]`.
224
+ - `--fields a,b` adds columns from a list's extra fields. `<command> --help` lists them. An unknown field exits 2.
225
+ - `--full` turns off truncation and row caps.
226
+ - `--query <text>` (`-q`) keeps only matching rows and patch lines, and reports `query:` and `matched: N of M`.
227
+ - `--help` (`-h`) prints short help for any command.
228
+ - `--version` (`-v`, `-V`) prints the version. A bare version flag does not load command handlers.
229
+
230
+ ### Exit codes and errors
231
+
232
+ | Exit | Meaning |
233
+ | ---- | ------- |
234
+ | 0 | Success, including no-op results such as `skipped` or `already exists` |
235
+ | 1 | Runtime error from `but` or but-axi, such as not a workspace, unknown ID, or a failed push |
236
+ | 2 | Usage error: unknown command, flag, or `--fields` value; missing or invalid argument (including missing `-m` and a bad `--limit`); extra argument |
237
+
238
+ Errors go to stdout in the same TOON shape. Debug output goes to stderr, and only when `BUT_AXI_DEBUG=1` is set.
239
+
240
+ ```text
241
+ $ but-axi status --verbose
242
+ error: unknown flag --verbose
243
+ code: UNKNOWN_FLAG
244
+ help[1]:
245
+ Run `but-axi status --help` to see supported flags
246
+ ```
247
+
248
+ ### help[] hints
249
+
250
+ Each response ends with `help[N]:` lines, which are ready-to-run command templates.
251
+ Fixed context (`-C <path>`) is carried forward. Values the agent has to choose stay as placeholders (`<branch>`, `<id>`, `"<message>"`). Values known from the result, such as the branch a commit landed on, are filled in.
252
+
253
+ ### Environment
254
+
255
+ - `BUT_AXI_BUT=/path/to/but` sets which `but` binary to use. By default but-axi looks on `PATH`, then in `/opt/homebrew/bin`, `/usr/local/bin`, and `~/.local/bin`.
256
+ - `BUT_AXI_NODE=/path/to/node` sets the node binary written into hook commands. The default is `/opt/homebrew/bin/node` when it exists.
257
+ - `BUT_AXI_DEBUG=1` writes the `but` invocations to stderr.
258
+
259
+ ## Fallback to raw `but`
260
+
261
+ but-axi wraps the core loop: inspect, commit, branch, push, and undo.
262
+ For everything else, use `but` directly: `amend`, `absorb`, `squash`, `move`, `reword`, `uncommit`, `discard`, `resolve`, `apply`, `unapply`, `pull`, `pr`, `land`, `pick`, `worktree`, `setup`, `teardown`.
263
+ If you call one of these on but-axi, it exits 2 and tells you to use `but <command> --help`.
264
+ CLI IDs from `but-axi status` and `but-axi diff` are the same IDs `but` uses, so you can pass them straight to `but`.
265
+
266
+ ## Agent skill
267
+
268
+ The `gitbutler-axi` Agent Skill (`~/.agents/skills/gitbutler-axi/SKILL.md` on the author's machine) teaches agents when to use but-axi, how to read its output, and when to fall back to raw `but`.
269
+ The hook gives an agent context at the start of every session. The skill gives it the full guide when it needs one.
270
+
271
+ ## Development
272
+
273
+ ```sh
274
+ npm install # dependencies + build (prepare)
275
+ npm run build # tsc -> dist/
276
+ npm test # build + vitest (unit tests + CLI exit-code tests + a real `but` flow in /tmp)
277
+ ```
278
+
279
+ The integration suite creates a throwaway repo and a bare remote under `/tmp`, runs `but setup`, then commits, pushes, and undoes there. It is skipped when `but` is not installed.
280
+
281
+ ## License
282
+
283
+ MIT
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { isBareVersion, VERSION } from "../src/version.js";
3
+ process.stdout.on("error", (e) => {
4
+ if (e.code === "EPIPE")
5
+ process.exit(0);
6
+ throw e;
7
+ });
8
+ const argv = process.argv.slice(2);
9
+ if (isBareVersion(argv)) {
10
+ process.stdout.write(`${VERSION}\n`, () => process.exit(0));
11
+ }
12
+ else {
13
+ const { main } = await import("../src/cli.js");
14
+ const { stdout, exitCode } = await main(argv);
15
+ process.stdout.write(stdout, () => process.exit(exitCode));
16
+ }
@@ -0,0 +1,118 @@
1
+ import { UsageError } from "./errors.js";
2
+ /** Flags every command accepts. */
3
+ export const GLOBAL_FLAGS = {
4
+ help: { type: "boolean", short: "h" },
5
+ full: { type: "boolean" },
6
+ fields: { type: "string" },
7
+ query: { type: "string", short: "q" },
8
+ cwd: { type: "string", short: "C" },
9
+ };
10
+ /**
11
+ * Strict argv parser: unknown flags and missing values throw UsageError (exit 2).
12
+ * Supports `--flag value`, `--flag=value`, `-f value`, `-fvalue` is NOT supported, `--` ends flags.
13
+ */
14
+ export function parseArgs(argv, spec, cmd) {
15
+ const all = { ...GLOBAL_FLAGS, ...spec };
16
+ const byLong = new Map();
17
+ const byShort = new Map();
18
+ for (const [name, def] of Object.entries(all)) {
19
+ byLong.set(name, name);
20
+ for (const a of def.aliases ?? [])
21
+ byLong.set(a, name);
22
+ if (def.short)
23
+ byShort.set(def.short, name);
24
+ for (const s of def.shorts ?? [])
25
+ byShort.set(s, name);
26
+ }
27
+ const flags = {};
28
+ const positionals = [];
29
+ const helpHint = `Run \`but-axi ${cmd ? cmd + " " : ""}--help\` to see supported flags`;
30
+ for (let i = 0; i < argv.length; i++) {
31
+ const arg = argv[i];
32
+ if (arg === "--") {
33
+ positionals.push(...argv.slice(i + 1));
34
+ break;
35
+ }
36
+ let name;
37
+ let inline;
38
+ let display = arg;
39
+ if (arg.startsWith("--")) {
40
+ const eq = arg.indexOf("=");
41
+ const key = eq >= 0 ? arg.slice(2, eq) : arg.slice(2);
42
+ if (eq >= 0)
43
+ inline = arg.slice(eq + 1);
44
+ display = `--${key}`;
45
+ name = byLong.get(key);
46
+ }
47
+ else if (arg.startsWith("-") && arg.length > 1 && !/^-\d/.test(arg)) {
48
+ const key = arg.slice(1);
49
+ name = key.length === 1 ? byShort.get(key) : undefined;
50
+ }
51
+ else {
52
+ positionals.push(arg);
53
+ continue;
54
+ }
55
+ if (!name)
56
+ throw new UsageError(`unknown flag ${display}`, [helpHint], "UNKNOWN_FLAG");
57
+ const def = all[name];
58
+ if (def.type === "boolean") {
59
+ if (inline !== undefined)
60
+ throw new UsageError(`flag ${display} does not take a value`, [helpHint]);
61
+ flags[name] = true;
62
+ continue;
63
+ }
64
+ let value = inline;
65
+ if (value === undefined) {
66
+ const next = argv[i + 1];
67
+ if (next === undefined)
68
+ throw new UsageError(`flag ${display} requires a value`, [helpHint], "MISSING_VALUE");
69
+ value = next;
70
+ i++;
71
+ }
72
+ if (def.type === "strings") {
73
+ const prev = flags[name] ?? [];
74
+ flags[name] = [...prev, value];
75
+ }
76
+ else {
77
+ flags[name] = value;
78
+ }
79
+ }
80
+ return { flags, positionals };
81
+ }
82
+ export function str(p, name) {
83
+ const v = p.flags[name];
84
+ return typeof v === "string" ? v : undefined;
85
+ }
86
+ export function bool(p, name) {
87
+ return p.flags[name] === true;
88
+ }
89
+ export function strs(p, name) {
90
+ const v = p.flags[name];
91
+ return Array.isArray(v) ? v : [];
92
+ }
93
+ export function fieldsOf(p) {
94
+ const v = str(p, "fields");
95
+ if (!v)
96
+ return [];
97
+ return v
98
+ .split(",")
99
+ .map((s) => s.trim())
100
+ .filter(Boolean);
101
+ }
102
+ /** Reject surplus positionals (fail loud instead of silently ignoring). */
103
+ export function maxPositionals(p, n, cmd) {
104
+ if (p.positionals.length > n) {
105
+ throw new UsageError(`unexpected argument ${p.positionals[n]}`, [`Run \`but-axi ${cmd} --help\``], "UNEXPECTED_ARGUMENT");
106
+ }
107
+ }
108
+ /** Reject flags that belong to a sibling subcommand (fail loud instead of silently ignoring). */
109
+ export function rejectFlags(p, names, cmd, hint) {
110
+ for (const name of names) {
111
+ if (p.flags[name] === undefined)
112
+ continue;
113
+ const help = [`Run \`but-axi ${cmd} --help\``];
114
+ if (hint)
115
+ help.push(hint);
116
+ throw new UsageError(`unexpected flag --${name}`, help, "UNEXPECTED_FLAG");
117
+ }
118
+ }
@@ -0,0 +1,134 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, join } from "node:path";
5
+ import { AxiError } from "./errors.js";
6
+ export function debug(msg) {
7
+ if (process.env.BUT_AXI_DEBUG)
8
+ process.stderr.write(`[but-axi] ${msg}\n`);
9
+ }
10
+ let cachedBut;
11
+ /** Locate the `but` binary: $BUT_AXI_BUT, then PATH, then common install dirs (hooks may run with a thin PATH). */
12
+ export function resolveBut() {
13
+ if (process.env.BUT_AXI_BUT)
14
+ return process.env.BUT_AXI_BUT;
15
+ if (cachedBut)
16
+ return cachedBut;
17
+ const dirs = [
18
+ ...(process.env.PATH ?? "").split(delimiter).filter(Boolean),
19
+ "/opt/homebrew/bin",
20
+ "/usr/local/bin",
21
+ join(homedir(), ".local", "bin"),
22
+ ];
23
+ for (const d of dirs) {
24
+ const p = join(d, "but");
25
+ if (existsSync(p)) {
26
+ cachedBut = p;
27
+ return p;
28
+ }
29
+ }
30
+ cachedBut = "but";
31
+ return cachedBut;
32
+ }
33
+ function parseJson(text) {
34
+ const t = text.trim();
35
+ if (!t || (t[0] !== "{" && t[0] !== "["))
36
+ return undefined;
37
+ try {
38
+ return JSON.parse(t);
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ /** Run `but -C <cwd> <args> --json` non-interactively (stdin closed, pager/editor disabled). */
45
+ export function runBut(args, cwd, json = true) {
46
+ const bin = resolveBut();
47
+ const full = ["-C", cwd, ...args, ...(json ? ["--json"] : [])];
48
+ debug(`exec ${bin} ${full.join(" ")}`);
49
+ const r = spawnSync(bin, full, {
50
+ encoding: "utf8",
51
+ stdio: ["ignore", "pipe", "pipe"],
52
+ timeout: 120_000,
53
+ maxBuffer: 64 * 1024 * 1024,
54
+ env: {
55
+ ...process.env,
56
+ BUT_PAGER: "cat",
57
+ PAGER: "cat",
58
+ GIT_PAGER: "cat",
59
+ NO_COLOR: "1",
60
+ GIT_TERMINAL_PROMPT: "0",
61
+ GIT_EDITOR: "true",
62
+ EDITOR: "true",
63
+ VISUAL: "true",
64
+ },
65
+ });
66
+ if (r.error) {
67
+ const code = r.error.code;
68
+ if (code === "ENOENT") {
69
+ throw new AxiError("GitButler CLI `but` not found", "BUT_NOT_FOUND", [
70
+ "Install GitButler (https://gitbutler.com) and enable its CLI: https://docs.gitbutler.com/cli-overview",
71
+ "Or set BUT_AXI_BUT=/path/to/but",
72
+ ]);
73
+ }
74
+ throw new AxiError(`failed to run but: ${r.error.message}`, "BUT_EXEC_FAILED");
75
+ }
76
+ const stdout = r.stdout ?? "";
77
+ const stderr = r.stderr ?? "";
78
+ debug(`exit ${r.status} stdout=${stdout.length}B stderr=${stderr.length}B`);
79
+ if (stderr && process.env.BUT_AXI_DEBUG)
80
+ process.stderr.write(stderr);
81
+ return { code: r.status ?? 1, stdout, stderr, json: parseJson(stdout) };
82
+ }
83
+ /** Run and return parsed JSON, throwing a structured AxiError on failure. */
84
+ export function butJson(args, cwd) {
85
+ const r = runBut(args, cwd);
86
+ if (r.code !== 0)
87
+ throw butError(r, args);
88
+ if (r.json === undefined) {
89
+ // Some mutations print nothing in JSON mode; treat as an empty object.
90
+ return {};
91
+ }
92
+ return r.json;
93
+ }
94
+ export function cleanMessage(text) {
95
+ const lines = text
96
+ .split("\n")
97
+ .map((l) => l.trim())
98
+ .filter(Boolean)
99
+ .filter((l) => !/^(Usage:|For more information)/.test(l));
100
+ const first = (lines[0] ?? "").replace(/^Error:\s*/i, "").replace(/^error:\s*/, "");
101
+ return first;
102
+ }
103
+ /** Convert a failed `but` invocation into a structured error. */
104
+ export function butError(r, args) {
105
+ const j = r.json;
106
+ const help = [];
107
+ let code = "BUT_ERROR";
108
+ let message;
109
+ if (j && typeof j === "object" && typeof j.error === "string") {
110
+ code = j.error.toUpperCase();
111
+ message = j.message ?? j.error;
112
+ if (j.hint)
113
+ help.push(`but hint: ${j.hint}`);
114
+ }
115
+ else {
116
+ message = cleanMessage(r.stderr) || cleanMessage(r.stdout) || `but ${args[0]} exited ${r.code}`;
117
+ // but sometimes repeats the message twice on one line
118
+ const half = message.length / 2;
119
+ if (Number.isInteger(half - 0.5) && message.slice(0, half - 0.5) === message.slice(half + 0.5)) {
120
+ message = message.slice(0, half - 0.5);
121
+ }
122
+ }
123
+ if (/No GitButler project|No git repository|setup required/i.test(message) || code === "SETUP_REQUIRED") {
124
+ code = "NOT_A_WORKSPACE";
125
+ help.length = 0;
126
+ help.push("Run `but setup` in the repository to enable GitButler (raw but; not wrapped)");
127
+ help.push("Or pass `-C <path>` to point at a GitButler workspace");
128
+ }
129
+ else {
130
+ const label = ["branch", "oplog"].includes(args[0] ?? "") && args[1] && !args[1].startsWith("-") ? `${args[0]} ${args[1]}` : args[0];
131
+ help.push(`Run \`but ${label} --help\` for raw but usage`);
132
+ }
133
+ return new AxiError(message, code, help);
134
+ }