@chatpanel/bridge 0.13.2 → 0.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.13.2",
3
+ "version": "0.13.3",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -1,4 +1,4 @@
1
- import{spawn as W}from"node:child_process";import{writeFile as $,unlink as I}from"node:fs/promises";import M from"node:os";import R from"node:path";import{resolveClaude as C,buildSpawnSpec as j,isCompiledBinary as V,selfMcpStdio as Z}from"../env.js";import{signInStatus as ee,signInMessage as D,loginRequired as te}from"../sign-in.js";import{buildCliPrompt as F}from"./prompt.js";import{summarizeCliError as re}from"../cli-errors.js";import{killOnAbort as oe}from"../proc.js";import{pushExtraArgs as ne,FORBIDDEN as se}from"./args.js";import{relayTimeoutMax as ae}from"../relay-timeout.js";import{displayPath as ie,resolveWorkdir as z}from"../workdir.js";import{connectorsFor as le}from"../connectors.js";import{chatWarm as ce}from"./claude-warm.js";async function ue(e,t){const o=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const n=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=R.join(M.tmpdir(),`chatpanel-claude-img-${t}-${i}.${n}`);await $(r,Buffer.from(s[2],"base64")),o.push(r)}return o}const H=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,U=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],B=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),de=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch"])}),pe=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),fe=Object.freeze(["remember","forget"]),G=Object.freeze({device:Object.freeze([]),trusted:pe});function he(e,t=[]){const o=G[e]||G.device,i=(t||[]).filter(r=>typeof r=="string"&&/^chatpanel/i.test(r)),s=[],n=[];for(const r of i){for(const a of o)s.push(`mcp__${r}__${a}`);for(const a of fe)n.push(`mcp__${r}__${a}`)}return{allow:s,deny:n}}function me(e){if(!e||e==="any")return null;const t=B[e]?e:"device";return{allow:[...B[t]],deny:[...de[t]]}}let k="Claude Code not found.",q=0,w=!1;async function De(){if(Date.now()-q>(w?3e4:4e3)){q=Date.now();try{C()||!V()&&await N()?w=!0:(w=!1,k=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{w=!1}}return w?await ee("claude",C()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:D("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:k}}async function Fe(){return["opus","sonnet","haiku"]}function ye(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:o,args:i}=Z(e.url),s=[...new Set(e.specs.map(n=>n?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:o,args:i}}},allowedTools:s.map(n=>`mcp__${t}__${n}`)}}function Y({prompt:e,args:t,cwd:o,env:i=null,emit:s,signal:n}){const r=C();if(!r)return null;const[a,l,h]=j(r,t,o,i);return new Promise((y,d)=>{let u;try{u=W(a,l,h)}catch(f){return d(new Error(`Failed to start claude: ${f.message}`))}const c=oe(u,n);let m="",_="",b=!1,p=null;const T={sawText:!1,tail:"",boundary:!1};let S="",x;const A=()=>{clearTimeout(x),x=setTimeout(()=>{u.kill("SIGKILL"),d(new Error(`Claude Code timed out — no output for ${Math.round(H/1e3)}s.`))},H)};A(),u.stdout.on("data",f=>{A(),m+=f.toString();let v;for(;(v=m.indexOf(`
1
+ import{spawn as W}from"node:child_process";import{writeFile as $,unlink as I}from"node:fs/promises";import M from"node:os";import R from"node:path";import{resolveClaude as C,buildSpawnSpec as j,isCompiledBinary as V,selfMcpStdio as Z}from"../env.js";import{signInStatus as ee,signInMessage as D,loginRequired as te}from"../sign-in.js";import{buildCliPrompt as F}from"./prompt.js";import{summarizeCliError as re}from"../cli-errors.js";import{killOnAbort as oe}from"../proc.js";import{pushExtraArgs as ne,FORBIDDEN as se}from"./args.js";import{relayTimeoutMax as ae}from"../relay-timeout.js";import{displayPath as ie,resolveWorkdir as z}from"../workdir.js";import{connectorsFor as le}from"../connectors.js";import{chatWarm as ce}from"./claude-warm.js";async function ue(e,t){const o=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const n=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=R.join(M.tmpdir(),`chatpanel-claude-img-${t}-${i}.${n}`);await $(r,Buffer.from(s[2],"base64")),o.push(r)}return o}const H=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,U=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],B=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),de=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch"])}),pe=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),fe=Object.freeze(["remember","forget"]),G=Object.freeze({device:Object.freeze([]),trusted:pe});function he(e,t=[]){const o=G[e]||G.device,i=(t||[]).filter(r=>typeof r=="string"&&/^chatpanel/i.test(r)),s=[],n=[];for(const r of i){for(const a of o)s.push(`mcp__${r}__${a}`);for(const a of fe)n.push(`mcp__${r}__${a}`)}return{allow:s,deny:n}}function me(e){if(!e||e==="any")return null;const t=B[e]?e:"device";return{allow:[...B[t]],deny:[...de[t]]}}let k="Claude Code not found.",q=0,w=!1;async function De(){if(Date.now()-q>(w?3e4:4e3)){q=Date.now();try{C()||!V()&&await N()?w=!0:(w=!1,k=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{w=!1}}return w?await ee("claude",C()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:D("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:k}}async function Fe(){return["opus","sonnet","haiku"]}function ye(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:o,args:i}=Z(e.url),s=[...new Set(e.specs.map(n=>n?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:o,args:i}}},allowedTools:s.map(n=>`mcp__${t}__${n}`)}}function Y({prompt:e,args:t,cwd:o,env:i=null,emit:s,signal:n}){const r=C();if(!r)return null;const[a,l,h]=j(r,t,o,i);return new Promise((y,d)=>{let u;try{u=W(a,l,h)}catch(f){return d(new Error(`Failed to start claude: ${f.message}`))}const c=oe(u,n);let m="",_="",b=!1,p=null;const T={sawText:!1,tail:"",boundary:!1};let S="",x;const A=()=>{clearTimeout(x),x=setTimeout(()=>{u.kill("SIGKILL"),d(new Error(`Claude Code timed out — no output for ${Math.round(H/1e3)}s.`))},H)};A(),u.stdout.on("data",f=>{A(),m+=f.toString();let v;for(;(v=m.indexOf(`
2
2
  `))>=0;){const P=m.slice(0,v).trim();if(m=m.slice(v+1),!P.startsWith("{"))continue;let L;try{L=JSON.parse(P)}catch{continue}const E=K(L,s,b,o,T);E.streamed&&(b=!0),E.result!=null&&(S=E.result),E.apiError&&(p=E.apiError)}}),u.stderr.on("data",f=>{A(),_+=f.toString()}),u.on("error",f=>{clearTimeout(x),c(),d(new Error(`Failed to start claude (${a}): ${f.message}`))}),u.on("close",f=>{if(clearTimeout(x),c(),n?.aborted){y({streamedAny:b,resultText:S});return}if(p&&te(p))return d(new Error(D("Claude Code","claude")));if(f===0&&p)return d(new Error(`Claude Code reported an error: ${p}`));f===0?y({streamedAny:b,resultText:S}):d(new Error(re("Claude Code",f,_,p||"",{agentId:"claude"})))}),u.stdin.write(e),u.stdin.end()})}function _e(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(o=>typeof o=="string"?o:o?.text||"").filter(Boolean).join(`
3
3
  `)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function J(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
4
4
 
package/src/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as fe}from"node:http";import P from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ce from"./engines/antigravity.js";import{pi as Ee,opencode as Oe,kiro as Ae,copilot as Pe,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{gitState as Ye,gitDelta as Qe}from"./scm.js";import{listConnections as Ze,putConnection as qe,removeConnection as et,runEnvFor as tt,testConnection as nt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as rt,removeWorktree as ot,withHook as at,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as it,enrichPath as st,enrichAgentEnv as ct,findAgentBin as ee,resolveCommand as lt}from"./env.js";import"./sanitize.js";import{checkForUpdate as dt,selfUpdate as te,isEmbedded as ut}from"./update.js";import{callLocalMcp as ht}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as pt,cancelAll as mt}from"./runs.js";import{closeWarmPools as ft,warmStatus as gt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as yt,chatCompletionStream as wt,completionStream as bt,createAnthropicMessage as St,createChatCompletion as kt,createCompletion as Tt,createResponse as vt,openAIError as w,parseAnthropicMessage as Ct,parseChatCompletion as Et,parseCompletion as Ot,parseResponse as At,responseStream as Pt}from"./api-compat.js";import{callerTrust as xt,isPaired as $,parseExtensionIds as $t,capRunOptions as It,engineHonoursReach as Nt,createPairingStore as Rt,formatPairingCode as _t}from"./pii/trust.js";const g="0.13.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ce,label:"Antigravity",tools:!1},pi:{engine:Ee,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Ae,label:"Kiro"},copilot:{engine:Pe,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const Ht=$t(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(t){return t.chatpanelTrust||(t.chatpanelTrust=xt({origin:t.headers.origin||"",hasToken:le(t),extensionIds:Ht})),t.chatpanelTrust}function Mt(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function Bt(t,e){const n=t.headers.origin||"",o=ae(n);e.setHeader("Access-Control-Allow-Origin",o?n||"*":"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 W=new Set(["127.0.0.1","localhost","::1"]);function Gt(t){if(!W.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(n)}const N=_(P.homedir(),".chatpanel","bridge-token");let S="";function Ut(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(P.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(t){d("error",`could not initialise bridge token: ${t?.message||t}`)}}const ie=Rt({random:()=>ye(0,1e6)/1e6});function Dt(t){if(!S)return i(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),i(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Lt(t,e){let n;try{n=await f(t)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(n?.code);return o.ok?(d("info",`paired a ${I(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(t)} caller`),i(e,403,{error:o.reason}))}function jt(t,e){const n=I(t);return i(e,200,{ok:!0,trust:n,paired:$(n),version:g})}let H=null;async function se(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(P.homedir(),".chatpanel"),dataDir:_(P.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(t,e,n){try{const o=await se(),r=t.method==="POST"?await f(t):{};if(n==="status")return i(e,200,await o.status());if(n==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return n==="pair"?i(e,200,await o.pair()):n==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):n==="settings"?i(e,200,await o.update(r)):n==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function le(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const o=Buffer.from(n),r=Buffer.from(S);return o.length===r.length&&we(o,r)}const Wt=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","/pair/code"]),Ft=new Set(["/debug"]),Jt=t=>Ft.has(t);function zt(t,e){if(!Gt(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!ae(n))return"forbidden origin";const o=t.method==="POST"&&Wt.has(e)||t.method==="GET"&&Jt(e);return o&&!(Mt(n)||le(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(t))&&!Vt.has(e)?Kt:null}const Kt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(t,e,n){const o=I(t),r=It(n,o);if(!Nt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=r.reach,l=$(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:r,note:l}}function i(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function f(t){return new Promise((e,n)=>{let o="";t.on("data",r=>{o+=r,o.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){n(r)}}),t.on("error",n)})}async function Xt(t){const e=await Promise.all(Object.entries(C).filter(([,r])=>!r.hidden).map(async([r,{engine:a,label:l,tools:m}])=>{const s=await a.available().catch(u=>({ok:!1,reason:String(u?.message||u)})),c=await Ie(r).catch(()=>[]);return{id:r,label:l,available:s.ok,reason:s.reason,connectors:c,...m===!1?{tools:!1}:{}}})),n=ut()?{current:g,updateAvailable:!1,embedded:"gateway"}:await dt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ue().catch(()=>null);i(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ze,worktrees:q,secretBackend:Q(),warm:gt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Yt(t,e){const{index:n,problems:o}=await D({extraDirs:e});i(t,200,{ok:!0,skills:Me(n),problems:o})}async function Qt(t,e){i(t,200,{ok:!0,quarantined:await De(e)})}async function Zt(t,e,n){const{index:o}=await D({extraDirs:n}),r=Be(o,e);if(!r)return i(t,404,{ok:!1,error:"unknown skill"});i(t,200,{ok:!0,skill:r})}async function qt(t,e,n,o){const{index:r}=await D({extraDirs:o}),a=await Ge(r,e,n);if(a.error)return i(t,a.error==="unknown skill"?404:400,{ok:!1,error:a.error});i(t,200,{ok:!0,...a})}async function en(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function de(t,e=""){const n=await en();if(e){const o=n.find(r=>r.id===e);return o?i(t,200,o):i(t,404,w(new x(`Model "${e}" not found`,404,"model")))}return i(t,200,{object:"list",data:n})}async function tn(t){try{const e=await te(g);i(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(t,400,{ok:!1,error:String(e?.message||e)})}}async function nn(t,e){let n;try{n=await f(t)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const o=C[n.agent];if(!o)return i(e,404,{error:`Unknown agent "${n.agent}"`});const r=F(t,n.agent,n.options||{});if(r.error)return i(e,403,{error:r.error});n.options=r.options,Array.isArray(n.images)&&n.images.length&&d("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
2
+ import{createServer as fe}from"node:http";import P from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ce from"./engines/antigravity.js";import{pi as Ee,opencode as Oe,kiro as Ae,copilot as Pe,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{gitState as Ye,gitDelta as Qe}from"./scm.js";import{listConnections as Ze,putConnection as qe,removeConnection as et,runEnvFor as tt,testConnection as nt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as rt,removeWorktree as ot,withHook as at,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as it,enrichPath as st,enrichAgentEnv as ct,findAgentBin as ee,resolveCommand as lt}from"./env.js";import"./sanitize.js";import{checkForUpdate as dt,selfUpdate as te,isEmbedded as ut}from"./update.js";import{callLocalMcp as ht}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as pt,cancelAll as mt}from"./runs.js";import{closeWarmPools as ft,warmStatus as gt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as yt,chatCompletionStream as wt,completionStream as bt,createAnthropicMessage as St,createChatCompletion as kt,createCompletion as Tt,createResponse as vt,openAIError as w,parseAnthropicMessage as Ct,parseChatCompletion as Et,parseCompletion as Ot,parseResponse as At,responseStream as Pt}from"./api-compat.js";import{callerTrust as xt,isPaired as $,parseExtensionIds as $t,capRunOptions as It,engineHonoursReach as Nt,createPairingStore as Rt,formatPairingCode as _t}from"./pii/trust.js";const g="0.13.3",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ce,label:"Antigravity",tools:!1},pi:{engine:Ee,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Ae,label:"Kiro"},copilot:{engine:Pe,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const Ht=$t(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(t){return t.chatpanelTrust||(t.chatpanelTrust=xt({origin:t.headers.origin||"",hasToken:le(t),extensionIds:Ht})),t.chatpanelTrust}function Mt(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function Bt(t,e){const n=t.headers.origin||"",o=ae(n);e.setHeader("Access-Control-Allow-Origin",o?n||"*":"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 W=new Set(["127.0.0.1","localhost","::1"]);function Gt(t){if(!W.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(n)}const N=_(P.homedir(),".chatpanel","bridge-token");let S="";function Ut(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(P.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(t){d("error",`could not initialise bridge token: ${t?.message||t}`)}}const ie=Rt({random:()=>ye(0,1e6)/1e6});function Dt(t){if(!S)return i(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),i(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Lt(t,e){let n;try{n=await f(t)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(n?.code);return o.ok?(d("info",`paired a ${I(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(t)} caller`),i(e,403,{error:o.reason}))}function jt(t,e){const n=I(t);return i(e,200,{ok:!0,trust:n,paired:$(n),version:g})}let H=null;async function se(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(P.homedir(),".chatpanel"),dataDir:_(P.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(t,e,n){try{const o=await se(),r=t.method==="POST"?await f(t):{};if(n==="status")return i(e,200,await o.status());if(n==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return n==="pair"?i(e,200,await o.pair()):n==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):n==="settings"?i(e,200,await o.update(r)):n==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function le(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const o=Buffer.from(n),r=Buffer.from(S);return o.length===r.length&&we(o,r)}const Wt=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","/pair/code"]),Ft=new Set(["/debug"]),Jt=t=>Ft.has(t);function zt(t,e){if(!Gt(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!ae(n))return"forbidden origin";const o=t.method==="POST"&&Wt.has(e)||t.method==="GET"&&Jt(e);return o&&!(Mt(n)||le(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(t))&&!Vt.has(e)?Kt:null}const Kt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(t,e,n){const o=I(t),r=It(n,o);if(!Nt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=r.reach,l=$(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:r,note:l}}function i(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function f(t){return new Promise((e,n)=>{let o="";t.on("data",r=>{o+=r,o.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){n(r)}}),t.on("error",n)})}async function Xt(t){const e=await Promise.all(Object.entries(C).filter(([,r])=>!r.hidden).map(async([r,{engine:a,label:l,tools:m}])=>{const s=await a.available().catch(u=>({ok:!1,reason:String(u?.message||u)})),c=await Ie(r).catch(()=>[]);return{id:r,label:l,available:s.ok,reason:s.reason,connectors:c,...m===!1?{tools:!1}:{}}})),n=ut()?{current:g,updateAvailable:!1,embedded:"gateway"}:await dt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ue().catch(()=>null);i(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ze,worktrees:q,secretBackend:Q(),warm:gt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Yt(t,e){const{index:n,problems:o}=await D({extraDirs:e});i(t,200,{ok:!0,skills:Me(n),problems:o})}async function Qt(t,e){i(t,200,{ok:!0,quarantined:await De(e)})}async function Zt(t,e,n){const{index:o}=await D({extraDirs:n}),r=Be(o,e);if(!r)return i(t,404,{ok:!1,error:"unknown skill"});i(t,200,{ok:!0,skill:r})}async function qt(t,e,n,o){const{index:r}=await D({extraDirs:o}),a=await Ge(r,e,n);if(a.error)return i(t,a.error==="unknown skill"?404:400,{ok:!1,error:a.error});i(t,200,{ok:!0,...a})}async function en(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function de(t,e=""){const n=await en();if(e){const o=n.find(r=>r.id===e);return o?i(t,200,o):i(t,404,w(new x(`Model "${e}" not found`,404,"model")))}return i(t,200,{object:"list",data:n})}async function tn(t){try{const e=await te(g);i(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(t,400,{ok:!1,error:String(e?.message||e)})}}async function nn(t,e){let n;try{n=await f(t)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const o=C[n.agent];if(!o)return i(e,404,{error:`Unknown agent "${n.agent}"`});const r=F(t,n.agent,n.options||{});if(r.error)return i(e,403,{error:r.error});n.options=r.options,Array.isArray(n.images)&&n.images.length&&d("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
3
3
 
4
4
  `)};let l=!1;const m=`run_${Math.random().toString(36).slice(2,10)}`,s=oe(m),c={signal:s.signal,abort:()=>s.cancel("client")},u=()=>{l=!0,s.cancel("disconnected")};t.on("close",u),e.on("close",u),e.on("error",u);const b=h=>{l||a(h)};a({type:"run",id:m}),r.note&&a({type:"status",text:r.note});let p=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const h=n.options.workspace;if(p=await Z({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),p.error){a({type:"error",error:`workspace: ${p.error}`}),L(m),e.writableEnded||e.end();return}}const J=p?p.path:Ve(n.options?.workingDir);let E=null;{const h=J,O=!!p||!Ke(n.options?.workingDir),y=Xe(n.agent,n.options?.permissionMode,h);a({type:"workdir",path:h,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${h}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await Ye(h),E&&a({type:"scm",phase:"before",...E})}let U=null;if(E||p){const h=Array.isArray(n.options?.grants)?n.options.grants:[],{env:O,connection:y}=tt({remote:E?.remote||null,grants:h,branch:p?.branch||null,connectionId:n.options?.connectionId||null});U=at(O),p&&a({type:"workspace",path:p.path,branch:p.branch,base:p.base,created:p.created,repo:p.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${p?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z={...n.options||{},...p?{workingDir:p.path}:{},...U?{runEnv:U}:{}};let R=null;n.pageTools?.specs?.length&&(R=We(b,n.pageTools.specs),z.mcp={url:`http://${k}:${v}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs});try{await o.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:z,images:Array.isArray(n.images)?n.images:[]},b,{signal:c.signal})}catch(h){d("error",`${n.agent} chat failed: ${h?.message||h}`),a({type:"error",error:h?.message||String(h)})}finally{if(!l){const h=await Qe(J,E).catch(()=>null);h&&b({type:"scm",phase:"after",...h})}L(m),R&&X(R.id),e.writableEnded||e.end()}}async function rn(t,e,n){if(t.method==="GET"&&n==="/connections")return i(e,200,{ok:!0,connections:Ze(),secretBackend:Q()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await f(t);if(n==="/connections")try{return i(e,200,{ok:!0,connection:qe(o.connection||o,{token:o.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return r?r[2]==="delete"?i(e,200,{ok:et(r[1])}):i(e,200,nt(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function on(t,e,n){if(t.method==="GET"&&n==="/worktrees")return i(e,200,{ok:!0,root:q,worktrees:await rt()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await f(t);if(n==="/worktrees"){const r=await Z({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return i(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(n==="/worktrees/remove"){const r=await ot({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return i(e,r.ok?200:400,r)}return i(e,404,{error:"Not found"})}async function T(t,e,n){const o=C[t.agent];if(!o||o.hidden)throw new x(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const r=await o.engine.available().catch(c=>({ok:!1,reason:c?.message||String(c)}));if(!r.ok)throw new x(r.reason||`${t.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,l=oe(a),m=()=>l.cancel("disconnected");n.on("close",m);let s="";try{return await o.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},c=>{c?.type==="delta"&&c.text?(s+=c.text,e(c.text)):c?.type==="done"&&c.text&&!s&&(s=c.text,e(c.text))},{signal:l.signal}),s}finally{n.off("close",m),L(a)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function A(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5