@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
@@ -1,588 +1,8 @@
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:
4
- //
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.
1
+ import{spawn as J}from"node:child_process";import{writeFile as P,unlink as L}from"node:fs/promises";import A from"node:os";import I from"node:path";import{resolveClaude as v,buildSpawnSpec as X,isCompiledBinary as K,selfMcpStdio as Q}from"../env.js";import{signInStatus as V,signInMessage as W,loginRequired as Z}from"../sign-in.js";import{buildCliPrompt as R}from"./prompt.js";import{summarizeCliError as ee}from"../cli-errors.js";import{killOnAbort as te}from"../proc.js";import{pushExtraArgs as re,FORBIDDEN as oe}from"./args.js";import{relayTimeoutMax as ne}from"../relay-timeout.js";import{displayPath as se,resolveWorkdir as j}from"../workdir.js";import{connectorsFor as ae}from"../connectors.js";async function le(e,o){const t=[];for(let a=0;a<(e?.length||0);a++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[a]?.dataUrl||"");if(!s)continue;const n=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=I.join(A.tmpdir(),`chatpanel-claude-img-${o}-${a}.${n}`);await P(r,Buffer.from(s[2],"base64")),t.push(r)}return t}const D=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,F=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],H=Object.freeze({device:Object.freeze(["TodoWrite","Task"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),ie=Object.freeze(["Bash","Edit","Write","WebFetch","WebSearch"]),ce=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),ue=Object.freeze(["remember","forget"]),z=Object.freeze({device:Object.freeze([]),trusted:ce});function de(e,o=[]){const t=z[e]||z.device,a=(o||[]).filter(r=>typeof r=="string"&&/^chatpanel/i.test(r)),s=[],n=[];for(const r of a){for(const l of t)s.push(`mcp__${r}__${l}`);for(const l of ue)n.push(`mcp__${r}__${l}`)}return{allow:s,deny:n}}function pe(e){return!e||e==="any"?null:{allow:[...H[e]||H.device],deny:[...ie]}}let k="Claude Code not found.",U=0,x=!1;async function $e(){if(Date.now()-U>(x?3e4:4e3)){U=Date.now();try{v()||!K()&&await O()?x=!0:(x=!1,k=process.platform==="win32"?"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.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{x=!1}}return x?await V("claude",v()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:W("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:k}}async function Ne(){return["opus","sonnet","haiku"]}function fe(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const o=e.serverName||"chatpanel_browser",{command:t,args:a}=Q(e.url),s=[...new Set(e.specs.map(n=>n?.name).filter(Boolean))];return{serverName:o,config:{mcpServers:{[o]:{command:t,args:a}}},allowedTools:s.map(n=>`mcp__${o}__${n}`)}}function B({prompt:e,args:o,cwd:t,env:a=null,emit:s,signal:n}){const r=v();if(!r)return null;const[l,m,i]=X(r,o,t,a);return new Promise((w,p)=>{let u;try{u=J(l,m,i)}catch(h){return p(new Error(`Failed to start claude: ${h.message}`))}const y=te(u,n);let f="",b="",_=!1,d=null;const g={sawText:!1,tail:"",boundary:!1};let T="",c;const C=()=>{clearTimeout(c),c=setTimeout(()=>{u.kill("SIGKILL"),p(new Error(`Claude Code timed out — no output for ${Math.round(D/1e3)}s.`))},D)};C(),u.stdout.on("data",h=>{C(),f+=h.toString();let S;for(;(S=f.indexOf(`
2
+ `))>=0;){const $=f.slice(0,S).trim();if(f=f.slice(S+1),!$.startsWith("{"))continue;let N;try{N=JSON.parse($)}catch{continue}const E=Y(N,s,_,t,g);E.streamed&&(_=!0),E.result!=null&&(T=E.result),E.apiError&&(d=E.apiError)}}),u.stderr.on("data",h=>{C(),b+=h.toString()}),u.on("error",h=>{clearTimeout(c),y(),p(new Error(`Failed to start claude (${l}): ${h.message}`))}),u.on("close",h=>{if(clearTimeout(c),y(),n?.aborted){w({streamedAny:_,resultText:T});return}if(d&&Z(d))return p(new Error(W("Claude Code","claude")));if(h===0&&d)return p(new Error(`Claude Code reported an error: ${d}`));h===0?w({streamedAny:_,resultText:T}):p(new Error(ee("Claude Code",h,b,d||"",{agentId:"claude"})))}),u.stdin.write(e),u.stdin.end()})}function me(e){let o="";return typeof e=="string"?o=e:Array.isArray(e)&&(o=e.map(t=>typeof t=="string"?t:t?.text||"").filter(Boolean).join(`
3
+ `)),o.length>4e3?`${o.slice(0,4e3)}…`:o}function G(e,o){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&o({type:"delta",text:`
15
4
 
16
- import { spawn } from 'node:child_process';
17
- import { writeFile, unlink } from 'node:fs/promises';
18
- import os from 'node:os';
19
- import path from 'node:path';
20
- import { resolveClaude, buildSpawnSpec, isCompiledBinary, selfMcpStdio } from '../env.js';
21
- import { signInStatus, signInMessage, loginRequired } from '../sign-in.js';
22
- import { buildCliPrompt } from './prompt.js';
23
- import { summarizeCliError } from '../cli-errors.js';
24
- import { killOnAbort } from '../proc.js';
25
- import { pushExtraArgs, FORBIDDEN } from './args.js';
26
- import { relayTimeoutMax } from '../relay-timeout.js';
27
- import { displayPath, resolveWorkdir } from '../workdir.js';
28
- import { connectorsFor } from '../connectors.js';
5
+ `}),e.boundary=!1)}function q(e,o){!e||!o||(e.sawText=!0,e.tail=o.slice(-2))}function Y(e,o,t,a="",s=null){const n={streamed:!1,result:null};if(e.type==="stream_event"){const r=e.event;r?.type==="content_block_delta"&&(r.delta?.type==="text_delta"?(n.streamed=!0,G(s,o),o({type:"delta",text:r.delta.text}),q(s,r.delta.text)):r.delta?.type==="thinking_delta"&&o({type:"reasoning",text:r.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return n.apiError=(e.message?.content||[]).filter(r=>r.type==="text").map(r=>r.text).join(`
6
+ `)||String(e.error||"api error"),n;for(const r of e.message?.content||[])r.type==="tool_use"?(s&&(s.boundary=!0),o({type:"tool",name:r.name,phase:"start",callId:r.id,input:r.input,summary:he(r,a)})):r.type==="text"&&!t&&(n.streamed=!0,G(s,o),o({type:"delta",text:r.text}),q(s,r.text))}else if(e.type==="user")for(const r of e.message?.content||[])r.type==="tool_result"&&o({type:"tool",phase:"done",callId:r.tool_use_id,status:r.is_error?"error":"ok",result:me(r.content)});else if(e.type==="result"){e.is_error?n.apiError=n.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?n.result=e.result||"":o({type:"status",text:`(${e.subtype})`});const r=e.usage||e.message?.usage;r&&o({type:"usage",provider:"bridge",inputTokens:r.input_tokens||0,outputTokens:r.output_tokens||0,cacheReadTokens:r.cache_read_input_tokens||0,cacheWriteTokens:r.cache_creation_input_tokens||0,costUsd:e.total_cost_usd!=null?e.total_cost_usd:null})}return n}async function Pe({messages:e,system:o,options:t,images:a},s,{signal:n}={}){const r=t.permissionMode||"default",l=j(t.workingDir),m=`${Date.now()}-${Math.random().toString(36).slice(2)}`,i=["--print","--output-format","stream-json","--include-partial-messages","--verbose"],w=[],p=[],u=fe(t.mcp);if(u){const c=I.join(A.tmpdir(),`chatpanel-mcp-${m}.json`);await P(c,JSON.stringify(u.config)),w.push(c),i.push("--mcp-config",c),p.push(...u.allowedTools)}const y=pe(t.reach);if(y){const c=de(t.reach,await ae("claude").catch(()=>[]));i.push("--allowedTools",...y.allow,...p,...c.allow),i.push("--disallowedTools",...y.deny,...c.deny)}else r==="bypassPermissions"?i.push("--permission-mode","bypassPermissions"):r==="acceptEdits"?(i.push("--permission-mode","acceptEdits"),p.length&&i.push("--allowedTools",...p)):i.push("--allowedTools",...F,...p);o&&i.push("--append-system-prompt",o),t.model&&i.push("--model",t.model),t.useLocalConfig===!1&&i.push("--setting-sources","");const f=await le(a,m),b=()=>{f.forEach(c=>L(c).catch(()=>{})),w.forEach(c=>L(c).catch(()=>{}))};let _=R(e);f.length&&(_+=`
29
7
 
30
- // Write base64 data-URL images to temp files. Claude Code reads them with its
31
- // Read tool (which feeds images to the model as vision), so we just reference the
32
- // paths in the prompt — no custom image flag needed. Returns paths (caller cleans).
33
- async function writeImages(images, tag) {
34
- const files = [];
35
- for (let i = 0; i < (images?.length || 0); i++) {
36
- const m = /^data:([^;]+);base64,(.+)$/s.exec(images[i]?.dataUrl || '');
37
- if (!m) continue;
38
- const ext = (m[1].split('/')[1] || 'png').replace(/[^a-z0-9]/gi, '').slice(0, 5) || 'png';
39
- const file = path.join(os.tmpdir(), `chatpanel-claude-img-${tag}-${i}.${ext}`);
40
- await writeFile(file, Buffer.from(m[2], 'base64'));
41
- files.push(file);
42
- }
43
- return files;
44
- }
45
-
46
- // Idle timeout: kill the run only after this long with NO output. The timer
47
- // re-arms on every stdout/stderr chunk, so a task that keeps streaming can run
48
- // indefinitely — only a truly stuck/silent process is killed. Override with
49
- // CHATPANEL_CLAUDE_TIMEOUT_MS (ms).
50
- const IDLE_MS = Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS) || 180_000;
51
- // Read-only tools allowed without approval in headless mode; writes/shell are
52
- // gated behind the agent's permission mode.
53
- const READONLY_TOOLS = ['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'TodoWrite', 'Task'];
54
-
55
- // A remote (channel) caller declares the actor's trust tier via options.reach. Unlike
56
- // permissionMode (which a local, already-trusted UI chooses), reach is a CEILING enforced HERE
57
- // at the trust boundary — a paired-but-prompt-injected phone cannot exceed its tier no matter
58
- // what the message says. This is the tool-authorization half of feature-f7 §7; pairing proves
59
- // WHO, this constrains WHAT.
60
- //
61
- // Posture (security-first): the exfil chain needs read-a-secret AND an egress to send it. We cut
62
- // the egress on every capped tier by dropping web tools, so even machine-wide reads can't phone
63
- // home; writes/shell are never granted to a capped tier.
64
- // device — conversational only: no filesystem, no web, no writes/shell.
65
- // trusted — machine-wide READ (inspect your own files/projects), but NO web and NO writes/shell.
66
- // any — no cap here (operator/local console); falls through to permissionMode below.
67
- const CHANNEL_ALLOW = Object.freeze({
68
- device: Object.freeze(['TodoWrite', 'Task']),
69
- trusted: Object.freeze(['Read', 'Grep', 'Glob', 'TodoWrite', 'Task']),
70
- });
71
- // Belt-and-suspenders: the allow-list already omits these, but we also forbid them explicitly so
72
- // a capped turn can never reach shell, writes, or a network egress even via an MCP alias.
73
- const CHANNEL_DENY = Object.freeze(['Bash', 'Edit', 'Write', 'WebFetch', 'WebSearch']);
74
-
75
- // ChatPanel's OWN history/memory tools, which arrive as a user-configured MCP server rather
76
- // than as built-ins — so the tier's allow-list, which only ever named built-ins, left them out
77
- // and a headless channel turn had no way to approve them. The phone got "the search tools need
78
- // your permission and it hasn't been granted yet", which is the one question a texting-your-
79
- // machine product must never ask: nobody is at the keyboard.
80
- //
81
- // Granting them changes nothing about the posture. `trusted` already allows Read/Grep/Glob
82
- // across the machine, so reading the user's own meetings and notes is narrower than what is
83
- // already permitted, and egress stays cut — the only place an answer can go is the reply to the
84
- // phone that is already paired. The MUTATING half is a different question and stays denied: a
85
- // prompt-injected message must not be able to rewrite what the assistant remembers about you.
86
- const CHANNEL_MCP_READ = Object.freeze([
87
- 'search_history', 'smart_search', 'get_record', 'list_history', 'find_related', 'recall',
88
- 'list_skills', 'open_skill', 'read_skill_file',
89
- ]);
90
- const CHANNEL_MCP_WRITE = Object.freeze(['remember', 'forget']);
91
- // Which tiers get the read half. `device` is "conversational only" and stays that way.
92
- const CHANNEL_MCP_BY_REACH = Object.freeze({ device: Object.freeze([]), trusted: CHANNEL_MCP_READ });
93
-
94
- /**
95
- * `mcp__<server>__<tool>` entries for the ChatPanel MCP servers this agent actually has
96
- * configured. Names come from the agent's own config (connectors.js) because the user chooses
97
- * them — 'chatpanel', 'chatpanel-history', whatever they typed. Anything not matching is left
98
- * alone: a capped turn must not be handed a stranger's MCP server because it was present.
99
- */
100
- export function channelMcpTools(reach, connectors = []) {
101
- const reads = CHANNEL_MCP_BY_REACH[reach] || CHANNEL_MCP_BY_REACH.device;
102
- const servers = (connectors || []).filter((n) => typeof n === 'string' && /^chatpanel/i.test(n));
103
- const allow = [];
104
- const deny = [];
105
- for (const server of servers) {
106
- for (const tool of reads) allow.push(`mcp__${server}__${tool}`);
107
- // Denied on every capped tier, including the ones that get no reads.
108
- for (const tool of CHANNEL_MCP_WRITE) deny.push(`mcp__${server}__${tool}`);
109
- }
110
- return { allow, deny };
111
- }
112
-
113
- /**
114
- * Tool policy for a channel/remote caller. Returns { allow, deny } for a capped tier, or null
115
- * when reach is absent or 'any' (no cap — the existing permissionMode logic applies). An unknown
116
- * tier is treated as the MOST restrictive ('device'), never as "no cap" — fail closed.
117
- */
118
- export function channelToolPolicy(reach) {
119
- if (!reach || reach === 'any') return null;
120
- const allow = CHANNEL_ALLOW[reach] || CHANNEL_ALLOW.device;
121
- return { allow: [...allow], deny: [...CHANNEL_DENY] };
122
- }
123
-
124
- let lastReason = 'Claude Code not found.';
125
- let lastProbe = 0;
126
- let cachedOk = false;
127
- export async function available() {
128
- // Availability = "can we launch claude somehow" (native / cli.js / WSL / SDK),
129
- // NOT "does `claude --version` exit 0" (which fails when it just needs login).
130
- // Re-probe in both directions (see codex.js): caching success forever meant an uninstalled
131
- // CLI still reported itself available.
132
- if (Date.now() - lastProbe > (cachedOk ? 30_000 : 4000)) {
133
- lastProbe = Date.now();
134
- try {
135
- const spec = resolveClaude();
136
- if (spec) {
137
- cachedOk = true;
138
- } else if (!isCompiledBinary() && (await loadSdk())) {
139
- cachedOk = true;
140
- } else {
141
- cachedOk = false;
142
- lastReason =
143
- process.platform === 'win32'
144
- ? '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.'
145
- : 'Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.';
146
- }
147
- } catch {
148
- cachedOk = false;
149
- }
150
- }
151
- if (!cachedOk) return { ok: false, reason: lastReason };
152
- // Installed is not signed in. `claude auth status` says which, cheaply and before a turn is
153
- // sent; only a clear "no" counts (sign-in.js), so an old CLI or a slow answer never blocks.
154
- const signedIn = await signInStatus('claude', resolveClaude()).catch(() => null);
155
- if (signedIn === false) return { ok: false, signedIn: false, reason: signInMessage('Claude Code', 'claude') };
156
- return { ok: true };
157
- }
158
-
159
- // Claude Code has no "list models" command — it takes stable aliases (or full
160
- // ids). Return the common aliases so the picker has sensible options; the user
161
- // can still type any model string (e.g. claude-opus-4-8).
162
- export async function listModels() {
163
- return ['opus', 'sonnet', 'haiku'];
164
- }
165
-
166
- export function claudeMcpConfig(mcp) {
167
- if (!mcp?.url || !Array.isArray(mcp.specs) || !mcp.specs.length) return null;
168
- const serverName = mcp.serverName || 'chatpanel_browser';
169
- const { command, args } = selfMcpStdio(mcp.url);
170
- const toolNames = [...new Set(mcp.specs.map((s) => s?.name).filter(Boolean))];
171
- return {
172
- serverName,
173
- config: { mcpServers: { [serverName]: { command, args } } },
174
- allowedTools: toolNames.map((name) => `mcp__${serverName}__${name}`),
175
- };
176
- }
177
-
178
- // Spawn claude (however it resolves) and stream its stream-json output via
179
- // `emit`. Resolves with { streamedAny, resultText } once it closes 0. Returns
180
- // null (no spawn) when claude can't be resolved, so the caller can fall back.
181
- function runClaude({ prompt, args, cwd, env = null, emit, signal }) {
182
- const spec = resolveClaude();
183
- if (!spec) return null;
184
- const [bin, argv, opts] = buildSpawnSpec(spec, args, cwd, env);
185
-
186
- return new Promise((resolve, reject) => {
187
- let child;
188
- try {
189
- child = spawn(bin, argv, opts);
190
- } catch (e) {
191
- return reject(new Error(`Failed to start claude: ${e.message}`));
192
- }
193
-
194
- const detach = killOnAbort(child, signal); // Stop → terminate the claude child
195
-
196
- let stdout = '';
197
- let stderr = '';
198
- let streamedAny = false;
199
- let apiError = null; // an API-level failure Claude reported as a message (not signed in, …)
200
- const flow = { sawText: false, tail: '', boundary: false };
201
- let resultText = '';
202
-
203
- let idleTimer;
204
- const armIdle = () => {
205
- clearTimeout(idleTimer);
206
- idleTimer = setTimeout(() => {
207
- child.kill('SIGKILL');
208
- reject(new Error(`Claude Code timed out — no output for ${Math.round(IDLE_MS / 1000)}s.`));
209
- }, IDLE_MS);
210
- };
211
- armIdle();
212
-
213
- child.stdout.on('data', (d) => {
214
- armIdle();
215
- stdout += d.toString();
216
- let nl;
217
- while ((nl = stdout.indexOf('\n')) >= 0) {
218
- const line = stdout.slice(0, nl).trim();
219
- stdout = stdout.slice(nl + 1);
220
- if (!line.startsWith('{')) continue;
221
- let msg;
222
- try {
223
- msg = JSON.parse(line);
224
- } catch {
225
- continue; // not a JSON event line
226
- }
227
- const r = handleMessage(msg, emit, streamedAny, cwd, flow);
228
- if (r.streamed) streamedAny = true;
229
- if (r.result != null) resultText = r.result;
230
- if (r.apiError) apiError = r.apiError;
231
- }
232
- });
233
- child.stderr.on('data', (d) => { armIdle(); stderr += d.toString(); });
234
- child.on('error', (e) => {
235
- clearTimeout(idleTimer);
236
- detach();
237
- reject(new Error(`Failed to start claude (${bin}): ${e.message}`));
238
- });
239
- child.on('close', (code) => {
240
- clearTimeout(idleTimer);
241
- detach();
242
- if (signal?.aborted) { resolve({ streamedAny, resultText }); return; } // Stop pressed — end quietly
243
- // Not signed in arrives as an assistant message flagged `authentication_failed`, then
244
- // exit 1. Say what to do — never "exited 1", and never the line as if it were the answer.
245
- if (apiError && loginRequired(apiError)) return reject(new Error(signInMessage('Claude Code', 'claude')));
246
- if (code === 0 && apiError) return reject(new Error(`Claude Code reported an error: ${apiError}`));
247
- if (code === 0) resolve({ streamedAny, resultText });
248
- else reject(new Error(summarizeCliError('Claude Code', code, stderr, apiError || '', { agentId: 'claude' })));
249
- });
250
-
251
- child.stdin.write(prompt);
252
- child.stdin.end();
253
- });
254
- }
255
-
256
- // A tool_result's content is either a string or Anthropic's block array. Flatten to text and
257
- // cap it: the panel truncates for display anyway, and an un-capped file read would otherwise
258
- // push megabytes through the SSE for no benefit.
259
- function toolResultText(content) {
260
- let text = '';
261
- if (typeof content === 'string') text = content;
262
- else if (Array.isArray(content)) {
263
- text = content.map((c) => (typeof c === 'string' ? c : (c?.text || ''))).filter(Boolean).join('\n');
264
- }
265
- return text.length > 4000 ? `${text.slice(0, 4000)}…` : text;
266
- }
267
-
268
- // Map one stream-json message to emit() calls. Returns { streamed, result }.
269
- // The CLI's stream-json mirrors the SDK message shapes. Exported so the custom
270
- // engine can reuse it for agents that emit Claude-style stream-json.
271
- // WHERE ONE TEXT ENDS AND THE NEXT BEGINS. Claude Code narrates before it acts ("I'll check the
272
- // catalog first…"), calls its tools, then answers — two assistant messages, both streamed as
273
- // text deltas. Concatenated as they arrive they read "…writing the table.> Assuming", and a
274
- // note or a chat bubble shows the blockquote marker glued to the previous sentence. `flow`
275
- // (one object per run, passed by the caller) remembers how the last text ended and whether a
276
- // tool call happened since; the next text after a tool call gets a paragraph break unless the
277
- // previous text already ended with one. A caller that passes no `flow` gets the old
278
- // behaviour — the custom engine reuses this and does not need it.
279
- function textBoundary(flow, emit) {
280
- if (!flow) return;
281
- if (flow.boundary && flow.sawText && !/\n$/.test(flow.tail)) emit({ type: 'delta', text: '\n\n' });
282
- flow.boundary = false;
283
- }
284
- function noteText(flow, text) {
285
- if (!flow || !text) return;
286
- flow.sawText = true;
287
- flow.tail = text.slice(-2);
288
- }
289
-
290
- export function handleMessage(msg, emit, alreadyStreamed, cwdForSteps = '', flow = null) {
291
- const out = { streamed: false, result: null };
292
- if (msg.type === 'stream_event') {
293
- const ev = msg.event;
294
- if (ev?.type === 'content_block_delta') {
295
- if (ev.delta?.type === 'text_delta') {
296
- out.streamed = true;
297
- textBoundary(flow, emit);
298
- emit({ type: 'delta', text: ev.delta.text });
299
- noteText(flow, ev.delta.text);
300
- } else if (ev.delta?.type === 'thinking_delta') {
301
- emit({ type: 'reasoning', text: ev.delta.thinking || '' });
302
- }
303
- }
304
- } else if (msg.type === 'assistant') {
305
- // An API error Claude Code phrases as an assistant message ("Not logged in · Please run
306
- // /login", `error: 'authentication_failed'`, `is_api_error_message`). Not an answer: it is
307
- // held for the close handler, which turns it into an instruction.
308
- if (msg.is_api_error_message || msg.error) {
309
- out.apiError = (msg.message?.content || []).filter((b) => b.type === 'text').map((b) => b.text).join('\n') || String(msg.error || 'api error');
310
- return out;
311
- }
312
- for (const block of msg.message?.content || []) {
313
- if (block.type === 'tool_use') {
314
- if (flow) flow.boundary = true;
315
- // PHASE-BASED, like the Codex engine: the panel renders a step with the call's
316
- // arguments and then fills in its status and output when the result arrives. The old
317
- // single `summary` event produced one anonymous line per call and no outcome — you
318
- // could see that Claude did something, never what it returned. `summary` is still
319
- // sent so an older extension keeps the line it used to draw.
320
- emit({
321
- type: 'tool', name: block.name, phase: 'start',
322
- callId: block.id, input: block.input,
323
- summary: toolSummary(block, cwdForSteps),
324
- });
325
- } else if (block.type === 'text' && !alreadyStreamed) {
326
- out.streamed = true;
327
- textBoundary(flow, emit);
328
- emit({ type: 'delta', text: block.text });
329
- noteText(flow, block.text);
330
- }
331
- }
332
- } else if (msg.type === 'user') {
333
- // Claude reports every tool's OUTCOME as a tool_result block on a synthetic user message.
334
- // Pairing it with the call by tool_use_id is what turns the step list into a readable
335
- // log: each action shows ok / error and the text the tool actually returned.
336
- for (const block of msg.message?.content || []) {
337
- if (block.type !== 'tool_result') continue;
338
- emit({
339
- type: 'tool', phase: 'done', callId: block.tool_use_id,
340
- status: block.is_error ? 'error' : 'ok',
341
- result: toolResultText(block.content),
342
- });
343
- }
344
- } else if (msg.type === 'result') {
345
- // `is_error` rides on a `success` result when the API refused (not signed in): the text
346
- // is the error, not the answer.
347
- if (msg.is_error) out.apiError = out.apiError || String(msg.result || msg.subtype || 'error');
348
- else if (msg.subtype === 'success') out.result = msg.result || '';
349
- else emit({ type: 'status', text: `(${msg.subtype})` });
350
- // Forward token usage so the client can account for CLI-agent turns. The
351
- // result message carries cumulative usage (+ a real subscription cost).
352
- // Additive event — older clients ignore an unknown SSE type.
353
- const u = msg.usage || msg.message?.usage;
354
- if (u) {
355
- emit({
356
- type: 'usage',
357
- provider: 'bridge',
358
- inputTokens: u.input_tokens || 0,
359
- outputTokens: u.output_tokens || 0,
360
- cacheReadTokens: u.cache_read_input_tokens || 0,
361
- cacheWriteTokens: u.cache_creation_input_tokens || 0,
362
- costUsd: msg.total_cost_usd != null ? msg.total_cost_usd : null,
363
- });
364
- }
365
- }
366
- return out;
367
- }
368
-
369
- export async function chat({ messages, system, options, images }, emit, { signal } = {}) {
370
- const permissionMode = options.permissionMode || 'default';
371
- // Explicit project dir, else null → CLI runs in home (or WSL home).
372
- const cwd = resolveWorkdir(options.workingDir);
373
-
374
- const tag = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
375
- const args = ['--print', '--output-format', 'stream-json', '--include-partial-messages', '--verbose'];
376
-
377
- // Browser-tools relay: ChatPanel hands this CLI the page-action tools through
378
- // the bridge's stdio MCP proxy, which forwards each call to the per-chat HTTP
379
- // MCP session and then to the extension.
380
- // options.mcp = { url, serverName, specs }. We pre-allow the tools so a headless
381
- // run doesn't block on approval, and merge alongside the user's own MCP servers.
382
- const mcpFiles = [];
383
- const mcpAllow = [];
384
- const mcpConfig = claudeMcpConfig(options.mcp);
385
- if (mcpConfig) {
386
- const cfgFile = path.join(os.tmpdir(), `chatpanel-mcp-${tag}.json`);
387
- await writeFile(cfgFile, JSON.stringify(mcpConfig.config));
388
- mcpFiles.push(cfgFile);
389
- args.push('--mcp-config', cfgFile);
390
- mcpAllow.push(...mcpConfig.allowedTools);
391
- }
392
-
393
- // A remote (channel) caller's reach tier caps the toolset and OVERRIDES permissionMode: a
394
- // capped tier never gets --permission-mode, so writes/shell stay denied headlessly even if a
395
- // message (or a bug upstream) asked to escalate. Local callers (no reach) keep the existing
396
- // permissionMode behavior unchanged.
397
- const channelPolicy = channelToolPolicy(options.reach);
398
- if (channelPolicy) {
399
- // Read from the agent's own config each turn rather than cached at boot: a server the user
400
- // added five minutes ago should work on the next message, not the next restart.
401
- const own = channelMcpTools(options.reach, await connectorsFor('claude').catch(() => []));
402
- args.push('--allowedTools', ...channelPolicy.allow, ...mcpAllow, ...own.allow);
403
- args.push('--disallowedTools', ...channelPolicy.deny, ...own.deny);
404
- }
405
- // Gate writes/shell behind the chosen mode; otherwise restrict to read-only
406
- // tools so headless runs never block on an approval prompt. The relayed browser
407
- // tools are always pre-allowed (the user explicitly armed them this turn).
408
- else if (permissionMode === 'bypassPermissions') args.push('--permission-mode', 'bypassPermissions');
409
- else if (permissionMode === 'acceptEdits') {
410
- args.push('--permission-mode', 'acceptEdits');
411
- if (mcpAllow.length) args.push('--allowedTools', ...mcpAllow);
412
- } else args.push('--allowedTools', ...READONLY_TOOLS, ...mcpAllow);
413
-
414
- // Native Claude Code behavior; append the user's own system prompt if they set
415
- // one (no ChatPanel persona injected).
416
- if (system) args.push('--append-system-prompt', system);
417
- if (options.model) args.push('--model', options.model);
418
- // Default loads your ~/.claude + project settings (skills, MCP, CLAUDE.md).
419
- // "Use my local skills & config" off → run clean.
420
- if (options.useLocalConfig === false) args.push('--setting-sources', '');
421
-
422
- // Attach images by writing them to temp files and asking Claude Code to Read
423
- // them — its Read tool loads images as vision (no special flag needed).
424
- const imageFiles = await writeImages(images, tag);
425
- const cleanup = () => {
426
- imageFiles.forEach((f) => unlink(f).catch(() => {}));
427
- mcpFiles.forEach((f) => unlink(f).catch(() => {}));
428
- };
429
- let prompt = buildCliPrompt(messages);
430
- if (imageFiles.length) {
431
- prompt += `\n\nThe user attached ${imageFiles.length} image file(s). Use the Read tool to view ${
432
- imageFiles.length === 1 ? 'it' : 'them'
433
- }: ${imageFiles.join(', ')}`;
434
- }
435
-
436
- // Never let caller-supplied extras re-open the read-only boundary the mode flags
437
- // above establish (shared sanitizer — see args.js).
438
- pushExtraArgs(args, options.extraArgs, FORBIDDEN.claude, emit);
439
- // The CLI's own MCP tool timeout matches the relay's longest tool (a team run's budget), or
440
- // Claude Code gives up on the call before the bridge does. The user's own setting wins.
441
- const mcpEnv = mcpConfig && !process.env.MCP_TOOL_TIMEOUT ? { MCP_TOOL_TIMEOUT: String(relayTimeoutMax(options.mcp?.specs)) } : null;
442
- const runEnv = mcpEnv || options.runEnv ? { ...(options.runEnv || {}), ...(mcpEnv || {}) } : null;
443
- const run = runClaude({ prompt, args, cwd, env: runEnv, emit, signal });
444
- if (run === null) {
445
- cleanup(); // SDK fallback doesn't take images yet
446
- return sdkChat({ messages, system, options }, emit, { signal });
447
- }
448
- try {
449
- const { streamedAny, resultText } = await run;
450
- emit({ type: 'done', text: streamedAny ? '' : resultText });
451
- } finally {
452
- cleanup();
453
- }
454
- }
455
-
456
- // A fast, tool-free single-shot completion — used for prompt autocomplete. No
457
- // tools, no local config: just a quick text continuation from a fast model.
458
- export async function complete({ prompt, system, model }) {
459
- const args = [
460
- '--print',
461
- '--output-format', 'stream-json',
462
- '--verbose',
463
- '--disallowedTools', 'Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'Bash', 'Edit', 'Write', 'Task', 'TodoWrite',
464
- '--setting-sources', '',
465
- '--model', model || 'haiku',
466
- '--system-prompt', system || "Continue the user's text briefly. Reply with only the continuation.",
467
- ];
468
- let text = '';
469
- const run = runClaude({
470
- prompt,
471
- args,
472
- cwd: null,
473
- emit: (e) => {
474
- if (e.type === 'delta') text += e.text;
475
- },
476
- });
477
- if (run === null) return sdkComplete({ prompt, system, model }); // no CLI → SDK
478
- const { resultText } = await run;
479
- return (text || resultText || '').trim();
480
- }
481
-
482
- function toolSummary(block, cwd = '') {
483
- const i = block.input || {};
484
- if (i.command) return String(i.command).slice(0, 60);
485
- // Relative to the working directory rather than a bare basename: "src/foo.js" says
486
- // where the file is, "foo.js" left the user guessing which of four roots it meant.
487
- if (i.file_path) return displayPath(i.file_path, cwd);
488
- if (i.pattern) return i.pattern;
489
- if (i.url) return i.url;
490
- if (i.description) return String(i.description).slice(0, 80); // Task (subagent) — what it's for
491
- if (i.query) return String(i.query).slice(0, 80); // WebSearch / search tools
492
- if (i.prompt) return String(i.prompt).slice(0, 80); // subagent prompt fallback
493
- return '';
494
- }
495
-
496
- // ---------------------------------------------------------------------------
497
- // Fallback: in-process Claude Agent SDK. Only reached when no native/WSL claude
498
- // CLI is resolvable (and we're not a compiled binary, where its bundled cli.js
499
- // is unreachable). The SDK ships its own cli.js and uses your ~/.claude login.
500
-
501
- let sdkPromise = null;
502
- function loadSdk() {
503
- // Optional dependency — absent in lean/compiled installs; import().catch makes
504
- // that a graceful "no fallback available" rather than a crash.
505
- if (!sdkPromise) sdkPromise = import('@anthropic-ai/claude-agent-sdk').catch(() => null);
506
- return sdkPromise;
507
- }
508
-
509
- async function sdkChat({ messages, system, options }, emit, { signal } = {}) {
510
- const sdk = await loadSdk();
511
- if (!sdk) throw new Error(lastReason);
512
- const { query } = sdk;
513
-
514
- // The SDK cancels the run when this controller aborts — forward the request signal.
515
- const abortController = new AbortController();
516
- if (signal) {
517
- if (signal.aborted) abortController.abort();
518
- else signal.addEventListener('abort', () => abortController.abort(), { once: true });
519
- }
520
-
521
- const permissionMode = options.permissionMode || 'default';
522
- const cwd = resolveWorkdir(options.workingDir);
523
- const writesAllowed = permissionMode === 'acceptEdits' || permissionMode === 'bypassPermissions';
524
- const readonly = new Set(READONLY_TOOLS);
525
- const canUseTool = async (toolName) =>
526
- readonly.has(toolName) || writesAllowed
527
- ? { behavior: 'allow', updatedInput: undefined }
528
- : { behavior: 'deny', message: `${toolName} blocked — set this agent's permission mode in ChatPanel to enable it.` };
529
-
530
- let streamedAny = false;
531
-
532
- const flow = { sawText: false, tail: '', boundary: false };
533
- let resultText = '';
534
- const iterator = query({
535
- prompt: buildCliPrompt(messages),
536
- options: {
537
- cwd,
538
- permissionMode,
539
- includePartialMessages: true,
540
- canUseTool,
541
- abortController,
542
- settingSources: options.useLocalConfig === false ? [] : ['user', 'project'],
543
- systemPrompt: system
544
- ? { type: 'preset', preset: 'claude_code', append: system }
545
- : { type: 'preset', preset: 'claude_code' },
546
- ...(options.model ? { model: options.model } : {}),
547
- ...(process.env.CHATPANEL_MAX_TURNS ? { maxTurns: Number(process.env.CHATPANEL_MAX_TURNS) } : {}),
548
- },
549
- });
550
- try {
551
- for await (const message of iterator) {
552
- const r = handleMessage(message, emit, streamedAny, cwd, flow);
553
- if (r.streamed) streamedAny = true;
554
- if (r.result != null) resultText = r.result;
555
- }
556
- } catch (e) {
557
- if (signal?.aborted || abortController.signal.aborted) return; // Stop pressed — end quietly
558
- throw e;
559
- }
560
- emit({ type: 'done', text: streamedAny ? '' : resultText });
561
- }
562
-
563
- async function sdkComplete({ prompt, system, model }) {
564
- const sdk = await loadSdk();
565
- if (!sdk) throw new Error(lastReason);
566
- const { query } = sdk;
567
- let text = '';
568
- const iterator = query({
569
- prompt,
570
- options: {
571
- cwd: os.homedir(),
572
- permissionMode: 'default',
573
- allowedTools: [],
574
- maxTurns: 1,
575
- settingSources: [],
576
- systemPrompt: system || "Continue the user's text briefly. Reply with only the continuation.",
577
- model: model || 'haiku',
578
- },
579
- });
580
- for await (const message of iterator) {
581
- if (message.type === 'assistant') {
582
- for (const block of message.message.content) if (block.type === 'text') text += block.text;
583
- } else if (message.type === 'result' && message.subtype === 'success' && !text) {
584
- text = message.result || '';
585
- }
586
- }
587
- return text.trim();
588
- }
8
+ The user attached ${f.length} image file(s). Use the Read tool to view ${f.length===1?"it":"them"}: ${f.join(", ")}`),re(i,t.extraArgs,oe.claude,s);const d=u&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(ne(t.mcp?.specs))}:null,g=d||t.runEnv?{...t.runEnv||{},...d||{}}:null,T=B({prompt:_,args:i,cwd:l,env:g,emit:s,signal:n});if(T===null)return b(),ye({messages:e,system:o,options:t},s,{signal:n});try{const{streamedAny:c,resultText:C}=await T;s({type:"done",text:c?"":C})}finally{b()}}async function Le({prompt:e,system:o,model:t}){const a=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",t||"haiku","--system-prompt",o||"Continue the user's text briefly. Reply with only the continuation."];let s="";const n=B({prompt:e,args:a,cwd:null,emit:l=>{l.type==="delta"&&(s+=l.text)}});if(n===null)return _e({prompt:e,system:o,model:t});const{resultText:r}=await n;return(s||r||"").trim()}function he(e,o=""){const t=e.input||{};return t.command?String(t.command).slice(0,60):t.file_path?se(t.file_path,o):t.pattern?t.pattern:t.url?t.url:t.description?String(t.description).slice(0,80):t.query?String(t.query).slice(0,80):t.prompt?String(t.prompt).slice(0,80):""}let M=null;function O(){return M||(M=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),M}async function ye({messages:e,system:o,options:t},a,{signal:s}={}){const n=await O();if(!n)throw new Error(k);const{query:r}=n,l=new AbortController;s&&(s.aborted?l.abort():s.addEventListener("abort",()=>l.abort(),{once:!0}));const m=t.permissionMode||"default",i=j(t.workingDir),w=m==="acceptEdits"||m==="bypassPermissions",p=new Set(F),u=async d=>p.has(d)||w?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${d} blocked — set this agent's permission mode in ChatPanel to enable it.`};let y=!1;const f={sawText:!1,tail:"",boundary:!1};let b="";const _=r({prompt:R(e),options:{cwd:i,permissionMode:m,includePartialMessages:!0,canUseTool:u,abortController:l,settingSources:t.useLocalConfig===!1?[]:["user","project"],systemPrompt:o?{type:"preset",preset:"claude_code",append:o}:{type:"preset",preset:"claude_code"},...t.model?{model:t.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const d of _){const g=Y(d,a,y,i,f);g.streamed&&(y=!0),g.result!=null&&(b=g.result)}}catch(d){if(s?.aborted||l.signal.aborted)return;throw d}a({type:"done",text:y?"":b})}async function _e({prompt:e,system:o,model:t}){const a=await O();if(!a)throw new Error(k);const{query:s}=a;let n="";const r=s({prompt:e,options:{cwd:A.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:o||"Continue the user's text briefly. Reply with only the continuation.",model:t||"haiku"}});for await(const l of r)if(l.type==="assistant")for(const m of l.message.content)m.type==="text"&&(n+=m.text);else l.type==="result"&&l.subtype==="success"&&!n&&(n=l.result||"");return n.trim()}export{$e as available,de as channelMcpTools,pe as channelToolPolicy,Pe as chat,fe as claudeMcpConfig,Le as complete,Y as handleMessage,Ne as listModels};