cli-setu 0.3.2 → 0.3.4

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.
@@ -1,302 +1,400 @@
1
- // Claude Code adapter. Ported straight out of supervisor-qr.js's old
2
- // hardcoded describePrompt/getDialogOptions - behavior unchanged, just
3
- // moved behind the adapter interface so supervisor-qr.js can treat this
4
- // as one of N CLIs instead of the only one it knows about.
5
- //
6
- // Approval detection: Claude Code's PermissionRequest hook
7
- // (onPermissionRequest.js, wired via .claude/settings.json) writes one
8
- // JSON line per prompt to a queue file THIS adapter knows how to read -
9
- // not a generic mechanism, a Claude-Code-specific one. No other CLI here
10
- // is expected to share this exact file-based queue approach; it's an
11
- // implementation detail of the hook wiring already built for Claude Code,
12
- // preserved as-is rather than generalized prematurely.
13
- //
14
- // Usage: Claude Code has no live token API for an interactive session
15
- // (see cli-adapters/README.md) - the closest available signal is its own
16
- // `/cost` slash command's rendered TUI output, which this adapter parses
17
- // on a best-effort basis. This is fragile by nature (breaks if a future
18
- // Claude Code version changes that output's wording) - see parseFromOutput's
19
- // regex for exactly what shape it expects today.
20
- const fs = require('fs');
21
- const path = require('path');
22
- const { resolveWindowsBin } = require('./resolveWindowsBin');
23
-
24
- function queueFileFor(baseDir, cwd) {
25
- const safeName = cwd.replace(/[\\/:]/g, '_');
26
- return path.join(baseDir, `pending-requests.${safeName}.json`);
27
- }
28
-
29
- // Real bug found by testing: this only ever described Write/Edit/Bash -
30
- // AskUserQuestion (Claude's own "let me ask you something" tool, a REAL,
31
- // commonly-used tool_name, not an edge case) fell through to the generic
32
- // `${tool_name}: ${JSON.stringify(tool_input)}` branch, showing raw JSON
33
- // instead of the actual question text Claude Code itself renders.
34
- // PowerShell is Windows Claude Code's own tool_name for shell commands
35
- // (distinct from Bash, which is what WSL/macOS/Linux sessions use for the
36
- // exact same kind of prompt) - previously undetected here entirely, so it
37
- // fell through to the same raw-JSON fallback Bash used to.
38
- function describePrompt(event) {
39
- const { tool_name, tool_input } = event;
40
- if (tool_name === 'Write' && tool_input?.file_path) return `Create ${tool_input.file_path.split(/[\\/]/).pop()}?`;
41
- if (tool_name === 'Edit' && tool_input?.file_path) return `Edit ${tool_input.file_path.split(/[\\/]/).pop()}?`;
42
- if ((tool_name === 'Bash' || tool_name === 'PowerShell') && tool_input?.command) {
43
- return tool_input.description ? `${tool_input.description}?\n${tool_input.command}` : `Run: ${tool_input.command}`;
44
- }
45
- if (tool_name === 'AskUserQuestion' && tool_input?.questions?.[0]) {
46
- return tool_input.questions[0].question || tool_input.questions[0].header || 'Claude has a question';
47
- }
48
- return `${tool_name}: ${JSON.stringify(tool_input)}`;
49
- }
50
-
51
- // Real bug found by testing: every option set here was a HARDCODED guess
52
- // keyed off tool_name, never the real options Claude Code actually
53
- // offered - correct by coincidence for Write/Edit/Bash's own fixed
54
- // 3-choice menu (verified against real captured PermissionRequest
55
- // payloads), but silently WRONG for AskUserQuestion, whose real options
56
- // (with real, meaningful labels like "Just delete existing file" or
57
- // "Overwrite then delete") are sitting right there in
58
- // tool_input.questions[0].options and were never read at all - the app
59
- // showed a generic "Approve/Reject" for a prompt that actually offered 4
60
- // distinct real choices. keystroke is the exact digit Claude Code's own
61
- // numbered menu expects (1-indexed, matching the real on-screen "1.", "2."
62
- // list) - this MUST match what's actually rendered, since supervisor.js
63
- // injects this keystroke directly with no translation.
64
- function getDialogOptions(event) {
65
- if (event.tool_name === 'AskUserQuestion' && event.tool_input?.questions?.[0]?.options?.length) {
66
- // Real payload verified live: tool_input.questions[0].options only
67
- // ever lists the REAL answer choices Claude proposed (e.g. "Just
68
- // delete existing file", "Overwrite then delete") - none of them is a
69
- // "reject". The on-screen "N. Type something." and "N+1. Chat about
70
- // this" the user actually sees are UI chrome this tool always appends
71
- // itself, at fixed positions right after the real options, and are
72
- // NOT present in this payload at all - added here explicitly (with
73
- // their own real, correct keystrokes) rather than silently missing
74
- // from the phone's choices, since without them there'd be no reject-
75
- // equivalent option at all for this tool.
76
- const opts = event.tool_input.questions[0].options;
77
- const real = opts.map((o, i) => ({ label: o.label, keystroke: String(i + 1), style: i === 0 ? 'approve' : 'approve-alt' }));
78
- return [
79
- ...real,
80
- { label: 'Type something', keystroke: String(opts.length + 1), style: 'reject' },
81
- ];
82
- }
83
- if (event.tool_name === 'Write' || event.tool_name === 'Edit') {
84
- return [
85
- { label: 'Yes', keystroke: '1', style: 'approve' },
86
- { label: 'Yes, and accept edits automatically for this session', keystroke: '2', style: 'approve-alt' },
87
- { label: 'No', keystroke: '3', style: 'reject' },
88
- ];
89
- }
90
- if (event.tool_name === 'Bash' || event.tool_name === 'PowerShell') {
91
- return [
92
- { label: 'Yes', keystroke: '1', style: 'approve' },
93
- { label: "Yes, don't ask again for this command in this project", keystroke: '2', style: 'approve-alt' },
94
- { label: 'No', keystroke: '3', style: 'reject' },
95
- ];
96
- }
97
- return [
98
- { label: 'Yes', keystroke: '1', style: 'approve' },
99
- { label: 'No', keystroke: '3', style: 'reject' },
100
- ];
101
- }
102
-
103
- // Real bug found by testing: getDialogOptions' Write/Edit/Bash/PowerShell
104
- // branches above are a HARDCODED GUESS at Claude Code's own menu, since
105
- // the PermissionRequest hook payload never includes the real options for
106
- // those tool types (confirmed live - only AskUserQuestion's payload
107
- // carries real options at all). That guess drifted the moment Claude Code
108
- // added a 4th choice ("switch to auto mode") to its Bash/Write menu - the
109
- // phone showed 3 buttons for a real 4-option prompt. This reads the ACTUAL
110
- // rendered menu directly from the terminal instead of guessing - the one
111
- // source of truth for what the user can really pick, immune to Claude
112
- // Code changing its wording or option COUNT in a future version.
113
- const ANSI_RE = /\x1b\[[0-9;?]*[a-zA-Z]/g;
114
- function stripAnsi(text) {
115
- return text.replace(ANSI_RE, '');
116
- }
117
-
118
- const PROCEED_RE = /do you want to (?:proceed|create|make this edit)\??/i;
119
- const ESC_FOOTER_RE = /esc to cancel/i;
120
- // A real numbered option line: "1. Yes", "❯ 2. Yes, and always allow...".
121
- // Real bug found by testing: the currently-highlighted option's pointer
122
- // glyph (❯) is NOT wrapped in its own ANSI color code the way the
123
- // original comment here assumed - it's a plain literal character sitting
124
- // before the digit, confirmed against a real captured "❯ 1. Yes" line -
125
- // so \s* alone (whitespace only) never matched it, silently dropping
126
- // EXACTLY the currently-selected option (always index 0) out of the
127
- // parsed list every single time. [^\d\n]* explicitly allows that glyph
128
- // (or any other non-digit marker Claude Code might use) before the
129
- // number, without allowing it to swallow a real digit from a different
130
- // line entirely (multiline mode - ^ anchors per line, not per string).
131
- const OPTION_LINE_RE = /^[^\d\n]*(\d+)\.\s+(.+)$/;
132
-
133
- // Reads the real, live menu straight from a trailing scrollback window.
134
- // Returns null (not a guess) if the window doesn't contain a complete
135
- // menu yet - supervisor.js retries a few times as the PTY catches up
136
- // before ever falling back to the static guess above.
137
- function parseLiveOptions(scrollbackWindow) {
138
- const clean = stripAnsi(scrollbackWindow);
139
- const startMatch = clean.match(PROCEED_RE);
140
- if (!startMatch) return null;
141
- const endMatch = clean.slice(startMatch.index).match(ESC_FOOTER_RE);
142
- if (!endMatch) return null; // menu still rendering - not a complete capture yet
143
-
144
- const section = clean.slice(startMatch.index, startMatch.index + endMatch.index);
145
- const options = [];
146
- // Real bug found by testing: Claude Code's real terminal output uses
147
- // \r\n line endings, and splitting on '\n' alone leaves a trailing \r
148
- // on every line. JavaScript's `.` does NOT match \r (confirmed - only
149
- // \n is excluded from `.` in most regex engines, but V8 excludes \r
150
- // too), so (.+)$ could never reach real end-of-line and OPTION_LINE_RE
151
- // silently matched ZERO option lines, not just the pointer-marked one -
152
- // this is what actually caused parseLiveOptions to return null on every
153
- // real menu, not just a pointer-glyph edge case. Stripping stray \r
154
- // before splitting is the fix that generalizes to any future capture,
155
- // not just this one.
156
- for (const line of section.replace(/\r/g, '').split('\n')) {
157
- const m = line.match(OPTION_LINE_RE);
158
- if (m) options.push({ number: Number(m[1]), label: m[2].trim() });
159
- }
160
- if (options.length === 0) return null;
161
-
162
- // Real, observed shape: the LAST numbered option is always the decline
163
- // ("No") - every live capture so far (3-option AND the newer 4-option
164
- // menu) confirms this holds regardless of how many "Yes, and also..."
165
- // variants sit in between. keystroke is the option's own real number as
166
- // rendered, not a re-numbered index - this is what makes this immune to
167
- // Claude Code adding/removing/reordering middle options.
168
- return options.map((o, i) => ({
169
- label: o.label,
170
- keystroke: String(o.number),
171
- style: i === options.length - 1 ? 'reject' : i === 0 ? 'approve' : 'approve-alt',
172
- }));
173
- }
174
-
175
- // Corrected against REAL `/cost` output (Claude Code CLI, captured live -
176
- // see project chat history for the exact screenshot), not guessed - the
177
- // actual shape is:
178
- // Total cost: $0.0000
179
- // ...
180
- // Usage: 0 input, 0 output, 0 cache read, 0 cache write
181
- // ...
182
- // Current session
183
- // ████████████████████████████▉ 58% used
184
- // Resets 8:20pm (Asia/Kolkata)
185
- // Two real surprises the first version of this regex got wrong: (1) the
186
- // line is literally "Usage:", not "Total tokens used:" - a guess that
187
- // never matched; (2) input/output here reflects only recent API calls,
188
- // not cumulative session usage - it read 0/0 on a hours-old session in
189
- // testing. The "Current session ... % used" context-window bar is the
190
- // actually-meaningful, reliably-nonzero signal for "how much of this
191
- // session have I used", so that's captured too and is what Devices/
192
- // Profile should lead with - raw input/output tokens are kept as a
193
- // secondary field since they're real numbers, just not the useful ones
194
- // for "how much have I used up" the user actually asked for.
195
- //
196
- // Wording/format has changed across Claude Code versions before and will
197
- // again - these regexes are intentionally loose (case-insensitive,
198
- // tolerant of box-drawing/ANSI noise around the numbers) but there's no
199
- // guarantee they survive the next release. If they stop matching,
200
- // parseFromOutput just keeps returning null (see supervisor-qr.js's
201
- // caller) - the rest of the app degrades to "no usage data," not a crash.
202
- const USAGE_LINE_RE = /usage:\s*([\d,]+)\s*input,\s*([\d,]+)\s*output,\s*([\d,]+)\s*cache read,\s*([\d,]+)\s*cache write/i;
203
- const COST_RE = /total cost:\s*\$([\d.]+)/i;
204
- // "Current session" and "Current week (all models)" each have their own
205
- // "NN% used" + "Resets ..." pair right below them - captured as separate
206
- // regexes (not one generic loop) since the two sections' reset-time
207
- // format actually differs (session: bare time "8:20pm (TZ)"; week: date +
208
- // time "Sep 19, 2:30am (TZ)") - confirmed against the real captured
209
- // output, not assumed to be the same shape.
210
- const SESSION_PCT_RE = /current session[\s\S]{0,200}?(\d{1,3})%\s*used/i;
211
- const SESSION_RESET_RE = /current session[\s\S]{0,300}?resets\s+([^\n(]+(?:\([^)]+\))?)/i;
212
- const WEEK_PCT_RE = /current week[^\n]*[\s\S]{0,200}?(\d{1,3})%\s*used/i;
213
- const WEEK_RESET_RE = /current week[^\n]*[\s\S]{0,300}?resets\s+([^\n(]+(?:\([^)]+\))?)/i;
214
-
215
- function parseFromOutput(chunk) {
216
- const usageMatch = chunk.match(USAGE_LINE_RE);
217
- const costMatch = chunk.match(COST_RE);
218
- const pctMatch = chunk.match(SESSION_PCT_RE);
219
- const sessionResetMatch = chunk.match(SESSION_RESET_RE);
220
- const weekPctMatch = chunk.match(WEEK_PCT_RE);
221
- const weekResetMatch = chunk.match(WEEK_RESET_RE);
222
- if (!usageMatch && !costMatch && !pctMatch && !weekPctMatch) return null;
223
-
224
- const inputTokens = usageMatch ? Number(usageMatch[1].replace(/,/g, '')) : null;
225
- const outputTokens = usageMatch ? Number(usageMatch[2].replace(/,/g, '')) : null;
226
- return {
227
- totalTokens: inputTokens != null && outputTokens != null ? inputTokens + outputTokens : null,
228
- inputTokens,
229
- outputTokens,
230
- cacheReadTokens: usageMatch ? Number(usageMatch[3].replace(/,/g, '')) : null,
231
- cacheWriteTokens: usageMatch ? Number(usageMatch[4].replace(/,/g, '')) : null,
232
- costUsd: costMatch ? Number(costMatch[1]) : null,
233
- sessionContextUsedPct: pctMatch ? Number(pctMatch[1]) : null,
234
- sessionResetsAt: sessionResetMatch ? sessionResetMatch[1].trim() : null,
235
- weekUsedPct: weekPctMatch ? Number(weekPctMatch[1]) : null,
236
- weekResetsAt: weekResetMatch ? weekResetMatch[1].trim() : null,
237
- raw: chunk,
238
- };
239
- }
240
-
241
- module.exports = {
242
- id: 'claude',
243
- displayName: 'Claude Code',
244
- // Adapter-declared icon (see README.md) - the app's Devices tab reads
245
- // this instead of hardcoding "if cliType === 'claude'" anywhere in the
246
- // UI, so a future third adapter just declares its own icon here too,
247
- // with no UI changes needed. No official Anthropic logo asset is
248
- // bundled (real brand marks need to be properly sourced by whoever
249
- // owns this app, not fabricated) - a distinct, well-chosen generic
250
- // icon + color stands in until a real logo image is supplied.
251
- icon: { name: 'sparkles', color: '#D97757' }, // Anthropic's own public brand accent is a terracotta/orange - approximated here, not an official value
252
- spawn: {
253
- command: process.platform === 'win32' ? resolveWindowsBin('claude') : 'claude',
254
- args: () => ['--permission-mode', 'default'],
255
- },
256
- approvals: {
257
- queueFileFor,
258
- describePrompt,
259
- getDialogOptions,
260
- parseLiveOptions,
261
- // Real gap found by testing: a PTY-text-scan for Claude Code's own
262
- // "Interrupted..." wording (resolvedLocallyPattern) was tried and
263
- // removed - real captured terminal output across several live
264
- // rejection tests never actually contained that literal text in a
265
- // form a regex could reliably match. This is a different, more
266
- // robust signal: it doesn't care WHAT replaced the menu (an
267
- // "Interrupted" message, a follow-up question, plain output - Claude
268
- // Code's exact wording can drift freely) - only whether the SAME
269
- // "Do you want to proceed?" style menu PROCEED_RE matched is still
270
- // physically on screen. supervisor.js polls this for a few seconds
271
- // right after relaying a prompt; once it stops matching, the prompt
272
- // is gone - approved, rejected, or interrupted, any of those means a
273
- // decision happened, so this is a fully reliable resolution signal
274
- // for the Bash/Write/PowerShell prompts that only ever get options
275
- // via parseLiveOptions in the first place (AskUserQuestion already
276
- // resolves correctly via PostToolUse+resolveIfPending's exact
277
- // question-text match - this is not used for that tool_name at all).
278
- isMenuStillOnScreen: (scrollbackWindow) => PROCEED_RE.test(stripAnsi(scrollbackWindow)),
279
- },
280
- usage: {
281
- // '/cost' + Enter - a real, visible command in the user's own
282
- // terminal (see supervisor-qr.js's usage-polling comment for why this
283
- // is opt-in-by-default rather than silent).
284
- triggerKeystrokes: '/cost\r',
285
- parseFromOutput,
286
- },
287
- // Remote slash-command palette (Section 15 roadmap item #6). Each entry
288
- // is just a label + the literal keystrokes to write into the PTY - the
289
- // SAME primitive terminal.input already uses for free-typed text (see
290
- // supervisor-qr.js's ws.on('message') handler), just named and one tap
291
- // instead of typing it out. Deliberately NOT a structured remote
292
- // sub-menu: /model opens Claude Code's own interactive picker on the
293
- // laptop's real screen, which the phone then sees via the existing
294
- // live terminal mirror (Phase 6) and can navigate with the same
295
- // quick-action arrow/Enter keys already in the Terminal tab - no new
296
- // blind multi-step remote flow being invented here.
297
- commands: [
298
- { id: 'cost', label: 'Check usage', keystrokes: '/cost\r' },
299
- { id: 'model', label: 'Switch model', keystrokes: '/model\r' },
300
- { id: 'compact', label: 'Compact context', keystrokes: '/compact\r' },
301
- ],
302
- };
1
+ // Claude Code adapter. Ported straight out of supervisor-qr.js's old
2
+ // hardcoded describePrompt/getDialogOptions - behavior unchanged, just
3
+ // moved behind the adapter interface so supervisor-qr.js can treat this
4
+ // as one of N CLIs instead of the only one it knows about.
5
+ //
6
+ // Approval detection: Claude Code's PermissionRequest hook
7
+ // (onPermissionRequest.js, wired via .claude/settings.json) writes one
8
+ // JSON line per prompt to a queue file THIS adapter knows how to read -
9
+ // not a generic mechanism, a Claude-Code-specific one. No other CLI here
10
+ // is expected to share this exact file-based queue approach; it's an
11
+ // implementation detail of the hook wiring already built for Claude Code,
12
+ // preserved as-is rather than generalized prematurely.
13
+ //
14
+ // Usage: Claude Code has no live token API for an interactive session
15
+ // (see cli-adapters/README.md) - the closest available signal is its own
16
+ // `/cost` slash command's rendered TUI output, which this adapter parses
17
+ // on a best-effort basis. This is fragile by nature (breaks if a future
18
+ // Claude Code version changes that output's wording) - see parseFromOutput's
19
+ // regex for exactly what shape it expects today.
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+ const { resolveWindowsBin } = require('./resolveWindowsBin');
23
+
24
+ function queueFileFor(baseDir, cwd) {
25
+ const safeName = cwd.replace(/[\\/:]/g, '_');
26
+ return path.join(baseDir, `pending-requests.${safeName}.json`);
27
+ }
28
+
29
+ // Real bug found by testing: this only ever described Write/Edit/Bash -
30
+ // AskUserQuestion (Claude's own "let me ask you something" tool, a REAL,
31
+ // commonly-used tool_name, not an edge case) fell through to the generic
32
+ // `${tool_name}: ${JSON.stringify(tool_input)}` branch, showing raw JSON
33
+ // instead of the actual question text Claude Code itself renders.
34
+ // PowerShell is Windows Claude Code's own tool_name for shell commands
35
+ // (distinct from Bash, which is what WSL/macOS/Linux sessions use for the
36
+ // exact same kind of prompt) - previously undetected here entirely, so it
37
+ // fell through to the same raw-JSON fallback Bash used to.
38
+ // Real gap found by testing (PM report): tool_input.questions can hold
39
+ // MULTIPLE questions in one single AskUserQuestion call (a real captured
40
+ // payload had 3: "Next task" -> "Approach" -> "Scope", the last one
41
+ // multiSelect) - Claude Code renders this as its own multi-step wizard
42
+ // (arrow keys to move between steps, a final "Submit"), but this used to
43
+ // hardcode questions[0], so only the FIRST step ever reached the phone at
44
+ // all; steps 2+ were silently invisible to it. questionIndex (default 0,
45
+ // every existing call site unchanged) lets supervisor.js step through the
46
+ // array one at a time, relaying each as its own update to the SAME
47
+ // promptId - see supervisor.js's askUserQuestionStep tracking.
48
+ function describePrompt(event, questionIndex = 0) {
49
+ const { tool_name, tool_input } = event;
50
+ if (tool_name === 'Write' && tool_input?.file_path) return `Create ${tool_input.file_path.split(/[\\/]/).pop()}?`;
51
+ if (tool_name === 'Edit' && tool_input?.file_path) return `Edit ${tool_input.file_path.split(/[\\/]/).pop()}?`;
52
+ if ((tool_name === 'Bash' || tool_name === 'PowerShell') && tool_input?.command) {
53
+ return tool_input.description ? `${tool_input.description}?\n${tool_input.command}` : `Run: ${tool_input.command}`;
54
+ }
55
+ if (tool_name === 'AskUserQuestion' && tool_input?.questions?.[questionIndex]) {
56
+ const q = tool_input.questions[questionIndex];
57
+ return q.question || q.header || 'Claude has a question';
58
+ }
59
+ return `${tool_name}: ${JSON.stringify(tool_input)}`;
60
+ }
61
+
62
+ // Real bug found by testing: every option set here was a HARDCODED guess
63
+ // keyed off tool_name, never the real options Claude Code actually
64
+ // offered - correct by coincidence for Write/Edit/Bash's own fixed
65
+ // 3-choice menu (verified against real captured PermissionRequest
66
+ // payloads), but silently WRONG for AskUserQuestion, whose real options
67
+ // (with real, meaningful labels like "Just delete existing file" or
68
+ // "Overwrite then delete") are sitting right there in
69
+ // tool_input.questions[0].options and were never read at all - the app
70
+ // showed a generic "Approve/Reject" for a prompt that actually offered 4
71
+ // distinct real choices. keystroke is the exact digit Claude Code's own
72
+ // numbered menu expects (1-indexed, matching the real on-screen "1.", "2."
73
+ // list) - this MUST match what's actually rendered, since supervisor.js
74
+ // injects this keystroke directly with no translation.
75
+ function getDialogOptions(event, questionIndex = 0) {
76
+ // Real gap found by testing: a multiSelect question (checkboxes +
77
+ // Submit) was falling into the single-choice branch below, handing the
78
+ // phone keystroke:'1'/'2'/... as if tapping an option picked it - but a
79
+ // real captured multiSelect screen needs Space to TOGGLE a checkbox (not
80
+ // select-and-advance) and a separate Tab+Enter to Submit. Returning null
81
+ // here (rather than a wrong single-choice shape) tells callers this
82
+ // needs the dedicated multiSelect path - see
83
+ // supervisor.js's advanceAskUserQuestion/buildMultiSelectKeystrokes,
84
+ // built from a real confirmed key mapping (Down arrow moves the
85
+ // highlight, Space toggles, Tab jumps to Submit, Enter confirms).
86
+ if (event.tool_name === 'AskUserQuestion' && event.tool_input?.questions?.[questionIndex]?.multiSelect) {
87
+ return null;
88
+ }
89
+ if (event.tool_name === 'AskUserQuestion' && event.tool_input?.questions?.[questionIndex]?.options?.length) {
90
+ // Real payload verified live: tool_input.questions[N].options only
91
+ // ever lists the REAL answer choices Claude proposed (e.g. "Just
92
+ // delete existing file", "Overwrite then delete") - none of them is a
93
+ // "reject". The on-screen "N. Type something." and "N+1. Chat about
94
+ // this" the user actually sees are UI chrome this tool always appends
95
+ // itself, at fixed positions right after the real options, and are
96
+ // NOT present in this payload at all - added here explicitly (with
97
+ // their own real, correct keystrokes) rather than silently missing
98
+ // from the phone's choices, since without them there'd be no reject-
99
+ // equivalent option at all for this tool.
100
+ const opts = event.tool_input.questions[questionIndex].options;
101
+ const real = opts.map((o, i) => ({ label: o.label, keystroke: String(i + 1), style: i === 0 ? 'approve' : 'approve-alt' }));
102
+ return [
103
+ ...real,
104
+ { label: 'Type something', keystroke: String(opts.length + 1), style: 'reject' },
105
+ ];
106
+ }
107
+ if (event.tool_name === 'Write' || event.tool_name === 'Edit') {
108
+ return [
109
+ { label: 'Yes', keystroke: '1', style: 'approve' },
110
+ { label: 'Yes, and accept edits automatically for this session', keystroke: '2', style: 'approve-alt' },
111
+ { label: 'No', keystroke: '3', style: 'reject' },
112
+ ];
113
+ }
114
+ if (event.tool_name === 'Bash' || event.tool_name === 'PowerShell') {
115
+ return [
116
+ { label: 'Yes', keystroke: '1', style: 'approve' },
117
+ { label: "Yes, don't ask again for this command in this project", keystroke: '2', style: 'approve-alt' },
118
+ { label: 'No', keystroke: '3', style: 'reject' },
119
+ ];
120
+ }
121
+ return [
122
+ { label: 'Yes', keystroke: '1', style: 'approve' },
123
+ { label: 'No', keystroke: '3', style: 'reject' },
124
+ ];
125
+ }
126
+
127
+ // Real bug found by testing: getDialogOptions' Write/Edit/Bash/PowerShell
128
+ // branches above are a HARDCODED GUESS at Claude Code's own menu, since
129
+ // the PermissionRequest hook payload never includes the real options for
130
+ // those tool types (confirmed live - only AskUserQuestion's payload
131
+ // carries real options at all). That guess drifted the moment Claude Code
132
+ // added a 4th choice ("switch to auto mode") to its Bash/Write menu - the
133
+ // phone showed 3 buttons for a real 4-option prompt. This reads the ACTUAL
134
+ // rendered menu directly from the terminal instead of guessing - the one
135
+ // source of truth for what the user can really pick, immune to Claude
136
+ // Code changing its wording or option COUNT in a future version.
137
+ const ANSI_RE = /\x1b\[[0-9;?]*[a-zA-Z]/g;
138
+ function stripAnsi(text) {
139
+ return text.replace(ANSI_RE, '');
140
+ }
141
+
142
+ const PROCEED_RE = /do you want to (?:proceed|create|make this edit)\??/i;
143
+ const ESC_FOOTER_RE = /esc to cancel/i;
144
+
145
+ // Real bug found by testing (live capture): Claude Code can have MORE
146
+ // THAN ONE Write/Edit/Bash/PowerShell/Read permission request queued for
147
+ // the same session at once (e.g. two Read calls issued together, each
148
+ // firing their own PermissionRequest ~200-400ms apart) - but
149
+ // isMenuStillOnScreen's generic PROCEED_RE check can't tell WHICH
150
+ // prompt's menu is currently showing, only that "a" proceed-style menu
151
+ // is up. Once the FIRST prompt is approved and dismissed, the SECOND
152
+ // prompt's own (textually identical) "Do you want to proceed?" menu
153
+ // renders - the first prompt's watcher correctly stops (harmless
154
+ // coincidence), but the SECOND prompt's own watcher can momentarily see
155
+ // no menu at all in the render gap between the two, or just always has
156
+ // no way to confirm it's really ITS OWN menu it's looking at - either
157
+ // way, the second prompt could be wrongly marked "resolved locally"
158
+ // despite nobody ever deciding it. distinguishingText (the file path for
159
+ // Read/Write/Edit, the command for Bash/PowerShell) must ALSO be present
160
+ // in the window when supplied, so a different prompt's menu happening to
161
+ // match PROCEED_RE is never mistaken for this one's.
162
+ function distinguishingTextFor(event) {
163
+ const { tool_name, tool_input } = event || {};
164
+ if ((tool_name === 'Write' || tool_name === 'Edit' || tool_name === 'Read') && tool_input?.file_path) return tool_input.file_path;
165
+ if ((tool_name === 'Bash' || tool_name === 'PowerShell') && tool_input?.command) return tool_input.command;
166
+ return null;
167
+ }
168
+ // A real numbered option line: "1. Yes", "❯ 2. Yes, and always allow...".
169
+ // Real bug found by testing: the currently-highlighted option's pointer
170
+ // glyph (❯) is NOT wrapped in its own ANSI color code the way the
171
+ // original comment here assumed - it's a plain literal character sitting
172
+ // before the digit, confirmed against a real captured "❯ 1. Yes" line -
173
+ // so \s* alone (whitespace only) never matched it, silently dropping
174
+ // EXACTLY the currently-selected option (always index 0) out of the
175
+ // parsed list every single time. [^\d\n]* explicitly allows that glyph
176
+ // (or any other non-digit marker Claude Code might use) before the
177
+ // number, without allowing it to swallow a real digit from a different
178
+ // line entirely (multiline mode - ^ anchors per line, not per string).
179
+ const OPTION_LINE_RE = /^[^\d\n]*(\d+)\.\s+(.+)$/;
180
+
181
+ // Reads the real, live menu straight from a trailing scrollback window.
182
+ // Returns null (not a guess) if the window doesn't contain a complete
183
+ // menu yet - supervisor.js retries a few times as the PTY catches up
184
+ // before ever falling back to the static guess above.
185
+ function parseLiveOptions(scrollbackWindow) {
186
+ const clean = stripAnsi(scrollbackWindow);
187
+ const startMatch = clean.match(PROCEED_RE);
188
+ if (!startMatch) return null;
189
+ const endMatch = clean.slice(startMatch.index).match(ESC_FOOTER_RE);
190
+ if (!endMatch) return null; // menu still rendering - not a complete capture yet
191
+
192
+ const section = clean.slice(startMatch.index, startMatch.index + endMatch.index);
193
+ const options = [];
194
+ // Real bug found by testing: Claude Code's real terminal output uses
195
+ // \r\n line endings, and splitting on '\n' alone leaves a trailing \r
196
+ // on every line. JavaScript's `.` does NOT match \r (confirmed - only
197
+ // \n is excluded from `.` in most regex engines, but V8 excludes \r
198
+ // too), so (.+)$ could never reach real end-of-line and OPTION_LINE_RE
199
+ // silently matched ZERO option lines, not just the pointer-marked one -
200
+ // this is what actually caused parseLiveOptions to return null on every
201
+ // real menu, not just a pointer-glyph edge case. Stripping stray \r
202
+ // before splitting is the fix that generalizes to any future capture,
203
+ // not just this one.
204
+ for (const line of section.replace(/\r/g, '').split('\n')) {
205
+ const m = line.match(OPTION_LINE_RE);
206
+ if (m) options.push({ number: Number(m[1]), label: m[2].trim() });
207
+ }
208
+ if (options.length === 0) return null;
209
+
210
+ // Real, observed shape: the LAST numbered option is always the decline
211
+ // ("No") - every live capture so far (3-option AND the newer 4-option
212
+ // menu) confirms this holds regardless of how many "Yes, and also..."
213
+ // variants sit in between. keystroke is the option's own real number as
214
+ // rendered, not a re-numbered index - this is what makes this immune to
215
+ // Claude Code adding/removing/reordering middle options.
216
+ return options.map((o, i) => ({
217
+ label: o.label,
218
+ keystroke: String(o.number),
219
+ style: i === options.length - 1 ? 'reject' : i === 0 ? 'approve' : 'approve-alt',
220
+ }));
221
+ }
222
+
223
+ // Corrected against REAL `/cost` output (Claude Code CLI, captured live -
224
+ // see project chat history for the exact screenshot), not guessed - the
225
+ // actual shape is:
226
+ // Total cost: $0.0000
227
+ // ...
228
+ // Usage: 0 input, 0 output, 0 cache read, 0 cache write
229
+ // ...
230
+ // Current session
231
+ // ████████████████████████████▉ 58% used
232
+ // Resets 8:20pm (Asia/Kolkata)
233
+ // Two real surprises the first version of this regex got wrong: (1) the
234
+ // line is literally "Usage:", not "Total tokens used:" - a guess that
235
+ // never matched; (2) input/output here reflects only recent API calls,
236
+ // not cumulative session usage - it read 0/0 on a hours-old session in
237
+ // testing. The "Current session ... % used" context-window bar is the
238
+ // actually-meaningful, reliably-nonzero signal for "how much of this
239
+ // session have I used", so that's captured too and is what Devices/
240
+ // Profile should lead with - raw input/output tokens are kept as a
241
+ // secondary field since they're real numbers, just not the useful ones
242
+ // for "how much have I used up" the user actually asked for.
243
+ //
244
+ // Wording/format has changed across Claude Code versions before and will
245
+ // again - these regexes are intentionally loose (case-insensitive,
246
+ // tolerant of box-drawing/ANSI noise around the numbers) but there's no
247
+ // guarantee they survive the next release. If they stop matching,
248
+ // parseFromOutput just keeps returning null (see supervisor-qr.js's
249
+ // caller) - the rest of the app degrades to "no usage data," not a crash.
250
+ const USAGE_LINE_RE = /usage:\s*([\d,]+)\s*input,\s*([\d,]+)\s*output,\s*([\d,]+)\s*cache read,\s*([\d,]+)\s*cache write/i;
251
+ const COST_RE = /total cost:\s*\$([\d.]+)/i;
252
+ // "Current session" and "Current week (all models)" each have their own
253
+ // "NN% used" + "Resets ..." pair right below them - captured as separate
254
+ // regexes (not one generic loop) since the two sections' reset-time
255
+ // format actually differs (session: bare time "8:20pm (TZ)"; week: date +
256
+ // time "Sep 19, 2:30am (TZ)") - confirmed against the real captured
257
+ // output, not assumed to be the same shape.
258
+ const SESSION_PCT_RE = /current session[\s\S]{0,200}?(\d{1,3})%\s*used/i;
259
+ const SESSION_RESET_RE = /current session[\s\S]{0,300}?resets\s+([^\n(]+(?:\([^)]+\))?)/i;
260
+ const WEEK_PCT_RE = /current week[^\n]*[\s\S]{0,200}?(\d{1,3})%\s*used/i;
261
+ const WEEK_RESET_RE = /current week[^\n]*[\s\S]{0,300}?resets\s+([^\n(]+(?:\([^)]+\))?)/i;
262
+
263
+ function parseFromOutput(chunk) {
264
+ const usageMatch = chunk.match(USAGE_LINE_RE);
265
+ const costMatch = chunk.match(COST_RE);
266
+ const pctMatch = chunk.match(SESSION_PCT_RE);
267
+ const sessionResetMatch = chunk.match(SESSION_RESET_RE);
268
+ const weekPctMatch = chunk.match(WEEK_PCT_RE);
269
+ const weekResetMatch = chunk.match(WEEK_RESET_RE);
270
+ if (!usageMatch && !costMatch && !pctMatch && !weekPctMatch) return null;
271
+
272
+ const inputTokens = usageMatch ? Number(usageMatch[1].replace(/,/g, '')) : null;
273
+ const outputTokens = usageMatch ? Number(usageMatch[2].replace(/,/g, '')) : null;
274
+ return {
275
+ totalTokens: inputTokens != null && outputTokens != null ? inputTokens + outputTokens : null,
276
+ inputTokens,
277
+ outputTokens,
278
+ cacheReadTokens: usageMatch ? Number(usageMatch[3].replace(/,/g, '')) : null,
279
+ cacheWriteTokens: usageMatch ? Number(usageMatch[4].replace(/,/g, '')) : null,
280
+ costUsd: costMatch ? Number(costMatch[1]) : null,
281
+ sessionContextUsedPct: pctMatch ? Number(pctMatch[1]) : null,
282
+ sessionResetsAt: sessionResetMatch ? sessionResetMatch[1].trim() : null,
283
+ weekUsedPct: weekPctMatch ? Number(weekPctMatch[1]) : null,
284
+ weekResetsAt: weekResetMatch ? weekResetMatch[1].trim() : null,
285
+ raw: chunk,
286
+ };
287
+ }
288
+
289
+ // Real key mapping, confirmed live against a real multiSelect
290
+ // AskUserQuestion screen (checkboxes, e.g. "Which areas should be in
291
+ // scope?"): Down arrow moves the highlight to the next option, Space
292
+ // toggles the highlighted option's checkbox, Tab jumps from the option
293
+ // list to "Submit", Enter confirms it. The cursor always starts on
294
+ // option 0. selectedIndices is 0-based, in any order - this always walks
295
+ // the options top-to-bottom once, toggling only the ones asked for, so
296
+ // the actual keystroke order doesn't depend on the order indices were
297
+ // supplied in.
298
+ //
299
+ // Real bug found by testing: this used to return ONE concatenated string,
300
+ // written to the PTY in a single ptyProcess.write() call - Claude Code's
301
+ // own input handling only reliably processed the FIRST keystroke
302
+ // (checking option 0) when a plain character and several \x1b[B escape
303
+ // sequences all arrived in the same burst with no real gap between them;
304
+ // everything after was silently dropped, same class of issue as a fast
305
+ // human paste outrunning a TUI's own input loop. Returns an ARRAY of
306
+ // discrete tokens instead - supervisor.js's injectKeystrokeSequence
307
+ // writes them one at a time with a short delay between each, which is
308
+ // what actually made every checkbox register correctly in testing.
309
+ const KEY_DOWN = '\x1b[B';
310
+ const KEY_TAB = '\t';
311
+ function buildMultiSelectKeystrokes(optionCount, selectedIndices) {
312
+ const selected = new Set(selectedIndices);
313
+ const tokens = [];
314
+ for (let i = 0; i < optionCount; i++) {
315
+ if (selected.has(i)) tokens.push(' ');
316
+ if (i < optionCount - 1) tokens.push(KEY_DOWN);
317
+ }
318
+ tokens.push(KEY_TAB, '\r');
319
+ return tokens;
320
+ }
321
+
322
+ module.exports = {
323
+ id: 'claude',
324
+ displayName: 'Claude Code',
325
+ // Adapter-declared icon (see README.md) - the app's Devices tab reads
326
+ // this instead of hardcoding "if cliType === 'claude'" anywhere in the
327
+ // UI, so a future third adapter just declares its own icon here too,
328
+ // with no UI changes needed. No official Anthropic logo asset is
329
+ // bundled (real brand marks need to be properly sourced by whoever
330
+ // owns this app, not fabricated) - a distinct, well-chosen generic
331
+ // icon + color stands in until a real logo image is supplied.
332
+ icon: { name: 'sparkles', color: '#D97757' }, // Anthropic's own public brand accent is a terracotta/orange - approximated here, not an official value
333
+ spawn: {
334
+ command: process.platform === 'win32' ? resolveWindowsBin('claude') : 'claude',
335
+ args: () => ['--permission-mode', 'default'],
336
+ },
337
+ approvals: {
338
+ queueFileFor,
339
+ describePrompt,
340
+ getDialogOptions,
341
+ buildMultiSelectKeystrokes,
342
+ parseLiveOptions,
343
+ // Real gap found by testing: a PTY-text-scan for Claude Code's own
344
+ // "Interrupted..." wording (resolvedLocallyPattern) was tried and
345
+ // removed - real captured terminal output across several live
346
+ // rejection tests never actually contained that literal text in a
347
+ // form a regex could reliably match. This is a different, more
348
+ // robust signal: it doesn't care WHAT replaced the menu (an
349
+ // "Interrupted" message, a follow-up question, plain output - Claude
350
+ // Code's exact wording can drift freely) - only whether the SAME
351
+ // "Do you want to proceed?" style menu PROCEED_RE matched is still
352
+ // physically on screen. supervisor.js polls this for a few seconds
353
+ // right after relaying a prompt; once it stops matching, the prompt
354
+ // is gone - approved, rejected, or interrupted, any of those means a
355
+ // decision happened, so this is a fully reliable resolution signal
356
+ // for the Bash/Write/PowerShell prompts that only ever get options
357
+ // via parseLiveOptions in the first place (AskUserQuestion already
358
+ // resolves correctly via PostToolUse+resolveIfPending's exact
359
+ // question-text match - this is not used for that tool_name at all).
360
+ //
361
+ // distinguishingText (see distinguishingTextFor's own comment, real
362
+ // bug found by testing against two back-to-back Read prompts): when
363
+ // supplied, the window must ALSO contain this exact text (the real
364
+ // file path/command Claude Code prints right above its own "Do you
365
+ // want to proceed?" line) for the menu to count as still on screen -
366
+ // without this, two queued prompts with identical generic wording
367
+ // couldn't be told apart, and the second one's watcher could
368
+ // conclude its own menu was gone while it was really just looking at
369
+ // a gap between dismissing prompt #1 and rendering prompt #2.
370
+ isMenuStillOnScreen: (scrollbackWindow, distinguishingText) => {
371
+ const clean = stripAnsi(scrollbackWindow);
372
+ if (!PROCEED_RE.test(clean)) return false;
373
+ if (distinguishingText && !clean.includes(distinguishingText)) return false;
374
+ return true;
375
+ },
376
+ distinguishingTextFor,
377
+ },
378
+ usage: {
379
+ // '/cost' + Enter - a real, visible command in the user's own
380
+ // terminal (see supervisor-qr.js's usage-polling comment for why this
381
+ // is opt-in-by-default rather than silent).
382
+ triggerKeystrokes: '/cost\r',
383
+ parseFromOutput,
384
+ },
385
+ // Remote slash-command palette (Section 15 roadmap item #6). Each entry
386
+ // is just a label + the literal keystrokes to write into the PTY - the
387
+ // SAME primitive terminal.input already uses for free-typed text (see
388
+ // supervisor-qr.js's ws.on('message') handler), just named and one tap
389
+ // instead of typing it out. Deliberately NOT a structured remote
390
+ // sub-menu: /model opens Claude Code's own interactive picker on the
391
+ // laptop's real screen, which the phone then sees via the existing
392
+ // live terminal mirror (Phase 6) and can navigate with the same
393
+ // quick-action arrow/Enter keys already in the Terminal tab - no new
394
+ // blind multi-step remote flow being invented here.
395
+ commands: [
396
+ { id: 'cost', label: 'Check usage', keystrokes: '/cost\r' },
397
+ { id: 'model', label: 'Switch model', keystrokes: '/model\r' },
398
+ { id: 'compact', label: 'Compact context', keystrokes: '/compact\r' },
399
+ ],
400
+ };