@chatpanel/bridge 0.11.20 → 0.11.22

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.11.20",
3
+ "version": "0.11.22",
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 Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
package/src/cli-errors.js CHANGED
@@ -12,6 +12,8 @@
12
12
  // it to DROP the offending server and run again, so the common cases never reach a human at
13
13
  // all. One set of patterns serves both — a second copy would drift.
14
14
 
15
+ import { loginRequired, signInMessage } from './sign-in.js';
16
+
15
17
  const NOISE = [
16
18
  /^\s*$/,
17
19
  /^\s*at\s+/, // stack frames
@@ -108,12 +110,18 @@ function knownCause(text) {
108
110
  return null;
109
111
  }
110
112
 
113
+ const AGENT_IDS = { 'claude code': 'claude', claude: 'claude', codex: 'codex', 'github copilot': 'copilot', copilot: 'copilot', opencode: 'opencode', kiro: 'kiro', hermes: 'hermes', antigravity: 'antigravity', pi: 'pi' };
114
+
111
115
  /**
112
116
  * A short, actionable summary of why a CLI agent exited. Never returns markup, and never more
113
117
  * than a couple of lines — the full output stays in the bridge log for anyone debugging.
118
+ *
119
+ * "Not signed in" comes FIRST and drops the exit code: "Claude Code exited 1" read as a
120
+ * ChatPanel bug, when the whole story was that the user had never run `/login`.
114
121
  */
115
- export function summarizeCliError(label, code, stderr, stdout = '') {
122
+ export function summarizeCliError(label, code, stderr, stdout = '', { agentId = null } = {}) {
116
123
  const raw = `${stderr || ''}\n${stdout || ''}`;
124
+ if (loginRequired(raw)) return signInMessage(label, agentId || AGENT_IDS[String(label).toLowerCase()] || null);
117
125
  const cause = knownCause(raw);
118
126
  if (cause) return `${label} exited ${code}: ${cause}`;
119
127
 
@@ -18,6 +18,7 @@ import { writeFile, unlink } from 'node:fs/promises';
18
18
  import os from 'node:os';
19
19
  import path from 'node:path';
20
20
  import { resolveClaude, buildSpawnSpec, isCompiledBinary, selfMcpStdio } from '../env.js';
21
+ import { signInStatus, signInMessage, loginRequired } from '../sign-in.js';
21
22
  import { buildCliPrompt } from './prompt.js';
22
23
  import { summarizeCliError } from '../cli-errors.js';
23
24
  import { killOnAbort } from '../proc.js';
@@ -146,7 +147,12 @@ export async function available() {
146
147
  cachedOk = false;
147
148
  }
148
149
  }
149
- return cachedOk ? { ok: true } : { ok: false, reason: lastReason };
150
+ if (!cachedOk) return { ok: false, reason: lastReason };
151
+ // Installed is not signed in. `claude auth status` says which, cheaply and before a turn is
152
+ // sent; only a clear "no" counts (sign-in.js), so an old CLI or a slow answer never blocks.
153
+ const signedIn = await signInStatus('claude', resolveClaude()).catch(() => null);
154
+ if (signedIn === false) return { ok: false, signedIn: false, reason: signInMessage('Claude Code', 'claude') };
155
+ return { ok: true };
150
156
  }
151
157
 
152
158
  // Claude Code has no "list models" command — it takes stable aliases (or full
@@ -189,6 +195,7 @@ function runClaude({ prompt, args, cwd, env = null, emit, signal }) {
189
195
  let stdout = '';
190
196
  let stderr = '';
191
197
  let streamedAny = false;
198
+ let apiError = null; // an API-level failure Claude reported as a message (not signed in, …)
192
199
  const flow = { sawText: false, tail: '', boundary: false };
193
200
  let resultText = '';
194
201
 
@@ -219,6 +226,7 @@ function runClaude({ prompt, args, cwd, env = null, emit, signal }) {
219
226
  const r = handleMessage(msg, emit, streamedAny, cwd, flow);
220
227
  if (r.streamed) streamedAny = true;
221
228
  if (r.result != null) resultText = r.result;
229
+ if (r.apiError) apiError = r.apiError;
222
230
  }
223
231
  });
224
232
  child.stderr.on('data', (d) => { armIdle(); stderr += d.toString(); });
@@ -231,8 +239,12 @@ function runClaude({ prompt, args, cwd, env = null, emit, signal }) {
231
239
  clearTimeout(idleTimer);
232
240
  detach();
233
241
  if (signal?.aborted) { resolve({ streamedAny, resultText }); return; } // Stop pressed — end quietly
242
+ // Not signed in arrives as an assistant message flagged `authentication_failed`, then
243
+ // exit 1. Say what to do — never "exited 1", and never the line as if it were the answer.
244
+ if (apiError && loginRequired(apiError)) return reject(new Error(signInMessage('Claude Code', 'claude')));
245
+ if (code === 0 && apiError) return reject(new Error(`Claude Code reported an error: ${apiError}`));
234
246
  if (code === 0) resolve({ streamedAny, resultText });
235
- else reject(new Error(summarizeCliError('Claude Code', code, stderr)));
247
+ else reject(new Error(summarizeCliError('Claude Code', code, stderr, apiError || '', { agentId: 'claude' })));
236
248
  });
237
249
 
238
250
  child.stdin.write(prompt);
@@ -289,6 +301,13 @@ export function handleMessage(msg, emit, alreadyStreamed, cwdForSteps = '', flow
289
301
  }
290
302
  }
291
303
  } else if (msg.type === 'assistant') {
304
+ // An API error Claude Code phrases as an assistant message ("Not logged in · Please run
305
+ // /login", `error: 'authentication_failed'`, `is_api_error_message`). Not an answer: it is
306
+ // held for the close handler, which turns it into an instruction.
307
+ if (msg.is_api_error_message || msg.error) {
308
+ out.apiError = (msg.message?.content || []).filter((b) => b.type === 'text').map((b) => b.text).join('\n') || String(msg.error || 'api error');
309
+ return out;
310
+ }
292
311
  for (const block of msg.message?.content || []) {
293
312
  if (block.type === 'tool_use') {
294
313
  if (flow) flow.boundary = true;
@@ -322,7 +341,10 @@ export function handleMessage(msg, emit, alreadyStreamed, cwdForSteps = '', flow
322
341
  });
323
342
  }
324
343
  } else if (msg.type === 'result') {
325
- if (msg.subtype === 'success') out.result = msg.result || '';
344
+ // `is_error` rides on a `success` result when the API refused (not signed in): the text
345
+ // is the error, not the answer.
346
+ if (msg.is_error) out.apiError = out.apiError || String(msg.result || msg.subtype || 'error');
347
+ else if (msg.subtype === 'success') out.result = msg.result || '';
326
348
  else emit({ type: 'status', text: `(${msg.subtype})` });
327
349
  // Forward token usage so the client can account for CLI-agent turns. The
328
350
  // result message carries cumulative usage (+ a real subscription cost).
@@ -20,11 +20,12 @@ import { readFile, unlink, writeFile } from 'node:fs/promises';
20
20
  import { existsSync, mkdirSync, symlinkSync, readFileSync } from 'node:fs';
21
21
  import os from 'node:os';
22
22
  import path from 'node:path';
23
- import { findAgentBin, selfMcpStdio } from '../env.js';
23
+ import { findAgentBin, selfMcpStdio, resolveCommand } from '../env.js';
24
24
  import { buildCliPrompt } from './prompt.js';
25
25
  import { pushExtraArgs, FORBIDDEN } from './args.js';
26
26
  import { resolveWorkdir } from '../workdir.js';
27
27
  import { summarizeCliError } from '../cli-errors.js';
28
+ import { signInStatus, signInMessage } from '../sign-in.js';
28
29
  import { disabledMcpServers, planMcpRetry, quarantine } from '../mcp-quarantine.js';
29
30
 
30
31
  // Idle timeout: re-armed on every stdout/stderr chunk, so a long run that keeps
@@ -95,9 +96,11 @@ export async function available() {
95
96
  installed = false;
96
97
  }
97
98
  }
98
- return installed
99
- ? { ok: true }
100
- : { ok: false, reason: 'codex not found on PATH. Install it and run `codex login`.' };
99
+ if (!installed) return { ok: false, reason: 'codex not found on PATH. Install it and run `codex login`.' };
100
+ // Installed is not signed in: `codex login status` says which before a turn is sent (sign-in.js).
101
+ const signedIn = await signInStatus('codex', resolveCommand('codex')).catch(() => null);
102
+ if (signedIn === false) return { ok: false, signedIn: false, reason: signInMessage('Codex', 'codex') };
103
+ return { ok: true };
101
104
  }
102
105
 
103
106
  export function codexMcpConfigArgs(mcp) {
@@ -328,7 +331,7 @@ export async function chat({ messages, system, options, images }, emit, { signal
328
331
  }
329
332
 
330
333
  if (signal?.aborted) return; // Stop pressed — end quietly, no error
331
- if (result.code !== 0) throw new Error(summarizeCliError('Codex', result.code, result.stderr));
334
+ if (result.code !== 0) throw new Error(summarizeCliError('Codex', result.code, result.stderr, '', { agentId: 'codex' }));
332
335
  emit({ type: 'delta', text: result.text || '(no output)' });
333
336
  emit({ type: 'done', text: '' });
334
337
  } finally {
package/src/env.js CHANGED
@@ -53,9 +53,14 @@ export function isCompiledBinary() {
53
53
  export function selfMcpStdio(url) {
54
54
  const args = ['--mcp-stdio', url];
55
55
  if (isCompiledBinary()) return { command: process.execPath, args };
56
- // Node/Bun: re-run this same entry script (server.js) under the same runtime.
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".
57
61
  const entry = process.argv[1] || path.join(process.cwd(), 'src', 'server.js');
58
- return { command: process.execPath, args: [entry, ...args] };
62
+ const via = process.env.CHATPANEL_BRIDGE_EMBEDDED === '1' ? ['--bridge'] : [];
63
+ return { command: process.execPath, args: [entry, ...via, ...args] };
59
64
  }
60
65
 
61
66
  // Ask the user's login shell to locate a command — no hardcoded locations, works
package/src/server.js CHANGED
@@ -78,7 +78,7 @@ import {
78
78
  // Hardcoded (not read from package.json) so it survives Bun's single-file
79
79
  // --compile, where package.json isn't on a readable FS. CI fails the publish if
80
80
  // this drifts from package.json, so the two can't silently diverge.
81
- const VERSION = '0.11.20';
81
+ const VERSION = '0.11.22';
82
82
  const HOST = process.env.CHATPANEL_BRIDGE_HOST || '127.0.0.1';
83
83
  const PORT = Number(process.env.CHATPANEL_BRIDGE_PORT) || 4319;
84
84
 
package/src/sign-in.js ADDED
@@ -0,0 +1,91 @@
1
+ // "Not signed in" — the commonest first-run failure, said as an instruction instead of an exit code.
2
+ //
3
+ // A user installs ChatPanel, picks Claude Code or Codex, and sends a message before they have
4
+ // ever signed in to that CLI. The CLI prints one line ("Not logged in · Please run /login"),
5
+ // exits 1, and what reached the panel was "Claude Code exited 1" — which reads as a ChatPanel
6
+ // bug, and says nothing about the one thing that fixes it. Worse, in stream-json mode Claude
7
+ // Code emits that line as an ASSISTANT message, so it could arrive as if it were the answer.
8
+ //
9
+ // Two halves, one vocabulary:
10
+ // • `signInStatus(agentId, spec)` asks the CLI itself, cheaply, BEFORE a turn is sent —
11
+ // `claude auth status` (JSON, `loggedIn`) and `codex login status` (a line) — so the
12
+ // agent's availability says "not signed in: run …" and the panel shows it up front. Only
13
+ // an answer that clearly says "not signed in" counts; an old CLI without the subcommand,
14
+ // a timeout or anything unreadable is taken as signed in, because the turn itself is the
15
+ // final judge and a wrong "not signed in" would block a working agent.
16
+ // • `loginRequired(text)` recognises the failure in a turn's output; `signInMessage` is
17
+ // the sentence both halves say.
18
+ //
19
+ // ChatPanel cannot sign in for the user: the login is the CLI's own OAuth flow, in a browser,
20
+ // started from a terminal. So the message names the exact command and says to send again.
21
+
22
+ import { spawn } from 'node:child_process';
23
+ import { buildSpawnSpec } from './env.js';
24
+
25
+ /** How to sign in, per harness — the command a person types. */
26
+ export const SIGN_IN_HINTS = Object.freeze({
27
+ claude: 'open a terminal, run `claude`, and type `/login`',
28
+ codex: 'open a terminal and run `codex login`',
29
+ copilot: 'open a terminal, run `copilot`, and type `/login`',
30
+ opencode: 'open a terminal and run `opencode auth login`',
31
+ kiro: 'open a terminal and run `kiro-cli login`',
32
+ hermes: 'open a terminal and run `hermes setup`',
33
+ antigravity: 'open a terminal, run `agy`, and sign in',
34
+ deepseek: 'open a terminal and sign in to the DeepSeek CLI',
35
+ pi: 'open a terminal, run `pi`, and sign in',
36
+ });
37
+
38
+ const LOGIN_RE = /not logged in|please run \/login|authentication_failed|invalid api key(?:\s*·\s*please run)?|please (?:log|sign) ?in|login required|not authenticated|unauthenticated|missing bearer token|no credentials|\b401\b.*unauthori[sz]ed|token (?:has )?expired.*(?:log|sign) ?in|run `?(?:codex|claude) login`?/i;
39
+
40
+ /** Does this output say the CLI is not signed in? MCP-server auth failures are a different thing and are excluded. */
41
+ export function loginRequired(text) {
42
+ const t = String(text || '');
43
+ if (!t) return false;
44
+ if (/\bmcp\b/i.test(t) && !/not logged in|please run \/login|authentication_failed/i.test(t)) return false;
45
+ return LOGIN_RE.test(t);
46
+ }
47
+
48
+ /** The one sentence: what happened, that nothing was sent, what to do, and that ChatPanel cannot do it. */
49
+ export function signInMessage(label, agentId) {
50
+ const hint = SIGN_IN_HINTS[agentId] || `sign in to ${label} in your terminal`;
51
+ return `${label} isn't signed in on this machine, so your message was not sent. ChatPanel uses your own ${label} login and can't sign in for you: ${hint}, finish the sign-in in the browser, then send your message again.`;
52
+ }
53
+
54
+ const CHECKS = {
55
+ claude: { args: ['auth', 'status'], read: (out) => { try { const j = JSON.parse(out.slice(out.indexOf('{'))); return typeof j.loggedIn === 'boolean' ? j.loggedIn : null; } catch { return null; } } },
56
+ codex: { args: ['login', 'status'], read: (out) => (/not logged in/i.test(out) ? false : /logged in/i.test(out) ? true : null) },
57
+ };
58
+
59
+ const cache = new Map(); // agentId -> { at, signedIn }
60
+ const TTL_MS = 15_000;
61
+
62
+ /**
63
+ * `true` / `false` when the CLI says so; `null` when it does not have a status command, did
64
+ * not answer in time, or said something unreadable — never a guess. `spec` is the launch spec
65
+ * from resolveCommand (native / script / cmd / wsl), so the check runs the SAME binary a turn
66
+ * would. Cached briefly: /health asks for every agent on every probe.
67
+ */
68
+ export async function signInStatus(agentId, spec, { timeoutMs = 5000, now = Date.now(), spawnImpl = spawn } = {}) {
69
+ const check = CHECKS[agentId];
70
+ if (!check || !spec) return null;
71
+ const hit = cache.get(agentId);
72
+ if (hit && now - hit.at < TTL_MS) return hit.signedIn;
73
+ const result = await new Promise((resolve) => {
74
+ let out = '';
75
+ let child;
76
+ try {
77
+ const [bin, argv, opts] = buildSpawnSpec(spec, check.args, process.cwd(), null);
78
+ child = spawnImpl(bin, argv, { ...opts, stdio: ['ignore', 'pipe', 'pipe'] });
79
+ } catch { return resolve(null); }
80
+ const t = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* gone */ } resolve(null); }, timeoutMs);
81
+ child.stdout?.on('data', (d) => { out += d.toString(); });
82
+ child.stderr?.on('data', (d) => { out += d.toString(); });
83
+ child.on('error', () => { clearTimeout(t); resolve(null); });
84
+ child.on('close', () => { clearTimeout(t); resolve(check.read(out)); });
85
+ });
86
+ cache.set(agentId, { at: now, signedIn: result });
87
+ return result;
88
+ }
89
+
90
+ /** Forget a cached answer — after a sign-in the next probe should ask again. */
91
+ export function resetSignInCache() { cache.clear(); }