@chatpanel/bridge 0.11.24 → 0.12.0

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 (69) hide show
  1. package/.env.example +12 -0
  2. package/README.md +7 -7
  3. package/package.json +1 -13
  4. package/scripts/sync-channels.mjs +8 -90
  5. package/scripts/sync-events.mjs +7 -78
  6. package/scripts/sync-pii.mjs +7 -68
  7. package/src/api-compat.js +5 -294
  8. package/src/channels/adapters/telegram.js +3 -298
  9. package/src/channels/bridge.js +1 -59
  10. package/src/channels/eventlog.js +3 -57
  11. package/src/channels/gateway.js +1 -114
  12. package/src/channels/invoke.js +1 -172
  13. package/src/channels/normalize.js +1 -58
  14. package/src/channels/pairing.js +1 -95
  15. package/src/channels/service.js +1 -329
  16. package/src/channels/stream.js +5 -104
  17. package/src/cli-errors.js +3 -136
  18. package/src/connections.js +1 -160
  19. package/src/connectors.js +1 -100
  20. package/src/engines/antigravity.js +5 -235
  21. package/src/engines/args.js +1 -47
  22. package/src/engines/claude-warm.js +3 -0
  23. package/src/engines/claude.js +6 -586
  24. package/src/engines/cli-agents.js +7 -312
  25. package/src/engines/codex-appserver.js +12 -0
  26. package/src/engines/codex.js +6 -481
  27. package/src/engines/custom.js +17 -577
  28. package/src/engines/prompt.js +6 -32
  29. package/src/engines/stream-formats.js +2 -222
  30. package/src/entitlement.js +1 -77
  31. package/src/env.js +3 -628
  32. package/src/events/capability.js +1 -134
  33. package/src/events/event.js +1 -183
  34. package/src/events/reach.js +1 -31
  35. package/src/events/ref.js +1 -63
  36. package/src/events/scm-connection.js +1 -188
  37. package/src/events/scopes.js +1 -20
  38. package/src/events/skill-manifest.js +1 -338
  39. package/src/events/skill-scan.js +3 -217
  40. package/src/events/view.js +1 -96
  41. package/src/mcp-capabilities.js +2 -139
  42. package/src/mcp-local.js +0 -0
  43. package/src/mcp-quarantine.js +1 -110
  44. package/src/mcp-sessions.js +1 -0
  45. package/src/net.js +1 -107
  46. package/src/pii/index.js +1 -29
  47. package/src/pii/net.js +1 -111
  48. package/src/pii/pii-detect.js +2 -296
  49. package/src/pii/pii-redact.js +1 -470
  50. package/src/pii/pipeline.js +1 -137
  51. package/src/pii/sanitize.js +2 -179
  52. package/src/pii/tool-harness.js +1 -184
  53. package/src/pii/tool-rank.js +1 -110
  54. package/src/proc.js +3 -91
  55. package/src/relay-timeout.js +1 -21
  56. package/src/rpc-child.js +3 -0
  57. package/src/runs.js +1 -49
  58. package/src/sanitize.js +1 -7
  59. package/src/scm.js +1 -76
  60. package/src/server.js +10 -1492
  61. package/src/service.js +11 -176
  62. package/src/sign-in.js +1 -91
  63. package/src/skills.js +1 -399
  64. package/src/ssrf.js +1 -70
  65. package/src/update.js +1 -216
  66. package/src/warm-pool.js +1 -0
  67. package/src/warm.js +1 -0
  68. package/src/workdir.js +1 -108
  69. package/src/worktree.js +3 -125
package/src/server.js CHANGED
@@ -1,1504 +1,22 @@
1
1
  #!/usr/bin/env node
2
- // ChatPanel Bridge — a tiny localhost server that exposes the coding agents
3
- // running on this machine (Claude Code, Codex and Antigravity, each via its CLI) to
4
- // the ChatPanel Chrome extension. Zero runtime dependencies.
5
- //
6
- // GET /health → { ok, version, agents: [{id,label,available,reason,connectors}], update }
7
- // POST /update → self-update to the latest release (compiled binary installs)
8
- // POST /chat → Server-Sent Events stream of { type, ... }:
9
- // {type:'delta', text} incremental assistant text
10
- // {type:'tool', name, summary}
11
- // {type:'status'|'reasoning', text?}
12
- // {type:'workdir', path, isDefault} where this run writes
13
- // {type:'scm', phase:'before'|'after', repo, remote?, branch, head, commits?}
14
- // the checkout it worked in, when it is one
15
- // {type:'workspace', path, branch, base, created, connection?}
16
- // the worktree the run was given (options.workspace)
17
- // {type:'done', text?} (text only if not streamed)
18
- // {type:'error', error}
19
- // POST /v1/chat/completions, /v1/completions, /v1/responses
20
- // → OpenAI-compatible text adapters for the local agents
21
- // POST /v1/messages → Anthropic-compatible text adapter for the local agents
22
- // GET /connections → SCM connections on this machine (records; never a token)
23
- // POST /connections → { connection, token? } save one; the token goes to the keychain
24
- // POST /connections/<id>/test { remote? } · POST /connections/<id>/delete
25
- // GET /worktrees → the job worktrees the bridge made · POST /worktrees/remove
26
- // GET /skills → skill packages on disk (name + description + files)
27
- // GET /skills/<name> → one skill, SKILL.md body included
28
- // GET /skills/<name>/file/<path> → one reference/template/asset from that package
29
- //
30
- // Binds to 127.0.0.1 only. A request guard (see `guard()`) enforces a loopback
31
- // Host (anti DNS-rebinding) and an allowlisted Origin; the command-spawning
32
- // endpoints (/chat, /mcp-local, /update, …) additionally require the extension
33
- // origin or the per-install bridge token, so a malicious web page can't drive
34
- // local execution. The CLI-facing /mcp endpoints stay open to no-Origin clients.
2
+ import{createServer as ce}from"node:http";import x from"node:os";import{randomBytes as le,timingSafeEqual as de}from"node:crypto";import{mkdirSync as ue,writeFileSync as he,readFileSync as pe,existsSync as me}from"node:fs";import{join as $}from"node:path";import*as fe from"./engines/claude.js";import*as ge from"./engines/codex.js";import*as ye from"./engines/antigravity.js";import{pi as we,opencode as be,kiro as Se,copilot as ke,deepseek as Te,hermes as ve}from"./engines/cli-agents.js";import{connectorsFor as Ce}from"./connectors.js";import*as Ee from"./engines/custom.js";import{installService as Oe,uninstallService as Ae,serviceStatus as xe,restartService as j}from"./service.js";import{skillIndex as B,listRecords as Pe,readRecord as $e,readPackageFile as Ie,skillsHealth as Ne,quarantinedSkills as Re}from"./skills.js";import{capabilityToolSpecs as He,runCapabilityTool as _e}from"./mcp-capabilities.js";import{createSession as Me,deleteSession as J,getSession as F,activeSession as Be,relayToolCall as Ge}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ue,isDefaultWorkdir as De,resolveWorkdir as Le,writeScopeNote as We}from"./workdir.js";import{gitState as je,gitDelta as Je}from"./scm.js";import{listConnections as Fe,putConnection as Ke,removeConnection as ze,runEnvFor as Ve,testConnection as Ye,secretBackend as K}from"./connections.js";import{worktreeFor as z,listWorktrees as Xe,removeWorktree as Qe,withHook as Ze,WORKTREE_ROOT as V}from"./worktree.js";import{AGENT_CLIS as qe,enrichPath as et,enrichAgentEnv as tt,findAgentBin as Y,resolveCommand as nt}from"./env.js";import"./sanitize.js";import{checkForUpdate as rt,selfUpdate as X,isEmbedded as ot}from"./update.js";import{callLocalMcp as at}from"./mcp-local.js";import{assertPublicHttpUrl as Q,assertPublicWebUrl as Z}from"./ssrf.js";import{startRun as q,endRun as G,cancelRun as it,cancelAll as st}from"./runs.js";import{closeWarmPools as ct,warmStatus as lt}from"./warm.js";import{CompatError as I,anthropicError as U,anthropicStream as dt,chatCompletionStream as ut,completionStream as ht,createAnthropicMessage as pt,createChatCompletion as mt,createCompletion as ft,createResponse as gt,openAIError as w,parseAnthropicMessage as yt,parseChatCompletion as wt,parseCompletion as bt,parseResponse as St,responseStream as kt}from"./api-compat.js";const g="0.12.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",O=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,T={claude:{engine:fe,label:"Claude Code"},codex:{engine:ge,label:"Codex"},antigravity:{engine:ye,label:"Antigravity"},pi:{engine:we,label:"Pi"},opencode:{engine:be,label:"OpenCode"},hermes:{engine:ve,label:"Hermes"},kiro:{engine:Se,label:"Kiro"},copilot:{engine:ke,label:"GitHub Copilot"},deepseek:{engine:Te,label:"DeepSeek Harness"},custom:{engine:Ee,label:"Custom",hidden:!0}};function ee(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Tt(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function vt(n,e){const t=n.headers.origin||"",o=ee(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const D=new Set(["127.0.0.1","localhost","::1"]);function Ct(n){if(!D.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return D.has(t)}const L=$(x.homedir(),".chatpanel","bridge-token");let v="";function Et(){try{me(L)&&(v=pe(L,"utf8").trim()),v||(v=le(32).toString("hex"),ue($(x.homedir(),".chatpanel"),{recursive:!0}),he(L,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}let N=null;async function te(){if(N)return N;const{createChannelService:n}=await import("./channels/service.js");return N=n({home:$(x.homedir(),".chatpanel"),dataDir:$(x.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${O}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),N}async function ne(n,e,t){try{const o=await te(),r=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await o.status());if(t==="connect"){const i=await o.connect(r);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await o.pair()):t==="unpair"?a(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?a(e,200,await o.update(r)):t==="disconnect"?a(e,200,await o.stop({forget:!!r.forget})):a(e,404,{error:"unknown channel action"})}catch(o){return a(e,400,{error:o?.message||String(o)})}}function Ot(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&de(o,r)}const At=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees"]),xt=new Set(["/debug"]),Pt=n=>xt.has(n);function $t(n,e){if(!Ct(n))return"forbidden host";const t=n.headers.origin||"";return t&&!ee(t)?"forbidden origin":(n.method==="POST"&&At.has(e)||n.method==="GET"&&Pt(e))&&!(Tt(t)||Ot(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":null}function a(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}async function It(n){const e=await Promise.all(Object.entries(T).filter(([,r])=>!r.hidden).map(async([r,{engine:i,label:l}])=>{const d=await i.available().catch(s=>({ok:!1,reason:String(s?.message||s)})),c=await Ce(r).catch(()=>[]);return{id:r,label:l,available:d.ok,reason:d.reason,connectors:c}})),t=ot()?{current:g,updateAvailable:!1,embedded:"gateway"}:await rt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ne().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:Ue,worktrees:V,secretBackend:K(),warm:lt(),...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Nt(n,e){const{index:t,problems:o}=await B({extraDirs:e});a(n,200,{ok:!0,skills:Pe(t),problems:o})}async function Rt(n,e){a(n,200,{ok:!0,quarantined:await Re(e)})}async function Ht(n,e,t){const{index:o}=await B({extraDirs:t}),r=$e(o,e);if(!r)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:r})}async function _t(n,e,t,o){const{index:r}=await B({extraDirs:o}),i=await Ie(r,e,t);if(i.error)return a(n,i.error==="unknown skill"?404:400,{ok:!1,error:i.error});a(n,200,{ok:!0,...i})}async function Mt(){return(await Promise.all(Object.entries(T).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function re(n,e=""){const t=await Mt();if(e){const o=t.find(r=>r.id===e);return o?a(n,200,o):a(n,404,w(new I(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function Bt(n){try{const e=await X(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>j(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function Gt(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const o=T[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const r=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
35
3
 
36
- import { createServer } from 'node:http';
37
- import os from 'node:os';
38
- import { randomUUID, randomBytes, timingSafeEqual } from 'node:crypto';
39
- import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
40
- import { join } from 'node:path';
41
- import * as claude from './engines/claude.js';
42
- import * as codex from './engines/codex.js';
43
- import * as antigravity from './engines/antigravity.js';
44
- import { pi, opencode, kiro, copilot, deepseek , hermes } from './engines/cli-agents.js';
45
- import { connectorsFor } from './connectors.js';
46
- import * as custom from './engines/custom.js';
47
- import { installService, uninstallService, serviceStatus, restartService } from './service.js';
48
- import { skillIndex, listRecords, readRecord, readPackageFile, skillsHealth, quarantinedSkills } from './skills.js';
49
- import { capabilityToolSpecs, runCapabilityTool } from './mcp-capabilities.js';
50
- import { relayTimeoutFor } from './relay-timeout.js';
51
- import { DEFAULT_WORKSPACE, isDefaultWorkdir, resolveWorkdir, writeScopeNote } from './workdir.js';
52
- import { gitState, gitDelta } from './scm.js';
53
- import { listConnections, putConnection, removeConnection, runEnvFor, testConnection, secretBackend } from './connections.js';
54
- import { worktreeFor, listWorktrees, removeWorktree, withHook, WORKTREE_ROOT } from './worktree.js';
55
- import { AGENT_CLIS, enrichPath, enrichAgentEnv, findAgentBin, resolveCommand } from './env.js';
56
- import { stripHidden } from './sanitize.js';
57
- import { checkForUpdate, selfUpdate, isEmbedded } from './update.js';
58
- import { callLocalMcp } from './mcp-local.js';
59
- import { assertPublicHttpUrl, assertPublicWebUrl } from './ssrf.js';
60
- import { startRun, endRun, cancelRun, cancelAll, activeRuns } from './runs.js';
61
- import {
62
- CompatError,
63
- anthropicError,
64
- anthropicStream,
65
- chatCompletionStream,
66
- completionStream,
67
- createAnthropicMessage,
68
- createChatCompletion,
69
- createCompletion,
70
- createResponse,
71
- openAIError,
72
- parseAnthropicMessage,
73
- parseChatCompletion,
74
- parseCompletion,
75
- parseResponse,
76
- responseStream,
77
- } from './api-compat.js';
4
+ `)};let i=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,d=q(l),c={signal:d.signal,abort:()=>d.cancel("client")},s=()=>{i=!0,d.cancel("disconnected")};n.on("close",s),e.on("close",s),e.on("error",s);const h=p=>{i||r(p)};r({type:"run",id:l});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const p=t.options.workspace;if(m=await z({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),m.error){r({type:"error",error:`workspace: ${m.error}`}),G(l),e.writableEnded||e.end();return}}const b=m?m.path:Le(t.options?.workingDir);let C=null;{const p=b,E=!!m||!De(t.options?.workingDir),y=We(t.agent,t.options?.permissionMode,p);r({type:"workdir",path:p,isDefault:!E,writeScope:y||void 0}),r({type:"status",text:`Working in ${p}${E?"":" (default)"}`}),y&&r({type:"status",text:y}),C=await je(p),C&&r({type:"scm",phase:"before",...C})}let M=null;if(C||m){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:E,connection:y}=Ve({remote:C?.remote||null,grants:p,branch:m?.branch||null,connectionId:t.options?.connectionId||null});M=Ze(E),m&&r({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&r({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${E.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:E.CHATPANEL_SCM_PUSH}`})}const W={...t.options||{},...m?{workingDir:m.path}:{},...M?{runEnv:M}:{}};let P=null;t.pageTools?.specs?.length&&(P=Me(h,t.pageTools.specs),W.mcp={url:`http://${k}:${O}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs});try{await o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:W,images:Array.isArray(t.images)?t.images:[]},h,{signal:c.signal})}catch(p){u("error",`${t.agent} chat failed: ${p?.message||p}`),r({type:"error",error:p?.message||String(p)})}finally{if(!i){const p=await Je(b,C).catch(()=>null);p&&h({type:"scm",phase:"after",...p})}G(l),P&&J(P.id),e.writableEnded||e.end()}}async function Ut(n,e,t){if(n.method==="GET"&&t==="/connections")return a(e,200,{ok:!0,connections:Fe(),secretBackend:K()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const o=await f(n);if(t==="/connections")try{return a(e,200,{ok:!0,connection:Ke(o.connection||o,{token:o.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return r?r[2]==="delete"?a(e,200,{ok:ze(r[1])}):a(e,200,Ye(r[1],o.remote||"")):a(e,404,{error:"Not found"})}async function Dt(n,e,t){if(n.method==="GET"&&t==="/worktrees")return a(e,200,{ok:!0,root:V,worktrees:await Xe()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const o=await f(n);if(t==="/worktrees"){const r=await z({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return a(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(t==="/worktrees/remove"){const r=await Qe({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return a(e,r.ok?200:400,r)}return a(e,404,{error:"Not found"})}async function S(n,e,t){const o=T[n.agent];if(!o||o.hidden)throw new I(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(s=>({ok:!1,reason:s?.message||String(s)}));if(!r.ok)throw new I(r.reason||`${n.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,l=q(i),d=()=>l.cancel("disconnected");t.on("close",d);let c="";try{return await o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},s=>{s?.type==="delta"&&s.text?(c+=s.text,e(s.text)):s?.type==="done"&&s.text&&!c&&(c=s.text,e(s.text))},{signal:l.signal}),c}finally{t.off("close",d),G(i)}}function R(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function A(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
78
5
 
79
- // Hardcoded (not read from package.json) so it survives Bun's single-file
80
- // --compile, where package.json isn't on a readable FS. CI fails the publish if
81
- // this drifts from package.json, so the two can't silently diverge.
82
- const VERSION = '0.11.24';
83
- const HOST = process.env.CHATPANEL_BRIDGE_HOST || '127.0.0.1';
84
- const PORT = Number(process.env.CHATPANEL_BRIDGE_PORT) || 4319;
6
+ `)}function H(n,e,t){n.writableEnded||n.write(`event: ${e}
7
+ data: ${JSON.stringify(t)}
85
8
 
86
- const ENGINES = {
87
- claude: { engine: claude, label: 'Claude Code' },
88
- codex: { engine: codex, label: 'Codex' },
89
- antigravity: { engine: antigravity, label: 'Antigravity' },
90
- pi: { engine: pi, label: 'Pi' },
91
- opencode: { engine: opencode, label: 'OpenCode' },
92
- hermes: { engine: hermes, label: 'Hermes' },
93
- kiro: { engine: kiro, label: 'Kiro' },
94
- copilot: { engine: copilot, label: 'GitHub Copilot' },
95
- deepseek: { engine: deepseek, label: 'DeepSeek Harness' },
96
- // "Bring your own" — one engine drives any user-onboarded CLI (Pro). Hidden
97
- // from /health (it's not a single installable agent; the extension manages the
98
- // list and validates commands via /agent-check).
99
- custom: { engine: custom, label: 'Custom', hidden: true },
100
- };
101
-
102
- // --------------------------------------------------------------------------
103
- // Browser-tools relay. When the extension arms "Act on page" for a CLI agent, it
104
- // sends the tool specs in /chat. We host an HTTP MCP server (/mcp/<session>) the
105
- // CLI connects to; each tools/call is RELAYED to the extension over the chat SSE
106
- // stream (a `tool_request` event), executed there (it owns the browser), and the
107
- // result POSTed back to /tool-result. The bridge itself never touches the page.
108
- // --------------------------------------------------------------------------
109
- const sessions = new Map(); // sessionId -> { id, emit, specs, pending: Map, nextId }
110
- let latestSessionId = null; // for the stable /mcp endpoint (CLIs configured once)
111
-
112
- function createSession(emit, specs) {
113
- const id = randomUUID();
114
- const s = { id, emit, specs, pending: new Map(), nextId: 0 };
115
- sessions.set(id, s);
116
- latestSessionId = id;
117
- return s;
118
- }
119
-
120
- function deleteSession(id) {
121
- const s = sessions.get(id);
122
- if (!s) return;
123
- for (const p of s.pending.values()) p.reject(new Error('chat ended'));
124
- sessions.delete(id);
125
- if (latestSessionId === id) {
126
- // fall back to the most-recently-created surviving session, if any
127
- const ids = [...sessions.keys()];
128
- latestSessionId = ids.length ? ids[ids.length - 1] : null;
129
- }
130
- }
131
-
132
- // The session a sessionless /mcp request maps to (CLIs configured once with a
133
- // stable URL — e.g. `opencode mcp add chatpanel --url …/mcp`). The active chat.
134
- function activeSession() {
135
- return (latestSessionId && sessions.get(latestSessionId)) || null;
136
- }
137
-
138
- // Ask the extension to run a tool and await its result. Resolves to MCP content.
139
- function relayToolCall(session, name, input) {
140
- return new Promise((resolve, reject) => {
141
- const id = `t${++session.nextId}`;
142
- const timer = setTimeout(() => {
143
- session.pending.delete(id);
144
- reject(new Error('tool call timed out'));
145
- }, relayTimeoutFor(session.specs, name)); // a team run declares its budget; see relay-timeout.js
146
- session.pending.set(id, {
147
- resolve: (result) => { clearTimeout(timer); resolve(toMcpContent(result)); },
148
- reject: (e) => { clearTimeout(timer); reject(e); },
149
- });
150
- session.emit({ type: 'tool_request', session: session.id, id, name, input });
151
- });
152
- }
153
-
154
- // The extension returns a string OR { text, image(dataURL) }; map to MCP content.
155
- function toMcpContent(result) {
156
- // L5: de-steganographize tool-result TEXT before it flows back to the CLI/model —
157
- // the bridge is a public localhost endpoint, so (like the prompt path) it must strip
158
- // ASCII-smuggled / bidi Unicode from relayed results, not assume the caller did.
159
- if (result == null) return { content: [{ type: 'text', text: 'ok' }] };
160
- if (typeof result === 'string') return { content: [{ type: 'text', text: stripHidden(result) }] };
161
- const content = [];
162
- if (result.text) content.push({ type: 'text', text: stripHidden(String(result.text)) });
163
- if (typeof result.image === 'string') {
164
- const m = /^data:([^;]+);base64,(.+)$/s.exec(result.image);
165
- if (m) content.push({ type: 'image', data: m[2], mimeType: m[1] });
166
- }
167
- if (!content.length) content.push({ type: 'text', text: 'ok' });
168
- return { content };
169
- }
170
-
171
- // --------------------------------------------------------------------------
172
- // CORS — allow the extension (chrome-extension://…) and localhost dev origins.
173
- // NOTE: CORS only controls whether a *page* may READ the response; it does NOT
174
- // stop a cross-origin request from running. The hard allow/deny gating that
175
- // actually protects the command-spawning endpoints lives in `guard()` below.
176
- // --------------------------------------------------------------------------
177
- function originAllowed(origin) {
178
- return (
179
- !origin ||
180
- origin.startsWith('chrome-extension://') ||
181
- origin.startsWith('moz-extension://') ||
182
- origin.startsWith('http://localhost') ||
183
- origin.startsWith('http://127.0.0.1') ||
184
- origin.startsWith('http://[::1]')
185
- );
186
- }
187
-
188
- // An origin that identifies the ChatPanel extension (or a local dev build).
189
- // Distinct from originAllowed(): this REQUIRES the header to be present, so a
190
- // no-Origin local process cannot pose as the extension on privileged routes.
191
- function isExtensionOrigin(origin) {
192
- return (
193
- origin.startsWith('chrome-extension://') ||
194
- origin.startsWith('moz-extension://') ||
195
- origin.startsWith('http://localhost') ||
196
- origin.startsWith('http://127.0.0.1') ||
197
- origin.startsWith('http://[::1]')
198
- );
199
- }
200
-
201
- function cors(req, res) {
202
- const origin = req.headers.origin || '';
203
- const allow = originAllowed(origin);
204
- res.setHeader('Access-Control-Allow-Origin', allow ? origin || '*' : 'null');
205
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
206
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token');
207
- res.setHeader('Vary', 'Origin');
208
- }
209
-
210
- // --------------------------------------------------------------------------
211
- // Security gates — defend the localhost server against a malicious web page.
212
- //
213
- // Two browser attack classes are in scope even though we bind to 127.0.0.1:
214
- // 1. DNS rebinding — a page on http://evil.example rebinds that name to
215
- // 127.0.0.1 and fetches http://evil.example:PORT/…; the request arrives
216
- // with Host: evil.example, which a naïve server happily serves.
217
- // 2. Cross-origin CSRF — a page POSTs a CORS "simple" request (text/plain)
218
- // to http://127.0.0.1:PORT/…; no preflight fires and the side effect runs.
219
- //
220
- // hostAllowed() closes (1) by rejecting any non-loopback Host. The Origin
221
- // checks close (2). Privileged endpoints additionally require the extension
222
- // origin or the per-install token, so a no-Origin local process can't drive
223
- // command execution either.
224
- // --------------------------------------------------------------------------
225
- const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '::1']);
226
-
227
- function hostAllowed(req) {
228
- // If the operator deliberately bound to a non-loopback/all interface
229
- // (CHATPANEL_BRIDGE_HOST=0.0.0.0 / a LAN IP), don't second-guess their Host.
230
- if (!LOOPBACK_HOSTNAMES.has(HOST)) return true;
231
- const raw = String(req.headers.host || '');
232
- if (!raw) return false; // HTTP/1.1 requires Host; absent → reject
233
- const hostname = raw
234
- .replace(/:\d+$/, '') // strip :port
235
- .replace(/^\[|\]$/g, '') // strip IPv6 brackets
236
- .toLowerCase();
237
- return LOOPBACK_HOSTNAMES.has(hostname);
238
- }
239
-
240
- // Per-install bearer token — defense-in-depth so a non-browser local client can
241
- // authenticate to privileged routes without relying on an Origin header. Written
242
- // 0600 to ~/.chatpanel/bridge-token; the extension is allowed by origin and need
243
- // not send it, so adding this never breaks the existing wire contract.
244
- const TOKEN_PATH = join(os.homedir(), '.chatpanel', 'bridge-token');
245
- let AUTH_TOKEN = '';
246
- function ensureToken() {
247
- try {
248
- if (existsSync(TOKEN_PATH)) AUTH_TOKEN = readFileSync(TOKEN_PATH, 'utf8').trim();
249
- if (!AUTH_TOKEN) {
250
- AUTH_TOKEN = randomBytes(32).toString('hex');
251
- mkdirSync(join(os.homedir(), '.chatpanel'), { recursive: true });
252
- writeFileSync(TOKEN_PATH, AUTH_TOKEN, { mode: 0o600 });
253
- }
254
- } catch (e) {
255
- // Token is optional hardening — never fail startup over it.
256
- log('error', `could not initialise bridge token: ${e?.message || e}`);
257
- }
258
- }
259
- // ---------------------------------------------------------------------------
260
- // CHANNELS — a messaging surface (Telegram today) driving a local agent.
261
- //
262
- // Hosted HERE because a channel has to be running when nobody is looking: the point is to
263
- // reach your machine from a phone with the browser closed, and the bridge is the only
264
- // always-on local process a ChatPanel user already has. The alternative — a second daemon, or
265
- // an npm install, or a service worker Chrome suspends — is another thing a non-technical
266
- // person has to install and keep alive, which is the same as not shipping it.
267
- //
268
- // The bridge owns transport and auth; @chatpanel/channels (vendored to src/channels) owns the
269
- // contract: verify a bot, hold its token 0600, enroll a phone by one-time code, cap it with
270
- // `reach`, redact both ways. Loaded lazily so the redaction engine never touches a boot where
271
- // no channel is configured.
272
- let channelsSvc = null;
273
- async function channelService() {
274
- if (channelsSvc) return channelsSvc;
275
- const { createChannelService } = await import('./channels/service.js');
276
- channelsSvc = createChannelService({
277
- home: join(os.homedir(), '.chatpanel'),
278
- dataDir: join(os.homedir(), '.chatpanel', 'channels'),
279
- // It talks to THIS bridge as a privileged local client — same port, same token it just
280
- // read. No second address to configure and get wrong.
281
- bridge: { baseUrl: `http://127.0.0.1:${PORT}`, token: AUTH_TOKEN },
282
- logger: { log: (m) => log('info', m), warn: (m) => log('info', m), error: (m) => log('error', m) },
283
- });
284
- return channelsSvc;
285
- }
286
-
287
- async function handleChannels(req, res, action) {
288
- try {
289
- const svc = await channelService();
290
- const body = req.method === 'POST' ? await readBody(req) : {};
291
- if (action === 'status') return json(res, 200, await svc.status());
292
- if (action === 'connect') {
293
- // The token is verified with Telegram before it is written, so a typo fails HERE, in the
294
- // settings screen, with a reason — not later as a silent poll loop nobody reads the logs of.
295
- const r = await svc.connect(body);
296
- return json(res, 200, { ok: true, ...r });
297
- }
298
- if (action === 'pair') return json(res, 200, await svc.pair());
299
- if (action === 'unpair') return json(res, 200, await svc.unpair(String(body.actorId || '')));
300
- if (action === 'settings') return json(res, 200, await svc.update(body));
301
- if (action === 'disconnect') return json(res, 200, await svc.stop({ forget: !!body.forget }));
302
- return json(res, 404, { error: 'unknown channel action' });
303
- } catch (e) {
304
- // A readable reason, because every one of these is something a person can fix: a bad token,
305
- // a bot not created yet, no network.
306
- return json(res, 400, { error: e?.message || String(e) });
307
- }
308
- }
309
-
310
- function tokenOk(req) {
311
- if (!AUTH_TOKEN) return false;
312
- const h = String(req.headers['authorization'] || '');
313
- const provided = (h.startsWith('Bearer ')
314
- ? h.slice(7)
315
- : String(req.headers['x-api-key'] || req.headers['x-chatpanel-token'] || '')).trim();
316
- if (!provided) return false;
317
- const a = Buffer.from(provided);
318
- const b = Buffer.from(AUTH_TOKEN);
319
- return a.length === b.length && timingSafeEqual(a, b);
320
- }
321
-
322
- // POST sinks that spawn local agents/commands or self-update, plus GET /debug
323
- // (leaks PATH/home). Only the extension (allowlisted origin) or a token-bearing
324
- // client may reach these. The CLI-facing /mcp and /mcp/<id> routes are NOT here:
325
- // local coding-agent CLIs connect to them with no Origin header by design.
326
- const PRIVILEGED_POST = new Set([
327
- '/chat',
328
- '/v1/chat/completions',
329
- '/v1/completions',
330
- '/v1/responses',
331
- '/v1/messages',
332
- '/mcp-local',
333
- '/mcp-remote',
334
- '/fetch-title',
335
- '/complete',
336
- '/list-models',
337
- '/agent-check',
338
- '/update',
339
- '/tool-result',
340
- // Cancelling someone else's run is a denial of service, small but real — and every other
341
- // endpoint that touches a run is already guarded. An unauthenticated hole next to nine
342
- // guarded neighbours is a hole regardless of how little it grants.
343
- '/cancel',
344
- // A channel is a way into this machine from the internet. Everything that configures one —
345
- // and the code that enrolls a phone — is as privileged as /chat itself.
346
- '/channels/connect',
347
- '/channels/pair',
348
- '/channels/unpair',
349
- '/channels/settings',
350
- '/channels/disconnect',
351
- // An SCM connection holds a token for this machine's git; a worktree is a checkout the
352
- // bridge makes. Both are as privileged as /chat.
353
- '/connections',
354
- '/worktrees',
355
- ]);
356
- // /channels is NOT here, for the same reason /skills is not, and it was a regression to add
357
- // it: a privileged GET is unreachable from the extension. The panel holds `<all_urls>`, so
358
- // its fetches bypass CORS altogether — no preflight fires — and the Fetch spec attaches
359
- // `Origin` only to requests whose method is not GET or HEAD. That is the whole asymmetry:
360
- // every privileged POST here works, and a privileged GET can only ever answer the settings
361
- // page with "forbidden: this endpoint requires the ChatPanel extension or a valid bridge
362
- // token", which is what shipped in 0.11.0.
363
- //
364
- // Nothing is opened up by removing it. `originAllowed` still refuses any web page (it is the
365
- // check doing the work), so the only caller admitted is a local no-Origin process — which can
366
- // already read ~/.chatpanel/channels/ off the disk. /debug stays privileged: it exposes
367
- // configuration a local process cannot otherwise see.
368
- const PRIVILEGED_GET = new Set(['/debug']);
369
-
370
- // /skills* is NOT privileged, and that is a considered position rather than a
371
- // convenience. `privileged` adds exactly one thing over the origin allowlist: it requires
372
- // the Origin header to be PRESENT, so a no-Origin local process cannot pose as the
373
- // extension. Work through who that actually excludes for a read-only listing of files:
374
- //
375
- // • a web page — always sends Origin, and a non-allowed one is already refused above;
376
- // • a page on http://localhost — sends Origin, which `isExtensionOrigin` already
377
- // accepts, so the privileged check never stopped it either way;
378
- // • a page using <img>/<script> to force a no-Origin GET — cannot read the response,
379
- // because it is JSON with no CORS grant to that origin;
380
- // • remote SSRF into 127.0.0.1 — arrives with a non-loopback Host and dies at
381
- // `hostAllowed` long before this;
382
- // • a local process — the only caller left, and it can read the very same SKILL.md
383
- // files straight off the disk.
384
- //
385
- // So the requirement excluded nothing that could not already read the bytes, while
386
- // breaking the one client that should have them: Chrome omits Origin on a simple GET from
387
- // an extension page (the POST routes get it only because a JSON body forces a preflight).
388
- // The origin allowlist stays and is what keeps web pages out. /debug remains privileged —
389
- // it exposes configuration a local process cannot otherwise see.
390
- const isPrivilegedGetPath = (p) => PRIVILEGED_GET.has(p);
391
-
392
- // SSRF guard for /mcp-remote lives in ./ssrf.js (assertPublicHttpUrl). Loopback
393
- // is allowed (the user's own localhost MCP server — the common "via bridge"
394
- // case; the extension can reach it directly anyway), cloud metadata is always
395
- // blocked, and other private/LAN ranges are blocked unless the operator sets
396
- // CHATPANEL_BRIDGE_ALLOW_PRIVATE_HOSTS=1. Checked on the initial URL AND after
397
- // any redirect.
398
-
399
- // Returns an error code if the request must be blocked, else null.
400
- function guard(req, pathname) {
401
- if (!hostAllowed(req)) return 'forbidden host';
402
- const origin = req.headers.origin || '';
403
- if (origin && !originAllowed(origin)) return 'forbidden origin';
404
- const privileged =
405
- (req.method === 'POST' && PRIVILEGED_POST.has(pathname)) ||
406
- (req.method === 'GET' && isPrivilegedGetPath(pathname));
407
- if (privileged && !(isExtensionOrigin(origin) || tokenOk(req))) {
408
- return 'forbidden: this endpoint requires the ChatPanel extension or a valid bridge token';
409
- }
410
- return null;
411
- }
412
-
413
- function json(res, code, obj) {
414
- res.writeHead(code, { 'Content-Type': 'application/json' });
415
- res.end(JSON.stringify(obj));
416
- }
417
-
418
- function readBody(req) {
419
- return new Promise((resolve, reject) => {
420
- let data = '';
421
- req.on('data', (c) => {
422
- data += c;
423
- if (data.length > 50 * 1024 * 1024) reject(new Error('Body too large'));
424
- });
425
- req.on('end', () => {
426
- try {
427
- resolve(data ? JSON.parse(data) : {});
428
- } catch (e) {
429
- reject(e);
430
- }
431
- });
432
- req.on('error', reject);
433
- });
434
- }
435
-
436
- // --------------------------------------------------------------------------
437
- // Routes
438
- // --------------------------------------------------------------------------
439
- async function handleHealth(res) {
440
- const agents = await Promise.all(
441
- Object.entries(ENGINES)
442
- .filter(([, e]) => !e.hidden)
443
- .map(async ([id, { engine, label }]) => {
444
- const a = await engine.available().catch((e) => ({ ok: false, reason: String(e?.message || e) }));
445
- // WHAT THIS AGENT CAN ALREADY REACH, so the client stops guessing. A CLI agent brings
446
- // its own connectors — a Slack MCP, a Jira MCP — that the extension cannot see, and
447
- // an agent that was never told it may use them answers "go and look it up yourself".
448
- // NAMES ONLY: a server's name is what a prompt needs; its URL, argv and env are what
449
- // a leak would be made of. Additive, so an older extension ignores it.
450
- const connectors = await connectorsFor(id).catch(() => []);
451
- return { id, label, available: a.ok, reason: a.reason, connectors };
452
- }),
453
- );
454
- // A bridge embedded in the gateway is whatever version the gateway shipped: the gateway's
455
- // update is its update, so the check is not made and no client offers to update it here.
456
- const update = isEmbedded() ? { current: VERSION, updateAvailable: false, embedded: 'gateway' }
457
- : await checkForUpdate(VERSION).catch(() => ({ current: VERSION, updateAvailable: false }));
458
- // ADDITIVE, and the client's only way to know this bridge can host skill packages —
459
- // an older bridge simply omits it, which is what stops a newer extension assuming the
460
- // endpoints exist. Never let a scan failure cost the caller its health check.
461
- const skills = await skillsHealth().catch(() => null);
462
- // So Settings can show what a blank "Working directory" actually resolves to, instead
463
- // of leaving the user to discover it from where their files did not appear.
464
- json(res, 200, {
465
- ok: true, version: VERSION, agents, update,
466
- workspace: DEFAULT_WORKSPACE,
467
- // Where job worktrees go and where a connection's token is kept — additive.
468
- worktrees: WORKTREE_ROOT, secretBackend: secretBackend(),
469
- // WHO STARTED THIS PROCESS — additive. ChatPanel Desktop sets CHATPANEL_MANAGED_BY=desktop on
470
- // the login service it registers; a client can then say so instead of offering install.sh.
471
- ...(process.env.CHATPANEL_MANAGED_BY ? { managedBy: String(process.env.CHATPANEL_MANAGED_BY).slice(0, 32) } : {}),
472
- ...(skills ? { skills } : {}),
473
- });
474
- }
475
-
476
- // --------------------------------------------------------------------------
477
- // Skill packages (F6 S2). Read-only: the store serves what is already on disk.
478
- // Installing FROM a hub waits for the scanner — a write endpoint that lands before
479
- // the gate is a window in which unscanned packages can be written, and windows like
480
- // that do not close on schedule.
481
- //
482
- // The three routes are the progressive-disclosure ladder, so a client pays for a
483
- // skill's body only when it picks one, and for a reference file only when it needs it.
484
- // --------------------------------------------------------------------------
485
- async function handleSkillsList(res, extraDirs) {
486
- const { index, problems } = await skillIndex({ extraDirs });
487
- json(res, 200, { ok: true, skills: listRecords(index), problems });
488
- }
489
-
490
- async function handleSkillsQuarantined(res, extraDirs) {
491
- json(res, 200, { ok: true, quarantined: await quarantinedSkills(extraDirs) });
492
- }
493
-
494
- async function handleSkillRead(res, name, extraDirs) {
495
- const { index } = await skillIndex({ extraDirs });
496
- const skill = readRecord(index, name);
497
- if (!skill) return json(res, 404, { ok: false, error: 'unknown skill' });
498
- json(res, 200, { ok: true, skill });
499
- }
500
-
501
- async function handleSkillFile(res, name, relPath, extraDirs) {
502
- const { index } = await skillIndex({ extraDirs });
503
- const out = await readPackageFile(index, name, relPath);
504
- // One shape for every refusal: a caller learns that it may not have the file, not
505
- // whether the path exists, which is the difference between an error and an oracle.
506
- if (out.error) return json(res, out.error === 'unknown skill' ? 404 : 400, { ok: false, error: out.error });
507
- json(res, 200, { ok: true, ...out });
508
- }
509
-
510
- async function compatibleModels() {
511
- const rows = await Promise.all(
512
- Object.entries(ENGINES)
513
- .filter(([, entry]) => !entry.hidden)
514
- .map(async ([id, entry]) => ({
515
- id,
516
- object: 'model',
517
- created: 0,
518
- owned_by: 'chatpanel',
519
- available: !!(await entry.engine.available().catch(() => ({ ok: false }))).ok,
520
- })),
521
- );
522
- return rows.filter((row) => row.available).map(({ available, ...row }) => row);
523
- }
524
-
525
- async function handleCompatibleModels(res, modelId = '') {
526
- const models = await compatibleModels();
527
- if (modelId) {
528
- const model = models.find((row) => row.id === modelId);
529
- return model ? json(res, 200, model) : json(res, 404, openAIError(new CompatError(`Model "${modelId}" not found`, 404, 'model')));
530
- }
531
- return json(res, 200, { object: 'list', data: models });
532
- }
533
-
534
- // POST /update — self-update (compiled-binary installs). Swaps the binary, replies,
535
- // then restarts the service into the new version. npm installs get instructions.
536
- async function handleUpdate(res) {
537
- try {
538
- const result = await selfUpdate(VERSION); // throws on npm install / no update / failure
539
- json(res, 200, { ok: true, updated: true, from: result.from, to: result.to });
540
- res.on('finish', () => setTimeout(() => restartService(), 400));
541
- } catch (e) {
542
- json(res, 400, { ok: false, error: String(e?.message || e) });
543
- }
544
- }
545
-
546
- async function handleChat(req, res) {
547
- let body;
548
- try {
549
- body = await readBody(req);
550
- } catch (e) {
551
- return json(res, 400, { error: 'Bad JSON: ' + e.message });
552
- }
553
- const target = ENGINES[body.agent];
554
- if (!target) return json(res, 404, { error: `Unknown agent "${body.agent}"` });
555
- if (Array.isArray(body.images) && body.images.length) {
556
- log('info', `chat: ${body.agent} received ${body.images.length} image(s)`);
557
- }
558
-
559
- // Open the SSE stream.
560
- res.writeHead(200, {
561
- 'Content-Type': 'text/event-stream',
562
- 'Cache-Control': 'no-cache',
563
- Connection: 'keep-alive',
564
- });
565
- const emit = (obj) => {
566
- if (!res.writableEnded) res.write(`data: ${JSON.stringify(obj)}\n\n`);
567
- };
568
-
569
- // If the client disconnects (Stop, or the panel closes), stop caring about late
570
- // writes AND abort the run so the engine kills its CLI child instead of letting it
571
- // finish in the background. Older engines ignore the signal (harmless); the spawn
572
- // engines honor it via killOnAbort.
573
- let closed = false;
574
- // A run id the client can cancel BY NAME. Emitted first, before anything else, so Stop
575
- // works from the first millisecond rather than from whenever the engine gets going.
576
- const runId = `run_${Math.random().toString(36).slice(2, 10)}`;
577
- const run = startRun(runId);
578
- const ac = { signal: run.signal, abort: () => run.cancel('client') };
579
- // BOTH close events. On a request whose body was already consumed, req 'close' does not
580
- // reliably signal a client disconnect — res 'close' does. Keeping both means a panel that
581
- // crashes or is closed still tears the CLI down, while the Stop button no longer depends
582
- // on either of them.
583
- const onGone = () => { closed = true; run.cancel('disconnected'); };
584
- req.on('close', onGone);
585
- res.on('close', onGone);
586
- res.on('error', onGone);
587
-
588
- const safeEmit = (obj) => { if (!closed) emit(obj); };
589
- emit({ type: 'run', id: runId });
590
-
591
- // WHERE THIS RUN WILL WRITE, said before it starts. "The agent created a file and I
592
- // cannot find it" was the single most confusing thing about a CLI agent, and the answer
593
- // used to depend on which engine answered — the filesystem root, the home directory, or
594
- // a temp folder the OS clears on its own schedule. Now there is one answer and it is
595
- // announced. Additive: a client that does not know `workdir` ignores it, and the same
596
- // information is repeated as a `status` line, which every client already renders.
597
- // AND WHICH CHECKOUT, when the directory is one (scm.js): the repo, branch and HEAD before
598
- // the agent starts, and after it ends what moved — so the team runner can put "worked on
599
- // cp/p/j, 2 commits" on the task and the agent's record, not "it said it committed".
600
- // A JOB'S WORKTREE, when the run names one (architecture-pillars.md §14.2):
601
- // options.workspace = { repo, projectId, jobId, base? } → a checkout of its own on
602
- // cp/<project>/<job>, which becomes the working directory. A worktree that cannot be
603
- // made ends the run here — an Implementer must not fall back to the main checkout.
604
- let workspace = null;
605
- if (body.options?.workspace && typeof body.options.workspace === 'object') {
606
- const w = body.options.workspace;
607
- workspace = await worktreeFor({ repo: w.repo, projectId: w.projectId, jobId: w.jobId, base: w.base || null });
608
- if (workspace.error) { emit({ type: 'error', error: `workspace: ${workspace.error}` }); endRun(runId); if (!res.writableEnded) res.end(); return; }
609
- }
610
- const workdir = workspace ? workspace.path : resolveWorkdir(body.options?.workingDir);
611
- let scmBefore = null;
612
- {
613
- const dir = workdir;
614
- const chosen = !!workspace || !isDefaultWorkdir(body.options?.workingDir);
615
- const scope = writeScopeNote(body.agent, body.options?.permissionMode, dir);
616
- emit({ type: 'workdir', path: dir, isDefault: !chosen, writeScope: scope || undefined });
617
- emit({ type: 'status', text: `Working in ${dir}${chosen ? '' : ' (default)'}` });
618
- if (scope) emit({ type: 'status', text: scope });
619
- scmBefore = await gitState(dir);
620
- if (scmBefore) emit({ type: 'scm', phase: 'before', ...scmBefore });
621
- }
622
- // THE CREDENTIAL AND THE LEASH, for this process only (connections.js, worktree.js): the
623
- // token of the connection that matches the checkout's remote, scoped to its host in the
624
- // spawned process's environment; the pre-push hook that keeps a push on the job's own
625
- // branch, or refuses every push when the role has no scm:push. Nothing is written to the
626
- // repository or the user's git config. Said on the stream, minus the secret.
627
- let runEnv = null;
628
- if (scmBefore || workspace) {
629
- const grants = Array.isArray(body.options?.grants) ? body.options.grants : [];
630
- const { env, connection } = runEnvFor({ remote: scmBefore?.remote || null, grants, branch: workspace?.branch || null, connectionId: body.options?.connectionId || null });
631
- runEnv = withHook(env);
632
- if (workspace) emit({ type: 'workspace', path: workspace.path, branch: workspace.branch, base: workspace.base, created: workspace.created, repo: workspace.repo, ...(connection ? { connection } : {}) });
633
- if (connection) emit({ type: 'status', text: `Git credential: ${connection.kind} · ${connection.host}${connection.hasSecret ? '' : ' (no token stored)'} · push: ${env.CHATPANEL_SCM_PUSH === 'own' ? `${workspace?.branch} only` : env.CHATPANEL_SCM_PUSH}` });
634
- }
635
-
636
- // Browser-tools relay: when the extension sends page-tool specs, host an MCP
637
- // server for this turn and tell the engine to point the CLI at it.
638
- const options = { ...(body.options || {}), ...(workspace ? { workingDir: workspace.path } : {}), ...(runEnv ? { runEnv } : {}) };
639
- let session = null;
640
- if (body.pageTools?.specs?.length) {
641
- session = createSession(safeEmit, body.pageTools.specs);
642
- options.mcp = {
643
- url: `http://${HOST}:${PORT}/mcp/${session.id}`,
644
- serverName: 'chatpanel_browser',
645
- specs: body.pageTools.specs,
646
- };
647
- }
648
-
649
- try {
650
- await target.engine.chat(
651
- {
652
- messages: Array.isArray(body.messages) ? body.messages : [],
653
- system: body.system || '',
654
- options,
655
- images: Array.isArray(body.images) ? body.images : [],
656
- },
657
- safeEmit,
658
- { signal: ac.signal },
659
- );
660
- } catch (e) {
661
- log('error', `${body.agent} chat failed: ${e?.message || e}`);
662
- emit({ type: 'error', error: e?.message || String(e) });
663
- } finally {
664
- // What the run left in the checkout — said before the stream closes, so a client that
665
- // already has the answer still gets the commits. A run that was cancelled is looked at
666
- // too: the commits it made before Stop are real.
667
- if (!closed) {
668
- const after = await gitDelta(workdir, scmBefore).catch(() => null);
669
- if (after) safeEmit({ type: 'scm', phase: 'after', ...after });
670
- }
671
- endRun(runId);
672
- if (session) deleteSession(session.id);
673
- if (!res.writableEnded) res.end();
674
- }
675
- }
676
-
677
- // --- SCM connections and job worktrees (architecture-pillars.md §14) ---------------------
678
- // GET is open like /skills (the panel's GET carries no Origin); every write is a POST and
679
- // privileged. A token arrives in a POST body once, goes to the keychain, and is never
680
- // returned — a client learns only `hasSecret`.
681
- async function handleConnections(req, res, pathname) {
682
- if (req.method === 'GET' && pathname === '/connections') return json(res, 200, { ok: true, connections: listConnections(), secretBackend: secretBackend() });
683
- if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
684
- const body = await readBody(req);
685
- if (pathname === '/connections') {
686
- try { return json(res, 200, { ok: true, connection: putConnection(body.connection || body, { token: body.token || null }) }); }
687
- catch (e) { return json(res, 400, { error: String(e?.message || e) }); }
688
- }
689
- const m = /^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(pathname);
690
- if (!m) return json(res, 404, { error: 'Not found' });
691
- if (m[2] === 'delete') return json(res, 200, { ok: removeConnection(m[1]) });
692
- return json(res, 200, testConnection(m[1], body.remote || ''));
693
- }
694
- async function handleWorktrees(req, res, pathname) {
695
- if (req.method === 'GET' && pathname === '/worktrees') return json(res, 200, { ok: true, root: WORKTREE_ROOT, worktrees: await listWorktrees() });
696
- if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });
697
- const body = await readBody(req);
698
- if (pathname === '/worktrees') {
699
- const r = await worktreeFor({ repo: body.repo, projectId: body.projectId, jobId: body.jobId, base: body.base || null });
700
- return json(res, r.error ? 400 : 200, r.error ? { error: r.error } : { ok: true, ...r });
701
- }
702
- if (pathname === '/worktrees/remove') {
703
- const r = await removeWorktree({ projectId: body.projectId, jobId: body.jobId, force: !!body.force });
704
- return json(res, r.ok ? 200 : 400, r);
705
- }
706
- return json(res, 404, { error: 'Not found' });
707
- }
708
-
709
- async function runCompatibleAgent(config, onDelta, res) {
710
- const target = ENGINES[config.agent];
711
- if (!target || target.hidden) throw new CompatError(`Unknown ChatPanel agent "${config.agent}"`, 400, 'model');
712
- const availability = await target.engine.available().catch((e) => ({ ok: false, reason: e?.message || String(e) }));
713
- if (!availability.ok) throw new CompatError(availability.reason || `${config.agent} is unavailable`, 503, 'model');
714
-
715
- const runId = `run_${Math.random().toString(36).slice(2, 10)}`;
716
- const run = startRun(runId);
717
- const onGone = () => run.cancel('disconnected');
718
- res.on('close', onGone);
719
- let output = '';
720
- try {
721
- await target.engine.chat(
722
- { messages: config.messages, system: config.system, options: config.options, images: [] },
723
- (event) => {
724
- if (event?.type === 'delta' && event.text) {
725
- output += event.text;
726
- onDelta(event.text);
727
- } else if (event?.type === 'done' && event.text && !output) {
728
- output = event.text;
729
- onDelta(event.text);
730
- }
731
- },
732
- { signal: run.signal },
733
- );
734
- return output;
735
- } finally {
736
- res.off('close', onGone);
737
- endRun(runId);
738
- }
739
- }
740
-
741
- function beginSse(res) {
742
- res.writeHead(200, {
743
- 'Content-Type': 'text/event-stream',
744
- 'Cache-Control': 'no-cache',
745
- Connection: 'keep-alive',
746
- });
747
- }
748
-
749
- function writeData(res, value) {
750
- if (!res.writableEnded) res.write(`data: ${typeof value === 'string' ? value : JSON.stringify(value)}\n\n`);
751
- }
752
-
753
- function writeNamedEvent(res, name, value) {
754
- if (!res.writableEnded) res.write(`event: ${name}\ndata: ${JSON.stringify(value)}\n\n`);
755
- }
756
-
757
- async function compatibleBody(req, res, parser, errorShape) {
758
- try {
759
- return parser(await readBody(req));
760
- } catch (error) {
761
- json(res, error?.status || 400, errorShape(error?.message?.startsWith('Unexpected') ? new CompatError(`Bad JSON: ${error.message}`) : error));
762
- return null;
763
- }
764
- }
765
-
766
- async function handleOpenAIChatCompletions(req, res) {
767
- const config = await compatibleBody(req, res, parseChatCompletion, openAIError);
768
- if (!config) return;
769
- if (!config.stream) {
770
- try {
771
- const text = await runCompatibleAgent(config, () => {}, res);
772
- return json(res, 200, createChatCompletion(config.requestedModel, text));
773
- } catch (error) {
774
- if (!res.writableEnded) return json(res, error?.status || 500, openAIError(error));
775
- return;
776
- }
777
- }
778
-
779
- beginSse(res);
780
- const stream = chatCompletionStream(config.requestedModel, (event) => writeData(res, event));
781
- try {
782
- await runCompatibleAgent(config, (text) => stream.delta(text), res);
783
- stream.done();
784
- } catch (error) {
785
- writeData(res, openAIError(error));
786
- }
787
- writeData(res, '[DONE]');
788
- res.end();
789
- }
790
-
791
- async function handleOpenAICompletions(req, res) {
792
- const config = await compatibleBody(req, res, parseCompletion, openAIError);
793
- if (!config) return;
794
- if (!config.stream) {
795
- try {
796
- const text = await runCompatibleAgent(config, () => {}, res);
797
- return json(res, 200, createCompletion(config.requestedModel, text));
798
- } catch (error) {
799
- if (!res.writableEnded) return json(res, error?.status || 500, openAIError(error));
800
- return;
801
- }
802
- }
803
-
804
- beginSse(res);
805
- const stream = completionStream(config.requestedModel, (event) => writeData(res, event));
806
- try {
807
- await runCompatibleAgent(config, (text) => stream.delta(text), res);
808
- stream.done();
809
- } catch (error) {
810
- writeData(res, openAIError(error));
811
- }
812
- writeData(res, '[DONE]');
813
- res.end();
814
- }
815
-
816
- async function handleOpenAIResponses(req, res) {
817
- const config = await compatibleBody(req, res, parseResponse, openAIError);
818
- if (!config) return;
819
- if (!config.stream) {
820
- try {
821
- const text = await runCompatibleAgent(config, () => {}, res);
822
- return json(res, 200, createResponse(config.requestedModel, text));
823
- } catch (error) {
824
- if (!res.writableEnded) return json(res, error?.status || 500, openAIError(error));
825
- return;
826
- }
827
- }
828
-
829
- beginSse(res);
830
- const stream = responseStream(config.requestedModel, (event) => writeNamedEvent(res, event.type, event));
831
- try {
832
- await runCompatibleAgent(config, (text) => stream.delta(text), res);
833
- stream.done();
834
- } catch (error) {
835
- const event = { type: 'error', sequence_number: 0, ...openAIError(error) };
836
- writeNamedEvent(res, 'error', event);
837
- }
838
- res.end();
839
- }
840
-
841
- async function handleAnthropicMessages(req, res) {
842
- const config = await compatibleBody(req, res, parseAnthropicMessage, anthropicError);
843
- if (!config) return;
844
- if (!config.stream) {
845
- try {
846
- const text = await runCompatibleAgent(config, () => {}, res);
847
- return json(res, 200, createAnthropicMessage(config.requestedModel, text));
848
- } catch (error) {
849
- if (!res.writableEnded) return json(res, error?.status || 500, anthropicError(error));
850
- return;
851
- }
852
- }
853
-
854
- beginSse(res);
855
- const stream = anthropicStream(config.requestedModel, (name, event) => writeNamedEvent(res, name, event));
856
- try {
857
- await runCompatibleAgent(config, (text) => stream.delta(text), res);
858
- stream.done();
859
- } catch (error) {
860
- writeNamedEvent(res, 'error', anthropicError(error));
861
- }
862
- res.end();
863
- }
864
-
865
- /**
866
- * POST /cancel { id } — stop a run by name.
867
- *
868
- * Stop is now an instruction, not something inferred from a socket. Answers 200 whether or
869
- * not the run was still live: 'already finished' and 'cancelled' are the same outcome to the
870
- * caller, and returning 404 would make a harmless race look like a failure.
871
- */
872
- async function handleCancel(req, res) {
873
- // readBody already PARSES. Wrapping it in JSON.parse threw on every call, so the id was
874
- // always empty and Stop silently cancelled nothing — the unit tests covered the registry
875
- // and not the handler that feeds it, which is exactly where this hid.
876
- let body = {};
877
- try { body = (await readBody(req)) || {}; } catch { /* an empty body cancels nothing */ }
878
- const id = String(body.id || '').trim();
879
- const cancelled = id ? cancelRun(id, 'stopped') : false;
880
- if (cancelled) log('info', `cancel: ${id} stopped by client`);
881
- return json(res, 200, { ok: true, cancelled });
882
- }
883
-
884
- // POST /mcp/<session> (per-run, bridge-injected) OR POST /mcp (stable: routes to
885
- // the active chat — for CLIs configured once, e.g. `opencode mcp add … …/mcp`).
886
- // JSON-RPC; tools/call relays to the extension and waits for /tool-result.
887
- async function handleMcp(req, res, sessionId) {
888
- let msg;
889
- try {
890
- msg = await readBody(req);
891
- } catch {
892
- return json(res, 200, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
893
- }
894
- // Explicit session id (per-run URL) or the active chat (stable /mcp).
895
- const session = sessionId ? sessions.get(sessionId) : activeSession();
896
- const reply = (result) => {
897
- if (session) res.setHeader('Mcp-Session-Id', session.id);
898
- json(res, 200, { jsonrpc: '2.0', id: msg.id ?? null, result });
899
- };
900
- const fail = (code, message) => json(res, 200, { jsonrpc: '2.0', id: msg.id ?? null, error: { code, message } });
901
-
902
- // Notifications (no id) — ack and ignore.
903
- if (msg.id == null) { res.writeHead(202); return res.end(); }
904
-
905
- if (msg.method === 'initialize') {
906
- return reply({
907
- protocolVersion: msg.params?.protocolVersion || '2025-06-18',
908
- capabilities: { tools: { listChanged: false } },
909
- serverInfo: { name: 'chatpanel-browser', version: VERSION },
910
- });
911
- }
912
- // ChatPanel's own bridge-native capabilities (skills today; redaction and more later) are
913
- // ALWAYS advertised — a CLI that added this server once gets them whether or not a browser
914
- // chat is open. The active session's page tools are added ON TOP when a chat is driving.
915
- const capTools = capabilityToolSpecs();
916
-
917
- if (msg.method === 'tools/list') {
918
- const pageTools = session
919
- ? session.specs.map((s) => ({
920
- name: s.name,
921
- description: s.description,
922
- inputSchema: s.parameters || { type: 'object', properties: {} },
923
- }))
924
- : [];
925
- return reply({ tools: [...capTools, ...pageTools] });
926
- }
927
- if (msg.method === 'tools/call') {
928
- // A capability tool runs in the bridge and needs no browser; a page tool relays to the
929
- // active chat. Capability tools win a name clash — they are ours and namespaced.
930
- const cap = await runCapabilityTool(msg.params?.name, msg.params?.arguments || {});
931
- if (cap) return reply(cap);
932
- if (!session) return fail(-32001, 'That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel\'s own tools (chatpanel_*) work without one.');
933
- try {
934
- return reply(await relayToolCall(session, msg.params?.name, msg.params?.arguments || {}));
935
- } catch (e) {
936
- return reply({ content: [{ type: 'text', text: `error: ${e?.message || e}` }], isError: true });
937
- }
938
- }
939
- return fail(-32601, `Method not found: ${msg.method}`);
940
- }
941
-
942
- // POST /mcp-local — proxy one JSON-RPC message to a user-configured STDIO MCP
943
- // server that the bridge spawns and keeps alive. Body: { server:{id,command,args,
944
- // env?,cwd?}, message }. Returns the full JSON-RPC response (or 202 for a
945
- // notification). Lets the extension use local MCP servers it can't spawn itself.
946
- async function handleMcpLocal(req, res) {
947
- let body;
948
- try {
949
- body = await readBody(req);
950
- } catch (e) {
951
- return json(res, 400, { error: 'Bad JSON: ' + e.message });
952
- }
953
- const server = body.server || {};
954
- const message = body.message;
955
- if (!server.command || !message) return json(res, 400, { error: 'need server.command and message' });
956
- try {
957
- const result = await callLocalMcp(
958
- { key: server.id, command: server.command, args: server.args, env: server.env, cwd: server.cwd },
959
- message,
960
- );
961
- if (message.id == null) { res.writeHead(202); return res.end(); }
962
- return json(res, 200, result); // the full JSON-RPC response message
963
- } catch (e) {
964
- return json(res, 200, {
965
- jsonrpc: '2.0',
966
- id: message.id ?? null,
967
- error: { code: -32000, message: String(e?.message || e) },
968
- });
969
- }
970
- }
971
-
972
- // POST /mcp-remote — proxy ONE JSON-RPC message to a remote Streamable-HTTP MCP
973
- // server FROM the bridge (server-side, no browser Origin header), so the extension
974
- // can reach servers that reject browser origins (their own DNS-rebinding/CORS
975
- // protection). Body: { url, headers?, message }. Returns the upstream
976
- // { status, sessionId, contentType, body } for the extension to parse. Privileged
977
- // route + SSRF guard, so it can't be driven by a page or relay into the LAN.
978
- async function handleMcpRemote(req, res) {
979
- let body;
980
- try {
981
- body = await readBody(req);
982
- } catch (e) {
983
- return json(res, 400, { error: 'Bad JSON: ' + e.message });
984
- }
985
- const { url, headers: hdrs, message } = body || {};
986
- if (!url || !message) return json(res, 400, { error: 'need url and message' });
987
- let target;
988
- try {
989
- target = assertPublicHttpUrl(url);
990
- } catch (e) {
991
- return json(res, 400, { error: String(e?.message || e) });
992
- }
993
- // Forward only safe, MCP-relevant client headers (auth, session, protocol, x-*);
994
- // never the Host/hop-by-hop headers. Content-Type/Accept are set by us.
995
- const fwd = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' };
996
- if (hdrs && typeof hdrs === 'object') {
997
- for (const [k, v] of Object.entries(hdrs)) {
998
- const lk = k.toLowerCase();
999
- if (['authorization', 'mcp-session-id', 'mcp-protocol-version', 'x-api-key'].includes(lk) || lk.startsWith('x-')) {
1000
- fwd[k] = String(v);
1001
- }
1002
- }
1003
- }
1004
- const ac = new AbortController();
1005
- const t = setTimeout(() => ac.abort(), 30_000);
1006
- try {
1007
- const up = await fetch(target.href, { method: 'POST', headers: fwd, body: JSON.stringify(message), redirect: 'follow', signal: ac.signal });
1008
- // A redirect may have landed on an internal host — re-check the final URL.
1009
- try { if (up.url) assertPublicHttpUrl(up.url); } catch (e) { return json(res, 400, { error: String(e?.message || e) }); }
1010
- const text = await up.text().catch(() => '');
1011
- return json(res, 200, {
1012
- status: up.status,
1013
- sessionId: up.headers.get('Mcp-Session-Id') || null,
1014
- contentType: up.headers.get('Content-Type') || '',
1015
- body: text,
1016
- });
1017
- } catch (e) {
1018
- const why = e?.name === 'AbortError' ? 'timed out' : String(e?.message || e);
1019
- return json(res, 502, { error: `couldn't reach MCP server ${target.host}: ${why}` });
1020
- } finally {
1021
- clearTimeout(t);
1022
- }
1023
- }
1024
-
1025
- // POST /fetch-title — fetch a PUBLIC web page and return ONLY its <title>, so a client can turn
1026
- // a bare URL into a readable [Title](url) link without the browser's Origin/CORS limits and
1027
- // without any third-party title service. This is the canonical "secure web fetch" the bridge
1028
- // offers on behalf of clients:
1029
- // • Privileged route (extension origin or bridge token only) — a random page can't drive it.
1030
- // • STRICTER SSRF guard than /mcp-remote (assertPublicWebUrl): loopback / LAN / metadata are
1031
- // blocked unconditionally — a page fetch has no business touching internal hosts.
1032
- // • Redirects are followed MANUALLY, re-validating EVERY hop, so it can never be bounced onto
1033
- // an internal address (stronger than an after-the-fact final-URL check).
1034
- // • Response is read with a hard byte cap and stops at </title> — we only need the <head>.
1035
- // • No cookies / auth / referer are ever sent; only the title string is returned.
1036
- const FT_MAX_BYTES = 256 * 1024;
1037
- const FT_MAX_REDIRECTS = 5;
1038
- const FT_TIMEOUT_MS = 8000;
1039
-
1040
- async function fetchTitleSafely(rawUrl) {
1041
- let current = assertPublicWebUrl(rawUrl); // throws on non-http(s) / private / loopback / metadata
1042
- const ac = new AbortController();
1043
- const timer = setTimeout(() => ac.abort(), FT_TIMEOUT_MS);
1044
- try {
1045
- for (let hop = 0; hop <= FT_MAX_REDIRECTS; hop++) {
1046
- const res = await fetch(current.href, {
1047
- method: 'GET',
1048
- redirect: 'manual', // follow hops ourselves so each target is re-validated before we call it
1049
- signal: ac.signal,
1050
- headers: { Accept: 'text/html,application/xhtml+xml', 'Accept-Language': 'en', 'User-Agent': `chatpanel-bridge/${VERSION} (+link-title)` },
1051
- });
1052
- if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
1053
- current = assertPublicWebUrl(new URL(res.headers.get('location'), current).href); // re-guard the redirect
1054
- if (res.body) { try { await res.body.cancel(); } catch { /* ignore */ } }
1055
- continue;
1056
- }
1057
- if (!res.ok) { if (res.body) { try { await res.body.cancel(); } catch { /* ignore */ } } return { title: null }; }
1058
- const ct = res.headers.get('content-type') || '';
1059
- if (!/text\/html|application\/xhtml/i.test(ct)) { if (res.body) { try { await res.body.cancel(); } catch { /* ignore */ } } return { title: null }; }
1060
- return { title: extractTitle(await readCapped(res)), url: current.href };
1061
- }
1062
- throw new Error('too many redirects');
1063
- } finally {
1064
- clearTimeout(timer);
1065
- }
1066
- }
1067
-
1068
- // Read the response body up to FT_MAX_BYTES, stopping as soon as we've seen the closing </title>.
1069
- async function readCapped(res) {
1070
- if (!res.body?.getReader) return (await res.text().catch(() => '')).slice(0, FT_MAX_BYTES);
1071
- const reader = res.body.getReader();
1072
- const decoder = new TextDecoder('utf-8', { fatal: false });
1073
- let out = '';
1074
- let total = 0;
1075
- try {
1076
- for (;;) {
1077
- const { done, value } = await reader.read();
1078
- if (done) break;
1079
- total += value.byteLength;
1080
- out += decoder.decode(value, { stream: true });
1081
- if (/<\/title\s*>/i.test(out) || total >= FT_MAX_BYTES) break;
1082
- }
1083
- } finally {
1084
- try { await reader.cancel(); } catch { /* ignore */ }
1085
- }
1086
- return out;
1087
- }
1088
-
1089
- function decodeEntities(s) {
1090
- return String(s)
1091
- .replace(/&amp;/g, '&')
1092
- .replace(/&lt;/g, '<')
1093
- .replace(/&gt;/g, '>')
1094
- .replace(/&quot;/g, '"')
1095
- .replace(/&(?:apos|#0*39|#x0*27);/gi, "'")
1096
- .replace(/&nbsp;/g, ' ')
1097
- .replace(/&#(\d+);/g, (_, d) => { try { return String.fromCodePoint(+d); } catch { return ''; } })
1098
- .replace(/&#x([0-9a-f]+);/gi, (_, h) => { try { return String.fromCodePoint(parseInt(h, 16)); } catch { return ''; } });
1099
- }
1100
-
1101
- function extractTitle(html) {
1102
- const m = /<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(html);
1103
- return m ? decodeEntities(m[1]).replace(/\s+/g, ' ').trim().slice(0, 200) : '';
1104
- }
1105
-
1106
- async function handleFetchTitle(req, res) {
1107
- let body;
1108
- try { body = await readBody(req); } catch (e) { return json(res, 400, { error: 'Bad JSON: ' + e.message }); }
1109
- const url = body && body.url;
1110
- if (!url || typeof url !== 'string') return json(res, 400, { error: 'need url' });
1111
- try {
1112
- const out = await fetchTitleSafely(url);
1113
- return json(res, 200, { title: out.title || null, url: out.url || url });
1114
- } catch (e) {
1115
- const why = e?.name === 'AbortError' ? 'timed out' : String(e?.message || e);
1116
- return json(res, 400, { error: `couldn't fetch title: ${why}` });
1117
- }
1118
- }
1119
-
1120
- // POST /tool-result — the extension returns a relayed tool's result.
1121
- async function handleToolResult(req, res) {
1122
- let body;
1123
- try {
1124
- body = await readBody(req);
1125
- } catch (e) {
1126
- return json(res, 400, { error: 'Bad JSON: ' + e.message });
1127
- }
1128
- const session = sessions.get(body.session);
1129
- if (!session) return json(res, 404, { error: 'no such session' });
1130
- const pending = session.pending.get(body.id);
1131
- if (!pending) return json(res, 404, { error: 'no such pending call' });
1132
- session.pending.delete(body.id);
1133
- pending.resolve(body.result);
1134
- return json(res, 200, { ok: true });
1135
- }
1136
-
1137
- // POST /complete → { agent, prompt, model? } → { text } — a fast, single-shot
1138
- // completion for prompt autocomplete. Uses the engine's complete() if it has one
1139
- // (Claude: Haiku, no tools), else a one-shot chat collected into text.
1140
- async function handleComplete(req, res) {
1141
- let body;
1142
- try {
1143
- body = await readBody(req);
1144
- } catch (e) {
1145
- return json(res, 400, { error: 'Bad JSON: ' + e.message });
1146
- }
1147
- const target = ENGINES[body.agent];
1148
- if (!target) return json(res, 404, { error: `Unknown agent "${body.agent}"` });
1149
- const prompt = String(body.prompt || '').slice(0, 6000);
1150
- if (!prompt) return json(res, 400, { error: 'Empty prompt' });
1151
- const model = body.model || '';
1152
- // The extension sends a strict "continue, don't answer" system prompt (with any
1153
- // page context already in `prompt`); fall back to a sensible default.
1154
- const system =
1155
- String(body.system || '').slice(0, 2000) ||
1156
- 'You autocomplete an unfinished message the user is typing. Output ONLY the ' +
1157
- 'few words that come next. Do not answer it. No quotes, no repetition.';
1158
- try {
1159
- let text = '';
1160
- if (typeof target.engine.complete === 'function') {
1161
- text = await target.engine.complete({ prompt, system, model });
1162
- } else {
1163
- await target.engine.chat(
1164
- { messages: [{ role: 'user', content: prompt }], system, options: { model } },
1165
- (obj) => {
1166
- if (obj.type === 'delta') text += obj.text || '';
1167
- else if (obj.type === 'done' && obj.text) text += obj.text;
1168
- },
1169
- );
1170
- }
1171
- return json(res, 200, { text: (text || '').trim() });
1172
- } catch (e) {
1173
- return json(res, 502, { error: e?.message || String(e) });
1174
- }
1175
- }
1176
-
1177
- // POST /list-models → { agent, options } → { models } — the unified model-list
1178
- // interface. Each engine decides HOW to enumerate (claude → known aliases; custom
1179
- // → runs the agent's configured `listModelsArgs`, e.g. pi `--list-models` /
1180
- // opencode `models`, and parses stdout). Engines without a lister return [].
1181
- async function handleListModels(req, res) {
1182
- let body;
1183
- try {
1184
- body = await readBody(req);
1185
- } catch (e) {
1186
- return json(res, 400, { error: 'Bad JSON: ' + e.message });
1187
- }
1188
- const target = ENGINES[body.agent];
1189
- if (!target) return json(res, 404, { error: `Unknown agent "${body.agent}"` });
1190
- if (typeof target.engine.listModels !== 'function') return json(res, 200, { models: [] });
1191
- try {
1192
- const models = await target.engine.listModels(body.options || {});
1193
- return json(res, 200, { models: Array.isArray(models) ? models : [] });
1194
- } catch (e) {
1195
- return json(res, 502, { error: e?.message || String(e) });
1196
- }
1197
- }
1198
-
1199
- // POST /agent-check → { command } → { ok, via } — does this command resolve on
1200
- // this machine? Powers the "✓ found" indicator when onboarding a custom agent.
1201
- // `via` tells the user HOW it resolved (native / script / cmd / wsl) so a Windows
1202
- // user sees e.g. "found in WSL". No execution, no entitlement needed (read-only).
1203
- async function handleAgentCheck(req, res) {
1204
- let body;
1205
- try {
1206
- body = await readBody(req);
1207
- } catch (e) {
1208
- return json(res, 400, { error: 'Bad JSON: ' + e.message });
1209
- }
1210
- const command = String(body.command || '').trim();
1211
- if (!command) return json(res, 400, { error: 'No command' });
1212
- let spec = null;
1213
- try {
1214
- spec = resolveCommand(command);
1215
- } catch {
1216
- spec = null;
1217
- }
1218
- return json(res, 200, { ok: !!spec, via: spec ? spec.kind : null });
1219
- }
1220
-
1221
- const server = createServer(async (req, res) => {
1222
- cors(req, res);
1223
- if (req.method === 'OPTIONS') {
1224
- res.writeHead(204);
1225
- return res.end();
1226
- }
1227
- let url;
1228
- try {
1229
- url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`);
1230
- } catch {
1231
- return json(res, 400, { error: 'bad request' });
1232
- }
1233
- // Block DNS-rebinding / cross-origin CSRF before any route runs.
1234
- const blocked = guard(req, url.pathname);
1235
- if (blocked) return json(res, 403, { error: blocked });
1236
- try {
1237
- if (req.method === 'GET' && url.pathname === '/health') return handleHealth(res);
1238
- // Custom skill folders the user configured in the extension, passed per request. They
1239
- // are the user's own absolute paths on their own machine; the bridge validates and
1240
- // scans them, and the same traversal/symlink guards apply to any file read from them.
1241
- const extraDirs = url.searchParams.getAll('dir');
1242
- if (req.method === 'GET' && url.pathname === '/skills') return handleSkillsList(res, extraDirs);
1243
- if (req.method === 'GET' && url.pathname === '/skills-quarantined') return handleSkillsQuarantined(res, extraDirs);
1244
- if (req.method === 'GET' && url.pathname.startsWith('/skills/')) {
1245
- const rest = url.pathname.slice('/skills/'.length);
1246
- const cut = rest.indexOf('/file/');
1247
- if (cut === -1) return handleSkillRead(res, decodeURIComponent(rest), extraDirs);
1248
- return handleSkillFile(
1249
- res,
1250
- decodeURIComponent(rest.slice(0, cut)),
1251
- decodeURIComponent(rest.slice(cut + '/file/'.length)),
1252
- extraDirs,
1253
- );
1254
- }
1255
- if (url.pathname === '/connections' || url.pathname.startsWith('/connections/')) return handleConnections(req, res, url.pathname);
1256
- if (url.pathname === '/worktrees' || url.pathname.startsWith('/worktrees/')) return handleWorktrees(req, res, url.pathname);
1257
- if (req.method === 'GET' && url.pathname === '/v1/models') return handleCompatibleModels(res);
1258
- if (req.method === 'GET' && url.pathname.startsWith('/v1/models/')) {
1259
- return handleCompatibleModels(res, decodeURIComponent(url.pathname.slice('/v1/models/'.length)));
1260
- }
1261
- if (req.method === 'GET' && url.pathname === '/debug') {
1262
- // L6: by default expose only version + agent AVAILABILITY (a boolean) — enough
1263
- // to diagnose "is codex installed?". The full home dir, $PATH, and resolved
1264
- // binary paths (which embed the username / home) leak environment detail, so
1265
- // they're opt-in behind CHATPANEL_BRIDGE_DEBUG=1. The extension doesn't read
1266
- // this route, so trimming it by default breaks nothing.
1267
- const verbose = /^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG || '');
1268
- return json(res, 200, {
1269
- version: VERSION,
1270
- agents: Object.fromEntries(AGENT_CLIS.map((name) => [name, verbose ? (findAgentBin(name) || null) : !!findAgentBin(name)])),
1271
- ...(verbose ? { home: os.homedir(), path: process.env.PATH } : {}),
1272
- });
1273
- }
1274
- if (req.method === 'POST' && url.pathname === '/chat') return handleChat(req, res);
1275
- if (req.method === 'POST' && url.pathname === '/v1/chat/completions') return handleOpenAIChatCompletions(req, res);
1276
- if (req.method === 'POST' && url.pathname === '/v1/completions') return handleOpenAICompletions(req, res);
1277
- if (req.method === 'POST' && url.pathname === '/v1/responses') return handleOpenAIResponses(req, res);
1278
- if (req.method === 'POST' && url.pathname === '/v1/messages') return handleAnthropicMessages(req, res);
1279
- // Stable endpoint: routes to the active chat. For CLIs configured once with a
1280
- // fixed URL (e.g. `opencode mcp add chatpanel --url http://127.0.0.1:4319/mcp`).
1281
- if (url.pathname === '/mcp') {
1282
- if (req.method === 'POST') return handleMcp(req, res, null);
1283
- if (req.method === 'GET') { res.writeHead(405); return res.end(); }
1284
- }
1285
- if (url.pathname.startsWith('/mcp/')) {
1286
- const sid = decodeURIComponent(url.pathname.slice(5));
1287
- if (req.method === 'POST') return handleMcp(req, res, sid);
1288
- if (req.method === 'GET') { res.writeHead(405); return res.end(); } // no server-initiated stream
1289
- if (req.method === 'DELETE') { deleteSession(sid); res.writeHead(204); return res.end(); }
1290
- }
1291
- if (req.method === 'GET' && url.pathname === '/channels') return handleChannels(req, res, 'status');
1292
- if (req.method === 'POST' && url.pathname.startsWith('/channels/')) {
1293
- return handleChannels(req, res, url.pathname.slice('/channels/'.length));
1294
- }
1295
- if (req.method === 'POST' && url.pathname === '/cancel') return handleCancel(req, res);
1296
- if (req.method === 'POST' && url.pathname === '/tool-result') return handleToolResult(req, res);
1297
- if (req.method === 'POST' && url.pathname === '/mcp-local') return handleMcpLocal(req, res);
1298
- if (req.method === 'POST' && url.pathname === '/mcp-remote') return handleMcpRemote(req, res);
1299
- if (req.method === 'POST' && url.pathname === '/fetch-title') return handleFetchTitle(req, res);
1300
- if (req.method === 'POST' && url.pathname === '/complete') return handleComplete(req, res);
1301
- if (req.method === 'POST' && url.pathname === '/list-models') return handleListModels(req, res);
1302
- if (req.method === 'POST' && url.pathname === '/agent-check') return handleAgentCheck(req, res);
1303
- if (req.method === 'POST' && url.pathname === '/update') return handleUpdate(res);
1304
- json(res, 404, { error: 'Not found' });
1305
- } catch (e) {
1306
- json(res, 500, { error: e?.message || String(e) });
1307
- }
1308
- });
1309
-
1310
- function log(level, msg) {
1311
- const fn = level === 'error' ? console.error : console.log;
1312
- fn(`[chatpanel-bridge] ${msg}`);
1313
- }
1314
-
1315
- // `--mcp-stdio <url>` — run as a stdio↔HTTP MCP proxy: read newline-delimited
1316
- // JSON-RPC from stdin, forward each message to the bridge's HTTP MCP endpoint
1317
- // (<url> = http://127.0.0.1:PORT/mcp/<session>), and write responses to stdout.
1318
- // This lets ANY stdio-MCP CLI (Codex, a custom CLI) use the browser tools with
1319
- // the bridge binary itself as the MCP server command — no extra runtime needed.
1320
- function runMcpStdioProxy(url) {
1321
- let buf = '';
1322
- const queue = [];
1323
- let draining = false;
1324
- let ended = false;
1325
- const maybeExit = () => { if (ended && !draining && !queue.length) process.exit(0); };
1326
- const drain = async () => {
1327
- if (draining) return;
1328
- draining = true;
1329
- while (queue.length) {
1330
- const line = queue.shift();
1331
- let msg;
1332
- try { msg = JSON.parse(line); } catch { continue; }
1333
- try {
1334
- const res = await fetch(url, {
1335
- method: 'POST',
1336
- headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
1337
- body: line,
1338
- });
1339
- if (msg.id == null) continue; // notification — no response expected
1340
- const text = (await res.text()).trim();
1341
- if (text) process.stdout.write(text + '\n');
1342
- } catch (e) {
1343
- if (msg.id != null) {
1344
- process.stdout.write(
1345
- JSON.stringify({ jsonrpc: '2.0', id: msg.id, error: { code: -32000, message: String(e?.message || e) } }) + '\n',
1346
- );
1347
- }
1348
- }
1349
- }
1350
- draining = false;
1351
- maybeExit(); // stdin closed mid-flight → exit only after the queue is drained
1352
- };
1353
- process.stdin.setEncoding('utf8');
1354
- process.stdin.on('data', (chunk) => {
1355
- buf += chunk;
1356
- let nl;
1357
- while ((nl = buf.indexOf('\n')) >= 0) {
1358
- const line = buf.slice(0, nl).trim();
1359
- buf = buf.slice(nl + 1);
1360
- if (line) queue.push(line);
1361
- }
1362
- drain();
1363
- });
1364
- process.stdin.on('end', () => { ended = true; maybeExit(); });
1365
- process.stdin.resume();
1366
- }
1367
-
1368
- function startServer() {
1369
- enrichPath(); // so codex/agy (Antigravity) are found even under a minimal service PATH
1370
- enrichAgentEnv(); // and so env-authenticated CLIs (dsh) have their key under launchd
1371
- ensureToken(); // per-install bearer token for privileged routes (defense-in-depth)
1372
- // Fail LOUD on a port clash. The bridge binds a FIXED 4319 so the extension always
1373
- // finds it; if it's taken, say how to recover instead of dying on a raw stack trace.
1374
- server.on('error', (e) => {
1375
- if (e && e.code === 'EADDRINUSE') {
1376
- log('error', `Port ${PORT} is already in use — another app (or a second bridge) has it.`);
1377
- log('error', `Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings.`);
1378
- process.exit(1);
1379
- }
1380
- log('error', `bridge server error: ${e?.message || e}`);
1381
- process.exit(1);
1382
- });
1383
- // Leaving a CLI running after the bridge exits is how orphans are made — and the user has
1384
- // no way to find or stop them, because the thing that spawned them is gone.
1385
- for (const sig of ['SIGINT', 'SIGTERM']) {
1386
- process.on(sig, () => {
1387
- const n = cancelAll('shutdown');
1388
- if (n) log('info', `shutdown: stopped ${n} running agent${n === 1 ? '' : 's'}`);
1389
- // Give SIGTERM a moment to land before the process goes; killTree escalates on its own.
1390
- setTimeout(() => process.exit(0), n ? 300 : 0).unref?.();
1391
- if (!n) process.exit(0);
1392
- });
1393
- }
1394
-
1395
- server.listen(PORT, HOST, async () => {
1396
- log('info', `listening on http://${HOST}:${PORT}`);
1397
- // M7: a non-loopback bind disables the anti-DNS-rebinding Host check (hostAllowed
1398
- // returns true for any Host), so the only inbound guard left is the per-install
1399
- // token / extension Origin. Make that trade-off LOUD — it's rarely what you want.
1400
- if (!LOOPBACK_HOSTNAMES.has(HOST)) {
1401
- log('error', `⚠ SECURITY: bound to NON-LOOPBACK host ${HOST}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);
1402
- }
1403
- for (const [, { engine, label, hidden }] of Object.entries(ENGINES)) {
1404
- if (hidden) continue;
1405
- const a = await engine.available().catch(() => ({ ok: false }));
1406
- log('info', ` ${a.ok ? '✓' : '✕'} ${label}${a.ok ? '' : ' — ' + (a.reason || 'unavailable')}`);
1407
- }
1408
- log('info', 'Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically.');
1409
- // A channel someone connected last week must come back by itself after a reboot — nobody
1410
- // is at the keyboard to press start, which is the entire premise of driving this from a
1411
- // phone. Nothing loads and nothing runs until a bot has actually been connected.
1412
- channelService()
1413
- .then((svc) => svc.startIfConfigured())
1414
- .then((r) => {
1415
- if (r?.skipped) return;
1416
- if (r?.ok) log('info', 'channels: telegram connected — polling for messages');
1417
- else log('error', `channels: telegram not started — ${r?.error || 'unknown error'}`);
1418
- })
1419
- .catch((e) => log('error', `channels: ${e?.message || e}`));
1420
- });
1421
- }
1422
-
1423
- function printHelp() {
1424
- console.log(`ChatPanel Bridge v${VERSION}
9
+ `)}async function _(n,e,t,o){try{return t(await f(n))}catch(r){return a(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new I(`Bad JSON: ${r.message}`):r)),null}}async function Lt(n,e){const t=await _(n,e,wt,w);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,mt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}R(e);const o=ut(t.requestedModel,r=>A(e,r));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){A(e,w(r))}A(e,"[DONE]"),e.end()}async function Wt(n,e){const t=await _(n,e,bt,w);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,ft(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}R(e);const o=ht(t.requestedModel,r=>A(e,r));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){A(e,w(r))}A(e,"[DONE]"),e.end()}async function jt(n,e){const t=await _(n,e,St,w);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,gt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}R(e);const o=kt(t.requestedModel,r=>H(e,r.type,r));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){const i={type:"error",sequence_number:0,...w(r)};H(e,"error",i)}e.end()}async function Jt(n,e){const t=await _(n,e,yt,U);if(!t)return;if(!t.stream)try{const r=await S(t,()=>{},e);return a(e,200,pt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,U(r))}R(e);const o=dt(t.requestedModel,(r,i)=>H(e,r,i));try{await S(t,r=>o.delta(r),e),o.done()}catch(r){H(e,"error",U(r))}e.end()}async function Ft(n,e){let t={};try{t=await f(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?it(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),a(e,200,{ok:!0,cancelled:r})}async function oe(n,e,t){let o;try{o=await f(n)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?F(t):Be(),i=c=>{r&&e.setHeader("Mcp-Session-Id",r.id),a(e,200,{jsonrpc:"2.0",id:o.id??null,result:c})},l=(c,s)=>a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:c,message:s}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return i({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=He();if(o.method==="tools/list"){const c=r?r.specs.map(s=>({name:s.name,description:s.description,inputSchema:s.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...c]})}if(o.method==="tools/call"){const c=await _e(o.params?.name,o.params?.arguments||{});if(c)return i(c);if(!r)return l(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return i(await Ge(r,o.params?.name,o.params?.arguments||{}))}catch(s){return i({content:[{type:"text",text:`error: ${s?.message||s}`}],isError:!0})}}return l(-32601,`Method not found: ${o.method}`)}async function Kt(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return a(e,400,{error:"need server.command and message"});try{const i=await at({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd},r);return r.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function zt(n,e){let t;try{t=await f(n)}catch(h){return a(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:i}=t||{};if(!o||!i)return a(e,400,{error:"need url and message"});let l;try{l=Q(o)}catch(h){return a(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,m]of Object.entries(r)){const b=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(b)||b.startsWith("x-"))&&(d[h]=String(m))}const c=new AbortController,s=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(l.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&Q(h.url)}catch(b){return a(e,400,{error:String(b?.message||b)})}const m=await h.text().catch(()=>"");return a(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",body:m})}catch(h){const m=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${l.host}: ${m}`})}finally{clearTimeout(s)}}const ae=256*1024,Vt=5,Yt=8e3;async function Xt(n){let e=Z(n);const t=new AbortController,o=setTimeout(()=>t.abort(),Yt);try{for(let r=0;r<=Vt;r++){const i=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=Z(new URL(i.headers.get("location"),e).href),i.body)try{await i.body.cancel()}catch{}continue}if(!i.ok){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}const l=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(l)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:qt(await Qt(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function Qt(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,ae);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:i,value:l}=await e.read();if(i||(r+=l.byteLength,o+=t.decode(l,{stream:!0}),/<\/title\s*>/i.test(o)||r>=ae))break}}finally{try{await e.cancel()}catch{}}return o}function Zt(n){return String(n).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function qt(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Zt(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function en(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return a(e,400,{error:"need url"});try{const r=await Xt(o);return a(e,200,{title:r.title||null,url:r.url||o})}catch(r){const i=r?.name==="AbortError"?"timed out":String(r?.message||r);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function tn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=F(t.session);if(!o)return a(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function nn(n,e){let t;try{t=await f(n)}catch(d){return a(e,400,{error:"Bad JSON: "+d.message})}const o=T[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return a(e,400,{error:"Empty prompt"});const i=t.model||"",l=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let d="";return typeof o.engine.complete=="function"?d=await o.engine.complete({prompt:r,system:l,model:i}):await o.engine.chat({messages:[{role:"user",content:r}],system:l,options:{model:i}},c=>{c.type==="delta"?d+=c.text||"":c.type==="done"&&c.text&&(d+=c.text)}),a(e,200,{text:(d||"").trim()})}catch(d){return a(e,502,{error:d?.message||String(d)})}}async function rn(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=T[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return a(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return a(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return a(e,502,{error:r?.message||String(r)})}}async function on(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=String(t.command||"").trim();if(!o)return a(e,400,{error:"No command"});let r=null;try{r=nt(o)}catch{r=null}return a(e,200,{ok:!!r,via:r?r.kind:null})}const ie=ce(async(n,e)=>{if(vt(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return a(e,400,{error:"bad request"})}const o=$t(n,t.pathname);if(o)return a(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return It(e);const r=t.searchParams.getAll("dir");if(n.method==="GET"&&t.pathname==="/skills")return Nt(e,r);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Rt(e,r);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const i=t.pathname.slice(8),l=i.indexOf("/file/");return l===-1?Ht(e,decodeURIComponent(i),r):_t(e,decodeURIComponent(i.slice(0,l)),decodeURIComponent(i.slice(l+6)),r)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Ut(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Dt(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return re(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return re(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const i=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(qe.map(l=>[l,i?Y(l)||null:!!Y(l)])),...i?{home:x.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return Gt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return Lt(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Wt(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return jt(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Jt(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return oe(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const i=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return oe(n,e,i);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return J(i),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ne(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ne(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Ft(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return tn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local")return Kt(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return zt(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return en(n,e);if(n.method==="POST"&&t.pathname==="/complete")return nn(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return rn(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return on(n,e);if(n.method==="POST"&&t.pathname==="/update")return Bt(e);a(e,404,{error:"Not found"})}catch(r){a(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function an(n){let e="";const t=[];let o=!1,r=!1;const i=()=>{r&&!o&&!t.length&&process.exit(0)},l=async()=>{if(!o){for(o=!0;t.length;){const d=t.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await s.text()).trim();h&&process.stdout.write(h+`
10
+ `)}catch(s){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(s?.message||s)}})+`
11
+ `)}}o=!1,i()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
12
+ `))>=0;){const s=e.slice(0,c).trim();e=e.slice(c+1),s&&t.push(s)}l()}),process.stdin.on("end",()=>{r=!0,i()}),process.stdin.resume()}function sn(){et(),tt(),Et(),ie.on("error",n=>{n&&n.code==="EADDRINUSE"&&(u("error",`Port ${O} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings."),process.exit(1)),u("error",`bridge server error: ${n?.message||n}`),process.exit(1)});for(const n of["SIGINT","SIGTERM"])process.on(n,()=>{const e=st("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const t=ct("shutdown");t&&u("info",`shutdown: closed ${t} warm agent process${t===1?"":"es"}`),setTimeout(()=>process.exit(0),e||t?300:0).unref?.(),!e&&!t&&process.exit(0)});ie.listen(O,k,async()=>{u("info",`listening on http://${k}:${O}`),D.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:n,label:e,hidden:t}]of Object.entries(T)){if(t)continue;const o=await n.available().catch(()=>({ok:!1}));u("info",` ${o.ok?"✓":"✕"} ${e}${o.ok?"":" — "+(o.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),te().then(n=>n.startIfConfigured()).then(n=>{n?.skipped||(n?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${n?.error||"unknown error"}`))}).catch(n=>u("error",`channels: ${n?.message||n}`))})}function cn(){console.log(`ChatPanel Bridge v${g}
1425
13
 
1426
14
  Usage:
1427
- chatpanel-bridge start the bridge (foreground) on ${HOST}:${PORT}
15
+ chatpanel-bridge start the bridge (foreground) on ${k}:${O}
1428
16
  chatpanel-bridge --install run automatically at login, in the background
1429
17
  chatpanel-bridge --uninstall remove the login auto-start
1430
18
  chatpanel-bridge --status show whether auto-start is set up
1431
19
  chatpanel-bridge --update download & install the latest version, then restart
1432
20
  chatpanel-bridge --version print the version
1433
21
 
1434
- Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`);
1435
- }
1436
-
1437
- // Handle CLI commands before starting the server. Returns true if a command ran.
1438
- function runCli() {
1439
- const argv = process.argv;
1440
- const has = (...flags) => flags.some((f) => argv.includes(f));
1441
-
1442
- if (has('--help', '-h')) {
1443
- printHelp();
1444
- return true;
1445
- }
1446
- if (has('--version', '-v')) {
1447
- console.log(VERSION);
1448
- return true;
1449
- }
1450
- if (has('--install')) {
1451
- try {
1452
- installService();
1453
- log('info', 'Installed. The bridge now starts automatically at login and is running in the background.');
1454
- } catch (e) {
1455
- log('error', 'Install failed: ' + (e?.message || e));
1456
- process.exitCode = 1;
1457
- }
1458
- return true;
1459
- }
1460
- if (has('--uninstall')) {
1461
- try {
1462
- uninstallService();
1463
- log('info', 'Removed the login auto-start.');
1464
- } catch (e) {
1465
- log('error', 'Uninstall failed: ' + (e?.message || e));
1466
- process.exitCode = 1;
1467
- }
1468
- return true;
1469
- }
1470
- if (has('--status')) {
1471
- let on = false;
1472
- try {
1473
- on = serviceStatus();
1474
- } catch (e) {
1475
- log('error', String(e?.message || e));
1476
- }
1477
- log('info', `auto-start: ${on ? 'installed' : 'not installed'}`);
1478
- return true;
1479
- }
1480
- return false;
1481
- }
1482
-
1483
- const mcpStdioIdx = process.argv.indexOf('--mcp-stdio');
1484
- if (mcpStdioIdx >= 0) {
1485
- const url = process.argv[mcpStdioIdx + 1];
1486
- if (!url) {
1487
- console.error('--mcp-stdio requires a URL');
1488
- process.exit(1);
1489
- }
1490
- runMcpStdioProxy(url);
1491
- } else if (process.argv.includes('--update')) {
1492
- (async () => {
1493
- try {
1494
- const r = await selfUpdate(VERSION);
1495
- log('info', `Updated v${r.from} → v${r.to}. Restarting the background service…`);
1496
- restartService();
1497
- } catch (e) {
1498
- log('error', 'Update failed: ' + (e?.message || e));
1499
- process.exitCode = 1;
1500
- }
1501
- })();
1502
- } else if (!runCli()) {
1503
- startServer();
1504
- }
22
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function ln(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return cn(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("--install")){try{Oe(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){u("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{Ae(),u("info","Removed the login auto-start.")}catch(t){u("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=xe()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const se=process.argv.indexOf("--mcp-stdio");if(se>=0){const n=process.argv[se+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),an(n)}else process.argv.includes("--update")?(async()=>{try{const n=await X(g);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),j()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():ln()||sn();