@chatpanel/bridge 0.11.24 → 0.11.25

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.
Files changed (62) hide show
  1. package/README.md +7 -7
  2. package/package.json +1 -13
  3. package/scripts/sync-channels.mjs +8 -90
  4. package/scripts/sync-events.mjs +7 -78
  5. package/scripts/sync-pii.mjs +7 -68
  6. package/src/api-compat.js +5 -294
  7. package/src/channels/adapters/telegram.js +3 -298
  8. package/src/channels/bridge.js +1 -59
  9. package/src/channels/eventlog.js +3 -57
  10. package/src/channels/gateway.js +1 -114
  11. package/src/channels/invoke.js +1 -172
  12. package/src/channels/normalize.js +1 -58
  13. package/src/channels/pairing.js +1 -95
  14. package/src/channels/service.js +1 -329
  15. package/src/channels/stream.js +5 -104
  16. package/src/cli-errors.js +3 -136
  17. package/src/connections.js +1 -160
  18. package/src/connectors.js +1 -100
  19. package/src/engines/antigravity.js +5 -235
  20. package/src/engines/args.js +1 -47
  21. package/src/engines/claude.js +6 -586
  22. package/src/engines/cli-agents.js +7 -312
  23. package/src/engines/codex.js +6 -481
  24. package/src/engines/custom.js +17 -577
  25. package/src/engines/prompt.js +6 -32
  26. package/src/engines/stream-formats.js +2 -222
  27. package/src/entitlement.js +1 -77
  28. package/src/env.js +3 -628
  29. package/src/events/capability.js +1 -134
  30. package/src/events/event.js +1 -183
  31. package/src/events/reach.js +1 -31
  32. package/src/events/ref.js +1 -63
  33. package/src/events/scm-connection.js +1 -188
  34. package/src/events/scopes.js +1 -20
  35. package/src/events/skill-manifest.js +1 -338
  36. package/src/events/skill-scan.js +3 -217
  37. package/src/events/view.js +1 -96
  38. package/src/mcp-capabilities.js +2 -139
  39. package/src/mcp-local.js +0 -0
  40. package/src/mcp-quarantine.js +1 -110
  41. package/src/net.js +1 -107
  42. package/src/pii/index.js +1 -29
  43. package/src/pii/net.js +1 -111
  44. package/src/pii/pii-detect.js +2 -296
  45. package/src/pii/pii-redact.js +1 -470
  46. package/src/pii/pipeline.js +1 -137
  47. package/src/pii/sanitize.js +2 -179
  48. package/src/pii/tool-harness.js +1 -184
  49. package/src/pii/tool-rank.js +1 -110
  50. package/src/proc.js +2 -91
  51. package/src/relay-timeout.js +1 -21
  52. package/src/runs.js +1 -49
  53. package/src/sanitize.js +1 -7
  54. package/src/scm.js +1 -76
  55. package/src/server.js +10 -1492
  56. package/src/service.js +11 -176
  57. package/src/sign-in.js +1 -91
  58. package/src/skills.js +1 -399
  59. package/src/ssrf.js +1 -70
  60. package/src/update.js +1 -216
  61. package/src/workdir.js +1 -108
  62. package/src/worktree.js +3 -125
package/src/env.js CHANGED
@@ -1,628 +1,3 @@
1
- // Resolve a usable PATH for spawning the agent CLIs (codex, agy).
2
- //
3
- // When the bridge runs as a login service (LaunchAgent / Scheduled Task) — or as
4
- // a double-clicked app — it inherits a MINIMAL PATH, not your interactive shell's.
5
- // So CLIs installed via Homebrew, npm-global, nvm, etc. aren't found. We fix that
6
- // by (1) asking your login shell for its PATH and (2) adding common bin dirs.
7
-
8
- import os from 'node:os';
9
- import { spawnGroupOpts } from './proc.js';
10
- import path from 'node:path';
11
- import { spawnSync } from 'node:child_process';
12
- import { readdirSync, readFileSync, existsSync } from 'node:fs';
13
-
14
- let enriched = false;
15
- let envEnriched = false;
16
-
17
- // The agent CLIs the bridge shells out to. Claude has its own richer resolution
18
- // (resolveClaude: native / cli.js / WSL / SDK) below.
19
- export const AGENT_CLIS = ['codex', 'claude', 'agy', 'pi', 'opencode', 'kiro-cli', 'copilot', 'dsh'];
20
-
21
- // Is `name` executable somewhere on the current PATH?
22
- function onPath(name) {
23
- const dirs = splitPathList(process.env.PATH || '', process.platform);
24
- return dirs.some((d) => d && (existsSync(path.join(d, name)) || existsSync(path.join(d, name + '.exe'))));
25
- }
26
-
27
- // Resolve an agent CLI to its absolute path: first on the (enriched) PATH, then
28
- // by asking the login shell. Returns the path, or null. Used for availability —
29
- // "is it installed/findable", NOT "does `--version` exit 0" (which can fail for
30
- // reasons unrelated to installation, e.g. the CLI needs login).
31
- export function findAgentBin(name) {
32
- for (const p of commandCandidateFiles(name)) {
33
- if (existsSync(p)) {
34
- return p;
35
- }
36
- }
37
- return shellWhich(name) || null;
38
- }
39
-
40
- // True when running as a Bun/Node single-file compiled binary (not under a
41
- // node/bun interpreter). Inside such a binary, bundled JS files live on a virtual
42
- // FS that child processes can't reach — notably the Claude SDK's CLI on Windows.
43
- export function isCompiledBinary() {
44
- const base = path.basename(process.execPath).toLowerCase();
45
- return !(base.startsWith('node') || base.startsWith('bun'));
46
- }
47
-
48
- // How to re-invoke THIS bridge as a child process running the stdio↔HTTP MCP
49
- // proxy (`--mcp-stdio <url>`). Lets ANY stdio-capable MCP CLI (Codex, a custom
50
- // CLI) reach the bridge's HTTP MCP server using the bridge itself as the server
51
- // command — no extra runtime to install. Compiled binary → the binary; Node →
52
- // node + this entry script. Returns { command, args }.
53
- export function selfMcpStdio(url) {
54
- const args = ['--mcp-stdio', url];
55
- if (isCompiledBinary()) return { command: process.execPath, args };
56
- // Node/Bun: re-run this same entry script under the same runtime. Embedded in the
57
- // gateway (CHATPANEL_BRIDGE_EMBEDDED=1) that script is the GATEWAY's bin, which only
58
- // hands argv to us behind its `--bridge` flag — without it the gateway CLI answers
59
- // "unknown option: --mcp-stdio", the proxy exits 2, and every CLI agent sees the
60
- // per-turn ChatPanel tools as "Connection closed".
61
- const entry = process.argv[1] || path.join(process.cwd(), 'src', 'server.js');
62
- const via = process.env.CHATPANEL_BRIDGE_EMBEDDED === '1' ? ['--bridge'] : [];
63
- return { command: process.execPath, args: [entry, ...via, ...args] };
64
- }
65
-
66
- // Ask the user's login shell to locate a command — no hardcoded locations, works
67
- // wherever the user actually installed it.
68
- function shellWhich(name) {
69
- if (process.platform === 'win32') return '';
70
- try {
71
- const shell = process.env.SHELL || '/bin/zsh';
72
- const r = spawnSync(shell, ['-lc', `command -v ${name} 2>/dev/null`], {
73
- encoding: 'utf8',
74
- timeout: 4000,
75
- });
76
- const out = (r.stdout || '').trim().split('\n').pop().trim();
77
- return out && out.startsWith('/') ? out : '';
78
- } catch {
79
- return '';
80
- }
81
- }
82
-
83
- // ---------------------------------------------------------------------------
84
- // Claude Code launcher resolution.
85
- //
86
- // The Codex/Antigravity engines can assume `spawn('codex', …)` runs a directly
87
- // executable file on the current OS's PATH. Claude needs more care:
88
- // • On Windows, npm installs `claude.cmd` / `claude.ps1` / an extensionless
89
- // bash shim — NONE of which Node's spawn() can execute directly (that's the
90
- // "spawn C:\… ENOENT"). The runnable thing is the package's `cli.js`, which
91
- // we run with our own Node/Bun.
92
- // • A very common setup is "Windows host, `claude` only installed inside WSL."
93
- // A Windows process can't see WSL's filesystem or PATH, so we cross the
94
- // boundary explicitly via `wsl.exe`.
95
- // On macOS/Linux (and WSL-native Node) none of this applies: we return the same
96
- // native binary the old code spawned, so behavior there is unchanged.
97
- //
98
- // Returns one of:
99
- // { kind: 'native', bin } → spawn(bin, args) (directly exec'able)
100
- // { kind: 'script', script } → spawn(process.execPath, [script, ...args])
101
- // { kind: 'cmd', bin } → spawn('cmd.exe', ['/c', bin, ...args])
102
- // { kind: 'wsl' } → spawn('wsl.exe', [wsl prefix, ...args])
103
- // null → not found (caller may fall back to SDK)
104
- //
105
- // We never use spawn's `shell: true` — with an args array it concatenates rather
106
- // than escapes (Node DEP0190 / a real injection surface). The 'script' and 'cmd'
107
- // kinds run the shim safely with a proper argv instead.
108
- export function resolveClaude() {
109
- if (process.env.CHATPANEL_CLAUDE_PATH) return resolveCommand(process.env.CHATPANEL_CLAUDE_PATH);
110
- // The Claude npm package additionally ships a cli.js we prefer; otherwise this
111
- // is the same generic resolution every command uses.
112
- return resolveCommand('claude');
113
- }
114
-
115
- // Resolve ANY command (a bare name like `opencode`, or an absolute/relative path)
116
- // to a launch spec, the same way resolveClaude does — so custom user-onboarded
117
- // agents get identical cross-platform launching (PATH, Windows cli.js/.cmd, WSL).
118
- //
119
- // Returns one of:
120
- // { kind: 'native', bin } → spawn(bin, args)
121
- // { kind: 'script', script } → spawn(process.execPath, [script, ...args])
122
- // { kind: 'cmd', bin } → spawn('cmd.exe', ['/c', bin, ...args])
123
- // { kind: 'wsl', command } → spawn('wsl.exe', [prefix, command, ...args])
124
- // null → not found
125
- //
126
- // We never use spawn's `shell: true` — with an args array it concatenates rather
127
- // than escapes (Node DEP0190 / a real injection surface). The 'script'/'cmd'/'wsl'
128
- // kinds run things safely with a proper argv instead.
129
- export function resolveCommand(command) {
130
- if (!command) return null;
131
- const looksLikePath = command.includes('/') || command.includes('\\') || /\.[a-z0-9]+$/i.test(command);
132
-
133
- if (looksLikePath) {
134
- if (!existsSync(command)) return null; // an explicit path: don't PATH-search
135
- const ext = path.extname(command).toLowerCase();
136
- if (!isCompiledBinary() && /^\.(c?js|mjs)$/.test(ext)) return { kind: 'script', script: command };
137
- if (process.platform === 'win32' && (ext === '.cmd' || ext === '.bat')) return { kind: 'cmd', bin: command };
138
- return { kind: 'native', bin: command };
139
- }
140
-
141
- if (process.platform === 'win32') {
142
- const win = findCommandWindows(command);
143
- if (win) return win;
144
- // Common: tool only installed inside WSL. Only probe safe, simple names.
145
- if (/^[\w.-]+$/.test(command) && commandInWsl(command)) return { kind: 'wsl', command };
146
- return null;
147
- }
148
-
149
- const bin = findAgentBin(command);
150
- return bin ? { kind: 'native', bin } : null;
151
- }
152
-
153
- // Locate a runnable command on Windows. Prefer a runnable JS entry (run with our
154
- // own Node/Bun — clean arg passing, no cmd.exe quoting), then a real .exe, then a
155
- // .cmd/.bat shim launched safely via cmd.exe.
156
- function findCommandWindows(name) {
157
- const p = pathFor('win32');
158
- for (const candidate of commandCandidateFiles(name, os.homedir(), 'win32', process.env)) {
159
- if (!existsSync(candidate)) continue;
160
- const d = p.dirname(candidate);
161
- const ext = p.extname(candidate).toLowerCase();
162
- // Running cli.js with our own interpreter only works under a real Node/Bun,
163
- // not inside a compiled single-file binary (which is not a JS interpreter).
164
- if (!isCompiledBinary()) {
165
- const js = (name === 'claude' && claudeCliJs(d)) || shimTarget(d, name);
166
- if (js) return { kind: 'script', script: js };
167
- if (/^\.(c?js|mjs)$/.test(ext)) return { kind: 'script', script: candidate };
168
- }
169
- if (ext === '.exe' || ext === '') return { kind: 'native', bin: candidate };
170
- if (ext === '.cmd' || ext === '.bat') return { kind: 'cmd', bin: candidate };
171
- }
172
- return null;
173
- }
174
-
175
- // The Claude npm package additionally ships a cli.js we prefer (static guesses
176
- // before parsing the shim).
177
- function claudeCliJs(dir) {
178
- const rels = [
179
- ['node_modules', '@anthropic-ai', 'claude-code', 'cli.js'],
180
- ['..', 'node_modules', '@anthropic-ai', 'claude-code', 'cli.js'],
181
- ['..', 'lib', 'node_modules', '@anthropic-ai', 'claude-code', 'cli.js'],
182
- ];
183
- for (const r of rels) {
184
- const c = path.join(dir, ...r);
185
- if (existsSync(c)) return c;
186
- }
187
- return null;
188
- }
189
-
190
- // Robust, general fallback: every npm/pnpm/yarn/volta shim literally names the JS
191
- // entry it runs, relative to the shim dir (`%dp0%\…\cli.js` in .cmd,
192
- // `$basedir/…/cli.js` in the sh/.ps1 shims). Extract that so any install layout
193
- // resolves to a real JS entry we can run with our own interpreter.
194
- function shimTarget(dir, name) {
195
- for (const shim of [`${name}.cmd`, name, `${name}.ps1`]) {
196
- let txt;
197
- try {
198
- txt = readFileSync(path.join(dir, shim), 'utf8');
199
- } catch {
200
- continue;
201
- }
202
- const m = txt.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);
203
- if (m) {
204
- const abs = path.join(dir, m[1].replace(/[\\/]+/g, path.sep));
205
- if (existsSync(abs)) return abs;
206
- }
207
- }
208
- return null;
209
- }
210
-
211
- // Is `name` reachable inside the default WSL distro's login shell? Cached per
212
- // name; re-probed (throttled) while not found so it self-heals once it appears.
213
- const wslSeen = new Map(); // name -> { ok, at }
214
- function commandInWsl(name) {
215
- const c = wslSeen.get(name);
216
- if (c && (c.ok || Date.now() - c.at < 4000)) return c.ok;
217
- let ok = false;
218
- try {
219
- const r = spawnSync('wsl.exe', ['-e', 'bash', '-lic', `command -v ${name}`], {
220
- encoding: 'utf8',
221
- timeout: 8000,
222
- windowsHide: true,
223
- });
224
- ok = r.status === 0 && /\S/.test(stripBom(r.stdout || ''));
225
- } catch {
226
- ok = false;
227
- }
228
- wslSeen.set(name, { ok, at: Date.now() });
229
- return ok;
230
- }
231
-
232
- // Turn a launch spec + CLI args into a concrete [bin, argv, opts] for spawn().
233
- // `cwd` is the resolved working dir (a Windows path on win32), or null for home.
234
- export function buildSpawnSpec(spec, args, cwd, env = null) {
235
- // `env` is what ONE run adds — a git credential scoped to a host, the pre-push leash
236
- // (connections.js, worktree.js). Merged over the process env, never into it.
237
- const runEnv = env && typeof env === 'object' && Object.keys(env).length ? { ...process.env, ...env } : process.env;
238
- if (spec.kind === 'wsl') {
239
- // Run inside WSL's login shell so nvm/etc. PATH resolves the tool. The
240
- // `exec <cmd> "$@"` + 'chatpanel' ($0) trick passes our args through as a
241
- // proper argv array — no manual quoting, even for multi-line prompts.
242
- const pre = [];
243
- if (cwd) {
244
- const wslCwd = toWslPath(cwd);
245
- if (wslCwd) pre.push('--cd', wslCwd); // else: run in WSL home
246
- }
247
- const argv = [...pre, '-e', 'bash', '-lic', `exec ${spec.command} "$@"`, 'chatpanel', ...args];
248
- return ['wsl.exe', argv, { stdio: ['pipe', 'pipe', 'pipe'], env: runEnv, windowsHide: true, ...spawnGroupOpts }];
249
- }
250
- // Every spawned CLI leads its own process group, so Stop can signal the whole tree. An
251
- // agent CLI is not one process — it runs shell commands and tools of its own — and killing
252
- // only the pid we hold leaves those running after the user has stopped the turn.
253
- const opts = {
254
- cwd: cwd || os.homedir(), stdio: ['pipe', 'pipe', 'pipe'], env: runEnv, windowsHide: true,
255
- ...spawnGroupOpts,
256
- };
257
- if (spec.kind === 'script') return [process.execPath, [spec.script, ...args], opts];
258
- if (spec.kind === 'cmd') return ['cmd.exe', ['/d', '/s', '/c', spec.bin, ...args], opts];
259
- return [spec.bin, args, opts]; // native
260
- }
261
-
262
- // Translate a Windows path to its WSL (/mnt/c/…) equivalent. Returns null on
263
- // failure so the caller can just run in WSL's home instead.
264
- export function toWslPath(winPath) {
265
- try {
266
- const r = spawnSync('wsl.exe', ['-e', 'wslpath', '-a', winPath], {
267
- encoding: 'utf8',
268
- timeout: 5000,
269
- windowsHide: true,
270
- });
271
- const out = stripBom(r.stdout || '').trim();
272
- return out.startsWith('/') ? out : null;
273
- } catch {
274
- return null;
275
- }
276
- }
277
-
278
- function stripBom(s) {
279
- return s.replace(/^/, '').trim();
280
- }
281
-
282
- // Version managers install CLIs under versioned bin dirs that a lazy-loaded
283
- // shell (nvm/fnm) doesn't export into a non-interactive service PATH. Add them.
284
- /**
285
- * The node version nvm would actually give you, and only that one.
286
- *
287
- * WHY THIS EXISTS. PATH discovery asks a LOGIN shell, which never reads .zshrc — and .zshrc
288
- * is where nvm lives. So the learned PATH has no nvm in it, and the hardcoded fallbacks
289
- * below take over. Those start with /opt/homebrew/bin, so a Homebrew copy of an agent CLI
290
- * beat the one the user's terminal uses.
291
- *
292
- * One machine had Claude Code 2.1.268 under nvm and 2.1.175 under Homebrew. Every turn
293
- * through the bridge answered "Claude Code 2.1.175 does not support this model" to a user
294
- * who had just updated Claude Code — twice.
295
- *
296
- * `versionManagerBins` cannot fix that on its own: it lists EVERY installed version, in
297
- * directory order, so preferring it wholesale would pick an arbitrary old node. This picks
298
- * the one nvm itself would: the `default` alias if it names a version, else the highest
299
- * installed. Pure filesystem reads — no shell, so nothing can block startup.
300
- */
301
- export function nvmCurrentBin(home = os.homedir(), env = process.env) {
302
- const root = path.join(env.NVM_DIR || path.join(home, '.nvm'), 'versions', 'node');
303
- let versions;
304
- try {
305
- versions = readdirSync(root).filter((v) => /^v\d+\./.test(v));
306
- } catch {
307
- return null; // no nvm on this machine
308
- }
309
- if (!versions.length) return null;
310
-
311
- const byVersion = (a, b) => {
312
- const pa = a.slice(1).split('.').map(Number);
313
- const pb = b.slice(1).split('.').map(Number);
314
- for (let i = 0; i < 3; i += 1) if ((pa[i] || 0) !== (pb[i] || 0)) return (pb[i] || 0) - (pa[i] || 0);
315
- return 0;
316
- };
317
-
318
- // The `default` alias is what a new shell resolves to. It may name a version directly
319
- // ("24.14.0"), or point at another alias ("lts/*"), which we do not chase — the highest
320
- // installed is a better guess than a wrong one.
321
- try {
322
- const alias = readFileSync(path.join(env.NVM_DIR || path.join(home, '.nvm'), 'alias', 'default'), 'utf8').trim();
323
- const want = alias.startsWith('v') ? alias : `v${alias}`;
324
- if (versions.includes(want)) return path.join(root, want, 'bin');
325
- } catch { /* no alias file — fall through */ }
326
-
327
- return path.join(root, versions.sort(byVersion)[0], 'bin');
328
- }
329
-
330
- function versionManagerBins(home) {
331
- const bins = [];
332
- const tryDir = (dir, sub) => {
333
- try {
334
- for (const v of readdirSync(dir)) bins.push(path.join(dir, v, sub));
335
- } catch {
336
- /* dir absent */
337
- }
338
- };
339
- // nvm: ~/.nvm/versions/node/<v>/bin
340
- tryDir(path.join(process.env.NVM_DIR || path.join(home, '.nvm'), 'versions', 'node'), 'bin');
341
- // fnm: ~/.local/share/fnm/node-versions/<v>/installation/bin (+ macOS app-support)
342
- tryDir(path.join(home, '.local', 'share', 'fnm', 'node-versions'), path.join('installation', 'bin'));
343
- tryDir(path.join(home, 'Library', 'Application Support', 'fnm', 'node-versions'), path.join('installation', 'bin'));
344
- // volta / asdf shims
345
- bins.push(path.join(home, '.volta', 'bin'));
346
- bins.push(path.join(home, '.asdf', 'shims'));
347
- return bins;
348
- }
349
-
350
- function pathFor(platform) {
351
- return platform === 'win32' ? path.win32 : path;
352
- }
353
-
354
- function pathDelimiterFor(platform) {
355
- return platform === 'win32' ? ';' : path.delimiter;
356
- }
357
-
358
- function splitPathList(value, platform) {
359
- return (value || '').split(pathDelimiterFor(platform)).filter(Boolean);
360
- }
361
-
362
- function unique(items) {
363
- return [...new Set(items.filter(Boolean))];
364
- }
365
-
366
- export function agentInstallDirs(home, platform = process.platform, env = process.env) {
367
- const p = pathFor(platform);
368
- if (platform === 'win32') {
369
- const appData = env.APPDATA || p.join(home, 'AppData', 'Roaming');
370
- const localAppData = env.LOCALAPPDATA || p.join(home, 'AppData', 'Local');
371
- const programFiles = env.ProgramFiles || 'C:\\Program Files';
372
- const programFilesX86 = env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
373
- const programData = env.ProgramData || 'C:\\ProgramData';
374
- return [
375
- p.join(home, '.local', 'bin'),
376
- p.join(home, '.codex', 'bin'),
377
- p.join(home, '.claude', 'bin'),
378
- p.join(home, '.claude', 'local'),
379
- p.join(home, '.claude', 'local', 'bin'),
380
- p.join(appData, 'npm'),
381
- p.join(localAppData, 'pnpm'),
382
- p.join(localAppData, 'Yarn', 'bin'),
383
- p.join(localAppData, 'Volta', 'bin'),
384
- p.join(home, '.yarn', 'bin'),
385
- p.join(home, '.bun', 'bin'),
386
- p.join(home, '.deno', 'bin'),
387
- p.join(home, 'scoop', 'shims'),
388
- p.join(programData, 'chocolatey', 'bin'),
389
- p.join(localAppData, 'Microsoft', 'WindowsApps'),
390
- p.join(localAppData, 'Programs', 'Claude Code'),
391
- p.join(localAppData, 'Anthropic', 'Claude Code'),
392
- p.join(programFiles, 'Claude Code'),
393
- p.join(programFiles, 'Anthropic', 'Claude Code'),
394
- p.join(programFilesX86, 'Claude Code'),
395
- p.join(programFilesX86, 'Anthropic', 'Claude Code'),
396
- ];
397
- }
398
- return [
399
- path.join(home, '.local', 'bin'),
400
- path.join(home, '.opencode', 'bin'),
401
- path.join(home, '.codex', 'bin'),
402
- path.join(home, '.claude', 'bin'),
403
- path.join(home, '.claude', 'local'),
404
- path.join(home, '.claude', 'local', 'bin'),
405
- ];
406
- }
407
-
408
- function claudeNativeBins(home, platform = process.platform) {
409
- const p = pathFor(platform);
410
- const versionsDir = p.join(home, '.local', 'share', 'claude', 'versions');
411
- let versions = [];
412
- try {
413
- versions = readdirSync(versionsDir)
414
- .filter((v) => /^\d+\.\d+\.\d+/.test(v))
415
- .sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
416
- } catch {
417
- /* native installer may not be present */
418
- }
419
- return versions.map((v) => p.join(versionsDir, v));
420
- }
421
-
422
- function withWindowsExts(file, platform) {
423
- if (platform !== 'win32') return [file];
424
- if (/\.(cmd|exe|bat|ps1)$/i.test(file)) return [file];
425
- return [file, `${file}.cmd`, `${file}.exe`, `${file}.bat`, `${file}.ps1`];
426
- }
427
-
428
- export function agentCandidateBins(name, home = os.homedir(), platform = process.platform, env = process.env) {
429
- const p = pathFor(platform);
430
- const local = p.join(home, '.local', 'bin', name);
431
- const localAppData = platform === 'win32' ? env.LOCALAPPDATA || p.join(home, 'AppData', 'Local') : null;
432
- const programFiles = platform === 'win32' ? env.ProgramFiles || 'C:\\Program Files' : null;
433
- const programFilesX86 = platform === 'win32' ? env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)' : null;
434
- const map = {
435
- claude: [
436
- local,
437
- p.join(home, '.claude', 'bin', 'claude'),
438
- p.join(home, '.claude', 'local', 'claude'),
439
- p.join(home, '.claude', 'local', 'bin', 'claude'),
440
- ...(platform === 'win32'
441
- ? [
442
- p.join(localAppData, 'Microsoft', 'WindowsApps', 'claude.exe'),
443
- p.join(localAppData, 'Programs', 'Claude Code', 'claude.exe'),
444
- p.join(localAppData, 'Anthropic', 'Claude Code', 'claude.exe'),
445
- p.join(programFiles, 'Claude Code', 'claude.exe'),
446
- p.join(programFiles, 'Anthropic', 'Claude Code', 'claude.exe'),
447
- p.join(programFilesX86, 'Claude Code', 'claude.exe'),
448
- p.join(programFilesX86, 'Anthropic', 'Claude Code', 'claude.exe'),
449
- ...claudeNativeBins(home, platform),
450
- ]
451
- : claudeNativeBins(home, platform)),
452
- ],
453
- codex: [
454
- local,
455
- p.join(home, '.codex', 'bin', 'codex'),
456
- ],
457
- agy: [
458
- local,
459
- '/Applications/Antigravity.app/Contents/MacOS/agy',
460
- '/Applications/Antigravity IDE.app/Contents/MacOS/agy',
461
- ],
462
- pi: [
463
- local,
464
- ],
465
- opencode: [
466
- p.join(home, '.opencode', 'bin', 'opencode'),
467
- local,
468
- ],
469
- 'kiro-cli': [
470
- local,
471
- '/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli',
472
- ],
473
- };
474
- return unique((map[name] || [local]).flatMap((file) => withWindowsExts(file, platform)));
475
- }
476
-
477
- export function commandCandidateFiles(name, home = os.homedir(), platform = process.platform, env = process.env) {
478
- const p = pathFor(platform);
479
- const fromDirs = unique([
480
- ...splitPathList(env.PATH || '', platform),
481
- ...agentInstallDirs(home, platform, env),
482
- ]).flatMap((dir) => withWindowsExts(p.join(dir, name), platform));
483
- return unique([...fromDirs, ...agentCandidateBins(name, home, platform, env)]);
484
- }
485
-
486
- // Agent credentials a LaunchAgent/systemd unit does NOT inherit.
487
- //
488
- // enrichPath() repairs the minimal PATH a service gets; this is the same problem
489
- // one layer up. A CLI that authenticates from a FILE (claude, codex, copilot:
490
- // ~/.copilot) works fine under the service, but one that reads an API key from
491
- // the ENVIRONMENT (dsh -> DEEPSEEK_API_KEY) fails with a missing-credential
492
- // error that looks like a ChatPanel bug — the launchd job's environment is just
493
- // SSH_AUTH_SOCK and a bare PATH.
494
- //
495
- // So: ask the user's login shell for a NARROW allowlist of agent credential
496
- // variables and fill in only the ones we don't already have. These are the
497
- // user's own credentials, on their own machine, handed to CLIs the user
498
- // configured ChatPanel to launch — exactly what would happen had they run the
499
- // CLI from their terminal. Values are never logged, and /debug never dumps the
500
- // environment (it exposes only PATH/home, and only under CHATPANEL_BRIDGE_DEBUG).
501
- const AGENT_ENV_KEYS = [
502
- 'DEEPSEEK_API_KEY', 'DSH_HOME',
503
- 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',
504
- 'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_API_BASE',
505
- 'GEMINI_API_KEY', 'GOOGLE_API_KEY',
506
- 'OPENROUTER_API_KEY', 'GROQ_API_KEY', 'XAI_API_KEY', 'MISTRAL_API_KEY',
507
- ];
508
-
509
- export function enrichAgentEnv() {
510
- if (envEnriched) return;
511
- envEnriched = true;
512
- if (process.platform === 'win32') return; // service env is inherited there
513
-
514
- const missing = AGENT_ENV_KEYS.filter((k) => !process.env[k]);
515
- if (!missing.length) return;
516
- try {
517
- const shell = process.env.SHELL || '/bin/zsh';
518
- // Emit NAME\tVALUE for each var that is actually set; trailing `true` keeps
519
- // the exit status clean when the last test fails.
520
- const script = `${missing
521
- .map((k) => `[ -n "\${${k}:-}" ] && printf '%s\\t%s\\n' ${k} "\$${k}"`)
522
- .join('; ')}; true`;
523
- // -lic, not -lc: these keys are typically exported from ~/.zshrc (or ~/.bashrc),
524
- // which a LOGIN-only shell does NOT source — that's interactive-only. TERM=dumb
525
- // keeps prompt/banner noise down, and the parser below ignores any line that
526
- // isn't a clean NAME<TAB>VALUE, so rc-file chatter is harmless.
527
- const r = spawnSync(shell, ['-lic', script], {
528
- encoding: 'utf8',
529
- timeout: 6000,
530
- env: { ...process.env, TERM: 'dumb' },
531
- });
532
- for (const line of String(r.stdout || '').split('\n')) {
533
- const i = line.indexOf('\t');
534
- if (i <= 0) continue;
535
- const key = line.slice(0, i).trim();
536
- const value = line.slice(i + 1);
537
- if (AGENT_ENV_KEYS.includes(key) && !process.env[key] && value) process.env[key] = value;
538
- }
539
- } catch {
540
- /* no login shell / timeout — agents that need a file-based login still work */
541
- }
542
- }
543
-
544
- export function enrichPath() {
545
- if (enriched) return;
546
- enriched = true;
547
-
548
- const home = os.homedir();
549
- if (process.platform === 'win32') {
550
- const merged = unique([
551
- ...splitPathList(process.env.PATH || '', 'win32'),
552
- ...agentInstallDirs(home, 'win32', process.env),
553
- ]);
554
- process.env.PATH = merged.join(pathDelimiterFor('win32'));
555
- return;
556
- }
557
-
558
- const nvmBin = nvmCurrentBin(home);
559
- const common = [
560
- // BEFORE the package-manager dirs. A version manager PREPENDS itself to PATH in the
561
- // user's shell, so its copy is the one their terminal runs — and the whole purpose of
562
- // this list is to reproduce what the terminal would do.
563
- ...(nvmBin ? [nvmBin] : []),
564
- '/opt/homebrew/bin',
565
- '/opt/homebrew/sbin',
566
- '/usr/local/bin',
567
- '/usr/bin',
568
- '/bin',
569
- '/usr/sbin',
570
- '/sbin',
571
- path.join(home, '.local', 'bin'),
572
- path.join(home, 'bin'),
573
- path.join(home, '.npm-global', 'bin'),
574
- path.join(home, '.cargo', 'bin'),
575
- path.join(home, '.deno', 'bin'),
576
- path.join(home, '.bun', 'bin'),
577
- ...agentInstallDirs(home),
578
- ...versionManagerBins(home),
579
- ];
580
-
581
- // Ask the user's login shell for its PATH — captures nvm / Homebrew / asdf, etc.
582
- let shellPath = '';
583
- try {
584
- const shell = process.env.SHELL || '/bin/zsh';
585
- // `-lc`, NOT `-ilc`, and deliberately: an INTERACTIVE shell can block on a prompt and
586
- // hang the daemon's own startup. tests/env-startup.test.mjs holds that line.
587
- //
588
- // The cost is that a login shell does not read .zshrc/.bashrc, which is where nvm and
589
- // friends install themselves — so this answer arrives WITHOUT the version manager, and
590
- // the merge below has to supply it. See nvmCurrentBin().
591
- const r = spawnSync(shell, ['-lc', 'command -p echo "$PATH"'], {
592
- encoding: 'utf8',
593
- timeout: 4000,
594
- });
595
- if (r.status === 0) shellPath = (r.stdout || '').trim();
596
- } catch {
597
- /* fall back to common dirs below */
598
- }
599
-
600
- const seen = new Set();
601
- const merged = [
602
- // THE VERSION MANAGER GOES FIRST, ahead even of the login shell's own answer.
603
- //
604
- // That looks aggressive until you see why the shell's answer is incomplete: `-lc` never
605
- // reads .zshrc, which is where nvm installs itself, so the PATH we learn is the user's
606
- // MINUS their version manager — while still containing /opt/homebrew/bin from .zprofile.
607
- // Merging it first therefore hands Homebrew the win over a tool the user manages with
608
- // nvm, which is the opposite of what their terminal does: nvm PREPENDS.
609
- //
610
- // So we put it back where nvm would have. `nvmCurrentBin` resolves the one version nvm
611
- // itself would pick, from the filesystem, with no shell to block on.
612
- ...(nvmBin ? [nvmBin] : []),
613
- ...(shellPath ? shellPath.split(':') : []),
614
- ...(process.env.PATH ? process.env.PATH.split(path.delimiter) : []),
615
- ...common,
616
- ].filter((p) => p && !seen.has(p) && (seen.add(p), true));
617
-
618
- process.env.PATH = merged.join(path.delimiter);
619
-
620
- // Final, hardcode-free backstop: if an agent CLI still isn't on PATH, ask the
621
- // login shell exactly where it is and prepend that dir. Covers any custom
622
- // install location (asdf shims, a one-off prefix, etc.).
623
- for (const cli of AGENT_CLIS) {
624
- if (onPath(cli)) continue;
625
- const found = shellWhich(cli);
626
- if (found) process.env.PATH = path.dirname(found) + path.delimiter + process.env.PATH;
627
- }
628
- }
1
+ import d from"node:os";import{spawnGroupOpts as w}from"./proc.js";import s from"node:path";import{spawnSync as f}from"node:child_process";import{readdirSync as A,readFileSync as C,existsSync as p}from"node:fs";let h=!1,x=!1;const $=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function k(n){return P(process.env.PATH||"",process.platform).some(o=>o&&(p(s.join(o,n))||p(s.join(o,n+".exe"))))}function N(n){for(const t of T(n))if(p(t))return t;return g(n)||null}function m(){const n=s.basename(process.execPath).toLowerCase();return!(n.startsWith("node")||n.startsWith("bun"))}function q(n){const t=["--mcp-stdio",n];if(m())return{command:process.execPath,args:t};const o=process.argv[1]||s.join(process.cwd(),"src","server.js"),i=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...i,...t]}}function g(n){if(process.platform==="win32")return"";try{const t=process.env.SHELL||"/bin/zsh",i=(f(t,["-lc",`command -v ${n} 2>/dev/null`],{encoding:"utf8",timeout:4e3}).stdout||"").trim().split(`
2
+ `).pop().trim();return i&&i.startsWith("/")?i:""}catch{return""}}function J(){return process.env.CHATPANEL_CLAUDE_PATH?E(process.env.CHATPANEL_CLAUDE_PATH):E("claude")}function E(n){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!p(n))return null;const i=s.extname(n).toLowerCase();return!m()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:{kind:"native",bin:n}}if(process.platform==="win32"){const i=O(n);return i||(/^[\w.-]+$/.test(n)&&B(n)?{kind:"wsl",command:n}:null)}const o=N(n);return o?{kind:"native",bin:o}:null}function O(n){const t=j("win32");for(const o of T(n,d.homedir(),"win32",process.env)){if(!p(o))continue;const i=t.dirname(o),e=t.extname(o).toLowerCase();if(!m()){const r=n==="claude"&&M(i)||F(i,n);if(r)return{kind:"script",script:r};if(/^\.(c?js|mjs)$/.test(e))return{kind:"script",script:o}}if(e===".exe"||e==="")return{kind:"native",bin:o};if(e===".cmd"||e===".bat")return{kind:"cmd",bin:o}}return null}function M(n){const t=[["node_modules","@anthropic-ai","claude-code","cli.js"],["..","node_modules","@anthropic-ai","claude-code","cli.js"],["..","lib","node_modules","@anthropic-ai","claude-code","cli.js"]];for(const o of t){const i=s.join(n,...o);if(p(i))return i}return null}function F(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let i;try{i=C(s.join(n,o),"utf8")}catch{continue}const e=i.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(e){const r=s.join(n,e[1].replace(/[\\/]+/g,s.sep));if(p(r))return r}}return null}const _=new Map;function B(n){const t=_.get(n);if(t&&(t.ok||Date.now()-t.at<4e3))return t.ok;let o=!1;try{const i=f("wsl.exe",["-e","bash","-lic",`command -v ${n}`],{encoding:"utf8",timeout:8e3,windowsHide:!0});o=i.status===0&&/\S/.test(D(i.stdout||""))}catch{o=!1}return _.set(n,{ok:o,at:Date.now()}),o}function Q(n,t,o,i=null){const e=i&&typeof i=="object"&&Object.keys(i).length?{...process.env,...i}:process.env;if(n.kind==="wsl"){const c=[];if(o){const l=R(o);l&&c.push("--cd",l)}return["wsl.exe",[...c,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:e,windowsHide:!0,...w}]}const r={cwd:o||d.homedir(),stdio:["pipe","pipe","pipe"],env:e,windowsHide:!0,...w};return n.kind==="script"?[process.execPath,[n.script,...t],r]:n.kind==="cmd"?["cmd.exe",["/d","/s","/c",n.bin,...t],r]:[n.bin,t,r]}function R(n){try{const t=f("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=D(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function D(n){return n.replace(/^/,"").trim()}function K(n=d.homedir(),t=process.env){const o=s.join(t.NVM_DIR||s.join(n,".nvm"),"versions","node");let i;try{i=A(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!i.length)return null;const e=(r,c)=>{const a=r.slice(1).split(".").map(Number),l=c.slice(1).split(".").map(Number);for(let u=0;u<3;u+=1)if((a[u]||0)!==(l[u]||0))return(l[u]||0)-(a[u]||0);return 0};try{const r=C(s.join(t.NVM_DIR||s.join(n,".nvm"),"alias","default"),"utf8").trim(),c=r.startsWith("v")?r:`v${r}`;if(i.includes(c))return s.join(o,c,"bin")}catch{}return s.join(o,i.sort(e)[0],"bin")}function W(n){const t=[],o=(i,e)=>{try{for(const r of A(i))t.push(s.join(i,r,e))}catch{}};return o(s.join(process.env.NVM_DIR||s.join(n,".nvm"),"versions","node"),"bin"),o(s.join(n,".local","share","fnm","node-versions"),s.join("installation","bin")),o(s.join(n,"Library","Application Support","fnm","node-versions"),s.join("installation","bin")),t.push(s.join(n,".volta","bin")),t.push(s.join(n,".asdf","shims")),t}function j(n){return n==="win32"?s.win32:s}function y(n){return n==="win32"?";":s.delimiter}function P(n,t){return(n||"").split(y(t)).filter(Boolean)}function b(n){return[...new Set(n.filter(Boolean))]}function v(n,t=process.platform,o=process.env){const i=j(t);if(t==="win32"){const e=o.APPDATA||i.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||i.join(n,"AppData","Local"),c=o.ProgramFiles||"C:\\Program Files",a=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",l=o.ProgramData||"C:\\ProgramData";return[i.join(n,".local","bin"),i.join(n,".codex","bin"),i.join(n,".claude","bin"),i.join(n,".claude","local"),i.join(n,".claude","local","bin"),i.join(e,"npm"),i.join(r,"pnpm"),i.join(r,"Yarn","bin"),i.join(r,"Volta","bin"),i.join(n,".yarn","bin"),i.join(n,".bun","bin"),i.join(n,".deno","bin"),i.join(n,"scoop","shims"),i.join(l,"chocolatey","bin"),i.join(r,"Microsoft","WindowsApps"),i.join(r,"Programs","Claude Code"),i.join(r,"Anthropic","Claude Code"),i.join(c,"Claude Code"),i.join(c,"Anthropic","Claude Code"),i.join(a,"Claude Code"),i.join(a,"Anthropic","Claude Code")]}return[s.join(n,".local","bin"),s.join(n,".opencode","bin"),s.join(n,".codex","bin"),s.join(n,".claude","bin"),s.join(n,".claude","local"),s.join(n,".claude","local","bin")]}function L(n,t=process.platform){const o=j(t),i=o.join(n,".local","share","claude","versions");let e=[];try{e=A(i).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,c)=>c.localeCompare(r,void 0,{numeric:!0}))}catch{}return e.map(r=>o.join(i,r))}function I(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[n,`${n}.cmd`,`${n}.exe`,`${n}.bat`,`${n}.ps1`]}function Y(n,t=d.homedir(),o=process.platform,i=process.env){const e=j(o),r=e.join(t,".local","bin",n),c=o==="win32"?i.LOCALAPPDATA||e.join(t,"AppData","Local"):null,a=o==="win32"?i.ProgramFiles||"C:\\Program Files":null,l=o==="win32"?i["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,u={claude:[r,e.join(t,".claude","bin","claude"),e.join(t,".claude","local","claude"),e.join(t,".claude","local","bin","claude"),...o==="win32"?[e.join(c,"Microsoft","WindowsApps","claude.exe"),e.join(c,"Programs","Claude Code","claude.exe"),e.join(c,"Anthropic","Claude Code","claude.exe"),e.join(a,"Claude Code","claude.exe"),e.join(a,"Anthropic","Claude Code","claude.exe"),e.join(l,"Claude Code","claude.exe"),e.join(l,"Anthropic","Claude Code","claude.exe"),...L(t,o)]:L(t,o)],codex:[r,e.join(t,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[e.join(t,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return b((u[n]||[r]).flatMap(S=>I(S,o)))}function T(n,t=d.homedir(),o=process.platform,i=process.env){const e=j(o),r=b([...P(i.PATH||"",o),...v(t,o,i)]).flatMap(c=>I(e.join(c,n),o));return b([...r,...Y(n,t,o,i)])}const H=["DEEPSEEK_API_KEY","DSH_HOME","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","GEMINI_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"];function Z(){if(x||(x=!0,process.platform==="win32"))return;const n=H.filter(t=>!process.env[t]);if(n.length)try{const t=process.env.SHELL||"/bin/zsh",o=`${n.map(e=>`[ -n "\${${e}:-}" ] && printf '%s\\t%s\\n' ${e} "$${e}"`).join("; ")}; true`,i=f(t,["-lic",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const e of String(i.stdout||"").split(`
3
+ `)){const r=e.indexOf(" ");if(r<=0)continue;const c=e.slice(0,r).trim(),a=e.slice(r+1);H.includes(c)&&!process.env[c]&&a&&(process.env[c]=a)}}catch{}}function nn(){if(h)return;h=!0;const n=d.homedir();if(process.platform==="win32"){const c=b([...P(process.env.PATH||"","win32"),...v(n,"win32",process.env)]);process.env.PATH=c.join(y("win32"));return}const t=K(n),o=[...t?[t]:[],"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",s.join(n,".local","bin"),s.join(n,"bin"),s.join(n,".npm-global","bin"),s.join(n,".cargo","bin"),s.join(n,".deno","bin"),s.join(n,".bun","bin"),...v(n),...W(n)];let i="";try{const c=process.env.SHELL||"/bin/zsh",a=f(c,["-lc",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});a.status===0&&(i=(a.stdout||"").trim())}catch{}const e=new Set,r=[...t?[t]:[],...i?i.split(":"):[],...process.env.PATH?process.env.PATH.split(s.delimiter):[],...o].filter(c=>c&&!e.has(c)&&(e.add(c),!0));process.env.PATH=r.join(s.delimiter);for(const c of $){if(k(c))continue;const a=g(c);a&&(process.env.PATH=s.dirname(a)+s.delimiter+process.env.PATH)}}export{$ as AGENT_CLIS,Y as agentCandidateBins,v as agentInstallDirs,Q as buildSpawnSpec,T as commandCandidateFiles,Z as enrichAgentEnv,nn as enrichPath,N as findAgentBin,m as isCompiledBinary,K as nvmCurrentBin,J as resolveClaude,E as resolveCommand,q as selfMcpStdio,R as toWslPath};