cli-setu 0.3.10 → 0.3.11

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cli-setu",
3
- "version": "0.3.10",
3
+ "version": "0.3.11",
4
4
  "description": "Bridge your terminal to your phone — run and approve Claude Code, Codex CLI and other AI coding agents from anywhere.",
5
5
  "type": "commonjs",
6
6
  "bin": {
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+ // Smooth (line by line) touch scrolling of Claude Code from the phone.
3
+ //
4
+ // Claude Code scrolls its own conversation view, and by default only offers half-page keys (Page Up / Page Down). Its docs name two line actions,
5
+ // `scroll:lineUp` and `scroll:lineDown`, that nothing triggers except the mouse wheel; the wheel never reaches Claude on Windows 10 (the console layer
6
+ // hides the mouse request from the phone). So the two actions are bound to Ctrl+Shift+Up / Ctrl+Shift+Down in Claude's own keybindings file and the phone
7
+ // sends one of those keys per text row of finger movement. Checked with real Claude Code: unbound, those keys do NOTHING (0 bytes redrawn); bound, each key
8
+ // scrolls exactly one line.
9
+ //
10
+ // This edits the user's own Claude configuration (~/.claude/keybindings.json), so it is conservative:
11
+ // - it only ever ADDS the two keys, inside a "Scroll" block; everything else in the file is kept as it is;
12
+ // - the first time it changes an EXISTING file it saves a copy next to it (keybindings.json.cli-setu-backup);
13
+ // - a file it cannot parse, or a key already used for something else, is left untouched (the phone then falls back to page scrolling);
14
+ // - it writes through a temporary file, so a crash cannot leave half a file.
15
+ // Claude re-reads the file by itself, no restart needed. `cli-setu` prints one line saying what it did.
16
+
17
+ const fs = require('node:fs');
18
+ const os = require('node:os');
19
+ const path = require('node:path');
20
+
21
+ const SCROLL_BINDINGS = Object.freeze({ 'ctrl+shift+up': 'scroll:lineUp', 'ctrl+shift+down': 'scroll:lineDown' });
22
+ const BACKUP_SUFFIX = '.cli-setu-backup';
23
+
24
+ function keybindingsPath(env = process.env, home = os.homedir()) {
25
+ const dir = env.CLAUDE_CONFIG_DIR && String(env.CLAUDE_CONFIG_DIR).trim() ? env.CLAUDE_CONFIG_DIR : path.join(home, '.claude');
26
+ return path.join(dir, 'keybindings.json');
27
+ }
28
+
29
+ const norm = (k) => String(k).toLowerCase().replace(/\s+/g, '');
30
+
31
+ // Pure: given the parsed file (or null for "no file"), returns { result, next } where result is one of
32
+ // 'already' - both keys are already bound to the line actions
33
+ // 'added' - next is the new content
34
+ // 'conflict' - one of the keys is bound to something else somewhere in the file (next is null)
35
+ // 'invalid' - the content is not the expected shape (next is null)
36
+ function planScrollKeys(parsed) {
37
+ const base = parsed === null ? { bindings: [] } : parsed;
38
+ if (!base || typeof base !== 'object' || Array.isArray(base)) return { result: 'invalid', next: null };
39
+ if (base.bindings === undefined) base.bindings = [];
40
+ if (!Array.isArray(base.bindings)) return { result: 'invalid', next: null };
41
+ const wanted = Object.entries(SCROLL_BINDINGS);
42
+ let scrollBlock = null;
43
+ for (const block of base.bindings) {
44
+ if (!block || typeof block !== 'object' || typeof block.bindings !== 'object' || block.bindings === null) continue;
45
+ for (const [key, action] of Object.entries(block.bindings)) {
46
+ const hit = wanted.find(([k]) => norm(k) === norm(key));
47
+ if (!hit) continue;
48
+ if (block.context === 'Scroll' && action === hit[1]) continue;
49
+ return { result: 'conflict', next: null }; // the key is already used for something else (or in another context)
50
+ }
51
+ if (block.context === 'Scroll' && !scrollBlock) scrollBlock = block;
52
+ }
53
+ const missing = wanted.filter(([k]) => !(scrollBlock && Object.keys(scrollBlock.bindings).some((x) => norm(x) === norm(k))));
54
+ if (missing.length === 0) return { result: 'already', next: null };
55
+ const next = JSON.parse(JSON.stringify(base));
56
+ let target = next.bindings.find((b) => b && b.context === 'Scroll' && b.bindings && typeof b.bindings === 'object');
57
+ if (!target) { target = { context: 'Scroll', bindings: {} }; next.bindings.push(target); }
58
+ for (const [k, a] of missing) target.bindings[k] = a;
59
+ if (parsed === null) {
60
+ next.$schema = 'https://www.schemastore.org/claude-code-keybindings.json';
61
+ next.$docs = 'https://code.claude.com/docs/en/keybindings';
62
+ }
63
+ return { result: 'added', next };
64
+ }
65
+
66
+ // -> { installed: boolean, changed: boolean, reason: string, file: string, backup?: string }
67
+ // installed: the two keys are bound (the phone may use them)
68
+ function ensureScrollKeys({ env = process.env, home = os.homedir(), fsImpl = fs } = {}) {
69
+ const file = keybindingsPath(env, home);
70
+ try {
71
+ let parsed = null;
72
+ let existed = false;
73
+ if (fsImpl.existsSync(file)) {
74
+ existed = true;
75
+ const raw = fsImpl.readFileSync(file, 'utf8').replace(/^/, '');
76
+ try { parsed = JSON.parse(raw); } catch { return { installed: false, changed: false, reason: 'unreadable', file }; }
77
+ }
78
+ const plan = planScrollKeys(parsed);
79
+ if (plan.result === 'already') return { installed: true, changed: false, reason: 'already', file };
80
+ if (plan.result !== 'added') return { installed: false, changed: false, reason: plan.result, file };
81
+ let backup;
82
+ if (existed) {
83
+ backup = file + BACKUP_SUFFIX;
84
+ if (!fsImpl.existsSync(backup)) fsImpl.copyFileSync(file, backup);
85
+ } else {
86
+ fsImpl.mkdirSync(path.dirname(file), { recursive: true });
87
+ }
88
+ const tmp = file + '.cli-setu-tmp';
89
+ fsImpl.writeFileSync(tmp, JSON.stringify(plan.next, null, 2) + '\n', 'utf8');
90
+ fsImpl.renameSync(tmp, file);
91
+ return { installed: true, changed: true, reason: 'added', file, ...(backup ? { backup } : {}) };
92
+ } catch (err) {
93
+ return { installed: false, changed: false, reason: 'error: ' + (err && err.message ? err.message : err), file };
94
+ }
95
+ }
96
+
97
+ // In-band announcement to the phone, inside the (encrypted) terminal stream: an OSC with a private number that xterm.js ignores unless the
98
+ // app registers a handler for it (the app does). No server change is needed.
99
+ const LINE_SCROLL_OSC = '\x1b]7727;setu-linescroll=1\x07';
100
+
101
+ module.exports = { ensureScrollKeys, planScrollKeys, keybindingsPath, SCROLL_BINDINGS, BACKUP_SUFFIX, LINE_SCROLL_OSC };
@@ -47,7 +47,13 @@ function queueFileFor(baseDir, cwd) {
47
47
  // promptId - see supervisor.js's askUserQuestionStep tracking.
48
48
  function describePrompt(event, questionIndex = 0) {
49
49
  const { tool_name, tool_input } = event;
50
- if (tool_name === 'Write' && tool_input?.file_path) return `Create ${tool_input.file_path.split(/[\\/]/).pop()}?`;
50
+ if (tool_name === 'Write' && tool_input?.file_path) {
51
+ // Claude Code asks "Do you want to overwrite <file>?" when the file already exists; the card must say the same (phone test 2026-11-19:
52
+ // it said "Create" for an overwrite). The check runs when the prompt is relayed, before the write, so it matches the prompt on screen.
53
+ let exists = false;
54
+ try { exists = fs.existsSync(tool_input.file_path); } catch { exists = false; }
55
+ return `${exists ? 'Overwrite' : 'Create'} ${tool_input.file_path.split(/[\\/]/).pop()}?`;
56
+ }
51
57
  if (tool_name === 'Edit' && tool_input?.file_path) return `Edit ${tool_input.file_path.split(/[\\/]/).pop()}?`;
52
58
  if ((tool_name === 'Bash' || tool_name === 'PowerShell') && tool_input?.command) {
53
59
  return tool_input.description ? `${tool_input.description}?\n${tool_input.command}` : `Run: ${tool_input.command}`;
@@ -139,7 +145,9 @@ function stripAnsi(text) {
139
145
  return text.replace(ANSI_RE, '');
140
146
  }
141
147
 
142
- const PROCEED_RE = /do you want to (?:proceed|create|make this edit)\??/i;
148
+ // 'overwrite' added 2026-11-19: Claude Code 2.1.327 asks "Do you want to overwrite <file>?" when a Write targets an existing file; with the
149
+ // pattern lacking it no card ever reached the phone and the agent waited at the laptop (found on a phone test).
150
+ const PROCEED_RE = /do you want to (?:proceed|create|overwrite|make this edit)\??/i;
143
151
  const ESC_FOOTER_RE = /esc to cancel/i;
144
152
 
145
153
  // Real bug found by testing (live capture): Claude Code can have MORE
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+ // Phone-typed lines reach the terminal as "text" + Enter in ONE message. Claude Code's input box treats a burst like that as a
3
+ // PASTE and keeps the trailing Enter as a new line instead of submitting (found on a phone 2026-11-19: the text sat in the box until
4
+ // Enter was sent again as its own message; same class of problem as injectKeystrokeSequence in supervisor.js).
5
+ // So a plain typed line is written as the text first and the Enter as a separate write a moment later. Shells do not care.
6
+ // Everything else (single keys, arrows and other escape sequences, Ctrl+C, text with control characters) is written as it always was.
7
+ // Writes stay in order: a later message never overtakes a pending Enter.
8
+
9
+ const ENTER_DELAY_MS = 80;
10
+
11
+ // "ls -la\r" -> { body: 'ls -la' }. Anything that is not a plain typed line -> null.
12
+ function splitTypedLine(data) {
13
+ if (typeof data !== 'string' || data.length < 2 || !data.endsWith('\r')) return null;
14
+ const body = data.slice(0, -1);
15
+ if (/[\x00-\x08\x0b-\x1f\x7f]/.test(body)) return null; // escape sequences, Ctrl keys, a second \r ...: leave untouched
16
+ return { body };
17
+ }
18
+
19
+ function createPhoneInputWriter({ write, enterDelayMs = ENTER_DELAY_MS, setTimer = setTimeout }) {
20
+ let chain = Promise.resolve();
21
+ const safe = (fn) => { try { fn(); } catch { /* a failed write must not stop later input */ } };
22
+ return function writePhoneInput(data) {
23
+ const split = splitTypedLine(data);
24
+ chain = chain.then(() => {
25
+ if (!split) { safe(() => write(data)); return undefined; }
26
+ safe(() => write(split.body));
27
+ return new Promise((resolve) => setTimer(() => { safe(() => write('\r')); resolve(); }, enterDelayMs));
28
+ });
29
+ return chain;
30
+ };
31
+ }
32
+
33
+ module.exports = { splitTypedLine, createPhoneInputWriter, ENTER_DELAY_MS };
package/src/supervisor.js CHANGED
@@ -40,6 +40,9 @@ const { getAdapter } = require('./cli-adapters');
40
40
  const { getGitDiff } = require('./gitDiff');
41
41
  const setuCrypto = require('./crypto');
42
42
  const { splitIntoParts, trimSnapshot, limitForProvider } = require('./transportSplit');
43
+ const { createPhoneInputWriter } = require('./phoneInput');
44
+ const { usageKeysAreSafe, sendWhenSafe } = require('./usageGuard');
45
+ const { ensureScrollKeys, LINE_SCROLL_OSC } = require('./claudeScrollKeys');
43
46
  const { createReconnectManager, WARN_AFTER_ATTEMPTS } = require('./reconnect');
44
47
  const { createDedupCache } = require('./dedup');
45
48
  const { attachProviderProtocol } = require('./providerProtocol');
@@ -176,6 +179,16 @@ LOG_FILE = path.join(CONFIG_DIR, `supervisor.${DEVICE_NAME.replace(/[^a-zA-Z0-9-
176
179
 
177
180
  const adapter = getAdapter(CLI_NAME);
178
181
  console.log(`[supervisor] Using CLI adapter: ${adapter.displayName} (${adapter.id})`);
182
+
183
+ // Smooth touch scrolling of Claude's own view from the phone (see claudeScrollKeys.js): two Claude line-scroll actions get the keys the phone sends.
184
+ // Only for the Claude adapter, only adds to ~/.claude/keybindings.json (backup of an existing file first), and says so.
185
+ let LINE_SCROLL_OK = false;
186
+ if (adapter.id === 'claude') {
187
+ const scrollKeys = ensureScrollKeys();
188
+ LINE_SCROLL_OK = scrollKeys.installed;
189
+ if (scrollKeys.changed) console.log(`[cli-setu] Added two scroll keys (Ctrl+Shift+Up/Down) to Claude's keybindings so the phone can scroll smoothly: ${scrollKeys.file}${scrollKeys.backup ? ` (backup: ${scrollKeys.backup})` : ''}`);
190
+ else if (!scrollKeys.installed) console.log(`[cli-setu] Smooth phone scrolling is off (${scrollKeys.reason}); the phone scrolls Claude by pages instead.`);
191
+ }
179
192
  log(`cli-setu ${require("../package.json").version} (node ${process.version}, ${process.platform}) - using CLI adapter: ${adapter.displayName} (${adapter.id})`);
180
193
 
181
194
  // Real bug found by testing: when the spawned adapter is 'shell' (the
@@ -259,6 +272,8 @@ const reconnectManager = createReconnectManager({
259
272
  // gone from any receiver's retry buffer anyway, so losing the OLDEST
260
273
  // entries first costs nothing real.
261
274
  const dedupCache = createDedupCache({ maxSize: 200 });
275
+ // Typed lines from the phone: text first, Enter as its own write a moment later (Claude Code's input box treats text+Enter in one burst as a paste). See phoneInput.js.
276
+ const writePhoneInput = createPhoneInputWriter({ write: (d) => ptyProcess.write(d) });
262
277
  function isDuplicateMessage(messageId) {
263
278
  return dedupCache.isDuplicate(messageId);
264
279
  }
@@ -600,7 +615,7 @@ async function connectToAzureOnce() {
600
615
  log('[supervisor] Failed to decrypt terminal.input, dropping:', err.message);
601
616
  return;
602
617
  }
603
- ptyProcess.write(data);
618
+ writePhoneInput(data);
604
619
  }
605
620
  if (msg.type === 'terminal.resize' && msg.sessionId === SESSION_ID) {
606
621
  // Real bug found by testing: this used to call ptyProcess.resize()
@@ -694,9 +709,19 @@ async function connectToAzureOnce() {
694
709
  // requested.
695
710
  const usageAdapter = getActiveUsageAdapter();
696
711
  if (usageAdapter?.triggerKeystrokes && ptyProcess) {
697
- ptyProcess.write(usageAdapter.triggerKeystrokes);
698
- usageListenUntil = Date.now() + USAGE_LISTEN_WINDOW_MS;
699
- log(`[supervisor] On-demand usage refresh requested for ${SESSION_ID}`);
712
+ // Phone test 2026-11-19: typing "/cost" + Enter into a permission menu CHOSE "Yes" (the Usage button approved a pending action), and
713
+ // the later Esc interrupts a running answer. The keys are only typed when Claude is idle at its prompt; otherwise wait, then give up
714
+ // without ever forcing them in (see usageGuard.js).
715
+ if (usageRefreshWaiter) usageRefreshWaiter.cancel();
716
+ usageRefreshWaiter = sendWhenSafe({
717
+ check: () => usageKeysAreSafe({ pendingCount: pendingPrompts.size, screen: scrollback }),
718
+ send: () => {
719
+ ptyProcess.write(usageAdapter.triggerKeystrokes);
720
+ usageListenUntil = Date.now() + USAGE_LISTEN_WINDOW_MS;
721
+ log(`[supervisor] On-demand usage refresh requested for ${SESSION_ID}`);
722
+ },
723
+ giveUp: (reason) => log(`[supervisor] On-demand usage refresh skipped for ${SESSION_ID}: ${reason} (the keys are never typed over an approval or a running answer)`),
724
+ });
700
725
  }
701
726
  }
702
727
  },
@@ -737,7 +762,8 @@ async function sendSnapshot() {
737
762
  if (trimmed.truncated) {
738
763
  log(`[supervisor] Snapshot trimmed: ${trimmed.droppedChars} older characters are not sent (limit ${SNAPSHOT_MAX_CHARS}).`);
739
764
  }
740
- const plainScreen = trimmed.text;
765
+ // In-band announcement for the phone that the line-scroll keys are installed (private OSC, ignored by terminals that do not know it).
766
+ const plainScreen = (LINE_SCROLL_OK ? LINE_SCROLL_OSC : '') + trimmed.text;
741
767
  const snapshotId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
742
768
  const encryptIfNeeded = (piece) => encryptStrict(piece);
743
769
  const parts = plainScreen
@@ -1256,6 +1282,7 @@ let usageTimer = null;
1256
1282
  // window lapses. See the onData handler's usage-polling comment for why
1257
1283
  // this window exists at all instead of parsing every chunk forever.
1258
1284
  let usageListenUntil = 0;
1285
+ let usageRefreshWaiter = null; // the pending, guarded on-demand usage request (usageGuard.js)
1259
1286
  const USAGE_LISTEN_WINDOW_MS = 10_000;
1260
1287
  // Codex-shape usage de-dup (no trigger keystrokes, and no reliable
1261
1288
  // persistent status line to gate a check on - see cli-adapters/codex.js
@@ -0,0 +1,57 @@
1
+ 'use strict';
2
+ // The phone's Usage button makes the supervisor type "/cost" + Enter into the CLI and, once the numbers are read, press Esc.
3
+ // Those are ordinary keystrokes, so they act on whatever Claude Code is showing at that moment (phone test 2026-11-19):
4
+ // - with a PERMISSION MENU on screen, Enter chose the highlighted "Yes": the Usage button APPROVED a pending action nobody had approved;
5
+ // - while Claude is WORKING, the later Esc is Claude's "interrupt" key.
6
+ // So the keystrokes are only sent when Claude is idle at its prompt: no pending approval, no permission menu on screen, nothing running.
7
+ // Pure and tested; supervisor.js polls it (requestUsageRefresh) and gives up after a while instead of ever forcing the keys in.
8
+
9
+ const ANSI_RE = /\x1b\[[0-9;?]*[a-zA-Z]|\x1b\][^\x07]*\x07/g;
10
+ const MENU_RE = /do you want to [a-z ]{0,40}\??/i; // "Do you want to proceed / create / overwrite / make this edit ...?"
11
+ const MENU_FOOTER_RE = /esc to cancel/i;
12
+ const NUMBERED_OPTION_RE = /(?:^|\s)(?:[>❯]\s*)?1\.\s+yes\b/im;
13
+ const BUSY_RE = /esc to interrupt/i;
14
+
15
+ function cleanTail(screen, chars = 2500) {
16
+ return String(screen || '').slice(-chars).replace(ANSI_RE, '').replace(/\r/g, '');
17
+ }
18
+
19
+ function lastIndexOfMatch(re, text) {
20
+ const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g');
21
+ let idx = -1; let m;
22
+ while ((m = g.exec(text)) !== null) { idx = m.index; if (m[0].length === 0) g.lastIndex++; }
23
+ return idx;
24
+ }
25
+ const IDLE_RE = /\? for shortcuts/i; // the footer Claude Code shows when it is idle at its prompt
26
+
27
+ // -> { safe: boolean, reason: 'ok' | 'pending-approval' | 'menu-on-screen' | 'busy' }
28
+ // A menu or busy marker only counts when no idle footer was drawn AFTER it (an answered menu stays in the recent text for a while).
29
+ function usageKeysAreSafe({ pendingCount = 0, screen = '' } = {}) {
30
+ if (pendingCount > 0) return { safe: false, reason: 'pending-approval' };
31
+ const recent = cleanTail(screen).slice(-1200);
32
+ const idleAt = lastIndexOfMatch(IDLE_RE, recent);
33
+ const menuAt = lastIndexOfMatch(MENU_RE, recent);
34
+ if (menuAt >= 0 && (MENU_FOOTER_RE.test(recent.slice(menuAt)) || NUMBERED_OPTION_RE.test(recent.slice(menuAt))) && idleAt < menuAt) return { safe: false, reason: 'menu-on-screen' };
35
+ const busyOffset = Math.max(0, recent.length - 400);
36
+ const busyAt = lastIndexOfMatch(BUSY_RE, recent.slice(busyOffset));
37
+ if (busyAt >= 0 && idleAt < busyOffset + busyAt) return { safe: false, reason: 'busy' };
38
+ return { safe: true, reason: 'ok' };
39
+ }
40
+
41
+ // Polls until the keys are safe (then calls send once) or the time runs out (then calls giveUp with the last reason). Returns { cancel }.
42
+ function sendWhenSafe({ check, send, giveUp, pollMs = 500, maxWaitMs = 30000, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
43
+ const start = now();
44
+ let timer = null;
45
+ let done = false;
46
+ const step = () => {
47
+ if (done) return;
48
+ const r = check();
49
+ if (r.safe) { done = true; send(); return; }
50
+ if (now() - start >= maxWaitMs) { done = true; if (giveUp) giveUp(r.reason); return; }
51
+ timer = setTimer(step, pollMs);
52
+ };
53
+ step();
54
+ return { cancel() { done = true; if (timer != null) clearTimer(timer); } };
55
+ }
56
+
57
+ module.exports = { usageKeysAreSafe, sendWhenSafe, cleanTail };