@halfwhey/claudraband 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
package/dist/bin.js CHANGED
@@ -5443,6 +5443,9 @@ class ClaudeWrapper {
5443
5443
  if (pane.includes("INSERT") || pane.includes("NORMAL")) {
5444
5444
  return;
5445
5445
  }
5446
+ if (pane.includes("Yes, I trust this folder") && pane.includes("No, exit") || pane.includes("Bypass Permissions mode") && pane.includes("Yes, I accept")) {
5447
+ return;
5448
+ }
5446
5449
  } catch {}
5447
5450
  await new Promise((r) => setTimeout(r, POLL_MS));
5448
5451
  }
@@ -5531,6 +5534,9 @@ var init_claude = __esm(() => {
5531
5534
 
5532
5535
  // ../claudraband-core/src/claude/inspect.ts
5533
5536
  import { readFile } from "node:fs/promises";
5537
+ function normalizeCapturedPane(paneText) {
5538
+ 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, "");
5539
+ }
5534
5540
  async function hasPendingQuestion(jsonlPath) {
5535
5541
  let data;
5536
5542
  try {
@@ -5564,10 +5570,20 @@ async function hasPendingQuestion(jsonlPath) {
5564
5570
  return pendingIds.size > 0;
5565
5571
  }
5566
5572
  function parseNativePermissionPrompt(paneText) {
5567
- const questionMatch = paneText.match(/(?:^|\n)\s*(Do you want to [^\n]+\?)/);
5573
+ const normalizedPane = normalizeCapturedPane(paneText);
5574
+ const isTrustPrompt = normalizedPane.includes("Yes, I trust this folder") && normalizedPane.includes("No, exit");
5575
+ const isBypassPrompt = normalizedPane.includes("Bypass Permissions mode") && normalizedPane.includes("Yes, I accept");
5576
+ let questionMatch;
5577
+ if (isTrustPrompt) {
5578
+ questionMatch = normalizedPane.match(/(Is this a project you created[^\n]*)/);
5579
+ } else if (isBypassPrompt) {
5580
+ questionMatch = normalizedPane.match(/(you accept all responsibility[^\n]*)/);
5581
+ } else {
5582
+ questionMatch = normalizedPane.match(/(?:^|\n)\s*(Do you want to [^\n]+\?)/);
5583
+ }
5568
5584
  if (!questionMatch)
5569
5585
  return null;
5570
- const afterQuestion = paneText.slice(paneText.indexOf(questionMatch[1]) + questionMatch[1].length);
5586
+ const afterQuestion = normalizedPane.slice(normalizedPane.indexOf(questionMatch[1]) + questionMatch[1].length);
5571
5587
  const optionRegex = /(?:❯\s*)?(\d+)\.\s+(.+)/g;
5572
5588
  const options = [];
5573
5589
  let match;
@@ -5699,6 +5715,10 @@ var init_session_registry = () => {};
5699
5715
  // ../claudraband-core/src/index.ts
5700
5716
  import { open as open2, readFile as readFile3, stat as stat2 } from "node:fs/promises";
5701
5717
  import { request as httpRequest } from "node:http";
5718
+ function isRejectingNativeOption(label) {
5719
+ const normalized = label.trim().toLowerCase();
5720
+ return normalized.startsWith("no") || normalized.startsWith("reject");
5721
+ }
5702
5722
  function makeDefaultLogger() {
5703
5723
  const noop = () => {};
5704
5724
  return {
@@ -5820,6 +5840,8 @@ class ClaudrabandSessionImpl {
5820
5840
  _permissionMode;
5821
5841
  allowTextResponses;
5822
5842
  sessionOwner;
5843
+ lastNativePermissionFingerprint = null;
5844
+ lastNativePermissionOutcome = "none";
5823
5845
  constructor(wrapper, sessionId, cwd, backend, model, permissionMode, allowTextResponses, logger, onPermissionRequest, lifetime, sessionOwner) {
5824
5846
  this.sessionId = sessionId;
5825
5847
  this.cwd = cwd;
@@ -5854,7 +5876,20 @@ class ClaudrabandSessionImpl {
5854
5876
  const prompt = this.newPromptWaiter(text);
5855
5877
  this.activePrompt = prompt;
5856
5878
  this.logger.info("prompt received", "sid", this.sessionId, "length", text.length);
5857
- await this.wrapper.send(text);
5879
+ const startupState = await this.prepareForInput(text);
5880
+ if (startupState === "blocked") {
5881
+ this.activePrompt = null;
5882
+ this.promptAbortController = null;
5883
+ return { stopReason: "end_turn" };
5884
+ }
5885
+ if (startupState === "cancelled") {
5886
+ this.activePrompt = null;
5887
+ this.promptAbortController = null;
5888
+ return { stopReason: "cancelled" };
5889
+ }
5890
+ if (startupState !== "consumed") {
5891
+ await this.wrapper.send(text);
5892
+ }
5858
5893
  try {
5859
5894
  const stopReason = await this.waitForPromptCompletion(prompt, controller.signal);
5860
5895
  this.logger.info("prompt completed", "sid", this.sessionId, "stop_reason", stopReason);
@@ -5877,6 +5912,17 @@ class ClaudrabandSessionImpl {
5877
5912
  const prompt = this.newPromptWaiter("");
5878
5913
  prompt.matchedUserEcho = true;
5879
5914
  this.activePrompt = prompt;
5915
+ const startupState = await this.prepareForInput(null);
5916
+ if (startupState === "blocked") {
5917
+ this.activePrompt = null;
5918
+ this.promptAbortController = null;
5919
+ return { stopReason: "end_turn" };
5920
+ }
5921
+ if (startupState === "cancelled") {
5922
+ this.activePrompt = null;
5923
+ this.promptAbortController = null;
5924
+ return { stopReason: "cancelled" };
5925
+ }
5880
5926
  this.logger.info("awaitTurn", "sid", this.sessionId);
5881
5927
  try {
5882
5928
  const stopReason = await this.waitForPromptCompletion(prompt, controller.signal);
@@ -5900,6 +5946,26 @@ class ClaudrabandSessionImpl {
5900
5946
  const prompt = this.newPromptWaiter("");
5901
5947
  prompt.matchedUserEcho = true;
5902
5948
  this.activePrompt = prompt;
5949
+ const startupState = await this.prepareForInput(text);
5950
+ if (startupState === "blocked") {
5951
+ this.activePrompt = null;
5952
+ this.promptAbortController = null;
5953
+ return { stopReason: "end_turn" };
5954
+ }
5955
+ if (startupState === "cancelled") {
5956
+ this.activePrompt = null;
5957
+ this.promptAbortController = null;
5958
+ return { stopReason: "cancelled" };
5959
+ }
5960
+ if (startupState === "consumed") {
5961
+ if (this.activePrompt === prompt) {
5962
+ this.activePrompt = null;
5963
+ }
5964
+ if (this.promptAbortController === controller) {
5965
+ this.promptAbortController = null;
5966
+ }
5967
+ return { stopReason: "end_turn" };
5968
+ }
5903
5969
  this.logger.info("sendAndAwaitTurn", "sid", this.sessionId, "length", text.length);
5904
5970
  await this.wrapper.send(text);
5905
5971
  try {
@@ -5918,6 +5984,21 @@ class ClaudrabandSessionImpl {
5918
5984
  send(text) {
5919
5985
  return this.wrapper.send(text);
5920
5986
  }
5987
+ async prepareForInput(intendedText) {
5988
+ const handled = await this.pollNativePermission(null, intendedText);
5989
+ if (handled === "handled" || handled === "consumed" || handled === "pending_clear") {
5990
+ const ready = await this.waitForInsertMode();
5991
+ if (!ready) {
5992
+ return this.wrapper.isProcessAlive() ? "blocked" : "cancelled";
5993
+ }
5994
+ return handled === "consumed" ? "consumed" : "ready";
5995
+ }
5996
+ const stillBlocking = hasPendingNativePrompt(await this.wrapper.capturePane().catch(() => ""));
5997
+ if (stillBlocking) {
5998
+ return "blocked";
5999
+ }
6000
+ return "ready";
6001
+ }
5921
6002
  async interrupt() {
5922
6003
  this.promptAbortController?.abort();
5923
6004
  await this.wrapper.interrupt();
@@ -6237,7 +6318,7 @@ class ClaudrabandSessionImpl {
6237
6318
  }
6238
6319
  if (prompt.pendingTools > 0) {
6239
6320
  const handled = await this.pollNativePermission(prompt.lastPendingTool);
6240
- if (handled) {
6321
+ if (handled === "handled" || handled === "consumed") {
6241
6322
  prompt.pendingTools = Math.max(0, prompt.pendingTools - 1);
6242
6323
  prompt.gotResponse = true;
6243
6324
  prompt.lastPendingTool = null;
@@ -6252,16 +6333,28 @@ class ClaudrabandSessionImpl {
6252
6333
  }
6253
6334
  }
6254
6335
  }
6255
- async pollNativePermission(pendingTool) {
6336
+ async pollNativePermission(pendingTool, intendedText = null) {
6256
6337
  let paneText;
6257
6338
  try {
6258
6339
  paneText = await this.wrapper.capturePane();
6259
6340
  } catch {
6260
- return false;
6341
+ return "none";
6261
6342
  }
6262
6343
  const prompt = parseNativePermissionPrompt(paneText);
6263
- if (!prompt)
6264
- return false;
6344
+ if (!prompt) {
6345
+ this.lastNativePermissionFingerprint = null;
6346
+ this.lastNativePermissionOutcome = "none";
6347
+ return "none";
6348
+ }
6349
+ const fingerprint = `${prompt.question}
6350
+ ${prompt.options.map((option) => `${option.number}:${option.label}`).join(`
6351
+ `)}`;
6352
+ if (this.lastNativePermissionFingerprint === fingerprint) {
6353
+ if (this.lastNativePermissionOutcome === "handled" || this.lastNativePermissionOutcome === "consumed") {
6354
+ return "pending_clear";
6355
+ }
6356
+ return this.lastNativePermissionOutcome;
6357
+ }
6265
6358
  const decision = await this.resolvePermission({
6266
6359
  source: "native_prompt",
6267
6360
  sessionId: this.sessionId,
@@ -6281,19 +6374,62 @@ class ClaudrabandSessionImpl {
6281
6374
  name: opt.label
6282
6375
  }))
6283
6376
  });
6377
+ let outcome;
6284
6378
  if (decision.outcome === "deferred") {
6285
- return false;
6379
+ outcome = "deferred";
6380
+ } else if (decision.outcome === "cancelled") {
6381
+ await this.safeInterruptNativePermission();
6382
+ outcome = "handled";
6383
+ } else if (decision.outcome === "text") {
6384
+ await this.safeSendNativePermission(decision.text, false);
6385
+ outcome = decision.text === intendedText ? "consumed" : "handled";
6386
+ } else {
6387
+ const selected = prompt.options.find((option) => option.number === decision.optionId);
6388
+ const tolerateExit = selected ? isRejectingNativeOption(selected.label) : false;
6389
+ await this.safeSendNativePermission(decision.optionId, tolerateExit);
6390
+ outcome = decision.optionId === intendedText ? "consumed" : "handled";
6286
6391
  }
6287
- if (decision.outcome === "cancelled") {
6392
+ this.lastNativePermissionFingerprint = fingerprint;
6393
+ this.lastNativePermissionOutcome = outcome;
6394
+ return outcome;
6395
+ }
6396
+ async safeSendNativePermission(input, tolerateExit) {
6397
+ try {
6398
+ await this.wrapper.send(input);
6399
+ } catch (error) {
6400
+ if (tolerateExit && !this.wrapper.isProcessAlive()) {
6401
+ this.logger.debug("native permission send ignored after pane exit", "sid", this.sessionId);
6402
+ return;
6403
+ }
6404
+ throw error;
6405
+ }
6406
+ }
6407
+ async safeInterruptNativePermission() {
6408
+ try {
6288
6409
  await this.wrapper.interrupt();
6289
- return true;
6410
+ } catch (error) {
6411
+ if (!this.wrapper.isProcessAlive()) {
6412
+ this.logger.debug("native permission interrupt ignored after pane exit", "sid", this.sessionId);
6413
+ return;
6414
+ }
6415
+ throw error;
6290
6416
  }
6291
- if (decision.outcome === "text") {
6292
- await this.wrapper.send(decision.text);
6293
- return true;
6417
+ }
6418
+ async waitForInsertMode(timeoutMs = 15000) {
6419
+ const POLL_MS = 300;
6420
+ const start = Date.now();
6421
+ while (Date.now() - start < timeoutMs) {
6422
+ if (!this.wrapper.isProcessAlive()) {
6423
+ return false;
6424
+ }
6425
+ try {
6426
+ const pane = await this.wrapper.capturePane();
6427
+ if (pane.includes("INSERT") || pane.includes("NORMAL"))
6428
+ return true;
6429
+ } catch {}
6430
+ await new Promise((r) => setTimeout(r, POLL_MS));
6294
6431
  }
6295
- await this.wrapper.send(decision.optionId);
6296
- return true;
6432
+ return false;
6297
6433
  }
6298
6434
  async handleUserQuestion(ev) {
6299
6435
  const parsed = parseAskUserQuestion(ev.toolInput);
@@ -6812,16 +6948,21 @@ var init_src = __esm(() => {
6812
6948
 
6813
6949
  // src/client.ts
6814
6950
  import { createInterface } from "node:readline/promises";
6951
+ function formatOptionLabel(name, kind) {
6952
+ const suffix = `(${kind})`;
6953
+ return name.trim().endsWith(suffix) ? name.trim() : `${name} (${kind})`;
6954
+ }
6815
6955
  async function requestPermission(renderer, config, params) {
6816
6956
  renderer.ensureNewline();
6817
6957
  process.stderr.write(`\x1B[33mPermission: ${params.title}\x1B[0m
6818
6958
  `);
6819
- for (const block of params.content) {
6959
+ const contentBlocks = params.content.length === 1 && params.content[0]?.text.trim() === params.title.trim() ? [] : params.content;
6960
+ for (const block of contentBlocks) {
6820
6961
  process.stderr.write(`${block.text}
6821
6962
  `);
6822
6963
  }
6823
6964
  for (const option of params.options) {
6824
- process.stderr.write(` ${option.optionId}. ${option.name} (${option.kind})
6965
+ process.stderr.write(` ${option.optionId}. ${formatOptionLabel(option.name, option.kind)}
6825
6966
  `);
6826
6967
  }
6827
6968
  if (config.answerChoice) {
@@ -6887,7 +7028,7 @@ function shouldReuseSession(ds) {
6887
7028
  return ds !== null && ds.session.isProcessAlive();
6888
7029
  }
6889
7030
  function resolveServerTerminalBackend(config) {
6890
- return config.hasExplicitTerminalBackend ? config.terminalBackend : "xterm";
7031
+ return config.hasExplicitTerminalBackend ? config.terminalBackend : "tmux";
6891
7032
  }
6892
7033
  function formatHostForUrl(host) {
6893
7034
  return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
@@ -6982,19 +7123,29 @@ function createDaemonServer(config, runtime, logger) {
6982
7123
  if (method === "POST" && path === "/sessions") {
6983
7124
  const body = JSON.parse(await readBody(req));
6984
7125
  const sessionConfig = resolveSessionConfig(config, body);
6985
- const session = await runtime.startSession({
7126
+ const sessionOwner = {
7127
+ kind: "daemon",
7128
+ serverUrl,
7129
+ serverPid: process.pid,
7130
+ serverInstanceId
7131
+ };
7132
+ const session = body.sessionId ? await runtime.resumeSession(body.sessionId, {
6986
7133
  cwd: sessionConfig.cwd,
6987
7134
  claudeArgs: sessionConfig.claudeArgs,
6988
7135
  model: sessionConfig.model,
6989
7136
  permissionMode: sessionConfig.permissionMode,
6990
7137
  allowTextResponses: true,
6991
7138
  logger,
6992
- sessionOwner: {
6993
- kind: "daemon",
6994
- serverUrl,
6995
- serverPid: process.pid,
6996
- serverInstanceId
6997
- },
7139
+ sessionOwner,
7140
+ onPermissionRequest: (request) => handlePermission(ds2, request)
7141
+ }) : await runtime.startSession({
7142
+ cwd: sessionConfig.cwd,
7143
+ claudeArgs: sessionConfig.claudeArgs,
7144
+ model: sessionConfig.model,
7145
+ permissionMode: sessionConfig.permissionMode,
7146
+ allowTextResponses: true,
7147
+ logger,
7148
+ sessionOwner,
6998
7149
  onPermissionRequest: (request) => handlePermission(ds2, request)
6999
7150
  });
7000
7151
  const ds2 = {
@@ -7302,6 +7453,7 @@ __export(exports_daemon_client, {
7302
7453
  __test: () => __test2
7303
7454
  });
7304
7455
  import { request as httpRequest2 } from "node:http";
7456
+ import { randomUUID as randomUUID3 } from "node:crypto";
7305
7457
  function daemonUrl(server, path) {
7306
7458
  const base = server.startsWith("http") ? server : `http://${server}`;
7307
7459
  return `${base}${path}`;
@@ -7352,6 +7504,7 @@ async function daemonRequest2(server, method, path, body) {
7352
7504
  }
7353
7505
  function buildSessionRequestBody(config, options = {}) {
7354
7506
  return {
7507
+ ...options.sessionId ? { sessionId: options.sessionId } : {},
7355
7508
  cwd: config.cwd,
7356
7509
  ...config.hasExplicitClaudeArgs ? { claudeArgs: config.claudeArgs } : {},
7357
7510
  ...config.hasExplicitModel ? { model: config.model } : {},
@@ -7603,13 +7756,14 @@ async function runWithDaemon(config, renderer, _logger) {
7603
7756
  sessionId = config.sessionId;
7604
7757
  sessionBackend = result.backend;
7605
7758
  } else {
7759
+ sessionId = randomUUID3();
7760
+ process.stderr.write(`session: ${sessionId}
7761
+ `);
7606
7762
  const result = await daemonPost(config.connect, "/sessions", {
7607
- ...buildSessionRequestBody(config)
7763
+ ...buildSessionRequestBody(config, { sessionId })
7608
7764
  });
7609
7765
  sessionId = result.sessionId;
7610
7766
  sessionBackend = result.backend;
7611
- process.stderr.write(`session: ${sessionId}
7612
- `);
7613
7767
  }
7614
7768
  const session = new DaemonSessionProxy(config.connect, sessionId, config.cwd, sessionBackend, config.model, config.permissionMode, permissionHandler);
7615
7769
  await session.startEventStream();
@@ -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
@@ -5455,6 +5455,9 @@ class ClaudeWrapper {
5455
5455
  if (pane.includes("INSERT") || pane.includes("NORMAL")) {
5456
5456
  return;
5457
5457
  }
5458
+ if (pane.includes("Yes, I trust this folder") && pane.includes("No, exit") || pane.includes("Bypass Permissions mode") && pane.includes("Yes, I accept")) {
5459
+ return;
5460
+ }
5458
5461
  } catch {}
5459
5462
  await new Promise((r) => setTimeout(r, POLL_MS));
5460
5463
  }
@@ -5537,6 +5540,9 @@ function parseClaudeArgs(args) {
5537
5540
  }
5538
5541
  // ../claudraband-core/src/claude/inspect.ts
5539
5542
  import { readFile } from "node:fs/promises";
5543
+ function normalizeCapturedPane(paneText) {
5544
+ 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, "");
5545
+ }
5540
5546
  async function hasPendingQuestion(jsonlPath) {
5541
5547
  let data;
5542
5548
  try {
@@ -5570,10 +5576,20 @@ async function hasPendingQuestion(jsonlPath) {
5570
5576
  return pendingIds.size > 0;
5571
5577
  }
5572
5578
  function parseNativePermissionPrompt(paneText) {
5573
- const questionMatch = paneText.match(/(?:^|\n)\s*(Do you want to [^\n]+\?)/);
5579
+ const normalizedPane = normalizeCapturedPane(paneText);
5580
+ const isTrustPrompt = normalizedPane.includes("Yes, I trust this folder") && normalizedPane.includes("No, exit");
5581
+ const isBypassPrompt = normalizedPane.includes("Bypass Permissions mode") && normalizedPane.includes("Yes, I accept");
5582
+ let questionMatch;
5583
+ if (isTrustPrompt) {
5584
+ questionMatch = normalizedPane.match(/(Is this a project you created[^\n]*)/);
5585
+ } else if (isBypassPrompt) {
5586
+ questionMatch = normalizedPane.match(/(you accept all responsibility[^\n]*)/);
5587
+ } else {
5588
+ questionMatch = normalizedPane.match(/(?:^|\n)\s*(Do you want to [^\n]+\?)/);
5589
+ }
5574
5590
  if (!questionMatch)
5575
5591
  return null;
5576
- const afterQuestion = paneText.slice(paneText.indexOf(questionMatch[1]) + questionMatch[1].length);
5592
+ const afterQuestion = normalizedPane.slice(normalizedPane.indexOf(questionMatch[1]) + questionMatch[1].length);
5577
5593
  const optionRegex = /(?:❯\s*)?(\d+)\.\s+(.+)/g;
5578
5594
  const options = [];
5579
5595
  let match;
@@ -5748,6 +5764,10 @@ var TERMINAL_BACKENDS = [
5748
5764
  description: "Run Claude Code in a headless xterm-backed PTY"
5749
5765
  }
5750
5766
  ];
5767
+ function isRejectingNativeOption(label) {
5768
+ const normalized = label.trim().toLowerCase();
5769
+ return normalized.startsWith("no") || normalized.startsWith("reject");
5770
+ }
5751
5771
  function makeDefaultLogger() {
5752
5772
  const noop = () => {};
5753
5773
  return {
@@ -5869,6 +5889,8 @@ class ClaudrabandSessionImpl {
5869
5889
  _permissionMode;
5870
5890
  allowTextResponses;
5871
5891
  sessionOwner;
5892
+ lastNativePermissionFingerprint = null;
5893
+ lastNativePermissionOutcome = "none";
5872
5894
  constructor(wrapper, sessionId, cwd, backend, model, permissionMode, allowTextResponses, logger, onPermissionRequest, lifetime, sessionOwner) {
5873
5895
  this.sessionId = sessionId;
5874
5896
  this.cwd = cwd;
@@ -5903,7 +5925,20 @@ class ClaudrabandSessionImpl {
5903
5925
  const prompt = this.newPromptWaiter(text);
5904
5926
  this.activePrompt = prompt;
5905
5927
  this.logger.info("prompt received", "sid", this.sessionId, "length", text.length);
5906
- await this.wrapper.send(text);
5928
+ const startupState = await this.prepareForInput(text);
5929
+ if (startupState === "blocked") {
5930
+ this.activePrompt = null;
5931
+ this.promptAbortController = null;
5932
+ return { stopReason: "end_turn" };
5933
+ }
5934
+ if (startupState === "cancelled") {
5935
+ this.activePrompt = null;
5936
+ this.promptAbortController = null;
5937
+ return { stopReason: "cancelled" };
5938
+ }
5939
+ if (startupState !== "consumed") {
5940
+ await this.wrapper.send(text);
5941
+ }
5907
5942
  try {
5908
5943
  const stopReason = await this.waitForPromptCompletion(prompt, controller.signal);
5909
5944
  this.logger.info("prompt completed", "sid", this.sessionId, "stop_reason", stopReason);
@@ -5926,6 +5961,17 @@ class ClaudrabandSessionImpl {
5926
5961
  const prompt = this.newPromptWaiter("");
5927
5962
  prompt.matchedUserEcho = true;
5928
5963
  this.activePrompt = prompt;
5964
+ const startupState = await this.prepareForInput(null);
5965
+ if (startupState === "blocked") {
5966
+ this.activePrompt = null;
5967
+ this.promptAbortController = null;
5968
+ return { stopReason: "end_turn" };
5969
+ }
5970
+ if (startupState === "cancelled") {
5971
+ this.activePrompt = null;
5972
+ this.promptAbortController = null;
5973
+ return { stopReason: "cancelled" };
5974
+ }
5929
5975
  this.logger.info("awaitTurn", "sid", this.sessionId);
5930
5976
  try {
5931
5977
  const stopReason = await this.waitForPromptCompletion(prompt, controller.signal);
@@ -5949,6 +5995,26 @@ class ClaudrabandSessionImpl {
5949
5995
  const prompt = this.newPromptWaiter("");
5950
5996
  prompt.matchedUserEcho = true;
5951
5997
  this.activePrompt = prompt;
5998
+ const startupState = await this.prepareForInput(text);
5999
+ if (startupState === "blocked") {
6000
+ this.activePrompt = null;
6001
+ this.promptAbortController = null;
6002
+ return { stopReason: "end_turn" };
6003
+ }
6004
+ if (startupState === "cancelled") {
6005
+ this.activePrompt = null;
6006
+ this.promptAbortController = null;
6007
+ return { stopReason: "cancelled" };
6008
+ }
6009
+ if (startupState === "consumed") {
6010
+ if (this.activePrompt === prompt) {
6011
+ this.activePrompt = null;
6012
+ }
6013
+ if (this.promptAbortController === controller) {
6014
+ this.promptAbortController = null;
6015
+ }
6016
+ return { stopReason: "end_turn" };
6017
+ }
5952
6018
  this.logger.info("sendAndAwaitTurn", "sid", this.sessionId, "length", text.length);
5953
6019
  await this.wrapper.send(text);
5954
6020
  try {
@@ -5967,6 +6033,21 @@ class ClaudrabandSessionImpl {
5967
6033
  send(text) {
5968
6034
  return this.wrapper.send(text);
5969
6035
  }
6036
+ async prepareForInput(intendedText) {
6037
+ const handled = await this.pollNativePermission(null, intendedText);
6038
+ if (handled === "handled" || handled === "consumed" || handled === "pending_clear") {
6039
+ const ready = await this.waitForInsertMode();
6040
+ if (!ready) {
6041
+ return this.wrapper.isProcessAlive() ? "blocked" : "cancelled";
6042
+ }
6043
+ return handled === "consumed" ? "consumed" : "ready";
6044
+ }
6045
+ const stillBlocking = hasPendingNativePrompt(await this.wrapper.capturePane().catch(() => ""));
6046
+ if (stillBlocking) {
6047
+ return "blocked";
6048
+ }
6049
+ return "ready";
6050
+ }
5970
6051
  async interrupt() {
5971
6052
  this.promptAbortController?.abort();
5972
6053
  await this.wrapper.interrupt();
@@ -6286,7 +6367,7 @@ class ClaudrabandSessionImpl {
6286
6367
  }
6287
6368
  if (prompt.pendingTools > 0) {
6288
6369
  const handled = await this.pollNativePermission(prompt.lastPendingTool);
6289
- if (handled) {
6370
+ if (handled === "handled" || handled === "consumed") {
6290
6371
  prompt.pendingTools = Math.max(0, prompt.pendingTools - 1);
6291
6372
  prompt.gotResponse = true;
6292
6373
  prompt.lastPendingTool = null;
@@ -6301,16 +6382,28 @@ class ClaudrabandSessionImpl {
6301
6382
  }
6302
6383
  }
6303
6384
  }
6304
- async pollNativePermission(pendingTool) {
6385
+ async pollNativePermission(pendingTool, intendedText = null) {
6305
6386
  let paneText;
6306
6387
  try {
6307
6388
  paneText = await this.wrapper.capturePane();
6308
6389
  } catch {
6309
- return false;
6390
+ return "none";
6310
6391
  }
6311
6392
  const prompt = parseNativePermissionPrompt(paneText);
6312
- if (!prompt)
6313
- return false;
6393
+ if (!prompt) {
6394
+ this.lastNativePermissionFingerprint = null;
6395
+ this.lastNativePermissionOutcome = "none";
6396
+ return "none";
6397
+ }
6398
+ const fingerprint = `${prompt.question}
6399
+ ${prompt.options.map((option) => `${option.number}:${option.label}`).join(`
6400
+ `)}`;
6401
+ if (this.lastNativePermissionFingerprint === fingerprint) {
6402
+ if (this.lastNativePermissionOutcome === "handled" || this.lastNativePermissionOutcome === "consumed") {
6403
+ return "pending_clear";
6404
+ }
6405
+ return this.lastNativePermissionOutcome;
6406
+ }
6314
6407
  const decision = await this.resolvePermission({
6315
6408
  source: "native_prompt",
6316
6409
  sessionId: this.sessionId,
@@ -6330,19 +6423,62 @@ class ClaudrabandSessionImpl {
6330
6423
  name: opt.label
6331
6424
  }))
6332
6425
  });
6426
+ let outcome;
6333
6427
  if (decision.outcome === "deferred") {
6334
- return false;
6428
+ outcome = "deferred";
6429
+ } else if (decision.outcome === "cancelled") {
6430
+ await this.safeInterruptNativePermission();
6431
+ outcome = "handled";
6432
+ } else if (decision.outcome === "text") {
6433
+ await this.safeSendNativePermission(decision.text, false);
6434
+ outcome = decision.text === intendedText ? "consumed" : "handled";
6435
+ } else {
6436
+ const selected = prompt.options.find((option) => option.number === decision.optionId);
6437
+ const tolerateExit = selected ? isRejectingNativeOption(selected.label) : false;
6438
+ await this.safeSendNativePermission(decision.optionId, tolerateExit);
6439
+ outcome = decision.optionId === intendedText ? "consumed" : "handled";
6440
+ }
6441
+ this.lastNativePermissionFingerprint = fingerprint;
6442
+ this.lastNativePermissionOutcome = outcome;
6443
+ return outcome;
6444
+ }
6445
+ async safeSendNativePermission(input, tolerateExit) {
6446
+ try {
6447
+ await this.wrapper.send(input);
6448
+ } catch (error) {
6449
+ if (tolerateExit && !this.wrapper.isProcessAlive()) {
6450
+ this.logger.debug("native permission send ignored after pane exit", "sid", this.sessionId);
6451
+ return;
6452
+ }
6453
+ throw error;
6335
6454
  }
6336
- if (decision.outcome === "cancelled") {
6455
+ }
6456
+ async safeInterruptNativePermission() {
6457
+ try {
6337
6458
  await this.wrapper.interrupt();
6338
- return true;
6459
+ } catch (error) {
6460
+ if (!this.wrapper.isProcessAlive()) {
6461
+ this.logger.debug("native permission interrupt ignored after pane exit", "sid", this.sessionId);
6462
+ return;
6463
+ }
6464
+ throw error;
6339
6465
  }
6340
- if (decision.outcome === "text") {
6341
- await this.wrapper.send(decision.text);
6342
- return true;
6466
+ }
6467
+ async waitForInsertMode(timeoutMs = 15000) {
6468
+ const POLL_MS = 300;
6469
+ const start = Date.now();
6470
+ while (Date.now() - start < timeoutMs) {
6471
+ if (!this.wrapper.isProcessAlive()) {
6472
+ return false;
6473
+ }
6474
+ try {
6475
+ const pane = await this.wrapper.capturePane();
6476
+ if (pane.includes("INSERT") || pane.includes("NORMAL"))
6477
+ return true;
6478
+ } catch {}
6479
+ await new Promise((r) => setTimeout(r, POLL_MS));
6343
6480
  }
6344
- await this.wrapper.send(decision.optionId);
6345
- return true;
6481
+ return false;
6346
6482
  }
6347
6483
  async handleUserQuestion(ev) {
6348
6484
  const parsed = parseAskUserQuestion(ev.toolInput);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@halfwhey/claudraband",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Control the official Claude Code CLI programmatically. Use as a library, a direct CLI, an ACP server, or a persistent session daemon.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",