@halfwhey/claudraband-core 0.1.0 → 0.3.0

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/README.md ADDED
@@ -0,0 +1,153 @@
1
+ <div align="center">
2
+
3
+ # claudraband
4
+
5
+ Claude Code for the power user
6
+
7
+ > Experimental: this project is still evolving and parts of it may break as Claude Code and ACP clients change.
8
+
9
+ [Quick start](#quick-start) •
10
+ [CLI](docs/cli.md) •
11
+ [Library](docs/library.md) •
12
+ [Examples](#examples) •
13
+ [Troubleshooting](#troubleshooting)
14
+
15
+ </div>
16
+
17
+ `claudraband` wraps a Claude Code TUI in a controlled terminal to enable extended workflows. This project provides:
18
+
19
+ - Resumable non-interactive workflows. Essentially `claude -p` with session support: `cband continue <session-id> 'what was the result of the research?'`
20
+ - HTTP server to remotely control a Claude Code session: `cband serve --port 1234`
21
+ - ACP server to use with alternative frontends such as Zed or Toad (https://github.com/batrachianai/toad): `cband acp --model haiku`
22
+ - TypeScript library so you can integrate these workflows into your own application.
23
+
24
+ ## Caveats
25
+
26
+ - This is not a replacement for the Claude SDK. It is geared toward personal, ad-hoc usage.
27
+ - We do not touch OAuth and we do not bypass the Claude Code TUI. You must authenticate through Claude Code, and every interaction runs through a real Claude Code session.
28
+
29
+ ## Requirements
30
+
31
+ - Node.js or Bun
32
+ - An already authenticated Claude Code
33
+ - `tmux` if you want visible persistent local sessions
34
+
35
+ ## Install
36
+
37
+ ```sh
38
+ # run without installing globally
39
+ npx @halfwhey/claudraband "review the staged diff"
40
+
41
+ # or install it once
42
+ npm install -g @halfwhey/claudraband
43
+ ```
44
+
45
+ If you prefer Bun:
46
+
47
+ ```sh
48
+ bunx @halfwhey/claudraband "review the staged diff"
49
+ ```
50
+
51
+ `claudraband` installs a pinned Claude Code version, `@anthropic-ai/claude-code@2.1.96`, as a dependency for compatibility. It will be bumped over time. If you need to point at a different Claude binary for debugging or compatibility work, set `CLAUDRABAND_CLAUDE_PATH`.
52
+
53
+
54
+ ## Quick start
55
+
56
+ The package installs both `cband` and `claudraband`. The shorter `cband` binary is the recommended CLI. The two first-class ways to use `cband` are:
57
+
58
+ - local persistent sessions with `tmux`
59
+ - headless persistent sessions with `serve`
60
+
61
+ ### Visible persistent sessions with `tmux`
62
+
63
+ ```sh
64
+ cband "audit the last commit and tell me what looks risky"
65
+
66
+ cband sessions
67
+
68
+ cband continue <session-id> "keep going"
69
+
70
+ # if Claude is waiting on a choice
71
+ cband continue <session-id> --select 2
72
+ cband continue <session-id> --select 3 "xyz"
73
+ ```
74
+
75
+ ### Headless persistent sessions with `serve`
76
+
77
+ ```sh
78
+ cband serve --host 127.0.0.1 --port 7842
79
+ cband --connect localhost:7842 "start a migration plan"
80
+ cband attach <session-id>
81
+ cband continue <session-id> --select 2
82
+ ```
83
+
84
+ The daemon now defaults to `tmux`, just like the local first-class path. Use `--connect` only when starting a new daemon-backed session. After that, `continue`, `attach`, and `sessions` route through the tracked session automatically.
85
+
86
+ `--backend xterm` still exists, but it is experimental while we improve it.
87
+
88
+ ### Using the CLI without tmux or server (experimental)
89
+
90
+ If you run `cband "..."` without `tmux` and without `--connect`, `cband` falls back to a local headless `xterm.js` session. This backend is **experimental** and slower than tmux. It is useful for one-off runs, but it is not a good default for interactive follow-up because the session is not kept alive between commands.
91
+
92
+ The xterm backend cannot handle Claude Code's initial startup prompts (trust folder, bypass permissions confirmation). You must disable these before using it:
93
+
94
+ - `-c "--dangerously-skip-permissions"`
95
+ - `--permission-mode bypassPermissions`
96
+
97
+ Without `tmux` or server mode, `cband` shuts down Claude Code after each command finishes and starts it again on the next one. If the last output was a question for the user, that question will not survive well across the next resume. Interactive question flows work best with persistent sessions.
98
+
99
+ ### ACP and editor integration
100
+
101
+ Use ACP when another tool wants to drive Claude through `claudraband`.
102
+
103
+ ```sh
104
+ cband acp --model opus
105
+
106
+ # for example with toad
107
+ uvx --from batrachian-toad toad acp 'cband acp -c "--model haiku"'
108
+ ```
109
+
110
+ Some ACP clients still have limitations around resuming existing sessions. `claudraband` itself supports session follow and resume as part of the ACP protocol, but the frontend you put on top may not expose all of that yet.
111
+
112
+ ## Session model
113
+
114
+ Live sessions are tracked in `~/.claudraband/`.
115
+
116
+ - `cband sessions` shows only live tracked sessions, either hosted by tmux directly or by the daemon.
117
+ - `continue` can resume an existing Claude Code session even when it is no longer live, but `attach` only works on live sessions.
118
+ - `sessions close ...` closes live sessions hosted by tmux directly or by the daemon
119
+ - `sessions close --all` will close all live sessions controlled by Claudraband
120
+
121
+ ## Examples
122
+
123
+ ### Self-interrogation
124
+
125
+ I have a Claude Code hook that saves the session id that was involved in a commit so I can ask it questions about the commit later. In this workflow, Claude can use `claudraband` to interrogate that older session and justify the choices it made.
126
+
127
+ ![Claude interrogating an older Claude session through claudraband](assets/self-interrogate.png)
128
+
129
+ ### Toad via ACP
130
+
131
+ Toad can use `claudraband acp` to be an alternative frontend for Claude Code.
132
+
133
+ ![Toad using claudraband ACP as an alternative frontend](assets/toad-acp.png)
134
+
135
+ That UI is backed by a real Claude Code pane underneath.
136
+
137
+ ![Backing Claude Code pane for the Toad ACP session](assets/toad-claude-pane.png)
138
+
139
+ ### Zed via ACP
140
+
141
+ Zed can also use `claudraband acp` to be an alternative frontend.
142
+
143
+ ![Zed using claudraband ACP as an alternative frontend](assets/zed-acp.png)
144
+
145
+ ## Library use
146
+
147
+ Runnable TypeScript examples live in [`examples/`](examples):
148
+
149
+ - [`examples/code-review.ts`](examples/code-review.ts) starts a session, asks for a review, and prints the result
150
+ - [`examples/multi-session.ts`](examples/multi-session.ts) runs multiple Claude sessions in parallel
151
+ - [`examples/session-journal.ts`](examples/session-journal.ts) resumes a session and writes a simple journal
152
+
153
+ For the full TypeScript API, see [docs/library.md](docs/library.md).
@@ -41,6 +41,9 @@ export declare class ClaudeWrapper implements Wrapper {
41
41
  /**
42
42
  * Poll the terminal until Claude Code is ready to accept input.
43
43
  * Looks for "INSERT" in the status bar, which indicates the TUI has loaded.
44
+ *
45
+ * Also handles the "trust this folder" prompt that appears before any JSONL
46
+ * is written when Claude Code runs in a directory for the first time.
44
47
  */
45
48
  private waitForReady;
46
49
  stop(): Promise<void>;
package/dist/index.js CHANGED
@@ -1096,6 +1096,9 @@ class ClaudeWrapper {
1096
1096
  if (pane.includes("INSERT") || pane.includes("NORMAL")) {
1097
1097
  return;
1098
1098
  }
1099
+ if (pane.includes("Yes, I trust this folder") && pane.includes("No, exit") || pane.includes("Bypass Permissions mode") && pane.includes("Yes, I accept")) {
1100
+ return;
1101
+ }
1099
1102
  } catch {}
1100
1103
  await new Promise((r) => setTimeout(r, POLL_MS));
1101
1104
  }
@@ -1178,6 +1181,9 @@ function parseClaudeArgs(args) {
1178
1181
  }
1179
1182
  // src/claude/inspect.ts
1180
1183
  import { readFile } from "node:fs/promises";
1184
+ function normalizeCapturedPane(paneText) {
1185
+ return paneText.replace(/\r/g, "").replace(/\x1b\[(\d+)C/g, (_match, count) => " ".repeat(Number.parseInt(count, 10) || 0)).replace(/\x1b\[[0-9;]*[ABDHJKf]/g, "").replace(/\x1b\[\?[0-9;]*[a-zA-Z]/g, "").replace(/\x1b\[[0-9;]*m/g, "").replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
1186
+ }
1181
1187
  async function hasPendingQuestion(jsonlPath) {
1182
1188
  let data;
1183
1189
  try {
@@ -1211,10 +1217,20 @@ async function hasPendingQuestion(jsonlPath) {
1211
1217
  return pendingIds.size > 0;
1212
1218
  }
1213
1219
  function parseNativePermissionPrompt(paneText) {
1214
- const questionMatch = paneText.match(/(?:^|\n)\s*(Do you want to [^\n]+\?)/);
1220
+ const normalizedPane = normalizeCapturedPane(paneText);
1221
+ const isTrustPrompt = normalizedPane.includes("Yes, I trust this folder") && normalizedPane.includes("No, exit");
1222
+ const isBypassPrompt = normalizedPane.includes("Bypass Permissions mode") && normalizedPane.includes("Yes, I accept");
1223
+ let questionMatch;
1224
+ if (isTrustPrompt) {
1225
+ questionMatch = normalizedPane.match(/(Is this a project you created[^\n]*)/);
1226
+ } else if (isBypassPrompt) {
1227
+ questionMatch = normalizedPane.match(/(you accept all responsibility[^\n]*)/);
1228
+ } else {
1229
+ questionMatch = normalizedPane.match(/(?:^|\n)\s*(Do you want to [^\n]+\?)/);
1230
+ }
1215
1231
  if (!questionMatch)
1216
1232
  return null;
1217
- const afterQuestion = paneText.slice(paneText.indexOf(questionMatch[1]) + questionMatch[1].length);
1233
+ const afterQuestion = normalizedPane.slice(normalizedPane.indexOf(questionMatch[1]) + questionMatch[1].length);
1218
1234
  const optionRegex = /(?:❯\s*)?(\d+)\.\s+(.+)/g;
1219
1235
  const options = [];
1220
1236
  let match;
@@ -1389,6 +1405,10 @@ var TERMINAL_BACKENDS = [
1389
1405
  description: "Run Claude Code in a headless xterm-backed PTY"
1390
1406
  }
1391
1407
  ];
1408
+ function isRejectingNativeOption(label) {
1409
+ const normalized = label.trim().toLowerCase();
1410
+ return normalized.startsWith("no") || normalized.startsWith("reject");
1411
+ }
1392
1412
  function makeDefaultLogger() {
1393
1413
  const noop = () => {};
1394
1414
  return {
@@ -1510,6 +1530,8 @@ class ClaudrabandSessionImpl {
1510
1530
  _permissionMode;
1511
1531
  allowTextResponses;
1512
1532
  sessionOwner;
1533
+ lastNativePermissionFingerprint = null;
1534
+ lastNativePermissionOutcome = "none";
1513
1535
  constructor(wrapper, sessionId, cwd, backend, model, permissionMode, allowTextResponses, logger, onPermissionRequest, lifetime, sessionOwner) {
1514
1536
  this.sessionId = sessionId;
1515
1537
  this.cwd = cwd;
@@ -1544,7 +1566,20 @@ class ClaudrabandSessionImpl {
1544
1566
  const prompt = this.newPromptWaiter(text);
1545
1567
  this.activePrompt = prompt;
1546
1568
  this.logger.info("prompt received", "sid", this.sessionId, "length", text.length);
1547
- await this.wrapper.send(text);
1569
+ const startupState = await this.prepareForInput(text);
1570
+ if (startupState === "blocked") {
1571
+ this.activePrompt = null;
1572
+ this.promptAbortController = null;
1573
+ return { stopReason: "end_turn" };
1574
+ }
1575
+ if (startupState === "cancelled") {
1576
+ this.activePrompt = null;
1577
+ this.promptAbortController = null;
1578
+ return { stopReason: "cancelled" };
1579
+ }
1580
+ if (startupState !== "consumed") {
1581
+ await this.wrapper.send(text);
1582
+ }
1548
1583
  try {
1549
1584
  const stopReason = await this.waitForPromptCompletion(prompt, controller.signal);
1550
1585
  this.logger.info("prompt completed", "sid", this.sessionId, "stop_reason", stopReason);
@@ -1567,6 +1602,17 @@ class ClaudrabandSessionImpl {
1567
1602
  const prompt = this.newPromptWaiter("");
1568
1603
  prompt.matchedUserEcho = true;
1569
1604
  this.activePrompt = prompt;
1605
+ const startupState = await this.prepareForInput(null);
1606
+ if (startupState === "blocked") {
1607
+ this.activePrompt = null;
1608
+ this.promptAbortController = null;
1609
+ return { stopReason: "end_turn" };
1610
+ }
1611
+ if (startupState === "cancelled") {
1612
+ this.activePrompt = null;
1613
+ this.promptAbortController = null;
1614
+ return { stopReason: "cancelled" };
1615
+ }
1570
1616
  this.logger.info("awaitTurn", "sid", this.sessionId);
1571
1617
  try {
1572
1618
  const stopReason = await this.waitForPromptCompletion(prompt, controller.signal);
@@ -1590,6 +1636,26 @@ class ClaudrabandSessionImpl {
1590
1636
  const prompt = this.newPromptWaiter("");
1591
1637
  prompt.matchedUserEcho = true;
1592
1638
  this.activePrompt = prompt;
1639
+ const startupState = await this.prepareForInput(text);
1640
+ if (startupState === "blocked") {
1641
+ this.activePrompt = null;
1642
+ this.promptAbortController = null;
1643
+ return { stopReason: "end_turn" };
1644
+ }
1645
+ if (startupState === "cancelled") {
1646
+ this.activePrompt = null;
1647
+ this.promptAbortController = null;
1648
+ return { stopReason: "cancelled" };
1649
+ }
1650
+ if (startupState === "consumed") {
1651
+ if (this.activePrompt === prompt) {
1652
+ this.activePrompt = null;
1653
+ }
1654
+ if (this.promptAbortController === controller) {
1655
+ this.promptAbortController = null;
1656
+ }
1657
+ return { stopReason: "end_turn" };
1658
+ }
1593
1659
  this.logger.info("sendAndAwaitTurn", "sid", this.sessionId, "length", text.length);
1594
1660
  await this.wrapper.send(text);
1595
1661
  try {
@@ -1608,6 +1674,21 @@ class ClaudrabandSessionImpl {
1608
1674
  send(text) {
1609
1675
  return this.wrapper.send(text);
1610
1676
  }
1677
+ async prepareForInput(intendedText) {
1678
+ const handled = await this.pollNativePermission(null, intendedText);
1679
+ if (handled === "handled" || handled === "consumed" || handled === "pending_clear") {
1680
+ const ready = await this.waitForInsertMode();
1681
+ if (!ready) {
1682
+ return this.wrapper.isProcessAlive() ? "blocked" : "cancelled";
1683
+ }
1684
+ return handled === "consumed" ? "consumed" : "ready";
1685
+ }
1686
+ const stillBlocking = hasPendingNativePrompt(await this.wrapper.capturePane().catch(() => ""));
1687
+ if (stillBlocking) {
1688
+ return "blocked";
1689
+ }
1690
+ return "ready";
1691
+ }
1611
1692
  async interrupt() {
1612
1693
  this.promptAbortController?.abort();
1613
1694
  await this.wrapper.interrupt();
@@ -1927,7 +2008,7 @@ class ClaudrabandSessionImpl {
1927
2008
  }
1928
2009
  if (prompt.pendingTools > 0) {
1929
2010
  const handled = await this.pollNativePermission(prompt.lastPendingTool);
1930
- if (handled) {
2011
+ if (handled === "handled" || handled === "consumed") {
1931
2012
  prompt.pendingTools = Math.max(0, prompt.pendingTools - 1);
1932
2013
  prompt.gotResponse = true;
1933
2014
  prompt.lastPendingTool = null;
@@ -1942,16 +2023,28 @@ class ClaudrabandSessionImpl {
1942
2023
  }
1943
2024
  }
1944
2025
  }
1945
- async pollNativePermission(pendingTool) {
2026
+ async pollNativePermission(pendingTool, intendedText = null) {
1946
2027
  let paneText;
1947
2028
  try {
1948
2029
  paneText = await this.wrapper.capturePane();
1949
2030
  } catch {
1950
- return false;
2031
+ return "none";
1951
2032
  }
1952
2033
  const prompt = parseNativePermissionPrompt(paneText);
1953
- if (!prompt)
1954
- return false;
2034
+ if (!prompt) {
2035
+ this.lastNativePermissionFingerprint = null;
2036
+ this.lastNativePermissionOutcome = "none";
2037
+ return "none";
2038
+ }
2039
+ const fingerprint = `${prompt.question}
2040
+ ${prompt.options.map((option) => `${option.number}:${option.label}`).join(`
2041
+ `)}`;
2042
+ if (this.lastNativePermissionFingerprint === fingerprint) {
2043
+ if (this.lastNativePermissionOutcome === "handled" || this.lastNativePermissionOutcome === "consumed") {
2044
+ return "pending_clear";
2045
+ }
2046
+ return this.lastNativePermissionOutcome;
2047
+ }
1955
2048
  const decision = await this.resolvePermission({
1956
2049
  source: "native_prompt",
1957
2050
  sessionId: this.sessionId,
@@ -1971,19 +2064,62 @@ class ClaudrabandSessionImpl {
1971
2064
  name: opt.label
1972
2065
  }))
1973
2066
  });
2067
+ let outcome;
1974
2068
  if (decision.outcome === "deferred") {
1975
- return false;
2069
+ outcome = "deferred";
2070
+ } else if (decision.outcome === "cancelled") {
2071
+ await this.safeInterruptNativePermission();
2072
+ outcome = "handled";
2073
+ } else if (decision.outcome === "text") {
2074
+ await this.safeSendNativePermission(decision.text, false);
2075
+ outcome = decision.text === intendedText ? "consumed" : "handled";
2076
+ } else {
2077
+ const selected = prompt.options.find((option) => option.number === decision.optionId);
2078
+ const tolerateExit = selected ? isRejectingNativeOption(selected.label) : false;
2079
+ await this.safeSendNativePermission(decision.optionId, tolerateExit);
2080
+ outcome = decision.optionId === intendedText ? "consumed" : "handled";
2081
+ }
2082
+ this.lastNativePermissionFingerprint = fingerprint;
2083
+ this.lastNativePermissionOutcome = outcome;
2084
+ return outcome;
2085
+ }
2086
+ async safeSendNativePermission(input, tolerateExit) {
2087
+ try {
2088
+ await this.wrapper.send(input);
2089
+ } catch (error) {
2090
+ if (tolerateExit && !this.wrapper.isProcessAlive()) {
2091
+ this.logger.debug("native permission send ignored after pane exit", "sid", this.sessionId);
2092
+ return;
2093
+ }
2094
+ throw error;
1976
2095
  }
1977
- if (decision.outcome === "cancelled") {
2096
+ }
2097
+ async safeInterruptNativePermission() {
2098
+ try {
1978
2099
  await this.wrapper.interrupt();
1979
- return true;
2100
+ } catch (error) {
2101
+ if (!this.wrapper.isProcessAlive()) {
2102
+ this.logger.debug("native permission interrupt ignored after pane exit", "sid", this.sessionId);
2103
+ return;
2104
+ }
2105
+ throw error;
1980
2106
  }
1981
- if (decision.outcome === "text") {
1982
- await this.wrapper.send(decision.text);
1983
- return true;
2107
+ }
2108
+ async waitForInsertMode(timeoutMs = 15000) {
2109
+ const POLL_MS = 300;
2110
+ const start = Date.now();
2111
+ while (Date.now() - start < timeoutMs) {
2112
+ if (!this.wrapper.isProcessAlive()) {
2113
+ return false;
2114
+ }
2115
+ try {
2116
+ const pane = await this.wrapper.capturePane();
2117
+ if (pane.includes("INSERT") || pane.includes("NORMAL"))
2118
+ return true;
2119
+ } catch {}
2120
+ await new Promise((r) => setTimeout(r, POLL_MS));
1984
2121
  }
1985
- await this.wrapper.send(decision.optionId);
1986
- return true;
2122
+ return false;
1987
2123
  }
1988
2124
  async handleUserQuestion(ev) {
1989
2125
  const parsed = parseAskUserQuestion(ev.toolInput);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@halfwhey/claudraband-core",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "TypeScript runtime for controlling local Claude Code sessions through a real terminal.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",