cli-setu 0.3.3 → 0.3.5

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.3",
3
+ "version": "0.3.5",
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,73 @@
1
+ // Reliable, idempotent delivery of approval requests to the backend (P0:
2
+ // "approvals do not arrive" and "approvals appear twice").
3
+ //
4
+ // Missing approvals, confirmed cause: relayApproval() POSTed once. A network
5
+ // error or a 5xx only wrote a log line, while the prompt stayed pending on the
6
+ // laptop, so the phone never learned about it. Delivery is now retried with
7
+ // backoff. Retrying is safe because the same promptId is sent every time and
8
+ // the backend inserts it with ON CONFLICT DO NOTHING; the phone also ignores a
9
+ // promptId it has already shown.
10
+ //
11
+ // Duplicate approvals, confirmed cause: every relay call minted a brand-new
12
+ // random promptId, so one logical permission request that reached the
13
+ // supervisor twice (for example the same hook registered in two settings files,
14
+ // or a repeated queue line) became two different cards. A fingerprint of the
15
+ // request (session, tool, tool_use_id, input) now identifies one logical
16
+ // approval; while an approval with that fingerprint is still pending, a repeat
17
+ // is dropped. Once it is resolved, the same command may legitimately ask again.
18
+ const crypto = require('crypto');
19
+
20
+ function approvalFingerprint(event) {
21
+ const basis = [event.session_id || null, event.tool_name || null, event.tool_use_id || null, event.tool_input === undefined ? null : event.tool_input];
22
+ return crypto.createHash('sha256').update(JSON.stringify(basis)).digest('hex').slice(0, 24);
23
+ }
24
+
25
+ // isPending(promptId) tells whether that prompt is still waiting for an answer.
26
+ function createApprovalDeduper({ isPending }) {
27
+ const byFingerprint = new Map(); // fingerprint -> promptId
28
+ return {
29
+ // Returns true when this is a repeat of a still-pending approval.
30
+ isDuplicate(fingerprint) {
31
+ const existing = byFingerprint.get(fingerprint);
32
+ if (existing && isPending(existing)) return true;
33
+ if (existing) byFingerprint.delete(fingerprint);
34
+ return false;
35
+ },
36
+ remember(fingerprint, promptId) { byFingerprint.set(fingerprint, promptId); },
37
+ size: () => byFingerprint.size,
38
+ };
39
+ }
40
+
41
+ // Statuses that will never succeed by retrying (the request itself is refused).
42
+ function isPermanentFailure(status) {
43
+ return status >= 400 && status < 500 && status !== 408 && status !== 429;
44
+ }
45
+
46
+ const DEFAULT_DELAYS_MS = [500, 1500, 4000, 10000];
47
+
48
+ // send() performs one attempt and resolves { ok, status } or rejects on a network error.
49
+ // isStillPending() lets us stop as soon as the prompt was answered or dismissed elsewhere.
50
+ async function relayWithRetry({ send, isStillPending, log = () => {}, delays = DEFAULT_DELAYS_MS, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
51
+ let attempts = 0;
52
+ for (let i = 0; i <= delays.length; i++) {
53
+ if (i > 0) {
54
+ await sleep(delays[i - 1]);
55
+ if (!isStillPending()) return { delivered: false, attempts, reason: 'no-longer-pending' };
56
+ }
57
+ attempts += 1;
58
+ try {
59
+ const res = await send();
60
+ if (res.ok) return { delivered: true, attempts, reason: null };
61
+ if (isPermanentFailure(res.status)) {
62
+ log(`approval relay refused (HTTP ${res.status}); not retrying`);
63
+ return { delivered: false, attempts, reason: `refused-${res.status}` };
64
+ }
65
+ log(`approval relay attempt ${attempts} failed (HTTP ${res.status})`);
66
+ } catch (err) {
67
+ log(`approval relay attempt ${attempts} failed: ${err.message}`);
68
+ }
69
+ }
70
+ return { delivered: false, attempts, reason: 'gave-up' };
71
+ }
72
+
73
+ module.exports = { approvalFingerprint, createApprovalDeduper, relayWithRetry, isPermanentFailure, DEFAULT_DELAYS_MS };
@@ -0,0 +1,35 @@
1
+ // Supervisor diagnostics routing (P0: "supervisor messages corrupt the prompt").
2
+ //
3
+ // While a PTY owns the terminal, nothing but the PTY's own bytes may be written
4
+ // to stdout/stderr: an interleaved line lands in the middle of the shell prompt
5
+ // or a full-screen TUI and breaks its cursor math (overwritten text, blank
6
+ // lines, a duplicated prompt). So once the terminal is owned:
7
+ // - every diagnostic goes to the log file only;
8
+ // - messages the user still needs to see (a rejected connection, an unpaired
9
+ // device) are kept and printed AFTER the PTY has exited, when the terminal
10
+ // is the user's again.
11
+ // Before the PTY exists, or after it exited, messages print normally.
12
+ function createDiagnostics({ log, isTerminalOwned, out = console }) {
13
+ const deferred = [];
14
+
15
+ function say(message, { error = false, showAtExit = false } = {}) {
16
+ if (isTerminalOwned()) {
17
+ log(`[notice] ${message}`);
18
+ if (showAtExit) deferred.push({ message, error });
19
+ return;
20
+ }
21
+ (error ? out.error : out.log)(message);
22
+ }
23
+
24
+ // Call once the PTY has exited and the terminal is free again.
25
+ function flushAtExit() {
26
+ while (deferred.length) {
27
+ const { message, error } = deferred.shift();
28
+ (error ? out.error : out.log)(message);
29
+ }
30
+ }
31
+
32
+ return { say, flushAtExit, pending: () => deferred.length };
33
+ }
34
+
35
+ module.exports = { createDiagnostics };
package/src/gitDiff.js ADDED
@@ -0,0 +1,200 @@
1
+ // Collects a session's git changes for the phone's Diff pane (SETU-020).
2
+ //
3
+ // Fixes over the old inline version in supervisor.js:
4
+ // - STAGED changes were never listed (`git diff --name-only` only shows
5
+ // unstaged edits), so a staged file simply vanished from the pane.
6
+ // - Renamed, deleted, binary and conflicted files were not distinguished.
7
+ // - Paths with spaces or non-ASCII characters were mis-parsed; `-z` output
8
+ // is used instead of quoted text.
9
+ // - The whole reply was one message with no total size limit, so many changed
10
+ // files could exceed the realtime provider's per-message limit (Ably
11
+ // Free/Standard: 64 KiB) and the diff would never arrive. A byte budget is
12
+ // applied and anything that does not fit is marked, never dropped silently.
13
+ //
14
+ // Backward compatible: every file keeps the legacy `status` ('modified' or
15
+ // 'untracked') and `diff` fields older apps read; the richer fields are extra.
16
+ 'use strict';
17
+
18
+ const { execFile } = require('node:child_process');
19
+ const { promisify } = require('node:util');
20
+
21
+ const execFileAsync = promisify(execFile);
22
+
23
+ const GIT_TIMEOUT_MS = 15_000;
24
+ const MAX_FILES = 200;
25
+ const MAX_DIFF_CHARS_PER_FILE = 20_000;
26
+ const TRUNCATION_NOTE = '\n\n... (diff truncated - too large to send in full)';
27
+
28
+ // Parses `git status --porcelain=v1 -z`. Each entry is `XY path`, and a
29
+ // rename or copy is followed by its ORIGINAL path as a separate field.
30
+ function parseStatusZ(out) {
31
+ const parts = out.split('\0');
32
+ const entries = [];
33
+ for (let i = 0; i < parts.length; i++) {
34
+ const raw = parts[i];
35
+ if (!raw) continue;
36
+ const x = raw[0];
37
+ const y = raw[1];
38
+ const entry = { x, y, path: raw.slice(3), origPath: null };
39
+ if (x === 'R' || x === 'C' || y === 'R' || y === 'C') entry.origPath = parts[++i] || null;
40
+ entries.push(entry);
41
+ }
42
+ return entries;
43
+ }
44
+
45
+ function categoryOf(x, y) {
46
+ if (x === 'U' || y === 'U' || (x === 'A' && y === 'A') || (x === 'D' && y === 'D')) return 'conflict';
47
+ if (x === '?' && y === '?') return 'untracked';
48
+ if (x === 'R' || y === 'R') return 'renamed';
49
+ if (x === 'D' || y === 'D') return 'deleted';
50
+ if (x === 'A' || y === 'A' || x === 'C' || y === 'C') return 'added';
51
+ return 'modified';
52
+ }
53
+
54
+ // Counts only inside hunks, so a removed line whose text starts with "--"
55
+ // (which prints as "---") is not mistaken for a file header.
56
+ function countChanges(diff) {
57
+ let additions = 0;
58
+ let deletions = 0;
59
+ let inHunk = false;
60
+ for (const line of diff.split('\n')) {
61
+ if (line.startsWith('diff --git') || line.startsWith('diff --cc')) inHunk = false;
62
+ else if (line.startsWith('@@')) inHunk = true;
63
+ else if (inHunk && line.startsWith('+')) additions++;
64
+ else if (inHunk && line.startsWith('-')) deletions++;
65
+ }
66
+ return { additions, deletions };
67
+ }
68
+
69
+ function isBinaryDiff(diff) {
70
+ return /^Binary files .* differ$/m.test(diff) || diff.includes('GIT binary patch');
71
+ }
72
+
73
+ function sizeOf(value) {
74
+ return Buffer.byteLength(JSON.stringify(value));
75
+ }
76
+
77
+ // Largest prefix of `text` whose JSON-encoded size fits `maxBytes`.
78
+ function fitPrefix(text, maxBytes) {
79
+ if (sizeOf(text) <= maxBytes) return text;
80
+ let lo = 0;
81
+ let hi = text.length;
82
+ while (lo < hi) {
83
+ const mid = Math.ceil((lo + hi) / 2);
84
+ if (sizeOf(text.slice(0, mid)) <= maxBytes) lo = mid;
85
+ else hi = mid - 1;
86
+ }
87
+ return text.slice(0, lo);
88
+ }
89
+
90
+ async function runGit(cwd, args, { allowFailureOutput = false } = {}) {
91
+ try {
92
+ const { stdout } = await execFileAsync('git', args, { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: 10 * 1024 * 1024 });
93
+ return stdout;
94
+ } catch (err) {
95
+ // `git diff --no-index` exits non-zero whenever the files differ, but its
96
+ // stdout still holds the real diff.
97
+ if (allowFailureOutput && err.stdout) return err.stdout;
98
+ throw err;
99
+ }
100
+ }
101
+
102
+ async function diffFor(cwd, entry, hasHead) {
103
+ const category = categoryOf(entry.x, entry.y);
104
+ if (category === 'untracked') {
105
+ return runGit(cwd, ['diff', '--no-index', '--', '/dev/null', entry.path], { allowFailureOutput: true });
106
+ }
107
+ if (category === 'conflict') return runGit(cwd, ['diff', '--', entry.path]);
108
+ const paths = entry.origPath ? [entry.origPath, entry.path] : [entry.path];
109
+ // Against HEAD, so a file with both staged and unstaged edits shows ALL of
110
+ // its changes since the last commit. A repo with no commit yet has no HEAD.
111
+ return hasHead ? runGit(cwd, ['diff', 'HEAD', '-M', '--', ...paths]) : runGit(cwd, ['diff', '--cached', '-M', '--', ...paths]);
112
+ }
113
+
114
+ // maxBodyBytes: the room available for the files list in one message (the
115
+ // caller subtracts its own envelope). Infinity keeps today's no-limit shape.
116
+ async function getGitDiff(cwd, { maxBodyBytes = Infinity, log = () => {} } = {}) {
117
+ try {
118
+ await runGit(cwd, ['rev-parse', '--is-inside-work-tree']);
119
+ } catch {
120
+ return { isGitRepo: false, files: [] };
121
+ }
122
+
123
+ let hasHead = true;
124
+ try {
125
+ await runGit(cwd, ['rev-parse', '--verify', '--quiet', 'HEAD']);
126
+ } catch {
127
+ hasHead = false;
128
+ }
129
+
130
+ const statusOut = await runGit(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);
131
+ const allEntries = parseStatusZ(statusOut);
132
+ const rank = (e) => {
133
+ const c = categoryOf(e.x, e.y);
134
+ return c === 'conflict' ? 0 : c === 'untracked' ? 2 : 1;
135
+ };
136
+ const entries = allEntries
137
+ .map((e, i) => ({ e, i }))
138
+ .sort((a, b) => rank(a.e) - rank(b.e) || a.i - b.i)
139
+ .map(({ e }) => e)
140
+ .slice(0, MAX_FILES);
141
+
142
+ const files = [];
143
+ let used = 0;
144
+ for (const entry of entries) {
145
+ const category = categoryOf(entry.x, entry.y);
146
+ let diff = '';
147
+ try {
148
+ diff = await diffFor(cwd, entry, hasHead);
149
+ } catch (err) {
150
+ log(`[supervisor] git diff failed for "${entry.path}":`, err.message);
151
+ }
152
+ const binary = isBinaryDiff(diff);
153
+ const { additions, deletions } = binary ? { additions: 0, deletions: 0 } : countChanges(diff);
154
+ const file = {
155
+ status: category === 'untracked' ? 'untracked' : 'modified',
156
+ category,
157
+ path: entry.path,
158
+ ...(entry.origPath ? { oldPath: entry.origPath } : {}),
159
+ staged: entry.x !== ' ' && entry.x !== '?',
160
+ unstaged: entry.y !== ' ' && entry.y !== '?',
161
+ additions,
162
+ deletions,
163
+ binary,
164
+ diff: '',
165
+ };
166
+
167
+ let text = binary ? '' : diff;
168
+ let truncated = false;
169
+ if (text.length > MAX_DIFF_CHARS_PER_FILE) {
170
+ text = text.slice(0, MAX_DIFF_CHARS_PER_FILE) + TRUNCATION_NOTE;
171
+ truncated = true;
172
+ }
173
+ const base = sizeOf(file) + 20;
174
+ if (used + base > maxBodyBytes) break; // no room even for this file's row
175
+ const room = maxBodyBytes - used - base;
176
+ if (text && sizeOf(text) > room) {
177
+ const prefix = fitPrefix(text, room - sizeOf(TRUNCATION_NOTE));
178
+ if (prefix.length >= 500) {
179
+ text = prefix + TRUNCATION_NOTE;
180
+ truncated = true;
181
+ } else {
182
+ text = '';
183
+ file.omitted = true;
184
+ }
185
+ }
186
+ file.diff = text;
187
+ if (truncated) file.truncated = true;
188
+ used += sizeOf(file) + 2;
189
+ files.push(file);
190
+ }
191
+
192
+ return {
193
+ isGitRepo: true,
194
+ files,
195
+ hasChanges: allEntries.length > 0,
196
+ summary: { total: allEntries.length, listed: files.length },
197
+ };
198
+ }
199
+
200
+ module.exports = { getGitDiff, parseStatusZ, categoryOf, countChanges, isBinaryDiff, fitPrefix, MAX_FILES, MAX_DIFF_CHARS_PER_FILE };
@@ -0,0 +1,45 @@
1
+ // Session identity and shutdown (PROD-003).
2
+ //
3
+ // - A session ID is minted fresh on every run and is never reused. It keeps a
4
+ // readable prefix (machine name + short folder hash, so a person can tell which
5
+ // project it is) and ends in 64 bits of randomness, so two runs can never share
6
+ // one. The backend also refuses any ID it has already ended.
7
+ // - When the session ends for good (shell exited, Ctrl+C, window closed) the CLI
8
+ // tells the backend straight away, so the phone drops it at once instead of
9
+ // showing it until the reconnect grace runs out. This is best effort and bounded:
10
+ // it must never delay or block the laptop's own exit.
11
+ 'use strict';
12
+
13
+ const crypto = require('node:crypto');
14
+
15
+ function newSessionId({ hostname, workingDir }) {
16
+ const dirHash = crypto.createHash('sha1').update(workingDir).digest('hex').slice(0, 8);
17
+ return `${hostname}-${dirHash}-${crypto.randomBytes(8).toString('hex')}`;
18
+ }
19
+
20
+ // Resolves { ok, status? , reason? }; never rejects and never takes longer than timeoutMs.
21
+ async function endSessionOnBackend({ fetchImpl, authServer, deviceToken, sessionId, reason = 'exit', timeoutMs = 2000 }) {
22
+ if (!deviceToken || !sessionId) return { ok: false, reason: 'not_paired' };
23
+ const ctl = typeof AbortController === 'function' ? new AbortController() : null;
24
+ const timer = ctl ? setTimeout(() => ctl.abort(), timeoutMs) : null;
25
+ try {
26
+ const res = await fetchImpl(`${authServer}/device/session-end`, {
27
+ method: 'POST',
28
+ headers: { Authorization: `Bearer ${deviceToken}`, 'Content-Type': 'application/json' },
29
+ body: JSON.stringify({ sessionId, reason }),
30
+ signal: ctl ? ctl.signal : undefined,
31
+ });
32
+ return { ok: !!res.ok, status: res.status };
33
+ } catch (err) {
34
+ return { ok: false, reason: err && err.name === 'AbortError' ? 'timeout' : 'network' };
35
+ } finally {
36
+ if (timer) clearTimeout(timer);
37
+ }
38
+ }
39
+
40
+ // The backend answers 410 to a heartbeat or reconnect for a session it has already ended.
41
+ function isSessionEndedResponse(res) {
42
+ return !!res && res.status === 410;
43
+ }
44
+
45
+ module.exports = { newSessionId, endSessionOnBackend, isSessionEndedResponse };
@@ -0,0 +1,40 @@
1
+ // Keeps the laptop's shared encryption secret in step with the phone's CURRENT
2
+ // public key (P0: "could not decrypt output from this device").
3
+ //
4
+ // Confirmed cause: the laptop derived its secret once, from the phone key saved
5
+ // at pair time, and never looked again. The backend is the key directory: it
6
+ // holds the phone key that the phone last registered for this device (pairing,
7
+ // a re-scan, a second phone, a reinstall, a late sync). When that key differed
8
+ // from the one frozen in config.json, every message the laptop encrypted failed
9
+ // the phone's GCM auth check, and the only "recovery" was a full unpair and
10
+ // re-pair.
11
+ //
12
+ // Now /device/connect returns the registered phone key and each session start
13
+ // calls adoptPhoneKey(). Encryption is never weakened: a key that cannot be
14
+ // used is rejected (the old secret is kept), nothing falls back to plaintext
15
+ // because of a key change, and private keys are never logged.
16
+ const setuCrypto = require('./crypto');
17
+
18
+ function deriveFor(config, phonePublicKeyB64) {
19
+ const privateKey = setuCrypto.privateKeyFromBase64(config.devicePrivateKey);
20
+ return setuCrypto.deriveSharedSecret(privateKey, phonePublicKeyB64);
21
+ }
22
+
23
+ // Returns { secret, changed, error }.
24
+ // - secret: the secret to use from now on (unchanged when nothing changed or the new key is unusable)
25
+ // - changed: true when config.phonePublicKey was replaced (caller persists)
26
+ // - error: a short reason when the offered key was rejected, never key material
27
+ function adoptPhoneKey({ config, offeredKey, currentSecret }) {
28
+ if (!config.devicePrivateKey) return { secret: currentSecret, changed: false, error: null };
29
+ if (!offeredKey) return { secret: currentSecret, changed: false, error: null };
30
+ if (offeredKey === config.phonePublicKey && currentSecret) return { secret: currentSecret, changed: false, error: null };
31
+ try {
32
+ const secret = deriveFor(config, offeredKey);
33
+ const changed = offeredKey !== config.phonePublicKey;
34
+ return { secret, changed, error: null };
35
+ } catch (err) {
36
+ return { secret: currentSecret, changed: false, error: `phone public key rejected: ${err.message}` };
37
+ }
38
+ }
39
+
40
+ module.exports = { adoptPhoneKey, deriveFor };
package/src/status.js CHANGED
@@ -93,7 +93,7 @@ async function status(authServer) {
93
93
  }
94
94
 
95
95
  if (running.length === 0) {
96
- console.log('[cli-setu] No sessions currently running. Run `cli-setu` in a project folder to start one.');
96
+ console.log('[cli-setu] No sessions currently running. Run `cli-setu session` in a project folder to start one.');
97
97
  return;
98
98
  }
99
99
 
@@ -0,0 +1,33 @@
1
+ // Forwards the laptop keyboard to the PTY (P0: "first character is dropped").
2
+ //
3
+ // Two defects this replaces in supervisor.js:
4
+ // 1. Raw mode and the data listener were attached at the END of main(), after
5
+ // all the other start-up work. Until then the console is in cooked
6
+ // (line-buffered) mode, so keys typed while the shell was still starting
7
+ // were held in the console's line buffer and could be discarded when raw mode
8
+ // was switched on. The forwarder is now attached the moment the PTY exists.
9
+ // 2. `data.toString()` on each chunk corrupts a multi-byte UTF-8 character
10
+ // that is split across two chunks. A StringDecoder keeps the partial bytes
11
+ // until the rest arrive.
12
+ // Every chunk is written exactly once, in order. Nothing here reads or echoes
13
+ // input itself: echo is the shell's job, through the PTY.
14
+ const { StringDecoder } = require('string_decoder');
15
+
16
+ function attachStdinForwarder({ stdin, write }) {
17
+ const decoder = new StringDecoder('utf8');
18
+ const onData = (chunk) => {
19
+ const text = typeof chunk === 'string' ? chunk : decoder.write(chunk);
20
+ if (text) write(text);
21
+ };
22
+ if (stdin.isTTY && typeof stdin.setRawMode === 'function') stdin.setRawMode(true);
23
+ stdin.on('data', onData);
24
+ stdin.resume();
25
+
26
+ return function detach() {
27
+ stdin.removeListener('data', onData);
28
+ try { if (stdin.isTTY && typeof stdin.setRawMode === 'function') stdin.setRawMode(false); } catch { /* terminal already gone */ }
29
+ stdin.pause();
30
+ };
31
+ }
32
+
33
+ module.exports = { attachStdinForwarder };
package/src/supervisor.js CHANGED
@@ -33,22 +33,19 @@ const { Terminal: HeadlessTerminal } = require('@xterm/headless');
33
33
  const fs = require('fs');
34
34
  const path = require('path');
35
35
  const WebSocket = require('ws');
36
- const { exec, execFile } = require('child_process');
37
- const { promisify } = require('util');
38
- const execAsync = promisify(exec);
39
- // execFile (not exec) for anything that embeds a real filesystem path -
40
- // exec runs through cmd.exe, string-interpolating a path into a shell
41
- // command line is a real injection risk if that path ever contained
42
- // shell metacharacters (an unlikely but not impossible filename the CLI
43
- // itself created). execFile passes args as a real array, no shell
44
- // involved, no interpolation - the correct tool whenever a path is
45
- // data, not part of the command syntax itself.
46
- const execFileAsync = promisify(execFile);
36
+ const { exec } = require('child_process');
47
37
  const { getAdapter } = require('./cli-adapters');
38
+ const { getGitDiff } = require('./gitDiff');
48
39
  const setuCrypto = require('./crypto');
40
+ const { splitIntoParts, trimSnapshot, limitForProvider } = require('./transportSplit');
49
41
  const { createReconnectManager, WARN_AFTER_ATTEMPTS } = require('./reconnect');
50
42
  const { createDedupCache } = require('./dedup');
51
43
  const { attachProviderProtocol } = require('./providerProtocol');
44
+ const { createDiagnostics } = require('./diagnostics');
45
+ const { attachStdinForwarder } = require('./stdinForwarder');
46
+ const { adoptPhoneKey } = require('./sharedKey');
47
+ const { approvalFingerprint, createApprovalDeduper, relayWithRetry } = require('./approvalRelay');
48
+ const { newSessionId, endSessionOnBackend, isSessionEndedResponse } = require('./sessionLifecycle');
52
49
 
53
50
  // Real bug found by testing: this script's own console.log/console.error
54
51
  // calls write to the SAME process.stdout the PTY's raw output is echoed
@@ -63,7 +60,7 @@ const { attachProviderProtocol } = require('./providerProtocol');
63
60
  // from that point on.
64
61
  const os = require('os');
65
62
  const crypto = require('crypto');
66
- const { readConfig, CONFIG_DIR } = require('./config');
63
+ const { readConfig, writeConfig, CONFIG_DIR } = require('./config');
67
64
 
68
65
  // Real gap in the proof-of-concept this replaces: every run required
69
66
  // typing <deviceName> <sessionId> as argv, and diagnostics went to a log
@@ -80,6 +77,31 @@ function log(...args) {
80
77
  fs.appendFileSync(LOG_FILE, line);
81
78
  }
82
79
 
80
+ // Once the PTY exists it owns the terminal: see diagnostics.js. Use diag.say()
81
+ // for every message that can fire after spawn; never console.log/error there.
82
+ // Declared up here, with its own flag rather than ptyProcess, because some
83
+ // callers run at module load, before ptyProcess is initialised.
84
+ let terminalOwned = false;
85
+ const diag = createDiagnostics({ log, isTerminalOwned: () => terminalOwned });
86
+
87
+ // No plaintext, ever: terminal content only leaves this computer encrypted. With no
88
+ // shared secret (this computer has no key for the phone yet) nothing is sent, and
89
+ // the user is told once, after the shell exits, what to do. The terminal on this
90
+ // laptop is unaffected.
91
+ // The only way terminal content is turned into a wire payload. It throws when
92
+ // there is no secret, so a missing key can never degrade into plaintext.
93
+ function encryptStrict(piece) {
94
+ if (!sharedSecret) throw new Error('refusing to send terminal content without an encryption key');
95
+ return setuCrypto.encrypt(sharedSecret, piece);
96
+ }
97
+ let warnedNoKey = false;
98
+ function noteNoEncryptionKey() {
99
+ log('[supervisor] No encryption key for the phone: terminal content is NOT being sent (plaintext is never used).');
100
+ if (warnedNoKey) return;
101
+ warnedNoKey = true;
102
+ diag.say('[cli-setu] Terminal output is NOT being sent to your phone: this computer has no encryption key for it yet, and plaintext is never used. Run `cli-setu pair` to pair this computer with your phone again. The terminal on this computer keeps working normally.', { error: true, showAtExit: true });
103
+ }
104
+
83
105
  // Real config, from pairing (src/pair.js, via the explicit `cli-setu pair`
84
106
  // command - see SETU-001: pairing and session creation are two distinct
85
107
  // steps now, bin/setu.js's `session` subcommand never pairs on its own
@@ -123,8 +145,8 @@ const WORKING_DIR = process.cwd();
123
145
  // "app" on the same machine) plus a short random suffix so re-running
124
146
  // `cli-setu` in the same folder twice at once (e.g. two terminal tabs) never
125
147
  // silently shares one session.
126
- const dirHash = crypto.createHash('sha1').update(WORKING_DIR).digest('hex').slice(0, 8);
127
- const SESSION_ID = `${os.hostname()}-${dirHash}-${crypto.randomBytes(3).toString('hex')}`;
148
+ // PROD-003: minted fresh every run and never reused (see sessionLifecycle.js).
149
+ const SESSION_ID = newSessionId({ hostname: os.hostname(), workingDir: WORKING_DIR });
128
150
 
129
151
  // SETU-005: the real identity a duplicate-session check needs - resolves
130
152
  // symlinks (fs.realpathSync) so two different-looking paths to the SAME
@@ -150,7 +172,7 @@ LOG_FILE = path.join(CONFIG_DIR, `supervisor.${DEVICE_NAME.replace(/[^a-zA-Z0-9-
150
172
 
151
173
  const adapter = getAdapter(CLI_NAME);
152
174
  console.log(`[supervisor] Using CLI adapter: ${adapter.displayName} (${adapter.id})`);
153
- log(`Using CLI adapter: ${adapter.displayName} (${adapter.id})`);
175
+ log(`cli-setu ${require("../package.json").version} (node ${process.version}, ${process.platform}) - using CLI adapter: ${adapter.displayName} (${adapter.id})`);
154
176
 
155
177
  // Real bug found by testing: when the spawned adapter is 'shell' (the
156
178
  // bare-`cli-setu` default - see cli-adapters/shell.js), the user is expected
@@ -194,7 +216,11 @@ let deviceToken = config.deviceToken;
194
216
  let deviceId = null;
195
217
  let ws = null;
196
218
  let azureReady = false;
219
+ // Which realtime provider this session actually connected through
220
+ // ('ably' | 'azure'); decides the per-message size limit (transportSplit.js).
221
+ let connectedProvider = null;
197
222
  const pendingPrompts = new Map();
223
+ const approvalDeduper = createApprovalDeduper({ isPending: (id) => pendingPrompts.has(id) });
198
224
 
199
225
  // Real gap found by investigation: both connectToAzure's own retry
200
226
  // paths (a failed /device/connect HTTP call, and the WebSocket's own
@@ -208,7 +234,7 @@ const pendingPrompts = new Map();
208
234
  const reconnectManager = createReconnectManager({
209
235
  onAttempt: () => connectToAzure(),
210
236
  onWarn: (attemptNumber) => {
211
- console.error(`\n[supervisor] Still unable to connect after ${attemptNumber} attempts - will keep retrying, but something is wrong (network, backend, or Azure). Check your connection; this is not a code bug if it eventually recovers.`);
237
+ diag.say(`[supervisor] Still unable to connect after ${attemptNumber} attempts - will keep retrying, but something is wrong (network, backend, or Azure). Check your connection; this is not a code bug if it eventually recovers.`, { error: true });
212
238
  log(`[supervisor] Reconnect warning threshold reached: ${attemptNumber} consecutive failures`);
213
239
  },
214
240
  log,
@@ -248,7 +274,7 @@ if (config.devicePrivateKey && config.phonePublicKey) {
248
274
  const privateKey = setuCrypto.privateKeyFromBase64(config.devicePrivateKey);
249
275
  sharedSecret = setuCrypto.deriveSharedSecret(privateKey, config.phonePublicKey);
250
276
  } catch (err) {
251
- console.error('[cli-setu] Could not derive E2E encryption key (falling back to unencrypted relay):', err.message);
277
+ diag.say(`[cli-setu] Could not derive E2E encryption key (falling back to unencrypted relay): ${err.message}`, { error: true, showAtExit: true });
252
278
  }
253
279
  }
254
280
 
@@ -298,7 +324,19 @@ let outputSeq = 0;
298
324
  // reused here for consistency (one unified "how patient are we before
299
325
  // saying something" policy, not two different numbers to reason about).
300
326
  let pollFocusFailureCount = 0;
327
+ // PROD-003: set when the backend says this session already ended (it was offline
328
+ // longer than the reconnect grace, or was closed). The ID is never revived: the
329
+ // laptop terminal keeps working, but nothing more is sent under it.
330
+ let sessionEndedByServer = false;
331
+ function handleSessionEndedByServer() {
332
+ if (sessionEndedByServer) return;
333
+ sessionEndedByServer = true;
334
+ if (focusTimer) clearInterval(focusTimer);
335
+ log('[supervisor] The backend reports this session has ended (HTTP 410); no further updates will be sent for it.');
336
+ diag.say('[supervisor] This session has ended on the server (it was offline too long, or was closed), so your phone can no longer see it. Your terminal here keeps working. Run `cli-setu session` again to start a new session.', { showAtExit: true });
337
+ }
301
338
  async function pollFocus() {
339
+ if (sessionEndedByServer) return;
302
340
  try {
303
341
  // detectedCliType (see detectRunningAdapter's own comment, further
304
342
  // down this file) piggybacks on this same already-running poll so
@@ -310,11 +348,12 @@ async function pollFocus() {
310
348
  // incorrectly downgrade a session that started with `--cli claude`
311
349
  // before this poll even has real data to report.
312
350
  const detectedParam = lastDetectedCliType ? `&detectedCliType=${encodeURIComponent(lastDetectedCliType)}` : '';
313
- await fetch(
351
+ const focusRes = await fetch(
314
352
  `${AUTH_SERVER}/terminal/is-focused?sessionId=${encodeURIComponent(SESSION_ID)}${deviceId ? `&deviceId=${encodeURIComponent(deviceId)}` : ''}${detectedParam}`
315
353
  );
354
+ if (isSessionEndedResponse(focusRes)) { handleSessionEndedByServer(); return; }
316
355
  if (pollFocusFailureCount >= WARN_AFTER_ATTEMPTS) {
317
- console.log('[supervisor] Heartbeat to the backend recovered.');
356
+ diag.say('[supervisor] Heartbeat to the backend recovered.');
318
357
  log('[supervisor] pollFocus heartbeat recovered after failures');
319
358
  }
320
359
  pollFocusFailureCount = 0;
@@ -325,7 +364,7 @@ async function pollFocus() {
325
364
  // tick," same as before) - this fix is purely about visibility.
326
365
  pollFocusFailureCount += 1;
327
366
  if (pollFocusFailureCount === WARN_AFTER_ATTEMPTS) {
328
- console.error(`\n[supervisor] Heartbeat to the backend has failed ${pollFocusFailureCount} times in a row (${err.message}) - the backend may be down. Terminal output/input may not sync correctly until this recovers.`);
367
+ diag.say(`[supervisor] Heartbeat to the backend has failed ${pollFocusFailureCount} times in a row (${err.message}) - the backend may be down. Terminal output/input may not sync correctly until this recovers.`, { error: true });
329
368
  }
330
369
  log(`[supervisor] pollFocus failed (consecutive=${pollFocusFailureCount}): ${err.message}`);
331
370
  }
@@ -412,8 +451,15 @@ async function connectToAzure() {
412
451
  }
413
452
  setTimeout(() => process.exit(1), 1500).unref();
414
453
  };
454
+ // PROD-003: 410 means this session ID already ended (e.g. the laptop was
455
+ // asleep longer than the reconnect grace). Retrying would never help and the ID
456
+ // is never revived, so say so clearly instead of looping.
457
+ if (isSessionEndedResponse(res)) {
458
+ handleSessionEndedByServer();
459
+ return;
460
+ }
415
461
  if (res.status === 403) {
416
- console.error(`\n[supervisor] Connection rejected: ${err.error || 'the server declined this session.'}`);
462
+ diag.say(`[supervisor] Connection rejected: ${err.error || 'the server declined this session.'}`, { error: true, showAtExit: true });
417
463
  log(`[supervisor] /device/connect rejected (403): ${err.error || 'no reason given'}`);
418
464
  killAndExit();
419
465
  }
@@ -425,8 +471,8 @@ async function connectToAzure() {
425
471
  // wrong or what to do about it. Treated the same as 403 now: stop,
426
472
  // say so clearly, point at the real fix.
427
473
  if (res.status === 401) {
428
- console.error(`\n[supervisor] This device is no longer paired (it may have been unpaired from the app).`);
429
- console.error('[supervisor] Run `cli-setu pair` to pair it again.');
474
+ diag.say('[supervisor] This device is no longer paired (it may have been unpaired from the app).', { error: true, showAtExit: true });
475
+ diag.say('[supervisor] Run `cli-setu pair` to pair it again.', { error: true, showAtExit: true });
430
476
  log(`[supervisor] /device/connect rejected (401): ${err.error || 'no reason given'}`);
431
477
  killAndExit();
432
478
  }
@@ -436,6 +482,20 @@ async function connectToAzure() {
436
482
  }
437
483
  const conn = await res.json();
438
484
  deviceId = conn.deviceId;
485
+ // The backend holds the phone key this device is CURRENTLY registered with.
486
+ // Adopt it so a phone key that changed after pairing (reinstall, second
487
+ // phone, late sync) does not leave us encrypting to a stale key - see
488
+ // sharedKey.js. Private keys and secrets are never logged.
489
+ {
490
+ const adopted = adoptPhoneKey({ config, offeredKey: conn.phonePublicKey, currentSecret: sharedSecret });
491
+ if (adopted.error) log(`[supervisor] ${adopted.error}`);
492
+ if (adopted.secret) sharedSecret = adopted.secret;
493
+ if (adopted.changed) {
494
+ config.phonePublicKey = conn.phonePublicKey;
495
+ try { writeConfig(config); } catch (e) { log(`[supervisor] could not save the updated phone key: ${e.message}`); }
496
+ log('[supervisor] phone public key updated from the backend; encryption secret re-derived');
497
+ }
498
+ }
439
499
  // See this function's own call site (main()'s former focusTimer
440
500
  // comment) for why this starts HERE and not unconditionally at
441
501
  // startup - deviceId must be real before pollFocus's heartbeat is
@@ -449,7 +509,7 @@ async function connectToAzure() {
449
509
  // actually makes a session show up before its first approval prompt)
450
510
  // was even attempted and whether it succeeded, right here, instead of
451
511
  // needing server log access to find out.
452
- console.log(`[supervisor] session.started broadcast: ${conn.sessionBroadcast || '(not reported by this server version)'}`);
512
+ diag.say(`[supervisor] session.started broadcast: ${conn.sessionBroadcast || '(not reported by this server version)'}`);
453
513
 
454
514
  ws = new WebSocket(conn.wssUrl);
455
515
 
@@ -464,6 +524,7 @@ async function connectToAzure() {
464
524
  const providerConnection = attachProviderProtocol(ws, conn.wssUrl, `device:${deviceId}`, {
465
525
  onReady: () => {
466
526
  azureReady = true;
527
+ connectedProvider = providerConnection.provider;
467
528
  reconnectManager.reset();
468
529
  log(`[supervisor] Connected (${providerConnection.provider}). Ready to forward permission requests.`);
469
530
  },
@@ -490,18 +551,21 @@ async function connectToAzure() {
490
551
  // build talking to each other don't try to decrypt plaintext or
491
552
  // vice versa - see this file's own sharedSecret comment for why
492
553
  // that fallback has to be all-or-nothing, never silent guessing.
493
- let data = msg.data;
494
- if (msg.encrypted) {
495
- if (!sharedSecret) {
496
- log('[supervisor] Dropped an encrypted terminal.input - this device has no shared secret to decrypt it (re-pair to fix).');
497
- return;
498
- }
499
- try {
500
- data = setuCrypto.decrypt(sharedSecret, msg.data);
501
- } catch (err) {
502
- log('[supervisor] Failed to decrypt terminal.input, dropping:', err.message);
503
- return;
504
- }
554
+ // Plaintext input is refused: it must arrive encrypted and decrypt cleanly.
555
+ if (!msg.encrypted) {
556
+ log('[supervisor] Refused a plaintext terminal.input (plaintext is never accepted).');
557
+ return;
558
+ }
559
+ if (!sharedSecret) {
560
+ log('[supervisor] Dropped an encrypted terminal.input - this device has no shared secret to decrypt it (re-pair to fix).');
561
+ return;
562
+ }
563
+ let data;
564
+ try {
565
+ data = setuCrypto.decrypt(sharedSecret, msg.data);
566
+ } catch (err) {
567
+ log('[supervisor] Failed to decrypt terminal.input, dropping:', err.message);
568
+ return;
505
569
  }
506
570
  ptyProcess.write(data);
507
571
  }
@@ -536,7 +600,7 @@ async function connectToAzure() {
536
600
  // cleanup and actually exits, avoiding the node-pty Windows
537
601
  // async-teardown race already fixed elsewhere in this file.
538
602
  log(`[supervisor] Received session.close from the phone - shutting down.`);
539
- console.log('\n[supervisor] Session closed from the mobile app.');
603
+ diag.say('[supervisor] Session closed from the mobile app.', { showAtExit: true });
540
604
  process.exitCode = 0;
541
605
  if (ptyProcess) {
542
606
  ptyProcess.kill();
@@ -614,26 +678,19 @@ async function connectToAzure() {
614
678
  ws.on('error', (err) => log('[supervisor] Azure socket error:', err.message));
615
679
  }
616
680
 
617
- // Real bug found by code review, fixed before ever shipping: `scrollback`
618
- // is now genuinely unbounded in memory (SETU-009/015's own explicit "full
619
- // session, no cap" requirement) - but Azure Web PubSub (and Ably) both
620
- // have a REAL, documented hard ceiling of 1MB per message. A session
621
- // whose history grew past that would have its snapshot broadcast
622
- // rejected outright the next time a phone reconnects, leaving it with a
623
- // BLANK terminal instead of the promised full mirror - worse than a cap.
624
- // This does NOT touch `scrollback` itself (still fully unbounded, still
625
- // used for live streaming - see appendScrollback's own comment) - it only
626
- // trims what gets sent in this ONE-TIME reconnect snapshot, so a phone
627
- // attaching to a genuinely huge session still gets a recent, working
628
- // view instead of nothing at all. Margin left well under the real 1MB
629
- // limit for JSON framing + the pre-TUI history prefix + encryption
630
- // overhead (encryption inflates size - confirmed this session via a real
631
- // backend log showing a 1549-byte plaintext snapshot arrive as 2972
632
- // encrypted bytes, roughly 2x - 900KB plaintext stays safely under 1MB
633
- // even after that).
634
- const SNAPSHOT_MAX_SCROLLBACK_BYTES = 900_000;
681
+ // The realtime provider refuses any single message over its size limit
682
+ // (Ably Free/Standard: 64 KiB; Azure Web PubSub: 1 MB), and the old code sent
683
+ // the whole snapshot as ONE message, so a session with more than about 45 KB
684
+ // of history could reach the phone blank. The snapshot is now split into
685
+ // parts that each fit (see transportSplit.js) and the phone reassembles them.
686
+ // `scrollback` itself stays unbounded (SETU-009/015: full-session mirror).
687
+ // Only this one-time reconnect snapshot is capped, at a large size, and
688
+ // when it is capped the phone is TOLD (a visible notice plus a log line)
689
+ // instead of the history silently shrinking.
690
+ const SNAPSHOT_MAX_CHARS = 8_000_000;
635
691
 
636
692
  async function sendSnapshot() {
693
+ if (!sharedSecret) { noteNoEncryptionKey(); return; }
637
694
  try {
638
695
  // preservedHistoryText() (see its own comment) is plain text, from
639
696
  // BEFORE the current full-screen TUI took over - prepended ahead of
@@ -642,24 +699,50 @@ async function sendSnapshot() {
642
699
  // pre-TUI history too, not just whatever the current alt-screen
643
700
  // buffer still happens to show.
644
701
  const history = await preservedHistoryText();
645
- const scrollbackForSnapshot = scrollback.length > SNAPSHOT_MAX_SCROLLBACK_BYTES
646
- ? scrollback.slice(scrollback.length - SNAPSHOT_MAX_SCROLLBACK_BYTES)
647
- : scrollback;
648
- const plainScreen = history ? `${history}\n${scrollbackForSnapshot}` : scrollbackForSnapshot;
702
+ const combined = history ? `${history}\n${scrollback}` : scrollback;
703
+ const trimmed = trimSnapshot(combined, SNAPSHOT_MAX_CHARS);
704
+ if (trimmed.truncated) {
705
+ log(`[supervisor] Snapshot trimmed: ${trimmed.droppedChars} older characters are not sent (limit ${SNAPSHOT_MAX_CHARS}).`);
706
+ }
707
+ const plainScreen = trimmed.text;
708
+ const snapshotId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
709
+ const encryptIfNeeded = (piece) => encryptStrict(piece);
710
+ const parts = plainScreen
711
+ ? splitIntoParts(plainScreen, {
712
+ maxBytes: limitForProvider(connectedProvider),
713
+ measure: (piece) =>
714
+ Buffer.byteLength(
715
+ JSON.stringify({ sessionId: SESSION_ID, snapshotId, part: 99999, totalParts: 99999, screen: encryptIfNeeded(piece), encrypted: true, cols: PTY_COLS, rows: PTY_ROWS })
716
+ ),
717
+ })
718
+ : [''];
649
719
  // TEMPORARY diagnostic logging (2026-10-28) - remove once the
650
720
  // scrollback-not-refreshed-on-reload bug is confirmed/fixed.
651
- log(`[supervisor][diag] sendSnapshot: history=${history.length} scrollback=${scrollback.length} sent=${scrollbackForSnapshot.length} total=${plainScreen.length} bytes, AUTH_SERVER=${AUTH_SERVER}`);
652
- // Section 1 E2E: see terminal.input's own comment on why this is
653
- // all-or-nothing, never a silent per-message guess.
654
- const screen = sharedSecret ? setuCrypto.encrypt(sharedSecret, plainScreen) : plainScreen;
655
- await fetch(`${AUTH_SERVER}/relay/terminal-snapshot`, {
656
- method: 'POST',
657
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
658
- // cols/rows: the real PTY's actual geometry, so a phone attaching
659
- // can lock its terminal to match instead of guessing its own size -
660
- // see auth-server.js's matching comment for why this matters.
661
- body: JSON.stringify({ sessionId: SESSION_ID, screen, encrypted: !!sharedSecret, cols: PTY_COLS, rows: PTY_ROWS }),
662
- });
721
+ log(`[supervisor][diag] sendSnapshot: history=${history.length} scrollback=${scrollback.length} total=${plainScreen.length} parts=${parts.length}`);
722
+ for (let i = 0; i < parts.length; i++) {
723
+ // Section 1 E2E: see terminal.input's own comment on why this is
724
+ // all-or-nothing, never a silent per-message guess.
725
+ const res = await fetch(`${AUTH_SERVER}/relay/terminal-snapshot`, {
726
+ method: 'POST',
727
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
728
+ // cols/rows: the real PTY's actual geometry, so a phone attaching
729
+ // can lock its terminal to match instead of guessing its own size -
730
+ // see auth-server.js's matching comment for why this matters.
731
+ // A single-part snapshot keeps the exact original body shape.
732
+ body: JSON.stringify({
733
+ sessionId: SESSION_ID,
734
+ screen: encryptIfNeeded(parts[i]),
735
+ encrypted: true,
736
+ cols: PTY_COLS,
737
+ rows: PTY_ROWS,
738
+ ...(parts.length > 1 ? { snapshotId, part: i, totalParts: parts.length } : {}),
739
+ }),
740
+ });
741
+ if (!res.ok) {
742
+ log(`[supervisor] Snapshot part ${i + 1}/${parts.length} was refused by the backend (HTTP ${res.status}); stopping.`);
743
+ return;
744
+ }
745
+ }
663
746
  } catch (err) {
664
747
  log('[supervisor] Failed to send snapshot:', err.message);
665
748
  }
@@ -676,88 +759,16 @@ async function sendSnapshot() {
676
759
  // against each untracked file (Windows git still accepts the POSIX
677
760
  // /dev/null form here) gets a real unified diff for those too, rather
678
761
  // than just a bare filename with no content shown.
679
- const GIT_TIMEOUT_MS = 15_000;
680
- // Web PubSub has a real per-message size ceiling - a genuinely huge diff
681
- // (a big refactor, an accidentally-modified generated/vendored file)
682
- // could otherwise silently fail to relay at all. Capping per-file and
683
- // truncating with a visible marker is safer than an unbounded payload -
684
- // the phone still sees SOMETHING and knows it's incomplete, rather than
685
- // the whole request quietly failing.
686
- const MAX_DIFF_CHARS_PER_FILE = 20_000;
687
-
688
- function capDiff(diffText) {
689
- if (diffText.length <= MAX_DIFF_CHARS_PER_FILE) return { diff: diffText, truncated: false };
690
- return {
691
- diff: diffText.slice(0, MAX_DIFF_CHARS_PER_FILE) + '\n\n... (diff truncated - too large to send in full)',
692
- truncated: true,
693
- };
694
- }
695
-
696
- async function getGitDiff(cwd) {
697
- // Not a git repo at all - a real, common, non-error state (the
698
- // session's working directory might just never have been a repo) -
699
- // distinguished from a real git failure so the phone can show an
700
- // honest "not a git repository" message instead of a blank/broken pane.
701
- try {
702
- await execAsync('git rev-parse --is-inside-work-tree', { cwd, timeout: GIT_TIMEOUT_MS });
703
- } catch {
704
- return { isGitRepo: false, files: [] };
705
- }
706
-
707
- const files = [];
708
-
709
- // --name-only first, then one `git diff` PER FILE - not a single
710
- // combined `git diff` call. A combined diff mixes every modified
711
- // file's text into one blob, which would make capDiff's per-file
712
- // truncation (below) chop arbitrarily mid-file instead of cleanly
713
- // per-file, and would collapse the phone's ability to show "which
714
- // specific files changed" as a real list rather than one wall of text.
715
- const { stdout: nameOnlyOut } = await execAsync('git diff --name-only', { cwd, timeout: GIT_TIMEOUT_MS });
716
- const modifiedPaths = nameOnlyOut.split('\n').map((l) => l.trim()).filter(Boolean);
717
-
718
- for (const relPath of modifiedPaths) {
719
- try {
720
- const { stdout } = await execFileAsync('git', ['diff', '--', relPath], { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: 10 * 1024 * 1024 });
721
- if (stdout) files.push({ status: 'modified', path: relPath, ...capDiff(stdout) });
722
- } catch (err) {
723
- log(`[supervisor] git diff failed for modified file "${relPath}":`, err.message);
724
- }
725
- }
726
-
727
- // --porcelain's stable, machine-parseable format - '??' is git's own
728
- // marker for untracked. Path may be quoted (e.g. contains a space) -
729
- // stripping surrounding quotes is enough for this app's own diff
730
- // request, not a full porcelain parser.
731
- const { stdout: statusOut } = await execAsync('git status --porcelain', { cwd, timeout: GIT_TIMEOUT_MS });
732
- const untrackedPaths = statusOut
733
- .split('\n')
734
- .filter((line) => line.startsWith('?? '))
735
- .map((line) => line.slice(3).trim().replace(/^"|"$/g, ''));
736
-
737
- for (const relPath of untrackedPaths) {
738
- try {
739
- // --no-index compares two paths outside git's own tracking - the
740
- // ONLY way to get a real content diff for a file git has never
741
- // seen before. Exits non-zero whenever the files differ (which is
742
- // always true here, comparing against nothing) - execFileAsync
743
- // treats that as a rejected promise even though stdout still has
744
- // the real diff text, so it's read off the caught error instead.
745
- // execFile, not exec - relPath is a real filesystem path (from git
746
- // status output, ultimately from whatever the CLI wrote to disk),
747
- // passed as a real argv entry with no shell involved, not
748
- // interpolated into a command string.
749
- await execFileAsync('git', ['diff', '--no-index', '--', '/dev/null', relPath], { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: 5 * 1024 * 1024 });
750
- } catch (err) {
751
- if (err.stdout) files.push({ status: 'untracked', path: relPath, ...capDiff(err.stdout) });
752
- }
753
- }
754
-
755
- return { isGitRepo: true, files, hasChanges: modifiedPaths.length > 0 || untrackedPaths.length > 0 };
756
- }
762
+ // The git collection (changed files, staged/renamed/deleted/binary/conflict,
763
+ // size budget) lives in gitDiff.js and is tested against real repositories.
764
+ const GIT_DIFF_ENVELOPE_BYTES = 4000;
757
765
 
758
766
  async function sendGitDiff(requestId) {
759
767
  try {
760
- const result = await getGitDiff(WORKING_DIR);
768
+ const result = await getGitDiff(WORKING_DIR, {
769
+ maxBodyBytes: limitForProvider(connectedProvider) - GIT_DIFF_ENVELOPE_BYTES,
770
+ log,
771
+ });
761
772
  await fetch(`${AUTH_SERVER}/relay/git-diff-response`, {
762
773
  method: 'POST',
763
774
  headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
@@ -834,24 +845,52 @@ function flushOutputBuffer() {
834
845
  // immediately and broadcasts to Azure in the background, so this
835
846
  // fetch() itself should resolve quickly regardless of Azure's own cost.
836
847
  sendInFlight = sendInFlight.then(async () => {
837
- try {
838
- // Section 1 E2E: see terminal.input's own comment on why this is
839
- // all-or-nothing, never a silent per-message guess.
840
- const data = sharedSecret ? setuCrypto.encrypt(sharedSecret, batch) : batch;
841
- await fetch(`${AUTH_SERVER}/relay/terminal-output`, {
842
- method: 'POST',
843
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
844
- body: JSON.stringify({ sessionId: SESSION_ID, seq: ++outputSeq, data, encrypted: !!sharedSecret }),
845
- });
846
- } catch (err) {
847
- // A dropped terminal.output batch isn't fatal the way a dropped
848
- // confirmation would be - the next batch (or a fresh session.attach
849
- // snapshot) catches the view back up, so just log and move on.
850
- log('[supervisor] Failed to stream output batch:', err.message);
848
+ if (sessionEndedByServer) return; // PROD-003: an ended session is never revived
849
+ // A batch can be far bigger than BATCH_MAX_BYTES (one large chunk from
850
+ // the terminal), and the realtime provider refuses any single message
851
+ // over its limit (Ably Free/Standard: 64 KiB). Each piece gets its own
852
+ // consecutive seq, which the phone already reorders by.
853
+ if (!sharedSecret) { noteNoEncryptionKey(); return; }
854
+ for (const piece of splitBatchForTransport(batch)) {
855
+ try {
856
+ // Section 1 E2E: see terminal.input's own comment on why this is
857
+ // all-or-nothing, never a silent per-message guess.
858
+ const data = encryptStrict(piece);
859
+ const res = await fetch(`${AUTH_SERVER}/relay/terminal-output`, {
860
+ method: 'POST',
861
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
862
+ body: JSON.stringify({ sessionId: SESSION_ID, seq: ++outputSeq, data, encrypted: true }),
863
+ });
864
+ if (!res.ok) log(`[supervisor] Output piece seq=${outputSeq} was refused by the backend (HTTP ${res.status}, ${data.length} chars).`);
865
+ } catch (err) {
866
+ // A dropped terminal.output batch isn't fatal the way a dropped
867
+ // confirmation would be - the next batch (or a fresh session.attach
868
+ // snapshot) catches the view back up, so just log and move on.
869
+ log('[supervisor] Failed to stream output batch:', err.message);
870
+ }
851
871
  }
852
872
  });
853
873
  }
854
874
 
875
+ // Short batches cannot exceed the limit even if every byte JSON-escapes to
876
+ // six (6000 * 6 = 36 KB), so they skip the size measurement.
877
+ const SMALL_BATCH_CHARS = 6000;
878
+ function splitBatchForTransport(batch) {
879
+ if (batch.length <= SMALL_BATCH_CHARS) return [batch];
880
+ return splitIntoParts(batch, {
881
+ maxBytes: limitForProvider(connectedProvider),
882
+ measure: (piece) =>
883
+ Buffer.byteLength(
884
+ JSON.stringify({
885
+ sessionId: SESSION_ID,
886
+ seq: outputSeq + 1,
887
+ data: encryptStrict(piece),
888
+ encrypted: true,
889
+ })
890
+ ),
891
+ });
892
+ }
893
+
855
894
  // Real bug found by testing: writing several keystrokes (a plain
856
895
  // character plus \x1b[B escape sequences) to the PTY in ONE
857
896
  // ptyProcess.write() call only ever registered the FIRST one on a real
@@ -1168,6 +1207,7 @@ async function preservedHistoryText() {
1168
1207
 
1169
1208
  let processedLines = 0;
1170
1209
  let ptyProcess = null;
1210
+ let detachStdin = null;
1171
1211
  let pollTimer = null;
1172
1212
  let focusTimer = null;
1173
1213
  // No longer an interval (see the on-demand usage.refresh.request handler
@@ -1752,59 +1792,46 @@ async function relayApproval(event, options, text, questionIndex = 0, totalQuest
1752
1792
  // treats the second, genuinely different prompt as a duplicate of the
1753
1793
  // first and drops it, or conflates their responses. DEVICE_NAME makes
1754
1794
  // the id unique per-process even under a same-millisecond collision.
1795
+ // One logical approval = one card: a repeat of a still-pending request (same
1796
+ // session, tool, tool_use_id and input) is dropped. Step updates of a wizard
1797
+ // (reusePromptId) are not new approvals. See approvalRelay.js.
1798
+ const fingerprint = reusePromptId ? null : approvalFingerprint(event);
1799
+ if (fingerprint && approvalDeduper.isDuplicate(fingerprint)) {
1800
+ log('[supervisor] Ignored a repeat of an approval that is still pending (same session, tool and input).');
1801
+ return;
1802
+ }
1755
1803
  const promptId = reusePromptId || `p-${DEVICE_NAME}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1756
1804
  pendingPrompts.set(promptId, { ...event, options, questionIndex, totalQuestions, isMultiSelect: !!multiSelectOptions });
1805
+ if (fingerprint) approvalDeduper.remember(fingerprint, promptId);
1757
1806
 
1758
1807
  log(`[supervisor] Detected approval prompt: ${text}`);
1759
1808
  log(`[supervisor] Relaying to auth-server as promptId=${promptId}${reusePromptId ? ' (step update)' : ''}...`);
1760
1809
 
1761
- try {
1762
- const res = await fetch(`${AUTH_SERVER}/relay/confirmation-request`, {
1763
- method: 'POST',
1764
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
1765
- body: JSON.stringify({
1766
- sessionId: SESSION_ID,
1767
- promptId,
1768
- text,
1769
- options: multiSelectOptions ? [] : options.map(({ label, style }) => ({ label, style })),
1770
- ...(multiSelectOptions ? { isMultiSelect: true, multiSelectOptions } : {}),
1771
- ...(totalQuestions > 1 ? { stepIndex: questionIndex, totalSteps: totalQuestions } : {}),
1772
- }),
1773
- });
1774
- if (!res.ok) {
1775
- const err = await res.json().catch(() => ({}));
1776
- log('[supervisor] Relay failed:', err.error || res.status);
1777
- }
1778
- } catch (err) {
1779
- log('[supervisor] Failed to reach auth-server:', err.message);
1780
- }
1810
+ // Delivery is retried with backoff (same promptId, so it is idempotent) until
1811
+ // it is accepted, permanently refused, or the prompt is no longer pending.
1812
+ // Not awaited: a slow or failing backend must not hold up the next prompt in the queue.
1813
+ relayWithRetry({
1814
+ send: async () => {
1815
+ const res = await fetch(`${AUTH_SERVER}/relay/confirmation-request`, {
1816
+ method: 'POST',
1817
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${deviceToken}` },
1818
+ body: JSON.stringify({
1819
+ sessionId: SESSION_ID,
1820
+ promptId,
1821
+ text,
1822
+ options: multiSelectOptions ? [] : options.map(({ label, style }) => ({ label, style })),
1823
+ ...(multiSelectOptions ? { isMultiSelect: true, multiSelectOptions } : {}),
1824
+ ...(totalQuestions > 1 ? { stepIndex: questionIndex, totalSteps: totalQuestions } : {}),
1825
+ }),
1826
+ });
1827
+ return { ok: res.ok, status: res.status };
1828
+ },
1829
+ isStillPending: () => pendingPrompts.has(promptId),
1830
+ log: (m) => log(`[supervisor] ${m} (promptId=${promptId})`),
1831
+ }).then((delivery) => {
1832
+ if (!delivery.delivered) log(`[supervisor] Approval ${promptId} was NOT delivered to the phone: ${delivery.reason} after ${delivery.attempts} attempt(s). It is still answerable at the laptop.`);
1833
+ });
1781
1834
 
1782
- // Real gap found by testing: an APPROVED Bash/Write/PowerShell prompt
1783
- // gets a PostToolUse event (resolveIfPending), but a REJECTED one
1784
- // doesn't - the tool never ran, so there's nothing to hook. Several
1785
- // attempts at matching Claude Code's own rejection wording proved
1786
- // unreliable (see cli-adapters/claude.js's isMenuStillOnScreen
1787
- // comment). This instead polls whether the SAME menu is still
1788
- // physically on screen - once it isn't, a decision happened (approved,
1789
- // rejected, or interrupted, doesn't matter which) and the prompt is
1790
- // resolved. Skipped for AskUserQuestion, which already resolves
1791
- // reliably and precisely via PostToolUse's exact question-text match -
1792
- // this cruder "is ANY proceed-style menu gone" check would be a
1793
- // downgrade for that tool_name, not an improvement.
1794
- //
1795
- // Real bug found by code review, fixed before ever shipping: this used
1796
- // to hardcode claudeAdapter.approvals.isMenuStillOnScreen/
1797
- // distinguishingTextFor regardless of which adapter actually produced
1798
- // the event - Codex's own approvals object defines neither (see
1799
- // codex.js - it has no on-screen-menu-text concept at all, just its own
1800
- // fingerprint-based dedup), so a Codex prompt was being watched against
1801
- // CLAUDE's "Do you want to proceed?" wording, which never matches real
1802
- // Codex menu text - the very first poll (500ms later) always saw "no
1803
- // menu" and wrongly resolved a still-genuinely-pending Codex approval
1804
- // as abandoned. Using the passed-in approvalsAdapter (defaults to
1805
- // claudeAdapter.approvals, correct for pollForRequestsOnce's own
1806
- // exclusively-Claude path) means this now correctly no-ops for Codex,
1807
- // which has no isMenuStillOnScreen to even check.
1808
1835
  if (approvalsAdapter.isMenuStillOnScreen && event.tool_name !== 'AskUserQuestion') {
1809
1836
  // Real bug found by testing (live capture): two back-to-back Read
1810
1837
  // prompts for the same session each got their own watcher, but
@@ -1886,6 +1913,12 @@ async function main() {
1886
1913
  throw new Error(`Could not start "${adapter.spawn.command}" in ${WORKING_DIR}: ${err.message}`);
1887
1914
  }
1888
1915
 
1916
+ // Attach the laptop keyboard IMMEDIATELY, before any other start-up work, so
1917
+ // the first keystroke is never typed into a console that is still in cooked
1918
+ // mode (see stdinForwarder.js).
1919
+ terminalOwned = true; // from here on the PTY owns stdout: see diag
1920
+ detachStdin = attachStdinForwarder({ stdin: process.stdin, write: (text) => ptyProcess.write(text) });
1921
+
1889
1922
  // SETU-014: keep the real PTY (and the headless buffer that mirrors it
1890
1923
  // for the phone, see headlessTerm's own comment) in sync with the
1891
1924
  // laptop's own terminal WINDOW size - see PTY_COLS/PTY_ROWS's own
@@ -2111,24 +2144,32 @@ async function main() {
2111
2144
  ptyProcess.onExit(({ exitCode }) => {
2112
2145
  if (finishedExiting) return;
2113
2146
  finishedExiting = true;
2147
+ try { if (detachStdin) detachStdin(); } catch {}
2148
+ terminalOwned = false; // the terminal is the user's again: diagnostics may print
2114
2149
  console.log(`\n[supervisor] ${adapter.displayName} exited with code ${exitCode}`);
2150
+ diag.flushAtExit();
2115
2151
  if (pollTimer) clearInterval(pollTimer);
2116
2152
  if (focusTimer) clearInterval(focusTimer);
2117
2153
  if (usageTimer) clearInterval(usageTimer);
2118
2154
  if (batteryTimer) clearInterval(batteryTimer);
2119
2155
  if (adapterDetectTimer) clearInterval(adapterDetectTimer);
2120
2156
  if (ws) ws.close();
2121
- try {
2122
- if (process.stdin.isTTY) process.stdin.setRawMode(false);
2123
- process.stdin.pause();
2124
- } catch {}
2125
2157
  removePidFile();
2126
2158
  // If a caller (connectToAzure's 403/401, or cleanupAndExit) already
2127
2159
  // set process.exitCode before calling .kill(), respect that instead
2128
2160
  // of the PTY's own exit code - a plan-limit rejection should exit
2129
2161
  // non-zero even though PowerShell itself was killed cleanly
2130
2162
  // (exitCode 0 from its own perspective).
2131
- process.exit(process.exitCode ?? exitCode ?? 0);
2163
+ const finalCode = process.exitCode ?? exitCode ?? 0;
2164
+ // PROD-003: tell the backend this session is over (shell exited, Ctrl+C or the
2165
+ // window was closed) so the phone drops it now instead of waiting out the
2166
+ // reconnect grace. Bounded to 2s and best effort: it can never keep the
2167
+ // laptop from exiting, and a crash or power loss is still covered by the
2168
+ // backend's own grace expiry.
2169
+ endSessionOnBackend({ fetchImpl: fetch, authServer: AUTH_SERVER, deviceToken, sessionId: SESSION_ID, reason: 'exit' })
2170
+ .then((r) => log(`[supervisor] session-end sent: ${JSON.stringify(r)}`))
2171
+ .catch(() => {})
2172
+ .finally(() => process.exit(finalCode));
2132
2173
  });
2133
2174
 
2134
2175
  // Real feedback: an automatic timer used to run here (every 5 minutes,
@@ -2176,10 +2217,6 @@ async function main() {
2176
2217
  adapterDetectTimer = setInterval(detectRunningAdapter, ADAPTER_DETECT_POLL_INTERVAL_MS);
2177
2218
  }
2178
2219
 
2179
- process.stdin.setRawMode(true);
2180
- process.stdin.resume();
2181
- process.stdin.on('data', (data) => ptyProcess.write(data.toString()));
2182
-
2183
2220
  // Real gap in the PoC this replaces: there was no way for `cli-setu status`
2184
2221
  // or `cli-setu stop` (both new - see src/status.js, src/stop.js) to know
2185
2222
  // whether a session watcher was even running, or on which PID, since
@@ -0,0 +1,72 @@
1
+ // Splits terminal text into pieces that each fit one realtime-provider message.
2
+ //
3
+ // Why: Ably's Free and Standard plans reject any single published message
4
+ // over 64 KiB (see Ably's published platform limits page). The CLI used
5
+ // to send each output batch and the whole reconnect snapshot as ONE message
6
+ // with no size limit, so a large chunk or a long history could be refused
7
+ // and never reach the phone. Encryption (about 1.33x for base64) and JSON
8
+ // escaping make the sent size differ from the text length, so sizes are
9
+ // MEASURED on the real message, not guessed.
10
+ 'use strict';
11
+
12
+ // Well under 64 KiB (65,536 bytes) to leave room for the backend and
13
+ // provider envelope around our fields.
14
+ const MAX_MESSAGE_BYTES = 48_000;
15
+ // Azure Web PubSub allows 1 MB per message; well under it. Keeping Azure at
16
+ // its larger size means a history that used to arrive whole still arrives
17
+ // whole, so apps that do not know about parts keep working on Azure.
18
+ const AZURE_MESSAGE_BYTES = 900_000;
19
+
20
+ // provider is what the CLI is actually connected through ('ably' | 'azure').
21
+ // Unknown means the small, safe limit.
22
+ function limitForProvider(provider) {
23
+ return provider === 'azure' ? AZURE_MESSAGE_BYTES : MAX_MESSAGE_BYTES;
24
+ }
25
+ const MIN_PIECE_CHARS = 512;
26
+
27
+ // Never cut between the two halves of a surrogate pair: each piece is
28
+ // encrypted and decoded on its own, and a lone surrogate turns into U+FFFD.
29
+ function safeEnd(text, start, end) {
30
+ if (end >= text.length) return text.length;
31
+ const code = text.charCodeAt(end - 1);
32
+ if (code >= 0xd800 && code <= 0xdbff && end - start > 1) return end - 1;
33
+ return end;
34
+ }
35
+
36
+ // measure(piece) must return the byte size of the FULL message that would
37
+ // carry that piece (after encryption and JSON.stringify of the body).
38
+ // The first attempt is the WHOLE text (so anything that fits stays one part);
39
+ // when it does not fit, the size shrinks in proportion to how far over it was
40
+ // and is re-measured until the real message fits.
41
+ function splitIntoParts(text, { measure, maxBytes = MAX_MESSAGE_BYTES, initialChars = Infinity, minChars = MIN_PIECE_CHARS }) {
42
+ const parts = [];
43
+ let i = 0;
44
+ let size = Math.min(initialChars, text.length) || 1;
45
+ while (i < text.length) {
46
+ const end = safeEnd(text, i, Math.min(text.length, i + size));
47
+ const piece = text.slice(i, end);
48
+ const bytes = measure(piece);
49
+ if (bytes > maxBytes && piece.length > minChars) {
50
+ size = Math.max(minChars, Math.floor(piece.length * (maxBytes / bytes) * 0.9));
51
+ continue;
52
+ }
53
+ parts.push(piece);
54
+ i = end;
55
+ }
56
+ return parts;
57
+ }
58
+
59
+ // Keeps the NEWEST output when a snapshot would be larger than maxChars.
60
+ // Cuts at a line boundary so the first kept line is whole, and says so with a
61
+ // visible notice instead of dropping history silently.
62
+ function trimSnapshot(text, maxChars) {
63
+ if (text.length <= maxChars) return { text, truncated: false, droppedChars: 0 };
64
+ let cut = text.length - maxChars;
65
+ const nl = text.indexOf('\n', cut);
66
+ if (nl !== -1 && nl < text.length - 1) cut = nl + 1;
67
+ const dropped = cut;
68
+ const notice = `\x1b[0m\r\n[cli-setu: ${dropped} characters of older output are not shown after a reconnect]\r\n`;
69
+ return { text: notice + text.slice(cut), truncated: true, droppedChars: dropped };
70
+ }
71
+
72
+ module.exports = { MAX_MESSAGE_BYTES, AZURE_MESSAGE_BYTES, limitForProvider, splitIntoParts, trimSnapshot };