@halfwhey/claudraband-core 0.2.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 CHANGED
@@ -75,17 +75,21 @@ cband continue <session-id> --select 3 "xyz"
75
75
  ### Headless persistent sessions with `serve`
76
76
 
77
77
  ```sh
78
- cband serve --host 127.0.0.1 --backend xterm --port 7842
78
+ cband serve --host 127.0.0.1 --port 7842
79
79
  cband --connect localhost:7842 "start a migration plan"
80
80
  cband attach <session-id>
81
81
  cband continue <session-id> --select 2
82
82
  ```
83
83
 
84
- Use `--connect` only when starting a new daemon-backed session. After that, `continue`, `attach`, and `sessions` route through the tracked session automatically. `attach` is especially useful here because it gives you a simple REPL for a headless xterm.js session.
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
85
 
86
- ### Using the CLI without tmux or server
86
+ `--backend xterm` still exists, but it is experimental while we improve it.
87
87
 
88
- If you run `cband "..."` without `tmux` and without `--connect`, `cband` falls back to a local headless `xterm.js` session. That mode 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. It only works properly when Claude itself can proceed without an interactive permission prompt. Use one of:
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:
89
93
 
90
94
  - `-c "--dangerously-skip-permissions"`
91
95
  - `--permission-mode bypassPermissions`
@@ -109,9 +113,9 @@ Some ACP clients still have limitations around resuming existing sessions. `clau
109
113
 
110
114
  Live sessions are tracked in `~/.claudraband/`.
111
115
 
112
- - `cband sessions` shows only live tracked sessions, either hosted by tmux or the xterm.js daemon.
116
+ - `cband sessions` shows only live tracked sessions, either hosted by tmux directly or by the daemon.
113
117
  - `continue` can resume an existing Claude Code session even when it is no longer live, but `attach` only works on live sessions.
114
- - `sessions close ...` closes live sessions hosted by tmux or the xterm.js daemon
118
+ - `sessions close ...` closes live sessions hosted by tmux directly or by the daemon
115
119
  - `sessions close --all` will close all live sessions controlled by Claudraband
116
120
 
117
121
  ## Examples
@@ -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.2.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",