@chatpanel/bridge 0.2.13 → 0.2.14

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": "@chatpanel/bridge",
3
- "version": "0.2.13",
3
+ "version": "0.2.14",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Gemini CLI — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -37,6 +37,9 @@
37
37
  "build:bin": "bash scripts/build-binaries.sh"
38
38
  },
39
39
  "dependencies": {},
40
+ "optionalDependencies": {
41
+ "@anthropic-ai/claude-agent-sdk": "^0.1.0"
42
+ },
40
43
  "publishConfig": {
41
44
  "registry": "https://registry.npmjs.org/",
42
45
  "access": "public"
@@ -1,40 +1,54 @@
1
- // Claude Code engine — drives the Claude Code CLI (`claude --print`) directly,
2
- // the SAME way the Codex engine drives `codex exec`. No Agent SDK, no bundled
3
- // cli.js, no native `sharp` dependency — so it works in any environment that has
4
- // `claude` on PATH (npm install, native installer, or `npx`), and there's nothing
5
- // to resolve inside a compiled binary (the old "/$bunfs/root/cli.js" failure).
1
+ // Claude Code engine — drives the Claude Code CLI (`claude --print`) the SAME
2
+ // way the Codex engine drives `codex exec`, but with cross-platform launching so
3
+ // it works no matter where `claude` lives:
6
4
  //
7
- // It uses your *local* Claude Code login. By default the agent can READ your code
8
- // (Read/Grep/Glob/WebFetch/…) but cannot write or run shell commands unless the
9
- // agent's permissionMode is 'acceptEdits' or 'bypassPermissions' in ChatPanel
10
- // Settings. The working directory comes from the agent config.
5
+ // macOS / Linux / WSL-native Node spawn the native `claude` on PATH.
6
+ // Windows (native install) run the package's cli.js with our own Node/Bun
7
+ // (npm's claude.cmd/.ps1 shims aren't directly spawnable "spawn …ENOENT").
8
+ // Windows host + claude only in WSL — cross the boundary via `wsl.exe`.
9
+ // • Last resort — the in-process Claude Agent SDK (bundled cli.js), if present.
10
+ //
11
+ // Resolution lives in env.js (resolveClaude); set CHATPANEL_CLAUDE_PATH to force
12
+ // a specific executable. It uses your *local* Claude Code login. By default the
13
+ // agent can READ your code but cannot write/run shell unless the agent's
14
+ // permissionMode is 'acceptEdits'/'bypassPermissions' in ChatPanel Settings.
11
15
 
12
16
  import { spawn } from 'node:child_process';
13
17
  import os from 'node:os';
14
18
  import path from 'node:path';
15
- import { findAgentBin } from '../env.js';
19
+ import { resolveClaude, toWslPath, isCompiledBinary } from '../env.js';
16
20
 
17
21
  const TIMEOUT_MS = Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS) || 180_000;
18
22
  // Read-only tools allowed without approval in headless mode; writes/shell are
19
23
  // gated behind the agent's permission mode.
20
24
  const READONLY_TOOLS = ['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'TodoWrite', 'Task'];
21
25
 
22
- let installed = false;
26
+ let lastReason = 'Claude Code not found.';
23
27
  let lastProbe = 0;
28
+ let cachedOk = false;
24
29
  export async function available() {
25
- // Availability = "is claude findable on PATH" (mirrors the codex engine), NOT
26
- // "does `claude --version` exit 0" (which fails when it just needs login).
27
- if (!installed && Date.now() - lastProbe > 4000) {
30
+ // Availability = "can we launch claude somehow" (native / cli.js / WSL / SDK),
31
+ // NOT "does `claude --version` exit 0" (which fails when it just needs login).
32
+ if (!cachedOk && Date.now() - lastProbe > 4000) {
28
33
  lastProbe = Date.now();
29
34
  try {
30
- installed = !!findAgentBin('claude');
35
+ const spec = resolveClaude();
36
+ if (spec) {
37
+ cachedOk = true;
38
+ } else if (!isCompiledBinary() && (await loadSdk())) {
39
+ cachedOk = true;
40
+ } else {
41
+ cachedOk = false;
42
+ lastReason =
43
+ process.platform === 'win32'
44
+ ? 'Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.'
45
+ : 'Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.';
46
+ }
31
47
  } catch {
32
- installed = false;
48
+ cachedOk = false;
33
49
  }
34
50
  }
35
- return installed
36
- ? { ok: true }
37
- : { ok: false, reason: 'Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.' };
51
+ return cachedOk ? { ok: true } : { ok: false, reason: lastReason };
38
52
  }
39
53
 
40
54
  // The bridge is stateless, so we replay the conversation as a single prompt.
@@ -51,15 +65,46 @@ function buildPrompt(messages) {
51
65
  return prompt;
52
66
  }
53
67
 
54
- // Spawn `claude` and stream its stream-json output, forwarding events via `emit`.
55
- // `extraArgs` lets complete() run a tool-free single shot. Resolves with the final
56
- // result text once the process closes 0.
68
+ // Turn a launch spec + the claude CLI args into a concrete [bin, argv, options]
69
+ // for spawn(). `cwd` is the resolved working dir (Windows path on win32), or null
70
+ // to use the home directory.
71
+ function buildSpawn(spec, args, cwd) {
72
+ if (spec.kind === 'wsl') {
73
+ // Run claude inside WSL's login shell so nvm/etc. PATH resolves it. The
74
+ // `'exec claude "$@"'` + 'chatpanel' ($0) trick passes our args through as a
75
+ // proper argv array — no manual quoting, even for multi-line system prompts.
76
+ const pre = [];
77
+ if (cwd) {
78
+ const wslCwd = toWslPath(cwd);
79
+ if (wslCwd) pre.push('--cd', wslCwd); // else: run in WSL home
80
+ }
81
+ const argv = [...pre, '-e', 'bash', '-lic', 'exec claude "$@"', 'chatpanel', ...args];
82
+ return ['wsl.exe', argv, { stdio: ['pipe', 'pipe', 'pipe'], env: process.env, windowsHide: true }];
83
+ }
84
+
85
+ const spawnCwd = cwd || os.homedir();
86
+ const opts = { cwd: spawnCwd, stdio: ['pipe', 'pipe', 'pipe'], env: process.env, windowsHide: true };
87
+ if (spec.kind === 'script') {
88
+ // Run cli.js with the interpreter already running the bridge (node/bun).
89
+ return [process.execPath, [spec.script, ...args], opts];
90
+ }
91
+ // kind === 'native' — direct executable (.exe / mac+linux binary), or a .cmd
92
+ // shim via the shell on Windows.
93
+ return [spec.bin, args, { ...opts, shell: !!spec.shell }];
94
+ }
95
+
96
+ // Spawn claude (however it resolves) and stream its stream-json output via
97
+ // `emit`. Resolves with { streamedAny, resultText } once it closes 0. Returns
98
+ // null (no spawn) when claude can't be resolved, so the caller can fall back.
57
99
  function runClaude({ prompt, args, cwd, emit }) {
58
- const bin = findAgentBin('claude') || 'claude';
100
+ const spec = resolveClaude();
101
+ if (!spec) return null;
102
+ const [bin, argv, opts] = buildSpawn(spec, args, cwd);
103
+
59
104
  return new Promise((resolve, reject) => {
60
105
  let child;
61
106
  try {
62
- child = spawn(bin, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'], env: process.env });
107
+ child = spawn(bin, argv, opts);
63
108
  } catch (e) {
64
109
  return reject(new Error(`Failed to start claude: ${e.message}`));
65
110
  }
@@ -95,7 +140,7 @@ function runClaude({ prompt, args, cwd, emit }) {
95
140
  child.stderr.on('data', (d) => (stderr += d.toString()));
96
141
  child.on('error', (e) => {
97
142
  clearTimeout(timer);
98
- reject(e);
143
+ reject(new Error(`Failed to start claude (${bin}): ${e.message}`));
99
144
  });
100
145
  child.on('close', (code) => {
101
146
  clearTimeout(timer);
@@ -140,7 +185,8 @@ function handleMessage(msg, emit, alreadyStreamed) {
140
185
 
141
186
  export async function chat({ messages, system, options }, emit) {
142
187
  const permissionMode = options.permissionMode || 'default';
143
- const cwd = options.workingDir ? path.resolve(options.workingDir) : os.homedir();
188
+ // Explicit project dir, else null → CLI runs in home (or WSL home).
189
+ const cwd = options.workingDir ? path.resolve(options.workingDir) : null;
144
190
 
145
191
  const args = ['--print', '--output-format', 'stream-json', '--include-partial-messages', '--verbose'];
146
192
 
@@ -158,7 +204,9 @@ export async function chat({ messages, system, options }, emit) {
158
204
  // "Use my local skills & config" off → run clean.
159
205
  if (options.useLocalConfig === false) args.push('--setting-sources', '');
160
206
 
161
- const { streamedAny, resultText } = await runClaude({ prompt: buildPrompt(messages), args, cwd, emit });
207
+ const run = runClaude({ prompt: buildPrompt(messages), args, cwd, emit });
208
+ if (run === null) return sdkChat({ messages, system, options }, emit); // no CLI → SDK
209
+ const { streamedAny, resultText } = await run;
162
210
  emit({ type: 'done', text: streamedAny ? '' : resultText });
163
211
  }
164
212
 
@@ -175,14 +223,16 @@ export async function complete({ prompt, system, model }) {
175
223
  '--system-prompt', system || "Continue the user's text briefly. Reply with only the continuation.",
176
224
  ];
177
225
  let text = '';
178
- const { resultText } = await runClaude({
226
+ const run = runClaude({
179
227
  prompt,
180
228
  args,
181
- cwd: os.homedir(),
229
+ cwd: null,
182
230
  emit: (e) => {
183
231
  if (e.type === 'delta') text += e.text;
184
232
  },
185
233
  });
234
+ if (run === null) return sdkComplete({ prompt, system, model }); // no CLI → SDK
235
+ const { resultText } = await run;
186
236
  return (text || resultText || '').trim();
187
237
  }
188
238
 
@@ -194,3 +244,82 @@ function toolSummary(block) {
194
244
  if (i.url) return i.url;
195
245
  return '';
196
246
  }
247
+
248
+ // ---------------------------------------------------------------------------
249
+ // Fallback: in-process Claude Agent SDK. Only reached when no native/WSL claude
250
+ // CLI is resolvable (and we're not a compiled binary, where its bundled cli.js
251
+ // is unreachable). The SDK ships its own cli.js and uses your ~/.claude login.
252
+
253
+ let sdkPromise = null;
254
+ function loadSdk() {
255
+ // Optional dependency — absent in lean/compiled installs; import().catch makes
256
+ // that a graceful "no fallback available" rather than a crash.
257
+ if (!sdkPromise) sdkPromise = import('@anthropic-ai/claude-agent-sdk').catch(() => null);
258
+ return sdkPromise;
259
+ }
260
+
261
+ async function sdkChat({ messages, system, options }, emit) {
262
+ const sdk = await loadSdk();
263
+ if (!sdk) throw new Error(lastReason);
264
+ const { query } = sdk;
265
+
266
+ const permissionMode = options.permissionMode || 'default';
267
+ const cwd = options.workingDir ? path.resolve(options.workingDir) : os.homedir();
268
+ const writesAllowed = permissionMode === 'acceptEdits' || permissionMode === 'bypassPermissions';
269
+ const readonly = new Set(READONLY_TOOLS);
270
+ const canUseTool = async (toolName) =>
271
+ readonly.has(toolName) || writesAllowed
272
+ ? { behavior: 'allow', updatedInput: undefined }
273
+ : { behavior: 'deny', message: `${toolName} blocked — set this agent's permission mode in ChatPanel to enable it.` };
274
+
275
+ let streamedAny = false;
276
+ let resultText = '';
277
+ const iterator = query({
278
+ prompt: buildPrompt(messages),
279
+ options: {
280
+ cwd,
281
+ permissionMode,
282
+ includePartialMessages: true,
283
+ canUseTool,
284
+ settingSources: options.useLocalConfig === false ? [] : ['user', 'project'],
285
+ systemPrompt: system
286
+ ? { type: 'preset', preset: 'claude_code', append: system }
287
+ : { type: 'preset', preset: 'claude_code' },
288
+ ...(options.model ? { model: options.model } : {}),
289
+ ...(process.env.CHATPANEL_MAX_TURNS ? { maxTurns: Number(process.env.CHATPANEL_MAX_TURNS) } : {}),
290
+ },
291
+ });
292
+ for await (const message of iterator) {
293
+ const r = handleMessage(message, emit, streamedAny);
294
+ if (r.streamed) streamedAny = true;
295
+ if (r.result != null) resultText = r.result;
296
+ }
297
+ emit({ type: 'done', text: streamedAny ? '' : resultText });
298
+ }
299
+
300
+ async function sdkComplete({ prompt, system, model }) {
301
+ const sdk = await loadSdk();
302
+ if (!sdk) throw new Error(lastReason);
303
+ const { query } = sdk;
304
+ let text = '';
305
+ const iterator = query({
306
+ prompt,
307
+ options: {
308
+ cwd: os.homedir(),
309
+ permissionMode: 'default',
310
+ allowedTools: [],
311
+ maxTurns: 1,
312
+ settingSources: [],
313
+ systemPrompt: system || "Continue the user's text briefly. Reply with only the continuation.",
314
+ model: model || 'haiku',
315
+ },
316
+ });
317
+ for await (const message of iterator) {
318
+ if (message.type === 'assistant') {
319
+ for (const block of message.message.content) if (block.type === 'text') text += block.text;
320
+ } else if (message.type === 'result' && message.subtype === 'success' && !text) {
321
+ text = message.result || '';
322
+ }
323
+ }
324
+ return text.trim();
325
+ }
package/src/env.js CHANGED
@@ -12,8 +12,9 @@ import { readdirSync, existsSync } from 'node:fs';
12
12
 
13
13
  let enriched = false;
14
14
 
15
- // The agent CLIs the bridge shells out to (Claude is the in-process SDK).
16
- const AGENT_CLIS = ['codex', 'gemini'];
15
+ // The agent CLIs the bridge shells out to. Claude has its own richer resolution
16
+ // (resolveClaude: native / cli.js / WSL / SDK) below.
17
+ const AGENT_CLIS = ['codex', 'gemini', 'claude'];
17
18
 
18
19
  // Is `name` executable somewhere on the current PATH?
19
20
  function onPath(name) {
@@ -64,6 +65,125 @@ function shellWhich(name) {
64
65
  }
65
66
  }
66
67
 
68
+ // ---------------------------------------------------------------------------
69
+ // Claude Code launcher resolution.
70
+ //
71
+ // The Codex/Gemini engines can assume `spawn('codex', …)` runs a directly
72
+ // executable file on the current OS's PATH. Claude needs more care:
73
+ // • On Windows, npm installs `claude.cmd` / `claude.ps1` / an extensionless
74
+ // bash shim — NONE of which Node's spawn() can execute directly (that's the
75
+ // "spawn C:\… ENOENT"). The runnable thing is the package's `cli.js`, which
76
+ // we run with our own Node/Bun.
77
+ // • A very common setup is "Windows host, `claude` only installed inside WSL."
78
+ // A Windows process can't see WSL's filesystem or PATH, so we cross the
79
+ // boundary explicitly via `wsl.exe`.
80
+ // On macOS/Linux (and WSL-native Node) none of this applies: we return the same
81
+ // native binary the old code spawned, so behavior there is unchanged.
82
+ //
83
+ // Returns one of:
84
+ // { kind: 'native', bin, shell } → spawn(bin, args, { shell })
85
+ // { kind: 'script', script } → spawn(process.execPath, [script, ...args])
86
+ // { kind: 'wsl' } → spawn('wsl.exe', [wsl prefix, ...args])
87
+ // null → not found (caller may fall back to SDK)
88
+ export function resolveClaude() {
89
+ const override = process.env.CHATPANEL_CLAUDE_PATH;
90
+ if (override) {
91
+ const ext = path.extname(override).toLowerCase();
92
+ if (!isCompiledBinary() && /\.(c?js|mjs)$/.test(ext)) return { kind: 'script', script: override };
93
+ return { kind: 'native', bin: override, shell: process.platform === 'win32' && (ext === '.cmd' || ext === '.bat') };
94
+ }
95
+
96
+ if (process.platform === 'win32') {
97
+ const win = findClaudeWindows();
98
+ if (win) return win;
99
+ if (claudeInWsl()) return { kind: 'wsl' };
100
+ return null;
101
+ }
102
+
103
+ // macOS / Linux / WSL-native: same resolution the engine used before.
104
+ const bin = findAgentBin('claude');
105
+ return bin ? { kind: 'native', bin, shell: false } : null;
106
+ }
107
+
108
+ // Locate a runnable Claude Code on Windows. Prefer the package's cli.js (run
109
+ // with our own Node/Bun — clean arg passing, no cmd.exe quoting), then a real
110
+ // .exe, then a .cmd shim via the shell as a last resort.
111
+ function findClaudeWindows() {
112
+ const dirs = (process.env.PATH || '').split(path.delimiter);
113
+ for (const d of dirs) {
114
+ if (!d) continue;
115
+ const hasShim = ['claude', 'claude.cmd', 'claude.exe', 'claude.ps1', 'claude.bat'].some((n) =>
116
+ existsSync(path.join(d, n)),
117
+ );
118
+ if (!hasShim) continue;
119
+ // Running cli.js with our own interpreter only works under a real Node/Bun,
120
+ // not inside a compiled single-file binary (which is not a JS interpreter).
121
+ if (!isCompiledBinary()) {
122
+ const js = claudeCliJs(d);
123
+ if (js) return { kind: 'script', script: js };
124
+ }
125
+ if (existsSync(path.join(d, 'claude.exe'))) return { kind: 'native', bin: path.join(d, 'claude.exe'), shell: false };
126
+ if (existsSync(path.join(d, 'claude.cmd'))) return { kind: 'native', bin: path.join(d, 'claude.cmd'), shell: true };
127
+ if (existsSync(path.join(d, 'claude.bat'))) return { kind: 'native', bin: path.join(d, 'claude.bat'), shell: true };
128
+ }
129
+ return null;
130
+ }
131
+
132
+ // The npm shim sits next to (or one level up from) the claude-code package.
133
+ function claudeCliJs(dir) {
134
+ const rels = [
135
+ ['node_modules', '@anthropic-ai', 'claude-code', 'cli.js'],
136
+ ['..', 'node_modules', '@anthropic-ai', 'claude-code', 'cli.js'],
137
+ ['..', 'lib', 'node_modules', '@anthropic-ai', 'claude-code', 'cli.js'],
138
+ ];
139
+ for (const r of rels) {
140
+ const c = path.join(dir, ...r);
141
+ if (existsSync(c)) return c;
142
+ }
143
+ return null;
144
+ }
145
+
146
+ // Is `claude` reachable inside the default WSL distro's login shell? Cached;
147
+ // re-probed (throttled) while not found so it self-heals once WSL/claude appear.
148
+ let wslClaude = null;
149
+ let wslProbe = 0;
150
+ function claudeInWsl() {
151
+ if (wslClaude === null || (!wslClaude && Date.now() - wslProbe > 4000)) {
152
+ wslProbe = Date.now();
153
+ try {
154
+ const r = spawnSync('wsl.exe', ['-e', 'bash', '-lic', 'command -v claude'], {
155
+ encoding: 'utf8',
156
+ timeout: 8000,
157
+ windowsHide: true,
158
+ });
159
+ wslClaude = r.status === 0 && /\S/.test(stripBom(r.stdout || ''));
160
+ } catch {
161
+ wslClaude = false;
162
+ }
163
+ }
164
+ return wslClaude;
165
+ }
166
+
167
+ // Translate a Windows path to its WSL (/mnt/c/…) equivalent. Returns null on
168
+ // failure so the caller can just run in WSL's home instead.
169
+ export function toWslPath(winPath) {
170
+ try {
171
+ const r = spawnSync('wsl.exe', ['-e', 'wslpath', '-a', winPath], {
172
+ encoding: 'utf8',
173
+ timeout: 5000,
174
+ windowsHide: true,
175
+ });
176
+ const out = stripBom(r.stdout || '').trim();
177
+ return out.startsWith('/') ? out : null;
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+
183
+ function stripBom(s) {
184
+ return s.replace(/^/, '').trim();
185
+ }
186
+
67
187
  // Version managers install CLIs under versioned bin dirs that a lazy-loaded
68
188
  // shell (nvm/fnm) doesn't export into a non-interactive service PATH. Add them.
69
189
  function versionManagerBins(home) {