@chatpanel/bridge 0.11.23 → 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 -463
  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
@@ -1,203 +1,18 @@
1
- // Custom ("bring your own") engine — runs ANY CLI the user onboards from the
2
- // extension's Agents settings (opencode, pi, ollama, a shell script, …) WITHOUT
3
- // a bridge code change per tool. The command spec travels in the chat request's
4
- // `options.custom`; this engine resolves the command cross-platform (PATH /
5
- // Windows cli.js+.cmd / WSL — same launcher as Claude), pipes the prompt in, and
6
- // streams output back.
7
- //
8
- // Custom agents require a valid entitlement token, verified offline here (no network).
9
- //
10
- // Output formats:
11
- // 'text' (default) — stream stdout straight through as text deltas. Works for
12
- // any program that prints a reply.
13
- // 'claude-stream-json' — parse Claude Code-style stream-json (for tools that
14
- // speak it), reusing the Claude engine's parser.
15
-
16
- import { spawn } from 'node:child_process';
17
- import { readFile, writeFile, unlink } from 'node:fs/promises';
18
- import os from 'node:os';
19
- import path from 'node:path';
20
- import { resolveCommand, buildSpawnSpec, selfMcpStdio } from '../env.js';
21
- import { isProEntitled } from '../entitlement.js';
22
- import { killOnAbort } from '../proc.js';
23
- import { buildCliPrompt } from './prompt.js';
24
- import { pushExtraArgs, FORBIDDEN } from './args.js';
25
- import { createStreamParser, STREAM_FORMATS, stripAnsi } from './stream-formats.js';
26
- import { resolveWorkdir } from '../workdir.js';
27
-
28
- // Write base64 data-URL images to temp files so a custom CLI can take them via
29
- // its configured `imageArg` template (e.g. "-i {path}", "@{path}"). Returns paths.
30
- async function writeImages(images, tag) {
31
- const files = [];
32
- for (let i = 0; i < (images?.length || 0); i++) {
33
- const m = /^data:([^;]+);base64,(.+)$/s.exec(images[i]?.dataUrl || '');
34
- if (!m) continue;
35
- const ext = (m[1].split('/')[1] || 'png').replace(/[^a-z0-9]/gi, '').slice(0, 5) || 'png';
36
- const file = path.join(os.tmpdir(), `chatpanel-custom-img-${tag}-${i}.${ext}`);
37
- await writeFile(file, Buffer.from(m[2], 'base64'));
38
- files.push(file);
39
- }
40
- return files;
41
- }
42
-
43
- // Expand the user's `imageArg` template across the image files into argv tokens.
44
- // "{path}" is substituted per image; a template without it appends the path.
45
- function imageTokensFor(imageArg, files) {
46
- const tmpl = String(imageArg || '').trim();
47
- if (!tmpl || !files.length) return [];
48
- const tokens = [];
49
- for (const f of files) {
50
- tokens.push(
51
- ...(tmpl.includes('{path}')
52
- ? tmpl.replaceAll('{path}', f).split(/\s+/).filter(Boolean)
53
- : [...tmpl.split(/\s+/).filter(Boolean), f]),
54
- );
55
- }
56
- return tokens;
57
- }
58
-
59
- // Idle timeout: re-armed on every stdout/stderr chunk, so a long run that keeps
60
- // streaming never trips it — only true silence does. Override with
61
- // CHATPANEL_CUSTOM_TIMEOUT_MS (ms).
62
- const IDLE_MS = Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS) || 180_000;
63
-
64
- // ANSI stripping moved to stream-formats.js (imported above), which is where
65
- // text output is actually rendered - one implementation for every format.
66
- const OPENCODE_STABLE_MCP_URL = 'http://127.0.0.1:4319/mcp';
67
- export const CHATPANEL_STABLE_MCP_URL = 'http://127.0.0.1:4319/mcp';
68
-
69
- export async function available() {
70
- // The engine ships in every bridge; individual custom agents are user-defined
71
- // (Pro) and validated per request and via /agent-check.
72
- return { ok: true };
73
- }
74
-
75
- // Parse a CLI's "list models" stdout into model ids. Tools format this very
76
- // differently (one-per-line, a table, "provider/model", …), so this is
77
- // best-effort: take the first token of each line that looks like an id and skip
78
- // obvious headers/prose. The picker always allows a custom value as a fallback.
79
- function parseModelList(stdout) {
80
- const out = [];
81
- const seen = new Set();
82
- for (const raw of String(stdout || '').split('\n')) {
83
- const tok = raw.trim().split(/\s+/)[0] || '';
84
- if (!/^[A-Za-z0-9][\w./:-]{1,79}$/.test(tok)) continue;
85
- if (/^(name|model|models|id|provider|available|usage|options|commands)$/i.test(tok)) continue;
86
- if (seen.has(tok)) continue;
87
- seen.add(tok);
88
- out.push(tok);
89
- if (out.length >= 200) break;
90
- }
91
- return out;
92
- }
93
-
94
- // Unified model listing: run the agent's CONFIGURED list-models invocation
95
- // (e.g. pi `--list-models`, opencode `models`) and parse the output. Returns []
96
- // when not configured. Requires Pro (runs the user's CLI).
97
- export async function listModels(options = {}) {
98
- if (!(await isProEntitled(options.entitlement))) {
99
- throw new Error('Custom agents require ChatPanel Pro.');
100
- }
101
- const spec = options.custom || {};
102
- return listSpecModels(spec.command, spec.listModelsArgs, options.workingDir);
103
- }
104
-
105
- // Shared model listing: run a CLI's list-models invocation and parse it. Used by
106
- // the custom engine and the built-in CLI agents.
107
- export async function listSpecModels(command, listModelsArgs, workingDir) {
108
- const listArgs = String(listModelsArgs || '').trim();
109
- if (!command || !listArgs) return [];
110
- const stdout = await runForStdout(command, listArgs.split(/\s+/).filter(Boolean), workingDir);
111
- return parseModelList(stdout);
112
- }
113
-
114
- // Run a CLI to completion and return its stdout. Shared by every "ask the CLI
115
- // something" path (model listing and the per-agent listModels overrides) so the
116
- // spawn/resolve/timeout handling exists once.
117
- export async function runForStdout(command, argvIn, workingDir, timeoutMs = 20000) {
118
- if (!command) return '';
119
- const resolved = resolveCommand(command);
120
- if (!resolved) throw new Error(`Couldn't find "${command}".`);
121
- const cwd = workingDir ? path.resolve(workingDir) : null;
122
- const [bin, argv, opts] = buildSpawnSpec(resolved, argvIn, cwd);
123
- opts.env = { ...(opts.env || process.env), NO_COLOR: '1', CLICOLOR: '0' };
124
- return new Promise((resolve, reject) => {
125
- let child;
126
- try { child = spawn(bin, argv, opts); } catch (e) { return reject(new Error(`Failed to start ${command}: ${e.message}`)); }
127
- let out = '';
128
- const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error(`${command} timed out.`)); }, timeoutMs);
129
- child.stdout.on('data', (d) => (out += d.toString()));
130
- child.on('error', (e) => { clearTimeout(timer); reject(new Error(`Failed to start ${command}: ${e.message}`)); });
131
- child.on('close', () => { clearTimeout(timer); resolve(out); });
132
- try { child.stdin.end(); } catch { /* some CLIs don't read stdin */ }
133
- });
134
- }
135
-
136
- function mcpToolSpecs(mcp) {
137
- return (mcp?.specs || []).filter((s) => s?.name);
138
- }
139
-
140
- function jsIdentifier(name, index) {
141
- const id = String(name).replace(/[^A-Za-z0-9_$]/g, '_');
142
- return /^[A-Za-z_$]/.test(id) ? id : `tool_${index}_${id}`;
143
- }
144
-
145
- export function piToolArgs(extensionFile, mcp) {
146
- return ['--extension', extensionFile];
147
- }
148
-
149
- export function trustToolArgs(template, mcp) {
150
- const tmpl = String(template || '').trim();
151
- const names = mcpToolSpecs(mcp).map((s) => s.name).filter(Boolean);
152
- if (!tmpl || !names.length) return [];
153
- const value = names.join(',');
154
- return tmpl.includes('{tools}')
155
- ? tmpl.replaceAll('{tools}', value).split(/\s+/).filter(Boolean)
156
- : [...tmpl.split(/\s+/).filter(Boolean), value];
157
- }
158
-
159
- export function mcpTrustArgs(spec = {}, mcp) {
160
- if (spec.trustAllToolsForMcp) return [spec.trustAllToolsArg || '--trust-all-tools'];
161
- return spec.trustToolsArg ? trustToolArgs(spec.trustToolsArg, mcp) : [];
162
- }
163
-
164
- export function stableMcpSetupCommand(spec = {}) {
165
- if (spec.stableMcpSetupCommand) return spec.stableMcpSetupCommand;
166
- return `opencode mcp add chatpanel --url ${CHATPANEL_STABLE_MCP_URL}`;
167
- }
168
-
169
- export function stableMcpSetupPlan(spec = {}) {
170
- // A FUNCTION is allowed as well as an array: a stdio registration has to name the bridge's
171
- // own executable, which is only known at runtime (compiled binary vs. node + entry script).
172
- const raw = typeof spec.stableMcpSetupArgs === 'function' ? spec.stableMcpSetupArgs() : spec.stableMcpSetupArgs;
173
- const args = Array.isArray(raw) ? raw.filter((a) => a != null).map(String) : null;
174
- if (!args?.length) return null;
175
- return { command: spec.stableMcpSetupCommandName || spec.command, args };
176
- }
177
-
178
- export function buildPiExtensionSource(mcp) {
179
- const specs = mcpToolSpecs(mcp);
180
- const declarations = specs.map((spec, index) => {
181
- const id = jsIdentifier(spec.name, index);
182
- const schema = spec.parameters || { type: 'object', properties: {} };
183
- return `const ${id}Tool = {
184
- name: ${JSON.stringify(spec.name)},
185
- label: ${JSON.stringify(spec.name)},
186
- description: ${JSON.stringify(spec.description || spec.name)},
187
- parameters: ${JSON.stringify(schema)},
1
+ import{spawn as O}from"node:child_process";import{readFile as G,writeFile as P,unlink as K}from"node:fs/promises";import A from"node:os";import C from"node:path";import{resolveCommand as L,buildSpawnSpec as _,selfMcpStdio as Z}from"../env.js";import{isProEntitled as R}from"../entitlement.js";import{killOnAbort as q}from"../proc.js";import{buildCliPrompt as V}from"./prompt.js";import{pushExtraArgs as W,FORBIDDEN as B}from"./args.js";import{createStreamParser as X,STREAM_FORMATS as Q}from"./stream-formats.js";import{resolveWorkdir as Y}from"../workdir.js";async function tt(t,n){const e=[];for(let r=0;r<(t?.length||0);r++){const o=/^data:([^;]+);base64,(.+)$/s.exec(t[r]?.dataUrl||"");if(!o)continue;const i=(o[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",d=C.join(A.tmpdir(),`chatpanel-custom-img-${n}-${r}.${i}`);await P(d,Buffer.from(o[2],"base64")),e.push(d)}return e}function et(t,n){const e=String(t||"").trim();if(!e||!n.length)return[];const r=[];for(const o of n)r.push(...e.includes("{path}")?e.replaceAll("{path}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]);return r}const j=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,rt="http://127.0.0.1:4319/mcp",F="http://127.0.0.1:4319/mcp";async function vt(){return{ok:!0}}function nt(t){const n=[],e=new Set;for(const r of String(t||"").split(`
2
+ `)){const o=r.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available|usage|options|commands)$/i.test(o)&&!e.has(o)&&(e.add(o),n.push(o),n.length>=200))break}return n}async function It(t={}){if(!await R(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return ot(n.command,n.listModelsArgs,t.workingDir)}async function ot(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await it(t,r.split(/\s+/).filter(Boolean),e);return nt(o)}async function it(t,n,e,r=2e4){if(!t)return"";const o=L(t);if(!o)throw new Error(`Couldn't find "${t}".`);const i=e?C.resolve(e):null,[d,u,a]=_(o,n,i);return a.env={...a.env||process.env,NO_COLOR:"1",CLICOLOR:"0"},new Promise((f,l)=>{let h;try{h=O(d,u,a)}catch(S){return l(new Error(`Failed to start ${t}: ${S.message}`))}let m="";const c=setTimeout(()=>{h.kill("SIGKILL"),l(new Error(`${t} timed out.`))},r);h.stdout.on("data",S=>m+=S.toString()),h.on("error",S=>{clearTimeout(c),l(new Error(`Failed to start ${t}: ${S.message}`))}),h.on("close",()=>{clearTimeout(c),f(m)});try{h.stdin.end()}catch{}})}function U(t){return(t?.specs||[]).filter(n=>n?.name)}function D(t,n){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${n}_${e}`}function st(t,n){return["--extension",t]}function at(t,n){const e=String(t||"").trim(),r=U(n).map(i=>i.name).filter(Boolean);if(!e||!r.length)return[];const o=r.join(",");return e.includes("{tools}")?e.replaceAll("{tools}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]}function lt(t={},n){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?at(t.trustToolsArg,n):[]}function ct(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${F}`}function mt(t={}){const n=typeof t.stableMcpSetupArgs=="function"?t.stableMcpSetupArgs():t.stableMcpSetupArgs,e=Array.isArray(n)?n.filter(r=>r!=null).map(String):null;return e?.length?{command:t.stableMcpSetupCommandName||t.command,args:e}:null}function ut(t){const n=U(t),e=n.map((o,i)=>{const d=D(o.name,i),u=o.parameters||{type:"object",properties:{}};return`const ${d}Tool = {
3
+ name: ${JSON.stringify(o.name)},
4
+ label: ${JSON.stringify(o.name)},
5
+ description: ${JSON.stringify(o.description||o.name)},
6
+ parameters: ${JSON.stringify(u)},
188
7
  async execute(toolCallId, params, signal) {
189
- return callMcpTool(${JSON.stringify(spec.name)}, toolCallId, params, signal);
8
+ return callMcpTool(${JSON.stringify(o.name)}, toolCallId, params, signal);
190
9
  },
191
- };`;
192
- }).join('\n\n');
193
- const registrations = specs.map((spec, index) => {
194
- const id = jsIdentifier(spec.name, index);
195
- return ` pi.registerTool(${id}Tool);`;
196
- }).join('\n');
10
+ };`}).join(`
197
11
 
198
- return `import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
+ `),r=n.map((o,i)=>` pi.registerTool(${D(o.name,i)}Tool);`).join(`
13
+ `);return`import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
199
14
 
200
- const MCP_URL = ${JSON.stringify(mcp.url)};
15
+ const MCP_URL = ${JSON.stringify(t.url)};
201
16
 
202
17
  function contentFromDataUrl(dataUrl) {
203
18
  const match = /^data:([^;]+);base64,(.+)$/s.exec(String(dataUrl || ""));
@@ -245,387 +60,12 @@ async function callMcpTool(toolName, toolCallId, params, signal) {
245
60
  };
246
61
  }
247
62
 
248
- ${declarations}
63
+ ${e}
249
64
 
250
65
  export default function (pi: ExtensionAPI) {
251
- ${registrations}
252
- }
253
- `;
254
- }
255
-
256
- async function writePiExtension(mcp, tag) {
257
- const file = path.join(os.tmpdir(), `chatpanel-pi-tools-${tag}.ts`);
258
- await writeFile(file, buildPiExtensionSource(mcp));
259
- return file;
260
- }
261
-
262
- async function opencodeHasStableMcpConfig() {
263
- const configHome = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
264
- const files = [
265
- path.join(configHome, 'opencode', 'opencode.jsonc'),
266
- path.join(os.homedir(), 'Library', 'Application Support', 'opencode', 'opencode.jsonc'),
267
- ];
268
- for (const file of files) {
269
- try {
270
- const text = await readFile(file, 'utf8');
271
- if (text.includes(OPENCODE_STABLE_MCP_URL)) return true;
272
- } catch {
273
- /* missing config is fine */
274
- }
275
- }
276
- return false;
277
- }
278
-
279
- export async function commandOutput(command, args, cwd) {
280
- const resolved = resolveCommand(command);
281
- if (!resolved) return '';
282
- const [bin, argv, opts] = buildSpawnSpec(resolved, args, cwd || null);
283
- return new Promise((resolve) => {
284
- const child = spawn(bin, argv, opts);
285
- let out = '';
286
- let err = '';
287
- const timer = setTimeout(() => {
288
- child.kill('SIGKILL');
289
- resolve(out + err);
290
- }, 4000);
291
- child.stdout.on('data', (d) => (out += d.toString()));
292
- child.stderr.on('data', (d) => (err += d.toString()));
293
- child.on('error', () => {
294
- clearTimeout(timer);
295
- resolve(out + err);
296
- });
297
- child.on('close', () => {
298
- clearTimeout(timer);
299
- resolve(out + err);
300
- });
301
- try { child.stdin.end(); } catch { /* ignore */ }
302
- });
303
- }
304
-
305
- async function kiroHasStableMcpConfig(command, cwd) {
306
- for (const scope of ['workspace', 'global', 'default']) {
307
- const out = await commandOutput(command, ['mcp', 'list', scope], cwd);
308
- if (out.includes(CHATPANEL_STABLE_MCP_URL) || /chatpanel_browser/i.test(out)) return true;
309
- }
310
- return false;
311
- }
312
-
313
- // Hermes keeps MCP servers in its own config; `hermes mcp list` is the one honest way to ask
314
- // whether ours is already registered (no scopes, unlike kiro).
315
- async function hermesHasStableMcpConfig(command, cwd) {
316
- const out = await commandOutput(command, ['mcp', 'list'], cwd);
317
- return out.includes(CHATPANEL_STABLE_MCP_URL) || /chatpanel_browser/i.test(out);
318
- }
319
-
320
- async function hasStableMcpConfig(spec, cwd) {
321
- if (spec.stableMcpConfigCheck === 'kiro') return kiroHasStableMcpConfig(spec.command || 'kiro-cli', cwd);
322
- if (spec.stableMcpConfigCheck === 'opencode') return opencodeHasStableMcpConfig();
323
- if (spec.stableMcpConfigCheck === 'hermes') return hermesHasStableMcpConfig(spec.command || 'hermes', cwd);
324
- return false;
325
- }
326
-
327
- async function runStableMcpSetup(plan, cwd) {
328
- const resolved = resolveCommand(plan.command);
329
- if (!resolved) throw new Error(`Couldn't find "${plan.command}" to set up browser tools.`);
330
- const [bin, argv, opts] = buildSpawnSpec(resolved, plan.args, cwd || null);
331
- opts.env = { ...(opts.env || process.env), NO_COLOR: '1', FORCE_COLOR: '0', CLICOLOR: '0', TERM: 'dumb' };
332
- await new Promise((resolve, reject) => {
333
- let child;
334
- try { child = spawn(bin, argv, opts); } catch (e) { return reject(new Error(`Failed to start ${plan.command}: ${e.message}`)); }
335
- let stderr = '';
336
- // The CLI often reports WHY it couldn't register on stdout while still exiting 0 (Hermes
337
- // prints "requires the 'mcp' Python SDK" and saves nothing). Capturing it is what lets
338
- // the caller turn a silent no-op into an actionable message.
339
- let stdout = '';
340
- const timer = setTimeout(() => {
341
- child.kill('SIGKILL');
342
- reject(new Error(`${plan.command} MCP setup timed out.`));
343
- }, 20_000);
344
- child.stderr.on('data', (d) => (stderr += d.toString()));
345
- child.stdout?.on('data', (d) => (stdout += d.toString()));
346
- child.on('error', (e) => {
347
- clearTimeout(timer);
348
- reject(new Error(`Failed to start ${plan.command}: ${e.message}`));
349
- });
350
- child.on('close', (code) => {
351
- clearTimeout(timer);
352
- if (code === 0) return resolve(`${stdout}\n${stderr}`.trim());
353
- reject(new Error(`${plan.command} MCP setup exited ${code}: ${stderr.trim().split('\n').pop() || 'failed'}`));
354
- });
355
- try { child.stdin.end(); } catch { /* ignore */ }
356
- });
357
- }
358
-
359
- // Turn a browser-tool setup failure into something the user can act on. The CLI's own words
360
- // are the most accurate signal available, so we forward them — but when they name a missing
361
- // SDK we say the fix, rather than repeating an `mcp add` that will fail identically.
362
- export function mcpSetupHint(label, err) {
363
- const msg = String(err?.message || err || '');
364
- if (/mcp['" ]* Python SDK|No module named ['"]?mcp|MCP support/i.test(msg)) {
365
- return `${label} has no MCP support installed. Run \`hermes setup\` (or install the \`mcp\` package in its environment), then retry.`;
366
- }
367
- if (/streamable_http|HTTP transport/i.test(msg)) {
368
- return `${label}'s MCP client has no HTTP transport; ChatPanel registers a stdio server instead. Upgrade its \`mcp\` package if this persists.`;
369
- }
370
- return msg.slice(0, 200) || 'the CLI could not register the tools';
371
- }
372
-
373
- export async function ensureStableMcpConfig(spec, cwd, label, emit, deps = {}) {
374
- if (!spec.requiresStableMcp) return true;
375
- const hasConfig = deps.hasConfig || hasStableMcpConfig;
376
- const runSetup = deps.runSetup || runStableMcpSetup;
377
- if (await hasConfig(spec, cwd)) return true;
378
-
379
- const setupCommand = stableMcpSetupCommand(spec);
380
- if (!spec.autoSetupStableMcp) {
381
- const text = `${label} needs one-time browser-tool setup: ${setupCommand}`;
382
- emit({ type: 'status', text });
383
- throw new Error(text);
384
- }
385
-
386
- const plan = stableMcpSetupPlan(spec);
387
- if (!plan?.command) {
388
- const text = `${label} needs one-time browser-tool setup: ${setupCommand}`;
389
- emit({ type: 'status', text });
390
- throw new Error(text);
391
- }
392
-
393
- emit({ type: 'status', text: `${label} is setting up one-time browser tools...` });
394
- // Keep what the CLI said: it commonly exits 0 while refusing to register (no MCP SDK, no
395
- // HTTP transport), and that sentence is the only accurate explanation available.
396
- const setupOutput = String((await runSetup(plan, cwd)) || '').trim();
397
- if (await hasConfig(spec, cwd)) return true;
398
- throw new Error(
399
- `${label} browser-tool setup did not register the server.`
400
- + (setupOutput ? ` ${setupOutput.split('\n').filter(Boolean).slice(-3).join(' ')}` : '')
401
- + ` Run: ${setupCommand}`,
402
- );
403
- }
404
-
405
- export async function chat({ messages, system, options, images }, emit, { signal } = {}) {
406
- // Require a valid signed entitlement before running.
407
- if (!(await isProEntitled(options.entitlement))) {
408
- throw new Error('Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.');
409
- }
410
- return runSpec(options.custom || {}, { messages, system, options, images }, emit, { signal });
411
- }
412
-
413
- // Run a CLI agent from a spec — shared by the custom engine and the built-in CLI engines.
414
- export async function runSpec(spec, { messages, system, options = {}, images }, emit, { signal } = {}) {
415
- if (!spec.command) throw new Error('This agent has no command configured.');
416
-
417
- const resolved = resolveCommand(spec.command);
418
- if (!resolved) {
419
- throw new Error(`Couldn't find "${spec.command}". Enter its full path, or install it on your PATH (or in WSL).`);
420
- }
421
-
422
- const prompt = buildCliPrompt(messages, system);
423
- let cwd = resolveWorkdir(options.workingDir);
424
- const label = spec.label || spec.command;
425
- // Output dialect — resolved against the stream-format registry, so a new agent
426
- // brings a format by NAME instead of a new branch in this runner. Unknown /
427
- // absent names fall back to plain text.
428
- const fmt = Object.hasOwn(STREAM_FORMATS, spec.format) ? spec.format : 'text';
429
-
430
- // Args: either a real array or a space-split string. With promptVia:'arg' we
431
- // substitute {prompt} (or append it if there's no placeholder); otherwise the
432
- // prompt goes in on stdin.
433
- const promptVia = spec.promptVia === 'arg' ? 'arg' : 'stdin';
434
- let args = Array.isArray(spec.args)
435
- ? spec.args.slice()
436
- : spec.args
437
- ? String(spec.args).split(/\s+/).filter(Boolean)
438
- : [];
439
- // User-supplied extra CLI flags (Settings → agent → "Extra arguments"), placed
440
- // right after the base args/subcommand. Sanitized (shared helper): escalation flags
441
- // (--dangerously*, --skip-permissions, --trust-all-tools, --no-sandbox …) are dropped
442
- // from the EXTRA args so an injected value can't unlock tools. The built-in agents'
443
- // intentional autonomy flags live in their BASE spec (cli-agents.js), not here, so
444
- // they're unaffected; a custom CLI that genuinely needs such a flag should carry it
445
- // in its configured command/args, not the extra-args field.
446
- // Built-in specs may name a stricter set than the generic `custom` one, since
447
- // each CLI's escalation flags are spelled differently (Copilot's --allow-all-*
448
- // family isn't matched by the generic pattern).
449
- pushExtraArgs(args, options.extraArgs, FORBIDDEN[spec.forbidden] || FORBIDDEN.custom, emit);
450
- // Inject the selected model via the agent's CONFIGURED model-arg template
451
- // (e.g. "--model {model}" or, for opencode, "-m {model}" with provider/model).
452
- // Without a template we can't know how this CLI takes a model, so options.model
453
- // is ignored — preserving back-compat with agents that bake the model into args.
454
- if (options.model && spec.modelArg) {
455
- const tmpl = String(spec.modelArg);
456
- const injected = tmpl.includes('{model}')
457
- ? tmpl.replaceAll('{model}', options.model).split(/\s+/).filter(Boolean)
458
- : [...tmpl.split(/\s+/).filter(Boolean), options.model];
459
- // APPEND (not prepend): subcommand CLIs (opencode `run`, kiro `chat`) must
460
- // keep the subcommand first — `opencode -m X run` makes `run` look like a
461
- // project path, so it never loads opencode.json / its MCP servers.
462
- args = [...args, ...injected];
463
- }
464
- // Permission mode -> flags, declared per agent as
465
- // permissionArgs: { default: [...], acceptEdits: [...], bypassPermissions: [...] }
466
- // Agents whose autonomy flags are unconditional keep them in `args`; this is for
467
- // CLIs (Copilot) with a real permission surface, so the extension's existing
468
- // per-agent Permission mode actually means something. Unknown mode -> `default`.
469
- if (spec.permissionArgs) {
470
- const mode = String(options.permissionMode || 'default');
471
- const perm = spec.permissionArgs[mode] || spec.permissionArgs.default || [];
472
- args = [...args, ...perm.map(String)];
473
- }
474
- // Images: write to temp files, expand the agent's imageArg template, then place
475
- // the tokens. An explicit {images} placeholder in args wins; otherwise they go
476
- // just before the prompt (arg mode) or get appended (stdin mode).
477
- const tag = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
478
- const imageFiles = spec.imageArg ? await writeImages(images, tag) : [];
479
- const mcpFiles = [];
480
- const cleanup = () => [...imageFiles, ...mcpFiles].forEach((f) => unlink(f).catch(() => {}));
481
-
482
- // Browser tools: when armed (options.mcp) AND this CLI knows how to take an MCP
483
- // config file (spec.mcpArg, e.g. "--mcp-config {file}"), write a standard
484
- // mcpServers JSON pointing at the bridge's stdio MCP proxy and inject the flag.
485
- // Covers any CLI that reads the de-facto {mcpServers:{name:{command,args}}} shape.
486
- if (options.mcp?.url && spec.toolAdapter === 'pi-extension') {
487
- const extensionFile = await writePiExtension(options.mcp, tag);
488
- mcpFiles.push(extensionFile);
489
- args = [...piToolArgs(extensionFile, options.mcp), ...args];
490
- } else if (options.mcp?.url && spec.mcpArg) {
491
- const name = options.mcp.serverName || 'chatpanel_browser';
492
- const { command, args: pargs } = selfMcpStdio(options.mcp.url);
493
- const cfgFile = path.join(os.tmpdir(), `chatpanel-mcp-${tag}.json`);
494
- await writeFile(cfgFile, JSON.stringify({ mcpServers: { [name]: { command, args: pargs } } }));
495
- mcpFiles.push(cfgFile);
496
- const tmpl = String(spec.mcpArg);
497
- const tokens = tmpl.includes('{file}')
498
- ? tmpl.replaceAll('{file}', cfgFile).split(/\s+/).filter(Boolean)
499
- : [...tmpl.split(/\s+/).filter(Boolean), cfgFile];
500
- args = [...tokens, ...args];
501
- }
502
- // Some CLIs only load MCP from their persistent config, so ensure that stable
503
- // /mcp endpoint is present before letting the agent answer with no tools.
504
- //
505
- // DEGRADE, DON'T FAIL. Browser tools are an ENHANCEMENT on top of a CLI that already has
506
- // its own; a turn that could have been answered should not die because they couldn't be
507
- // registered. (Hermes ships without the `mcp` Python SDK unless `hermes setup` installed
508
- // it, so every tool-armed turn failed — and the error told the user to run a command that
509
- // fails the same way.) We now say what happened, drop the browser tools, and answer.
510
- if (options.mcp?.url) {
511
- try {
512
- await ensureStableMcpConfig(spec, cwd, label, emit);
513
- } catch (e) {
514
- emit({ type: 'status', text: `${label}: continuing without ChatPanel's browser tools — ${mcpSetupHint(label, e)}` });
515
- options = { ...options, mcp: null };
516
- }
517
- }
518
- // Trust flags only make sense once the server is actually registered — pushing them for
519
- // tools we then dropped would widen the CLI's permissions for nothing.
520
- if (options.mcp?.url) args.push(...mcpTrustArgs(spec, options.mcp));
521
-
522
- // Model via a CONFIG-PATCH FILE, for agents with no --model flag (dsh takes the
523
- // model as a Cordis config overlay: `--patch <file>` replacing one row by id).
524
- // `build` is a function, so this can only come from a built-in spec — a custom
525
- // BYO agent's spec arrives as JSON over HTTP and cannot carry one.
526
- if (options.model && typeof spec.modelPatch?.build === 'function') {
527
- // Keep the value to a conservative id charset: it lands in a config file the
528
- // agent parses, so no quotes/newlines/path characters.
529
- const safeModel = /^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(options.model)) ? String(options.model) : '';
530
- if (safeModel) {
531
- const patchFile = path.join(os.tmpdir(), `chatpanel-modelpatch-${tag}.yml`);
532
- await writeFile(patchFile, spec.modelPatch.build(safeModel));
533
- mcpFiles.push(patchFile); // cleaned up with the other temp files
534
- const tmpl = String(spec.modelPatch.arg || '--patch {file}');
535
- const tokens = tmpl.includes('{file}')
536
- ? tmpl.replaceAll('{file}', patchFile).split(/\s+/).filter(Boolean)
537
- : [...tmpl.split(/\s+/).filter(Boolean), patchFile];
538
- // PREPEND: these are launcher flags and must precede the task text (same
539
- // reason mcpArg prepends).
540
- args = [...tokens, ...args];
541
- }
542
- }
543
-
544
- const imageTokens = imageTokensFor(spec.imageArg, imageFiles);
545
- let placedImages = false;
546
- if (imageTokens.length) {
547
- args = args.flatMap((a) => {
548
- if (a === '{images}') {
549
- placedImages = true;
550
- return imageTokens;
551
- }
552
- return [a];
553
- });
554
- }
555
-
556
- if (promptVia === 'arg') {
557
- let placed = false;
558
- args = args.map((a) => {
559
- if (a.includes('{prompt}')) {
560
- placed = true;
561
- return a.replaceAll('{prompt}', prompt);
562
- }
563
- return a;
564
- });
565
- if (!placed) {
566
- if (imageTokens.length && !placedImages) args.push(...imageTokens); // images, then prompt
567
- args.push(prompt);
568
- }
569
- } else if (imageTokens.length && !placedImages) {
570
- args.push(...imageTokens); // stdin prompt: image tokens go on argv
571
- }
572
-
573
- const [bin, argv, opts] = buildSpawnSpec(resolved, args, cwd, options.runEnv || null);
574
- // Discourage CLIs from colourizing output (kiro-cli etc.) when piped.
575
- opts.env = { ...(opts.env || process.env), NO_COLOR: '1', FORCE_COLOR: '0', CLICOLOR: '0', TERM: 'dumb' };
576
-
577
- await new Promise((resolve, reject) => {
578
- let child;
579
- try {
580
- child = spawn(bin, argv, opts);
581
- } catch (e) {
582
- cleanup();
583
- return reject(new Error(`Failed to start ${label}: ${e.message}`));
584
- }
585
-
586
- const detach = killOnAbort(child, signal); // Stop → terminate the CLI child
587
-
588
- let stderr = '';
589
- // The output dialect is a plugin (stream-formats.js); it owns line buffering,
590
- // "did anything stream", and the fallback answer text.
591
- const parser = createStreamParser(fmt, emit);
592
-
593
- let idleTimer;
594
- const armIdle = () => {
595
- clearTimeout(idleTimer);
596
- idleTimer = setTimeout(() => {
597
- child.kill('SIGKILL');
598
- cleanup();
599
- reject(new Error(`${label} timed out — no output for ${Math.round(IDLE_MS / 1000)}s.`));
600
- }, IDLE_MS);
601
- };
602
- armIdle();
603
-
604
- child.stdout.on('data', (d) => {
605
- armIdle();
606
- parser.push(d.toString());
607
- });
608
- child.stderr.on('data', (d) => { armIdle(); stderr += d.toString(); });
609
- child.on('error', (e) => {
610
- clearTimeout(idleTimer);
611
- detach();
612
- cleanup();
613
- reject(new Error(`Failed to start ${label}: ${e.message}`));
614
- });
615
- child.on('close', (code) => {
616
- clearTimeout(idleTimer);
617
- detach();
618
- cleanup();
619
- if (signal?.aborted) { resolve(); return; } // Stop pressed — end quietly
620
- if (code === 0) {
621
- emit({ type: 'done', text: parser.streamed ? '' : parser.finish() });
622
- resolve();
623
- } else {
624
- reject(new Error(summarizeCliError(label, code, stderr)));
625
- }
626
- });
627
-
628
- if (promptVia === 'stdin') child.stdin.write(prompt);
629
- child.stdin.end();
630
- });
66
+ ${r}
631
67
  }
68
+ `}async function pt(t,n){const e=C.join(A.tmpdir(),`chatpanel-pi-tools-${n}.ts`);return await P(e,ut(t)),e}async function dt(){const t=process.env.XDG_CONFIG_HOME||C.join(A.homedir(),".config"),n=[C.join(t,"opencode","opencode.jsonc"),C.join(A.homedir(),"Library","Application Support","opencode","opencode.jsonc")];for(const e of n)try{if((await G(e,"utf8")).includes(rt))return!0}catch{}return!1}async function H(t,n,e){const r=L(t);if(!r)return"";const[o,i,d]=_(r,n,e||null);return new Promise(u=>{const a=O(o,i,d);let f="",l="";const h=setTimeout(()=>{a.kill("SIGKILL"),u(f+l)},4e3);a.stdout.on("data",m=>f+=m.toString()),a.stderr.on("data",m=>l+=m.toString()),a.on("error",()=>{clearTimeout(h),u(f+l)}),a.on("close",()=>{clearTimeout(h),u(f+l)});try{a.stdin.end()}catch{}})}async function ft(t,n){for(const e of["workspace","global","default"]){const r=await H(t,["mcp","list",e],n);if(r.includes(F)||/chatpanel_browser/i.test(r))return!0}return!1}async function gt(t,n){const e=await H(t,["mcp","list"],n);return e.includes(F)||/chatpanel_browser/i.test(e)}async function ht(t,n){return t.stableMcpConfigCheck==="kiro"?ft(t.command||"kiro-cli",n):t.stableMcpConfigCheck==="opencode"?dt():t.stableMcpConfigCheck==="hermes"?gt(t.command||"hermes",n):!1}async function St(t,n){const e=L(t.command);if(!e)throw new Error(`Couldn't find "${t.command}" to set up browser tools.`);const[r,o,i]=_(e,t.args,n||null);i.env={...i.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"},await new Promise((d,u)=>{let a;try{a=O(r,o,i)}catch(m){return u(new Error(`Failed to start ${t.command}: ${m.message}`))}let f="",l="";const h=setTimeout(()=>{a.kill("SIGKILL"),u(new Error(`${t.command} MCP setup timed out.`))},2e4);a.stderr.on("data",m=>f+=m.toString()),a.stdout?.on("data",m=>l+=m.toString()),a.on("error",m=>{clearTimeout(h),u(new Error(`Failed to start ${t.command}: ${m.message}`))}),a.on("close",m=>{if(clearTimeout(h),m===0)return d(`${l}
69
+ ${f}`.trim());u(new Error(`${t.command} MCP setup exited ${m}: ${f.trim().split(`
70
+ `).pop()||"failed"}`))});try{a.stdin.end()}catch{}})}function wt(t,n){const e=String(n?.message||n||"");return/mcp['" ]* Python SDK|No module named ['"]?mcp|MCP support/i.test(e)?`${t} has no MCP support installed. Run \`hermes setup\` (or install the \`mcp\` package in its environment), then retry.`:/streamable_http|HTTP transport/i.test(e)?`${t}'s MCP client has no HTTP transport; ChatPanel registers a stdio server instead. Upgrade its \`mcp\` package if this persists.`:e.slice(0,200)||"the CLI could not register the tools"}async function yt(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const i=o.hasConfig||ht,d=o.runSetup||St;if(await i(t,n))return!0;const u=ct(t);if(!t.autoSetupStableMcp){const l=`${e} needs one-time browser-tool setup: ${u}`;throw r({type:"status",text:l}),new Error(l)}const a=mt(t);if(!a?.command){const l=`${e} needs one-time browser-tool setup: ${u}`;throw r({type:"status",text:l}),new Error(l)}r({type:"status",text:`${e} is setting up one-time browser tools...`});const f=String(await d(a,n)||"").trim();if(await i(t,n))return!0;throw new Error(`${e} browser-tool setup did not register the server.`+(f?` ${f.split(`
71
+ `).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${u}`)}async function Ft({messages:t,system:n,options:e,images:r},o,{signal:i}={}){if(!await R(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return Ct(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:i})}async function Ct(t,{messages:n,system:e,options:r={},images:o},i,{signal:d}={}){if(!t.command)throw new Error("This agent has no command configured.");const u=L(t.command);if(!u)throw new Error(`Couldn't find "${t.command}". Enter its full path, or install it on your PATH (or in WSL).`);const a=V(n,e);let f=Y(r.workingDir);const l=t.label||t.command,h=Object.hasOwn(Q,t.format)?t.format:"text",m=t.promptVia==="arg"?"arg":"stdin";let c=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];if(W(c,r.extraArgs,B[t.forbidden]||B.custom,i),r.model&&t.modelArg){const s=String(t.modelArg),p=s.includes("{model}")?s.replaceAll("{model}",r.model).split(/\s+/).filter(Boolean):[...s.split(/\s+/).filter(Boolean),r.model];c=[...c,...p]}if(t.permissionArgs){const s=String(r.permissionMode||"default"),p=t.permissionArgs[s]||t.permissionArgs.default||[];c=[...c,...p.map(String)]}const S=`${Date.now()}-${Math.random().toString(36).slice(2)}`,N=t.imageArg?await tt(o,S):[],x=[],T=()=>[...N,...x].forEach(s=>K(s).catch(()=>{}));if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const s=await pt(r.mcp,S);x.push(s),c=[...st(s,r.mcp),...c]}else if(r.mcp?.url&&t.mcpArg){const s=r.mcp.serverName||"chatpanel_browser",{command:p,args:g}=Z(r.mcp.url),y=C.join(A.tmpdir(),`chatpanel-mcp-${S}.json`);await P(y,JSON.stringify({mcpServers:{[s]:{command:p,args:g}}})),x.push(y);const b=String(t.mcpArg);c=[...b.includes("{file}")?b.replaceAll("{file}",y).split(/\s+/).filter(Boolean):[...b.split(/\s+/).filter(Boolean),y],...c]}if(r.mcp?.url)try{await yt(t,f,l,i)}catch(s){i({type:"status",text:`${l}: continuing without ChatPanel's browser tools — ${wt(l,s)}`}),r={...r,mcp:null}}if(r.mcp?.url&&c.push(...lt(t,r.mcp)),r.model&&typeof t.modelPatch?.build=="function"){const s=/^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(r.model))?String(r.model):"";if(s){const p=C.join(A.tmpdir(),`chatpanel-modelpatch-${S}.yml`);await P(p,t.modelPatch.build(s)),x.push(p);const g=String(t.modelPatch.arg||"--patch {file}");c=[...g.includes("{file}")?g.replaceAll("{file}",p).split(/\s+/).filter(Boolean):[...g.split(/\s+/).filter(Boolean),p],...c]}}const $=et(t.imageArg,N);let k=!1;if($.length&&(c=c.flatMap(s=>s==="{images}"?(k=!0,$):[s])),m==="arg"){let s=!1;c=c.map(p=>p.includes("{prompt}")?(s=!0,p.replaceAll("{prompt}",a)):p),s||($.length&&!k&&c.push(...$),c.push(a))}else $.length&&!k&&c.push(...$);const[J,z,v]=_(u,c,f,r.runEnv||null);v.env={...v.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"},await new Promise((s,p)=>{let g;try{g=O(J,z,v)}catch(w){return T(),p(new Error(`Failed to start ${l}: ${w.message}`))}const y=q(g,d);let b="";const M=X(h,i);let E;const I=()=>{clearTimeout(E),E=setTimeout(()=>{g.kill("SIGKILL"),T(),p(new Error(`${l} timed out — no output for ${Math.round(j/1e3)}s.`))},j)};I(),g.stdout.on("data",w=>{I(),M.push(w.toString())}),g.stderr.on("data",w=>{I(),b+=w.toString()}),g.on("error",w=>{clearTimeout(E),y(),T(),p(new Error(`Failed to start ${l}: ${w.message}`))}),g.on("close",w=>{if(clearTimeout(E),y(),T(),d?.aborted){s();return}w===0?(i({type:"done",text:M.streamed?"":M.finish()}),s()):p(new Error(summarizeCliError(l,w,b)))}),m==="stdin"&&g.stdin.write(a),g.stdin.end()})}export{F as CHATPANEL_STABLE_MCP_URL,vt as available,ut as buildPiExtensionSource,Ft as chat,H as commandOutput,yt as ensureStableMcpConfig,It as listModels,ot as listSpecModels,wt as mcpSetupHint,lt as mcpTrustArgs,st as piToolArgs,it as runForStdout,Ct as runSpec,ct as stableMcpSetupCommand,mt as stableMcpSetupPlan,at as trustToolArgs};