cli-setu 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -40
- package/bin/setu.js +172 -149
- package/package.json +4 -1
- package/src/approvalRelay.js +73 -0
- package/src/cli-adapters/claude.js +400 -302
- package/src/cli-adapters/index.js +28 -27
- package/src/cli-adapters/shell.js +96 -88
- package/src/dedup.js +35 -0
- package/src/diagnostics.js +35 -0
- package/src/gitDiff.js +200 -0
- package/src/pair.js +162 -131
- package/src/providerProtocol.js +155 -0
- package/src/reconnect.js +94 -0
- package/src/sharedKey.js +40 -0
- package/src/status.js +1 -1
- package/src/stdinForwarder.js +33 -0
- package/src/supervisor.js +2234 -1369
- package/src/transportSplit.js +72 -0
|
@@ -1,27 +1,28 @@
|
|
|
1
|
-
// One place supervisor.js asks "which adapter for this CLI name" -
|
|
2
|
-
// unrecognized names fall through to the generic PTY-only adapter
|
|
3
|
-
// (see generic.js) rather than erroring out, since "not yet integrated"
|
|
4
|
-
// should never mean "can't run this CLI through the bridge at all."
|
|
5
|
-
const claude = require('./claude');
|
|
6
|
-
const codex = require('./codex');
|
|
7
|
-
const shell = require('./shell');
|
|
8
|
-
const makeGeneric = require('./generic');
|
|
9
|
-
|
|
10
|
-
const KNOWN_ADAPTERS = {
|
|
11
|
-
claude,
|
|
12
|
-
codex,
|
|
13
|
-
shell,
|
|
14
|
-
};
|
|
15
|
-
|
|
16
|
-
// Real product decision (confirmed directly by the PM):
|
|
17
|
-
// no --cli flag bridges the user's own plain terminal, not Claude
|
|
18
|
-
// specifically - the user decides what to run once it's open.
|
|
19
|
-
// to 'claude' here silently assumed every user wanted an AI
|
|
20
|
-
// the instant they typed `cli-setu`, which isn't
|
|
21
|
-
// intent (a genuine remote terminal, not an
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
1
|
+
// One place supervisor.js asks "which adapter for this CLI name" -
|
|
2
|
+
// unrecognized names fall through to the generic PTY-only adapter
|
|
3
|
+
// (see generic.js) rather than erroring out, since "not yet integrated"
|
|
4
|
+
// should never mean "can't run this CLI through the bridge at all."
|
|
5
|
+
const claude = require('./claude');
|
|
6
|
+
const codex = require('./codex');
|
|
7
|
+
const shell = require('./shell');
|
|
8
|
+
const makeGeneric = require('./generic');
|
|
9
|
+
|
|
10
|
+
const KNOWN_ADAPTERS = {
|
|
11
|
+
claude,
|
|
12
|
+
codex,
|
|
13
|
+
shell,
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// Real product decision (confirmed directly by the PM): `cli-setu session`
|
|
17
|
+
// with no --cli flag bridges the user's own plain terminal, not Claude
|
|
18
|
+
// Code specifically - the user decides what to run once it's open.
|
|
19
|
+
// Defaulting to 'claude' here silently assumed every user wanted an AI
|
|
20
|
+
// CLI running the instant they typed `cli-setu session`, which isn't
|
|
21
|
+
// actually the product's real intent (a genuine remote terminal, not an
|
|
22
|
+
// AI-agent-only bridge).
|
|
23
|
+
function getAdapter(cliName) {
|
|
24
|
+
const normalized = (cliName || 'shell').toLowerCase();
|
|
25
|
+
return KNOWN_ADAPTERS[normalized] || makeGeneric(cliName);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
module.exports = { getAdapter, KNOWN_ADAPTERS };
|
|
@@ -1,88 +1,96 @@
|
|
|
1
|
-
// The default adapter when a user runs plain `cli-setu` with no --cli flag at
|
|
2
|
-
// all - a real gap in the earlier design: `cli-setu` (bare) always launched
|
|
3
|
-
// Claude Code specifically, silently assuming that's what every user
|
|
4
|
-
// wants. The actual product intent (confirmed directly by the PM) is
|
|
5
|
-
// simpler and more honest: `cli-setu` bridges the user's OWN real terminal to
|
|
6
|
-
// their phone - a genuine remote shell, nothing AI-specific - and the
|
|
7
|
-
// user decides what to run inside it once it's open (`claude`, `codex`,
|
|
8
|
-
// `npm install`, `git status`, anything). Running an AI CLI inside this
|
|
9
|
-
// bridged shell still gets real approval detection IF that CLI has its
|
|
10
|
-
// own adapter (this adapter itself has none - see approvals: null below)
|
|
11
|
-
// - detection is about what's actually running inside the PTY moment to
|
|
12
|
-
// moment, not about which adapter spawned the shell around it.
|
|
13
|
-
const os = require('os');
|
|
14
|
-
const fs = require('fs');
|
|
15
|
-
|
|
16
|
-
// Real bug found by testing (PM report, multiple real macOS users hit
|
|
17
|
-
// this): node-pty's spawn() throws synchronously with an opaque native
|
|
18
|
-
// "posix_spawnp failed" error - and nothing ever caught it - whenever
|
|
19
|
-
// $SHELL points at a path that doesn't actually exist or isn't
|
|
20
|
-
// executable anymore (a shell installed via Homebrew/nvm/asdf that was
|
|
21
|
-
// later upgraded, moved, or uninstalled; a stale value left over from a
|
|
22
|
-
// deleted user profile; a corporate-managed Mac with $SHELL pointing at
|
|
23
|
-
// something sandboxed). This crashed the ENTIRE supervisor process on
|
|
24
|
-
// startup with no actionable message - "not able to start any session"
|
|
25
|
-
// was the only thing the user could see. Validating the path exists AND
|
|
26
|
-
// is actually a regular file before trusting it, falling back through a
|
|
27
|
-
// short list of real, almost-always-present POSIX shells, means a
|
|
28
|
-
// broken $SHELL no longer takes down the whole bridge - it just quietly
|
|
29
|
-
// uses a working shell instead, same as if $SHELL had never been set at
|
|
30
|
-
// all.
|
|
31
|
-
function isExecutableFile(path) {
|
|
32
|
-
try {
|
|
33
|
-
return fs.statSync(path).isFile();
|
|
34
|
-
} catch {
|
|
35
|
-
return false;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function resolveShellCommand() {
|
|
40
|
-
if (process.platform === 'win32') {
|
|
41
|
-
// Real users' machines vary here - PowerShell is the modern Windows
|
|
42
|
-
// default (present on every Windows 10/11 install), but COMSPEC
|
|
43
|
-
// (usually cmd.exe) is what Windows itself considers "the" shell for
|
|
44
|
-
// a process that doesn't ask for anything more specific. Preferring
|
|
45
|
-
// PowerShell when it's genuinely on PATH, falling back to COMSPEC
|
|
46
|
-
// (or a bare cmd.exe) otherwise, covers both cases without assuming
|
|
47
|
-
// one specific install layout the way a hardcoded path would.
|
|
48
|
-
return 'powershell.exe';
|
|
49
|
-
}
|
|
50
|
-
// SHELL is the real, standard POSIX convention for "the user's own
|
|
51
|
-
// configured shell" (bash, zsh, fish, ...) - respecting it here means
|
|
52
|
-
// this bridges whatever shell the user already actually uses day to
|
|
53
|
-
// day, not a hardcoded assumption that might not even be installed.
|
|
54
|
-
// Only trusted if it actually resolves to a real file on disk right
|
|
55
|
-
// now - see isExecutableFile's own comment for why this check exists.
|
|
56
|
-
if (process.env.SHELL && isExecutableFile(process.env.SHELL)) {
|
|
57
|
-
return process.env.SHELL;
|
|
58
|
-
}
|
|
59
|
-
for (const candidate of ['/bin/zsh', '/bin/bash', '/bin/sh']) {
|
|
60
|
-
if (isExecutableFile(candidate)) return candidate;
|
|
61
|
-
}
|
|
62
|
-
// Every one of those is a standard part of macOS/Linux and should
|
|
63
|
-
// never actually be missing - this is a last-resort value, not an
|
|
64
|
-
// expected path, kept only so spawn() still gets SOME string instead
|
|
65
|
-
// of undefined.
|
|
66
|
-
return '/bin/sh';
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
module.exports = {
|
|
70
|
-
id: 'shell',
|
|
71
|
-
displayName: os.platform() === 'win32' ? 'PowerShell' : 'Shell',
|
|
72
|
-
icon: { name: 'terminal-outline', color: '#7C8B99' },
|
|
73
|
-
spawn: {
|
|
74
|
-
command: resolveShellCommand(),
|
|
75
|
-
args: () => [],
|
|
76
|
-
},
|
|
77
|
-
// No structured Confirmations card - a plain shell has no permission-
|
|
78
|
-
// prompt concept of its own to detect. If the user launches an AI CLI
|
|
79
|
-
// INSIDE this shell, that CLI's own real adapter (claude.js/codex.js)
|
|
80
|
-
// still isn't active here, since supervisor.js picks exactly one
|
|
81
|
-
// adapter per process/session at startup - a real user wanting
|
|
82
|
-
// structured approvals for a specific CLI should run `cli-setu
|
|
83
|
-
// claude` (or codex) directly, same as always. This adapter is
|
|
84
|
-
// specifically for "just give me my terminal, I'll decide what to run."
|
|
85
|
-
approvals: null,
|
|
86
|
-
usage: null,
|
|
87
|
-
|
|
88
|
-
|
|
1
|
+
// The default adapter when a user runs plain `cli-setu` with no --cli flag at
|
|
2
|
+
// all - a real gap in the earlier design: `cli-setu` (bare) always launched
|
|
3
|
+
// Claude Code specifically, silently assuming that's what every user
|
|
4
|
+
// wants. The actual product intent (confirmed directly by the PM) is
|
|
5
|
+
// simpler and more honest: `cli-setu` bridges the user's OWN real terminal to
|
|
6
|
+
// their phone - a genuine remote shell, nothing AI-specific - and the
|
|
7
|
+
// user decides what to run inside it once it's open (`claude`, `codex`,
|
|
8
|
+
// `npm install`, `git status`, anything). Running an AI CLI inside this
|
|
9
|
+
// bridged shell still gets real approval detection IF that CLI has its
|
|
10
|
+
// own adapter (this adapter itself has none - see approvals: null below)
|
|
11
|
+
// - detection is about what's actually running inside the PTY moment to
|
|
12
|
+
// moment, not about which adapter spawned the shell around it.
|
|
13
|
+
const os = require('os');
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
|
|
16
|
+
// Real bug found by testing (PM report, multiple real macOS users hit
|
|
17
|
+
// this): node-pty's spawn() throws synchronously with an opaque native
|
|
18
|
+
// "posix_spawnp failed" error - and nothing ever caught it - whenever
|
|
19
|
+
// $SHELL points at a path that doesn't actually exist or isn't
|
|
20
|
+
// executable anymore (a shell installed via Homebrew/nvm/asdf that was
|
|
21
|
+
// later upgraded, moved, or uninstalled; a stale value left over from a
|
|
22
|
+
// deleted user profile; a corporate-managed Mac with $SHELL pointing at
|
|
23
|
+
// something sandboxed). This crashed the ENTIRE supervisor process on
|
|
24
|
+
// startup with no actionable message - "not able to start any session"
|
|
25
|
+
// was the only thing the user could see. Validating the path exists AND
|
|
26
|
+
// is actually a regular file before trusting it, falling back through a
|
|
27
|
+
// short list of real, almost-always-present POSIX shells, means a
|
|
28
|
+
// broken $SHELL no longer takes down the whole bridge - it just quietly
|
|
29
|
+
// uses a working shell instead, same as if $SHELL had never been set at
|
|
30
|
+
// all.
|
|
31
|
+
function isExecutableFile(path) {
|
|
32
|
+
try {
|
|
33
|
+
return fs.statSync(path).isFile();
|
|
34
|
+
} catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function resolveShellCommand() {
|
|
40
|
+
if (process.platform === 'win32') {
|
|
41
|
+
// Real users' machines vary here - PowerShell is the modern Windows
|
|
42
|
+
// default (present on every Windows 10/11 install), but COMSPEC
|
|
43
|
+
// (usually cmd.exe) is what Windows itself considers "the" shell for
|
|
44
|
+
// a process that doesn't ask for anything more specific. Preferring
|
|
45
|
+
// PowerShell when it's genuinely on PATH, falling back to COMSPEC
|
|
46
|
+
// (or a bare cmd.exe) otherwise, covers both cases without assuming
|
|
47
|
+
// one specific install layout the way a hardcoded path would.
|
|
48
|
+
return 'powershell.exe';
|
|
49
|
+
}
|
|
50
|
+
// SHELL is the real, standard POSIX convention for "the user's own
|
|
51
|
+
// configured shell" (bash, zsh, fish, ...) - respecting it here means
|
|
52
|
+
// this bridges whatever shell the user already actually uses day to
|
|
53
|
+
// day, not a hardcoded assumption that might not even be installed.
|
|
54
|
+
// Only trusted if it actually resolves to a real file on disk right
|
|
55
|
+
// now - see isExecutableFile's own comment for why this check exists.
|
|
56
|
+
if (process.env.SHELL && isExecutableFile(process.env.SHELL)) {
|
|
57
|
+
return process.env.SHELL;
|
|
58
|
+
}
|
|
59
|
+
for (const candidate of ['/bin/zsh', '/bin/bash', '/bin/sh']) {
|
|
60
|
+
if (isExecutableFile(candidate)) return candidate;
|
|
61
|
+
}
|
|
62
|
+
// Every one of those is a standard part of macOS/Linux and should
|
|
63
|
+
// never actually be missing - this is a last-resort value, not an
|
|
64
|
+
// expected path, kept only so spawn() still gets SOME string instead
|
|
65
|
+
// of undefined.
|
|
66
|
+
return '/bin/sh';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = {
|
|
70
|
+
id: 'shell',
|
|
71
|
+
displayName: os.platform() === 'win32' ? 'PowerShell' : 'Shell',
|
|
72
|
+
icon: { name: 'terminal-outline', color: '#7C8B99' },
|
|
73
|
+
spawn: {
|
|
74
|
+
command: resolveShellCommand(),
|
|
75
|
+
args: () => [],
|
|
76
|
+
},
|
|
77
|
+
// No structured Confirmations card - a plain shell has no permission-
|
|
78
|
+
// prompt concept of its own to detect. If the user launches an AI CLI
|
|
79
|
+
// INSIDE this shell, that CLI's own real adapter (claude.js/codex.js)
|
|
80
|
+
// still isn't active here, since supervisor.js picks exactly one
|
|
81
|
+
// adapter per process/session at startup - a real user wanting
|
|
82
|
+
// structured approvals for a specific CLI should run `cli-setu session
|
|
83
|
+
// --cli claude` (or codex) directly, same as always. This adapter is
|
|
84
|
+
// specifically for "just give me my terminal, I'll decide what to run."
|
|
85
|
+
approvals: null,
|
|
86
|
+
usage: null,
|
|
87
|
+
// SETU-012: a one-tap way to launch Claude Code from a plain bridged
|
|
88
|
+
// shell - ties directly into supervisor.js's own detectRunningAdapter
|
|
89
|
+
// (SETU-006): tapping this sends the literal `claude` command into the
|
|
90
|
+
// real PTY, the live process-tree detector picks up the new child
|
|
91
|
+
// process within its own poll interval, and the phone's Usage button
|
|
92
|
+
// appears automatically, same as if the user had typed it by hand.
|
|
93
|
+
// Keystroke format matches claude.js/codex.js's own commands (`\r`, the
|
|
94
|
+
// same Enter sequence this adapter's own PTY already expects).
|
|
95
|
+
commands: [{ id: 'launch-claude', label: 'Open Claude', keystrokes: 'claude\r' }],
|
|
96
|
+
};
|
package/src/dedup.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Bounded FIFO dedup cache for inbound relay messages - used by
|
|
2
|
+
// supervisor.js to make sure a terminal.input message delivered twice
|
|
3
|
+
// (e.g. the phone retries because it didn't see an ack in time, or a
|
|
4
|
+
// provider redelivers during a reconnect) is never executed twice.
|
|
5
|
+
//
|
|
6
|
+
// Extracted out of supervisor.js into its own module (same pattern as
|
|
7
|
+
// reconnect.js) specifically so this logic can be unit-tested in
|
|
8
|
+
// isolation - it was previously a module-level Set + function inline in
|
|
9
|
+
// supervisor.js, which works fine at runtime but can't be imported by a
|
|
10
|
+
// test script on its own.
|
|
11
|
+
//
|
|
12
|
+
// Bounded by COUNT, not just a TTL - a pure time-based cache risks
|
|
13
|
+
// unbounded growth under a burst of distinct messages within one
|
|
14
|
+
// window; capping the actual entry count is the harder guarantee. FIFO
|
|
15
|
+
// eviction (insertion order, which a plain Set already preserves) is
|
|
16
|
+
// the right policy here: a message genuinely re-delivered after the
|
|
17
|
+
// window has passed is already long gone from any receiver's retry
|
|
18
|
+
// buffer anyway, so losing the OLDEST entries first costs nothing real.
|
|
19
|
+
function createDedupCache({ maxSize = 200 } = {}) {
|
|
20
|
+
const seen = new Set();
|
|
21
|
+
|
|
22
|
+
function isDuplicate(messageId) {
|
|
23
|
+
if (!messageId) return false; // no ID at all (older server build) - can't dedup, don't block it
|
|
24
|
+
if (seen.has(messageId)) return true;
|
|
25
|
+
seen.add(messageId);
|
|
26
|
+
if (seen.size > maxSize) {
|
|
27
|
+
seen.delete(seen.values().next().value); // oldest (first-inserted)
|
|
28
|
+
}
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return { isDuplicate, size: () => seen.size };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = { createDedupCache };
|
|
@@ -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 };
|