cli-setu 0.3.4 → 0.3.6

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.4",
3
+ "version": "0.3.6",
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,40 @@
1
+ // node-pty 1.1.0 ships its macOS "spawn-helper" program WITHOUT the execute bit
2
+ // (-rw-r--r-- in the npm tarball) and its install script does not fix that, so on a Mac every
3
+ // terminal start fails with "posix_spawnp failed". Found 2026-11-15 by the GitHub Actions macOS
4
+ // job (the first real macOS run of this CLI). Linux builds the helper itself (already
5
+ // executable) and Windows has no helper, so only the prebuilt macOS one is affected.
6
+ //
7
+ // ensureSpawnHelperExecutable() runs before node-pty is first used and adds the execute bits to
8
+ // every spawn-helper it can find. It never throws: a read-only install folder or a missing file
9
+ // must not stop the CLI, node-pty then reports its own clear error.
10
+ 'use strict';
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+
14
+ function helperCandidates(ptyDir, platform, arch) {
15
+ return [
16
+ path.join(ptyDir, 'build', 'Release', 'spawn-helper'),
17
+ path.join(ptyDir, 'build', 'Debug', 'spawn-helper'),
18
+ path.join(ptyDir, 'prebuilds', `${platform}-${arch}`, 'spawn-helper'),
19
+ ];
20
+ }
21
+
22
+ // Returns the list of files it changed (for tests and diagnostics).
23
+ function ensureSpawnHelperExecutable(opts = {}) {
24
+ const platform = opts.platform || process.platform;
25
+ if (platform === 'win32') return [];
26
+ let ptyDir = opts.ptyDir;
27
+ if (!ptyDir) {
28
+ try { ptyDir = path.dirname(require.resolve('node-pty/package.json')); } catch { return []; }
29
+ }
30
+ const changed = [];
31
+ for (const file of helperCandidates(ptyDir, platform, opts.arch || process.arch)) {
32
+ try {
33
+ const mode = fs.statSync(file).mode;
34
+ if ((mode & 0o111) !== 0o111) { fs.chmodSync(file, mode | 0o755); changed.push(file); }
35
+ } catch { /* file not there, or not ours to change: nothing to do */ }
36
+ }
37
+ return changed;
38
+ }
39
+
40
+ module.exports = { ensureSpawnHelperExecutable, helperCandidates };
@@ -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 };
package/src/supervisor.js CHANGED
@@ -28,6 +28,8 @@
28
28
  // card, no usage tracking) instead of refusing to start. See
29
29
  // cli-adapters/README.md for the adapter interface this script drives.
30
30
 
31
+ // macOS: node-pty's prebuilt spawn-helper ships without the execute bit (see ptyHelperPerms.js).
32
+ require('./ptyHelperPerms').ensureSpawnHelperExecutable();
31
33
  const pty = require('node-pty');
32
34
  const { Terminal: HeadlessTerminal } = require('@xterm/headless');
33
35
  const fs = require('fs');
@@ -45,6 +47,7 @@ const { createDiagnostics } = require('./diagnostics');
45
47
  const { attachStdinForwarder } = require('./stdinForwarder');
46
48
  const { adoptPhoneKey } = require('./sharedKey');
47
49
  const { approvalFingerprint, createApprovalDeduper, relayWithRetry } = require('./approvalRelay');
50
+ const { newSessionId, endSessionOnBackend, isSessionEndedResponse } = require('./sessionLifecycle');
48
51
 
49
52
  // Real bug found by testing: this script's own console.log/console.error
50
53
  // calls write to the SAME process.stdout the PTY's raw output is echoed
@@ -144,8 +147,8 @@ const WORKING_DIR = process.cwd();
144
147
  // "app" on the same machine) plus a short random suffix so re-running
145
148
  // `cli-setu` in the same folder twice at once (e.g. two terminal tabs) never
146
149
  // silently shares one session.
147
- const dirHash = crypto.createHash('sha1').update(WORKING_DIR).digest('hex').slice(0, 8);
148
- const SESSION_ID = `${os.hostname()}-${dirHash}-${crypto.randomBytes(3).toString('hex')}`;
150
+ // PROD-003: minted fresh every run and never reused (see sessionLifecycle.js).
151
+ const SESSION_ID = newSessionId({ hostname: os.hostname(), workingDir: WORKING_DIR });
149
152
 
150
153
  // SETU-005: the real identity a duplicate-session check needs - resolves
151
154
  // symlinks (fs.realpathSync) so two different-looking paths to the SAME
@@ -323,7 +326,19 @@ let outputSeq = 0;
323
326
  // reused here for consistency (one unified "how patient are we before
324
327
  // saying something" policy, not two different numbers to reason about).
325
328
  let pollFocusFailureCount = 0;
329
+ // PROD-003: set when the backend says this session already ended (it was offline
330
+ // longer than the reconnect grace, or was closed). The ID is never revived: the
331
+ // laptop terminal keeps working, but nothing more is sent under it.
332
+ let sessionEndedByServer = false;
333
+ function handleSessionEndedByServer() {
334
+ if (sessionEndedByServer) return;
335
+ sessionEndedByServer = true;
336
+ if (focusTimer) clearInterval(focusTimer);
337
+ log('[supervisor] The backend reports this session has ended (HTTP 410); no further updates will be sent for it.');
338
+ 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 });
339
+ }
326
340
  async function pollFocus() {
341
+ if (sessionEndedByServer) return;
327
342
  try {
328
343
  // detectedCliType (see detectRunningAdapter's own comment, further
329
344
  // down this file) piggybacks on this same already-running poll so
@@ -335,9 +350,10 @@ async function pollFocus() {
335
350
  // incorrectly downgrade a session that started with `--cli claude`
336
351
  // before this poll even has real data to report.
337
352
  const detectedParam = lastDetectedCliType ? `&detectedCliType=${encodeURIComponent(lastDetectedCliType)}` : '';
338
- await fetch(
353
+ const focusRes = await fetch(
339
354
  `${AUTH_SERVER}/terminal/is-focused?sessionId=${encodeURIComponent(SESSION_ID)}${deviceId ? `&deviceId=${encodeURIComponent(deviceId)}` : ''}${detectedParam}`
340
355
  );
356
+ if (isSessionEndedResponse(focusRes)) { handleSessionEndedByServer(); return; }
341
357
  if (pollFocusFailureCount >= WARN_AFTER_ATTEMPTS) {
342
358
  diag.say('[supervisor] Heartbeat to the backend recovered.');
343
359
  log('[supervisor] pollFocus heartbeat recovered after failures');
@@ -437,6 +453,13 @@ async function connectToAzure() {
437
453
  }
438
454
  setTimeout(() => process.exit(1), 1500).unref();
439
455
  };
456
+ // PROD-003: 410 means this session ID already ended (e.g. the laptop was
457
+ // asleep longer than the reconnect grace). Retrying would never help and the ID
458
+ // is never revived, so say so clearly instead of looping.
459
+ if (isSessionEndedResponse(res)) {
460
+ handleSessionEndedByServer();
461
+ return;
462
+ }
440
463
  if (res.status === 403) {
441
464
  diag.say(`[supervisor] Connection rejected: ${err.error || 'the server declined this session.'}`, { error: true, showAtExit: true });
442
465
  log(`[supervisor] /device/connect rejected (403): ${err.error || 'no reason given'}`);
@@ -824,6 +847,7 @@ function flushOutputBuffer() {
824
847
  // immediately and broadcasts to Azure in the background, so this
825
848
  // fetch() itself should resolve quickly regardless of Azure's own cost.
826
849
  sendInFlight = sendInFlight.then(async () => {
850
+ if (sessionEndedByServer) return; // PROD-003: an ended session is never revived
827
851
  // A batch can be far bigger than BATCH_MAX_BYTES (one large chunk from
828
852
  // the terminal), and the realtime provider refuses any single message
829
853
  // over its limit (Ably Free/Standard: 64 KiB). Each piece gets its own
@@ -2138,7 +2162,16 @@ async function main() {
2138
2162
  // of the PTY's own exit code - a plan-limit rejection should exit
2139
2163
  // non-zero even though PowerShell itself was killed cleanly
2140
2164
  // (exitCode 0 from its own perspective).
2141
- process.exit(process.exitCode ?? exitCode ?? 0);
2165
+ const finalCode = process.exitCode ?? exitCode ?? 0;
2166
+ // PROD-003: tell the backend this session is over (shell exited, Ctrl+C or the
2167
+ // window was closed) so the phone drops it now instead of waiting out the
2168
+ // reconnect grace. Bounded to 2s and best effort: it can never keep the
2169
+ // laptop from exiting, and a crash or power loss is still covered by the
2170
+ // backend's own grace expiry.
2171
+ endSessionOnBackend({ fetchImpl: fetch, authServer: AUTH_SERVER, deviceToken, sessionId: SESSION_ID, reason: 'exit' })
2172
+ .then((r) => log(`[supervisor] session-end sent: ${JSON.stringify(r)}`))
2173
+ .catch(() => {})
2174
+ .finally(() => process.exit(finalCode));
2142
2175
  });
2143
2176
 
2144
2177
  // Real feedback: an automatic timer used to run here (every 5 minutes,
@@ -2218,7 +2251,18 @@ async function main() {
2218
2251
  const cleanupAndExit = () => {
2219
2252
  process.exitCode = 0;
2220
2253
  ptyProcess.kill();
2221
- setTimeout(() => process.exit(0), 1500).unref(); // safety net - see onExit's own comment
2254
+ // Safety net - see onExit's own comment. 2026-11-15: on a slow machine the shell can take longer
2255
+ // than this timer to die (the Actions Linux node 20 job lost the end notice once), and onExit is
2256
+ // the only place that tells the backend the session ended. So when the net fires first, send
2257
+ // that notice here (bounded to 2 s, best effort) and only then exit. finishedExiting stops the
2258
+ // notice being sent twice (onExit sets it the moment it runs).
2259
+ setTimeout(() => {
2260
+ if (finishedExiting) return; // onExit is already ending the process, with its own notice
2261
+ finishedExiting = true;
2262
+ endSessionOnBackend({ fetchImpl: fetch, authServer: AUTH_SERVER, deviceToken, sessionId: SESSION_ID, reason: 'exit' })
2263
+ .catch(() => {})
2264
+ .finally(() => process.exit(0));
2265
+ }, 1500).unref();
2222
2266
  };
2223
2267
  process.on('SIGINT', cleanupAndExit);
2224
2268
  process.on('SIGTERM', cleanupAndExit);