@anupha/claude-bridge 0.0.0-stage → 1.0.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.
@@ -0,0 +1,659 @@
1
+ // Phase 4: talk back to the terminal.
2
+ // - readTranscript: parse the session's .jsonl so the app can render the chat
3
+ // - sendInput / capturePane: type into and screenshot the real terminal via tmux
4
+
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { execFile, execFileSync } from 'node:child_process';
9
+ import { promisify } from 'node:util';
10
+
11
+ // Pasted images are stored inline as base64 in the transcript (100s of KB
12
+ // each), so a small byte-tail can land entirely inside one image and hide all
13
+ // the text history. Read a generous tail and strip image data before parsing.
14
+ const TAIL_BYTES = 8_000_000;
15
+ const IMAGE_DATA = /"data":"[A-Za-z0-9+/=\r\n]{300,}"/g;
16
+
17
+ // The daemon runs from launchd with a bare PATH (/usr/bin:/bin:/usr/sbin:/sbin),
18
+ // so a plain 'tmux' lookup misses Homebrew installs. Resolve an absolute path up
19
+ // front (honoring $TMUX_BIN) and fall back to a bare name if none is found.
20
+ const TMUX_BIN = (() => {
21
+ const candidates = [
22
+ process.env.TMUX_BIN,
23
+ '/opt/homebrew/bin/tmux',
24
+ '/usr/local/bin/tmux',
25
+ '/usr/bin/tmux',
26
+ ];
27
+ for (const p of candidates) {
28
+ if (p && fs.existsSync(p)) return p;
29
+ }
30
+ return 'tmux';
31
+ })();
32
+
33
+ // Only real .jsonl files under Claude's projects folder may be read as a
34
+ // transcript. The path arrives from hooks (any local process can call them) and
35
+ // is persisted, so a FIFO or arbitrary file there could freeze or misuse the
36
+ // daemon. Missing-but-plausible paths pass (a new session writes it lazily).
37
+ const TRANSCRIPT_ROOT = process.env.BRIDGE_TRANSCRIPT_ROOT || path.join(os.homedir(), '.claude', 'projects');
38
+ export function safeTranscriptPath(p) {
39
+ if (typeof p !== 'string' || !p.endsWith('.jsonl')) return null;
40
+ let root;
41
+ try { root = fs.realpathSync(TRANSCRIPT_ROOT); } catch { root = path.resolve(TRANSCRIPT_ROOT); }
42
+ let real;
43
+ try {
44
+ real = fs.realpathSync(p);
45
+ if (!fs.lstatSync(real).isFile()) return null;
46
+ } catch {
47
+ // not created yet: judge the folder it will live in
48
+ try { real = path.join(fs.realpathSync(path.dirname(p)), path.basename(p)); } catch { real = path.resolve(p); }
49
+ }
50
+ return real.startsWith(root + path.sep) ? real : null;
51
+ }
52
+
53
+ export function readTranscript(file, limit = 80) {
54
+ file = safeTranscriptPath(file);
55
+ if (!file || !fs.existsSync(file)) return [];
56
+ const size = fs.statSync(file).size;
57
+ const start = Math.max(0, size - TAIL_BYTES);
58
+ const fd = fs.openSync(file, 'r');
59
+ const buf = Buffer.alloc(size - start);
60
+ fs.readSync(fd, buf, 0, buf.length, start);
61
+ fs.closeSync(fd);
62
+
63
+ // Drop the heavy base64 image payloads so they neither bloat the phone
64
+ // response nor slow parsing; the block still renders as "🖼 image".
65
+ const raw = buf.toString('utf8').replace(IMAGE_DATA, '"data":""');
66
+ let lines = raw.split('\n');
67
+ if (start > 0) lines = lines.slice(1); // first line is probably cut in half
68
+
69
+ const messages = [];
70
+ for (const line of lines) {
71
+ if (!line.trim()) continue;
72
+ let entry;
73
+ try { entry = JSON.parse(line); } catch { continue; }
74
+ // One odd entry (a new Claude Code record shape) must not fail the whole
75
+ // transcript — that used to leave the chat unloadable.
76
+ let msg = null;
77
+ try { msg = extract(entry); } catch { continue; }
78
+ if (msg) messages.push(msg);
79
+ }
80
+ return messages.slice(-limit);
81
+ }
82
+
83
+ // Render a tool call the way the terminal shows it — the action plus its
84
+ // key argument (which file, which command) instead of a bare tool name.
85
+ export function toolLine(name, input) {
86
+ const short = (p) => String(p || '').split('/').slice(-2).join('/');
87
+ switch (name) {
88
+ case 'Edit':
89
+ case 'MultiEdit':
90
+ return `⚙︎ Edit ${short(input.file_path)}`;
91
+ case 'Write':
92
+ return `⚙︎ Write ${short(input.file_path)}`;
93
+ case 'Read':
94
+ return `⚙︎ Read ${short(input.file_path)}`;
95
+ case 'Bash': {
96
+ const cmd = String(input.command || '').replace(/\s+/g, ' ').trim();
97
+ return `⚙︎ $ ${cmd.slice(0, 120)}`;
98
+ }
99
+ case 'Grep':
100
+ return `⚙︎ Grep ${String(input.pattern || '').slice(0, 60)}`;
101
+ case 'Glob':
102
+ return `⚙︎ Glob ${input.pattern || ''}`;
103
+ case 'WebFetch':
104
+ return `⚙︎ Fetch ${input.url || ''}`;
105
+ case 'Task':
106
+ return `⚙︎ Task ${input.description || input.subagent_type || ''}`;
107
+ case 'TodoWrite':
108
+ return '⚙︎ Update todos';
109
+ default:
110
+ return `⚙︎ ${name}`;
111
+ }
112
+ }
113
+
114
+ // Extract before/after pairs from an editing tool so the app can render a diff.
115
+ export function editsFrom(name, input) {
116
+ const short = (p) => String(p || '').split('/').slice(-2).join('/');
117
+ const cap = (s) => String(s ?? '').slice(0, 4000);
118
+ if (name === 'Edit') return [{ file: short(input.file_path), before: cap(input.old_string), after: cap(input.new_string) }];
119
+ if (name === 'Write') return [{ file: short(input.file_path), before: '', after: cap(input.content) }];
120
+ if (name === 'MultiEdit') {
121
+ return (input.edits || []).slice(0, 20)
122
+ .map((e) => ({ file: short(input.file_path), before: cap(e.old_string), after: cap(e.new_string) }));
123
+ }
124
+ return [];
125
+ }
126
+
127
+ function extract(entry) {
128
+ if ((entry.type !== 'user' && entry.type !== 'assistant') || entry.isMeta || !entry.message) return null;
129
+ const parts = [];
130
+ const edits = [];
131
+ const content = entry.message.content;
132
+ if (typeof content === 'string') {
133
+ parts.push(content);
134
+ } else {
135
+ for (const block of content || []) {
136
+ if (block.type === 'text') parts.push(block.text);
137
+ else if (block.type === 'tool_use') {
138
+ parts.push(toolLine(block.name, block.input || {}));
139
+ edits.push(...editsFrom(block.name, block.input || {}));
140
+ } else if (block.type === 'image') parts.push('🖼 image');
141
+ // tool_result blocks are terminal noise on a phone screen — skip
142
+ }
143
+ }
144
+ const text = parts.join('\n').trim();
145
+ // harness-injected content (system reminders, slash-command echoes) starts with '<'
146
+ if (!text || text.startsWith('<')) return null;
147
+ const msg = {
148
+ role: entry.message.role,
149
+ text: text.slice(0, 4000),
150
+ ts: Date.parse(entry.timestamp) || 0,
151
+ };
152
+ if (edits.length) msg.edits = edits;
153
+ return msg;
154
+ }
155
+
156
+ function tmux(...args) {
157
+ return execFileSync(TMUX_BIN, args, { encoding: 'utf8', timeout: 5000 });
158
+ }
159
+
160
+ export function sendInput(pane, text) {
161
+ // Literal text first, Enter as a separate keypress — works for the Claude TUI prompt.
162
+ tmux('send-keys', '-t', pane, '-l', '--', text);
163
+ tmux('send-keys', '-t', pane, 'Enter');
164
+ }
165
+
166
+ export function capturePane(pane, lines = 50) {
167
+ return tmux('capture-pane', '-t', pane, '-p', '-S', `-${lines}`);
168
+ }
169
+
170
+ // eslint-disable-next-line no-control-regex
171
+ const ANSI = /\[[0-9;]*[A-Za-z]/g;
172
+ function stripAnsi(s) { return s.replace(ANSI, ''); }
173
+
174
+ // The Claude spinner's distinctive meter (elapsed time in parens, or the
175
+ // "esc to interrupt" hint) — NOT any chat line that merely says "tokens".
176
+ const SPINNER_RE = /\(\s*\d+m\s*\d+s\s*·|\(\s*\d+s\s*·|esc to interrupt/i;
177
+
178
+ // True while the terminal is actively working (spinner running). Lets the app's
179
+ // session card reflect real-time activity instead of the last hook event.
180
+ export function paneSpinnerActive(pane) {
181
+ try {
182
+ return tmux('capture-pane', '-t', pane, '-p', '-S', '-16')
183
+ .split('\n').some((l) => SPINNER_RE.test(l));
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+
189
+ // Named keys the app can drive the TUI with; everything else is sent literally.
190
+ const NAMED_KEYS = new Set([
191
+ 'Tab', 'Enter', 'Escape', 'BSpace', 'Space',
192
+ 'Up', 'Down', 'Left', 'Right', 'Home', 'End',
193
+ 'C-c', 'C-u', 'C-l', 'C-a', 'C-e', 'C-w', 'S-Tab', 'BTab',
194
+ ]);
195
+
196
+ // Send a sequence of key tokens to the pane. Each token is either
197
+ // { t: "literal text" } (typed verbatim) or { k: "Tab" } (a named keypress).
198
+ // Lets the phone reproduce Tab-to-accept, arrows, Esc, Ctrl-C, etc.
199
+ export function sendKeys(pane, keys) {
200
+ for (const key of keys) {
201
+ if (key && typeof key.t === 'string') {
202
+ if (key.t.length) tmux('send-keys', '-t', pane, '-l', '--', key.t);
203
+ } else if (key && typeof key.k === 'string' && NAMED_KEYS.has(key.k)) {
204
+ tmux('send-keys', '-t', pane, key.k);
205
+ }
206
+ }
207
+ }
208
+
209
+ // Set of every live tmux pane id, so the daemon can drop restored sessions
210
+ // whose terminal has since closed.
211
+ export function livePanes() {
212
+ try {
213
+ return new Set(tmux('list-panes', '-a', '-F', '#{pane_id}').split('\n').filter(Boolean));
214
+ } catch {
215
+ return null; // tmux failed/timed out — "unknown", not "no panes"
216
+ }
217
+ }
218
+
219
+ // Panes whose tmux session has at least one attached client, i.e. an actual
220
+ // terminal window is open on the Mac. Detached sessions (window closed but tmux
221
+ // kept the process alive in the background) are excluded, so the app's count
222
+ // matches the terminals the user can actually see.
223
+ export function attachedPanes() {
224
+ try {
225
+ return new Set(
226
+ tmux('list-panes', '-a', '-F', '#{pane_id} #{session_attached}')
227
+ .split('\n').filter(Boolean)
228
+ .map((l) => { const i = l.indexOf(' '); return { pane: l.slice(0, i), n: parseInt(l.slice(i + 1), 10) || 0 }; })
229
+ .filter((x) => x.pane && x.n > 0)
230
+ .map((x) => x.pane),
231
+ );
232
+ } catch {
233
+ return null; // tmux failed/timed out — "unknown", not "no panes"
234
+ }
235
+ }
236
+
237
+ // Every live claude-* tmux session with its pane id and a project name derived
238
+ // from the session name, so the daemon can surface terminals that never
239
+ // registered via a hook (started before the daemon, or missed SessionStart).
240
+ export function claudePanes() {
241
+ try {
242
+ // pane_id first (never contains a space) then session_name; split on the
243
+ // first space. Avoids relying on tmux interpreting a "\t" escape, which the
244
+ // daemon's launchd-resolved tmux does not do.
245
+ const out = tmux('list-panes', '-a', '-F', '#{pane_id} #{session_name}');
246
+ return out.split('\n').filter(Boolean).map((l) => {
247
+ const i = l.indexOf(' ');
248
+ const pane = i < 0 ? '' : l.slice(0, i);
249
+ const name = i < 0 ? '' : l.slice(i + 1);
250
+ return { name, pane, project: name.replace(/^claude-/, '').replace(/-\d+$/, '') };
251
+ }).filter((x) => x.name.startsWith('claude-') && x.pane);
252
+ } catch {
253
+ return null; // tmux failed/timed out — "unknown", not "no panes"
254
+ }
255
+ }
256
+
257
+ // Claude Code records each running interactive session in
258
+ // ~/.claude/sessions/<pid>.json, including its tmux pane ("name:@win.%pane").
259
+ // Map pane -> { sessionId, cwd, transcriptPath } for live pids only, so a
260
+ // terminal the daemon discovers without a hook still gets its real id and
261
+ // transcript (instead of an empty "terminal only" stand-in).
262
+ export function paneClaudeSessions(dir = path.join(os.homedir(), '.claude', 'sessions')) {
263
+ const out = new Map();
264
+ let files = [];
265
+ try { files = fs.readdirSync(dir).filter((f) => /^\d+\.json$/.test(f)); } catch { return out; }
266
+ for (const f of files) {
267
+ let j;
268
+ try { j = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')); } catch { continue; }
269
+ const pane = /(%\d+)$/.exec(String(j.tmux || ''))?.[1];
270
+ if (!pane || !j.cwd || !Number.isInteger(j.pid)) continue;
271
+ if (!/^[0-9a-f-]{36}$/i.test(String(j.sessionId || ''))) continue; // it becomes a file name
272
+ try { process.kill(j.pid, 0); } catch (e) { if (e.code !== 'EPERM') continue; } // dead pid → stale file
273
+ const prev = out.get(pane);
274
+ if (prev && (prev.updatedAt || 0) >= (j.updatedAt || 0)) continue; // pane reused: newest wins
275
+ out.set(pane, {
276
+ sessionId: String(j.sessionId),
277
+ cwd: String(j.cwd),
278
+ updatedAt: j.updatedAt || 0,
279
+ transcriptPath: path.join(os.homedir(), '.claude', 'projects',
280
+ String(j.cwd).replace(/[^a-zA-Z0-9]/g, '-'), `${j.sessionId}.jsonl`),
281
+ });
282
+ }
283
+ return out;
284
+ }
285
+
286
+ // A screenshot of the Mac's main display as JPEG bytes, downscaled so it streams
287
+ // cheaply. Needs Screen Recording permission for whatever launched the daemon;
288
+ // without it macOS returns just the wallpaper. Returns null on failure.
289
+ // A shot of the user's whole desktop is as sensitive as anything on it, so it
290
+ // never touches a fixed, world-readable path: a private 0700 directory per
291
+ // capture (no other local user can read it, and no one can pre-create the path),
292
+ // deleted as soon as the bytes are in memory.
293
+ export function captureScreen() {
294
+ let dir = '';
295
+ try {
296
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-bridge-screen-'));
297
+ const tmp = path.join(dir, 'screen.jpg');
298
+ execFileSync('screencapture', ['-x', '-t', 'jpg', '-T', '0', tmp], { timeout: 6000 });
299
+ fs.chmodSync(tmp, 0o600);
300
+ try { execFileSync('sips', ['-Z', '1600', tmp], { timeout: 5000, stdio: 'ignore' }); } catch { /* keep full-size */ }
301
+ return fs.readFileSync(tmp);
302
+ } catch {
303
+ return null;
304
+ } finally {
305
+ if (dir) { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ } }
306
+ }
307
+ }
308
+
309
+ // Candidate project directories for the "open new terminal" picker: git repos
310
+ // a couple levels under $HOME.
311
+ export function listProjectDirs() {
312
+ const home = process.env.HOME || '';
313
+ if (!home) return [];
314
+ let out = '';
315
+ try {
316
+ out = execFileSync('find', [home, '-maxdepth', '2', '-name', '.git', '-type', 'd'],
317
+ { encoding: 'utf8', timeout: 5000 });
318
+ } catch { /* find exits non-zero on permission errors but still prints hits */ }
319
+ return out.split('\n')
320
+ .filter(Boolean)
321
+ .map((g) => g.replace(/\/\.git$/, ''))
322
+ .filter((d) => d && d !== home)
323
+ .sort()
324
+ .slice(0, 60)
325
+ .map((path) => ({ path, name: path.split('/').pop() }));
326
+ }
327
+
328
+ // Browse folders under $HOME so the app can pick a directory to start a session
329
+ // in — for when you don't remember the exact path. Clamped to the home subtree;
330
+ // returns the resolved dir, its parent (null at HOME), and the child folders.
331
+ export function browseDir(dir) {
332
+ const home = fs.realpathSync(process.env.HOME || '/');
333
+ let target = dir ? path.resolve(dir) : home;
334
+ try { target = fs.realpathSync(target); } catch { target = home; }
335
+ if (target !== home && !target.startsWith(home + path.sep)) target = home;
336
+ if (!fs.existsSync(target) || !fs.statSync(target).isDirectory()) target = home;
337
+
338
+ let dirs = [];
339
+ try {
340
+ dirs = fs.readdirSync(target, { withFileTypes: true })
341
+ .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
342
+ .map((e) => ({ name: e.name, path: path.join(target, e.name) }))
343
+ .sort((a, b) => a.name.localeCompare(b.name))
344
+ .slice(0, 300);
345
+ } catch { /* unreadable dir — return what we have */ }
346
+
347
+ const parent = target === home ? null : path.dirname(target);
348
+ return { path: target, parent, dirs };
349
+ }
350
+
351
+ // Create a new folder (within $HOME) and return its path — so a session can be
352
+ // started in a brand-new project directory straight from the phone.
353
+ export function makeDir(parent, name) {
354
+ const home = fs.realpathSync(process.env.HOME || '/');
355
+ const base = path.resolve(parent || home);
356
+ if (base !== home && !base.startsWith(home + path.sep)) throw new Error('outside home folder');
357
+ const clean = String(name || '').trim();
358
+ if (!clean || clean.includes('/') || clean.includes('..')) throw new Error('invalid folder name');
359
+ const target = path.join(base, clean);
360
+ fs.mkdirSync(target, { recursive: true });
361
+ return { path: target, name: clean };
362
+ }
363
+
364
+ // Launch an agent (default `claude`) in a fresh detached tmux session in `dir`.
365
+ // Typing the command in a login shell reuses aliases/wrappers, so Claude's
366
+ // global hooks still register a claude session with the daemon; other agents
367
+ // (codex/gemini/aider/opencode/…) run fine too — the daemon registers those
368
+ // itself since tmux input/preview are agent-agnostic.
369
+ export function createTerminal(dir, command = 'claude') {
370
+ if (!dir || !fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
371
+ throw new Error('directory not found');
372
+ }
373
+ const cmd = String(command || 'claude').trim() || 'claude';
374
+ const base = (dir.split('/').pop() || 'term').replace(/[^A-Za-z0-9-]/g, '');
375
+ const name = `claude-${base}-${process.pid}${sessionCounter++}`;
376
+ tmux('new-session', '-d', '-s', name, '-c', dir);
377
+ tmux('send-keys', '-t', name, cmd, 'Enter');
378
+ let pane = '';
379
+ try { pane = tmux('list-panes', '-t', name, '-F', '#{pane_id}').trim().split('\n')[0]; } catch { /* */ }
380
+ return { session: name, dir, pane, command: cmd, agent: cmd.split(/\s+/)[0] };
381
+ }
382
+ let sessionCounter = 0;
383
+
384
+ // Send an image to the Claude prompt. Claude Code only ingests images via a
385
+ // clipboard paste, so: write the bytes to a file, load it onto the macOS
386
+ // clipboard as PNG, then Ctrl-V into the pane (Claude shows "[Image #N]").
387
+ // Optionally type a caption and submit.
388
+ const execFileP = promisify(execFile);
389
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
390
+
391
+ // Paste one or more images into the pane, then the caption, then (optionally)
392
+ // Enter — all as ONE message. Async so the daemon keeps answering polls/SSE
393
+ // while sips/osascript run; serialized globally because they all go through
394
+ // the one system clipboard (two uploads at once would paste each other's image).
395
+ let imageQueue = Promise.resolve();
396
+ let imageJobs = 0;
397
+ export const imagesBusy = () => imageJobs > 0;
398
+ export function sendImages(pane, buffers, { caption = '', submit = true } = {}) {
399
+ imageJobs++;
400
+ const run = imageQueue.then(() => pasteImages(pane, buffers, { caption, submit }));
401
+ imageQueue = run.catch(() => {}).finally(() => { imageJobs--; });
402
+ return run;
403
+ }
404
+ export const sendImage = (pane, buffer, opts) => sendImages(pane, [buffer], opts);
405
+
406
+ async function pasteImages(pane, buffers, { caption, submit }) {
407
+ const dir = `${process.env.HOME}/.claude-bridge/uploads`;
408
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
409
+ try { fs.chmodSync(dir, 0o700); } catch { /* best-effort: photos are private */ }
410
+ const files = [];
411
+ for (const buffer of buffers) {
412
+ const stamp = `${Date.now()}-${imageCounter++}`;
413
+ // Phones upload JPEG (far smaller than PNG for photos); Claude's clipboard
414
+ // paste needs PNG, so convert with sips unless it already is a PNG.
415
+ const isPng = buffer.length > 8 && buffer[0] === 0x89 && buffer[1] === 0x50
416
+ && buffer[2] === 0x4e && buffer[3] === 0x47;
417
+ const file = `${dir}/img-${stamp}.png`;
418
+ if (isPng) {
419
+ fs.writeFileSync(file, buffer, { mode: 0o600 });
420
+ } else {
421
+ const src = `${dir}/img-${stamp}.jpg`;
422
+ fs.writeFileSync(src, buffer, { mode: 0o600 });
423
+ try { await execFileP('sips', ['-s', 'format', 'png', src, '--out', file], { timeout: 8000 }); }
424
+ finally { fs.rmSync(src, { force: true }); }
425
+ }
426
+ files.push(file);
427
+ }
428
+ let pasted = 0;
429
+ try {
430
+ for (const file of files) {
431
+ // Load the PNG onto the clipboard, then paste it into the TUI.
432
+ await execFileP('osascript', ['-e', `set the clipboard to (read (POSIX file "${file}") as «class PNGf»)`], { timeout: 5000 });
433
+ tmux('send-keys', '-t', pane, 'C-v');
434
+ pasted++;
435
+ // Give Claude a beat to grab the clipboard image before the next paste.
436
+ await sleep(800);
437
+ }
438
+ } catch (err) {
439
+ // Don't leave half a batch sitting in the prompt for the next Enter.
440
+ if (pasted) { try { tmux('send-keys', '-t', pane, 'C-u'); } catch { /* pane gone */ } }
441
+ throw err;
442
+ } finally {
443
+ // Claude has the images once pasted; don't keep private photos on disk.
444
+ for (const f of files) fs.rmSync(f, { force: true });
445
+ }
446
+ if (caption && caption.trim()) tmux('send-keys', '-t', pane, '-l', '--', caption);
447
+ if (submit) tmux('send-keys', '-t', pane, 'Enter');
448
+ return { files };
449
+ }
450
+ let imageCounter = 0;
451
+
452
+ // Close a terminal: kill the tmux session that owns this pane. The session-end
453
+ // hook then drops it from the daemon's list.
454
+ export function killTerminal(pane) {
455
+ const sess = tmux('display-message', '-p', '-t', pane, '#{session_name}').trim();
456
+ if (!sess) throw new Error('no tmux session for pane');
457
+ tmux('kill-session', '-t', sess);
458
+ return { killed: sess };
459
+ }
460
+
461
+ // Parse the account-wide usage meters (5h / 7d rate-limit windows + model)
462
+ // from the Claude Code status footer. These limits are per-account, so reading
463
+ // any live session's pane gives the current numbers.
464
+ export function accountUsage(pane) {
465
+ const raw = tmux('capture-pane', '-t', pane, '-p', '-S', '-40');
466
+ return parseUsage(raw.split('\n').map((l) => stripAnsi(l)));
467
+ }
468
+
469
+ // "claude-opus-4-8" → "Opus 4.8". Family-first ids only (current naming).
470
+ function friendlyModel(raw) {
471
+ if (!raw) return null;
472
+ const m = String(raw).replace(/^claude-/, '').replace(/\[.*?\]/g, '');
473
+ const parts = m.split('-').filter(Boolean);
474
+ if (!parts.length) return null;
475
+ const fam = parts.shift();
476
+ const family = fam.charAt(0).toUpperCase() + fam.slice(1);
477
+ const ver = parts.filter((p) => /^\d+$/.test(p) && p.length <= 2).join('.');
478
+ return ver ? `${family} ${ver}` : family;
479
+ }
480
+
481
+ // The model a session is actually running, read from the last assistant message
482
+ // in its transcript (Claude's TUI footer no longer shows the model).
483
+ export function lastModel(file) {
484
+ if (!file || !fs.existsSync(file)) return null;
485
+ const size = fs.statSync(file).size;
486
+ const start = Math.max(0, size - 300_000);
487
+ const fd = fs.openSync(file, 'r');
488
+ const buf = Buffer.alloc(size - start);
489
+ fs.readSync(fd, buf, 0, buf.length, start);
490
+ fs.closeSync(fd);
491
+ const matches = buf.toString('utf8').match(/"model":"(claude-[^"]+)"/g);
492
+ if (!matches || !matches.length) return null;
493
+ const last = matches[matches.length - 1].match(/"model":"([^"]+)"/)[1];
494
+ return friendlyModel(last);
495
+ }
496
+
497
+ // Rough USD estimate of a session's spend, summed from every assistant turn's
498
+ // token usage in the transcript and priced per model (per 1M tokens). Cached by
499
+ // the file's mtime+size so a big transcript isn't re-read on every poll.
500
+ const RATES = {
501
+ opus: { in: 15, out: 75, cw: 18.75, cr: 1.5 },
502
+ sonnet: { in: 3, out: 15, cw: 3.75, cr: 0.3 },
503
+ haiku: { in: 0.8, out: 4, cw: 1.0, cr: 0.08 },
504
+ };
505
+ const rateFor = (m) => (/opus/i.test(m) ? RATES.opus : /haiku/i.test(m) ? RATES.haiku : RATES.sonnet);
506
+ const costCache = new Map();
507
+ export function sessionCost(file) {
508
+ if (!file || !fs.existsSync(file)) return null;
509
+ const st = fs.statSync(file);
510
+ const key = `${st.mtimeMs}:${st.size}`;
511
+ const hit = costCache.get(file);
512
+ if (hit && hit.key === key) return hit.value;
513
+ let usd = 0, inTok = 0, outTok = 0;
514
+ try {
515
+ const lines = fs.readFileSync(file, 'utf8').split('\n');
516
+ for (const line of lines) {
517
+ if (!line.includes('"usage"')) continue;
518
+ let o; try { o = JSON.parse(line); } catch { continue; }
519
+ const u = o?.message?.usage;
520
+ if (!u) continue;
521
+ const r = rateFor(o.message.model || '');
522
+ const i = u.input_tokens || 0, out = u.output_tokens || 0;
523
+ const cw = u.cache_creation_input_tokens || 0, cr = u.cache_read_input_tokens || 0;
524
+ usd += (i * r.in + out * r.out + cw * r.cw + cr * r.cr) / 1e6;
525
+ inTok += i + cw + cr; outTok += out;
526
+ }
527
+ } catch { return null; }
528
+ const value = { usd: Math.round(usd * 100) / 100, inTokens: inTok, outTokens: outTok };
529
+ costCache.set(file, { key, value });
530
+ return value;
531
+ }
532
+
533
+ // Pure parse of the usage meters from already-captured, ANSI-stripped lines.
534
+ export function parseUsage(lines) {
535
+ const u = {};
536
+ for (const l of lines) {
537
+ let m;
538
+ if ((m = /\b5h\b[^%]*?(\d+)%/.exec(l))) {
539
+ u.pct5h = Number(m[1]);
540
+ const r = /resets in (.+?)\s*\(at/i.exec(l); if (r) u.reset5h = r[1].trim();
541
+ }
542
+ if ((m = /\b7d\b[^%]*?(\d+)%/.exec(l))) {
543
+ u.pct7d = Number(m[1]);
544
+ const r = /resets in (.+?)\s*\(at/i.exec(l); if (r) u.reset7d = r[1].trim();
545
+ }
546
+ if (!u.model && (m = /\b(Opus|Sonnet|Haiku|Fable)\s*[\d.]*/i.exec(l))) u.model = m[0].trim();
547
+ }
548
+ return (u.pct5h != null || u.pct7d != null || u.model) ? u : null;
549
+ }
550
+
551
+ // Pull the Claude Code status area (project / model / git / usage / mode) and
552
+ // the current activity/spinner line so the app can mirror the terminal footer.
553
+ export function terminalStatus(pane) {
554
+ const raw = tmux('capture-pane', '-t', pane, '-p', '-S', '-40');
555
+ const lines = raw.split('\n').map((l) => stripAnsi(l).replace(/\s+$/, ''));
556
+
557
+ // Activity/spinner line, e.g. "✻ Sublimating… (2m 20s · ↓ 4.5k tokens)".
558
+ let activity = '';
559
+ for (let i = lines.length - 1; i >= 0; i--) {
560
+ if (SPINNER_RE.test(lines[i])) { activity = lines[i].trim(); break; }
561
+ }
562
+
563
+ // Status footer starts at the project/model line (top of the footer block)
564
+ // and runs down through the usage bars / mode line to the end.
565
+ let start = -1;
566
+ for (let i = lines.length - 1; i >= 0; i--) {
567
+ if (/Project:|\b(Opus|Sonnet|Haiku|Fable)\b/i.test(lines[i])) { start = i; break; }
568
+ }
569
+ if (start < 0) {
570
+ for (let i = lines.length - 1; i >= 0; i--) {
571
+ if (/accept edits|plan mode|bypass/i.test(lines[i])) { start = i; break; }
572
+ }
573
+ }
574
+ const status = start >= 0
575
+ ? lines.slice(start).filter((l) => l.trim()).slice(0, 6)
576
+ : [];
577
+
578
+ return { activity, status, prompt: detectPrompt(lines), suggestions: detectSuggestions(lines) };
579
+ }
580
+
581
+ // Parse the live autocomplete dropdown Claude shows above the input box when
582
+ // you type "/" (slash commands / skills) — "/command description" lines.
583
+ export function detectSuggestions(lines) {
584
+ let promptIdx = -1;
585
+ for (let i = lines.length - 1; i >= 0; i--) {
586
+ if (/❯/.test(lines[i])) { promptIdx = i; break; }
587
+ }
588
+ if (promptIdx < 1) return [];
589
+ const out = [];
590
+ for (let i = promptIdx - 1; i >= Math.max(0, promptIdx - 16); i--) {
591
+ const l = lines[i];
592
+ if (/^\s*[─—-]{5,}/.test(l)) continue; // box border
593
+ const m = /^\s{1,4}(\/[A-Za-z0-9_:.-]+)\s{2,}(.+?)\s*$/.exec(l);
594
+ if (m) out.unshift({ value: m[1], hint: m[2].trim().slice(0, 70) });
595
+ else if (l.trim() && !/^\s{2,}/.test(l)) break; // hit real content, stop
596
+ }
597
+ return out.slice(0, 12);
598
+ }
599
+
600
+ // Detect an interactive numbered / yes-no prompt in the TUI (e.g. option
601
+ // pickers or "1: Bad 2: Fine 3: Good") so the app can offer tap-to-answer
602
+ // buttons. These aren't permission hooks, so they'd otherwise be unanswerable.
603
+ export function detectPrompt(lines) {
604
+ const tail = lines.slice(-16);
605
+
606
+ // Vertical selection menu (e.g. /model, /agents): one option per line as
607
+ // "N. Label description", usually with a ❯ cursor and an "Esc to cancel"
608
+ // footer. Gate on those strong signals so ordinary numbered prose isn't caught.
609
+ const hasCursor = tail.some((l) => /^\s*[>❯]\s*\d+[.:]/.test(l));
610
+ const hasFooter = tail.some((l) => /esc to cancel|to set as default|use this session|to select|to navigate/i.test(l));
611
+ if (hasCursor || hasFooter) {
612
+ const menu = new Map();
613
+ let multi = false;
614
+ for (const raw of tail) {
615
+ const m = /^\s*[>❯]?\s*(\d+)[.:]\s+(\S.*)$/.exec(raw);
616
+ if (!m) continue;
617
+ let label = m[2].split(/\s{2,}|·/)[0].trim().replace(/\s+/g, ' ');
618
+ // A leading "[ ]" / "[✓]" / "[x]" means this is a checkbox multi-select:
619
+ // remember that, capture whether this row is ticked, and drop the marker
620
+ // so the label reads cleanly (the app renders its own checkbox).
621
+ let checked;
622
+ const box = /^\[([ xX✓✔*·]*)\]\s*/.exec(label);
623
+ if (box) { multi = true; checked = /[xX✓✔*·]/.test(box[1]); label = label.slice(box[0].length); }
624
+ label = label.replace(/[✓✔]\s*$/, '').trim();
625
+ // Never drop an option for length — truncate the display label instead, so
626
+ // the app always shows the complete set (a missing option = wrong answer).
627
+ if (label.length > 60) label = label.slice(0, 59).trimEnd() + '…';
628
+ if (label && label.length <= 120 && !menu.has(m[1])) menu.set(m[1], { label, checked });
629
+ }
630
+ if (menu.size >= 2 && menu.size <= 12) {
631
+ return { multi, options: [...menu.entries()].map(([key, o]) => ({ key, label: o.label, checked: o.checked })) };
632
+ }
633
+ }
634
+
635
+ // Inline rating / numbered prompt on a single line ("1: Bad 2: Fine 3: Good").
636
+ const opts = new Map();
637
+ for (const raw of tail) {
638
+ const l = raw.trim();
639
+ // skip obvious command output / paths, not menus
640
+ if (!l || l.includes('$') || l.includes('/') || l.startsWith('5h') || l.startsWith('7d')) continue;
641
+ const re = /(?:^|\s|❯)(\d+)\s*[.:]\s+([A-Za-z][^│|]{0,34}?)(?=\s{2,}\d+\s*[.:]|\s*$)/g;
642
+ let m;
643
+ while ((m = re.exec(l))) {
644
+ const key = m[1];
645
+ const label = m[2].trim().replace(/\s+/g, ' ');
646
+ if (label && !opts.has(key)) opts.set(key, label);
647
+ }
648
+ }
649
+ if (opts.size >= 2 && opts.size <= 9) {
650
+ return { options: [...opts.entries()].map(([key, label]) => ({ key, label })) };
651
+ }
652
+
653
+ for (const raw of tail) {
654
+ if (/\(y\/n\)|\[y\/n\]/i.test(raw)) {
655
+ return { options: [{ key: 'y', label: 'Yes' }, { key: 'n', label: 'No' }] };
656
+ }
657
+ }
658
+ return null;
659
+ }