@chatpanel/bridge 0.32.2 → 0.42.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.
package/src/server.js CHANGED
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as Te}from"node:http";import E from"node:os";import{randomBytes as Ee,randomInt as ve,timingSafeEqual as Oe}from"node:crypto";import{mkdirSync as Ce,writeFileSync as Ae,readFileSync as Y,existsSync as xe}from"node:fs";import{join as _}from"node:path";import*as Pe from"./engines/claude.js";import*as Re from"./engines/codex.js";import*as Ie from"./engines/antigravity.js";import{pi as $e,opencode as Ne,kiro as De,copilot as _e,deepseek as He,hermes as Me}from"./engines/cli-agents.js";import{connectorsFor as Ue}from"./connectors.js";import*as We from"./engines/custom.js";import{installService as Be,uninstallService as Ge,serviceStatus as Le,restartService as Q}from"./service.js";import{skillIndex as G,listRecords as je,readRecord as Fe,readPackageFile as Je,skillsHealth as Xe,quarantinedSkills as ze,clearSkillCache as L}from"./skills.js";import{writeSkillPackage as Ke,writeSkillFile as Ve,deleteSkillPackage as Ye,SkillWriteError as Qe}from"./skill-write.js";import{agentDefRoots as Ze,scanAgentDefs as qe,listAgentDefs as et,readAgentDef as tt,planAgentExport as nt,exportAgentDef as ot,agentDefsHealth as rt,AgentDefError as at}from"./agent-defs.js";import{capabilityToolSpecs as it,runCapabilityTool as st}from"./mcp-capabilities.js";import{createSession as ct,deleteSession as Z,getSession as q,activeSession as lt,relayToolCall as dt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ut,isDefaultWorkdir as ht,resolveWorkdir as pt,writeScopeNote as ft}from"./workdir.js";import{sandbox as ee,runSandboxCli as mt,withGrant as te,withoutOutsideWhenCapped as gt,grantedWriteRoots as yt,acceptRefusalReport as wt,liveProcesses as bt}from"./sandbox.js";import{gitState as St,gitDelta as kt}from"./scm.js";import{listConnections as Tt,putConnection as Et,removeConnection as vt,runEnvFor as Ot,testConnection as Ct,secretBackend as ne}from"./connections.js";import{worktreeFor as oe,listWorktrees as At,removeWorktree as xt,withHook as Pt,WORKTREE_ROOT as re}from"./worktree.js";import{AGENT_CLIS as Rt,agentAvailable as It,agentInstallDirs as $t,enrichPath as Nt,enrichAgentEnv as Dt,findAgentBin as _t,resolveCommand as ae}from"./env.js";import"./sanitize.js";import{checkForUpdate as Ht,selfUpdate as ie,isEmbedded as Mt}from"./update.js";import{callLocalMcp as Ut,localMcpStatus as Wt,signInLocalMcp as Bt,signInStatusLocalMcp as Gt}from"./mcp-local.js";import{assertPublicHttpUrl as se,assertPublicWebUrl as ce}from"./ssrf.js";import{startRun as le,endRun as j,cancelRun as Lt,cancelAll as jt}from"./runs.js";import{closeWarmPools as Ft,warmStatus as Jt}from"./warm.js";import{CompatError as R,anthropicError as F,anthropicStream as Xt,chatCompletionStream as zt,completionStream as Kt,createAnthropicMessage as Vt,createChatCompletion as Yt,createCompletion as Qt,createResponse as Zt,openAIError as b,parseAnthropicMessage as qt,parseChatCompletion as en,parseCompletion as tn,parseResponse as nn,responseStream as on}from"./api-compat.js";import{callerTrust as rn,isPaired as I,parseExtensionIds as an,capRunOptions as sn,engineHonoursReach as cn,createPairingStore as ln,formatPairingCode as dn}from"./pii/trust.js";const g="0.32.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:Pe,label:"Claude Code"},codex:{engine:Re,label:"Codex"},antigravity:{engine:Ie,label:"Antigravity",tools:!1},pi:{engine:$e,label:"Pi"},opencode:{engine:Ne,label:"OpenCode"},hermes:{engine:Me,label:"Hermes"},kiro:{engine:De,label:"Kiro"},copilot:{engine:_e,label:"GitHub Copilot"},deepseek:{engine:He,label:"DeepSeek Harness"},custom:{engine:We,label:"Custom",hidden:!0}};function de(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 un=an(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function $(t){return t.chatpanelTrust||(t.chatpanelTrust=rn({origin:t.headers.origin||"",hasToken:fe(t),extensionIds:un})),t.chatpanelTrust}function hn(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 pn(t,e){const n=t.headers.origin||"",r=de(n);e.setHeader("Access-Control-Allow-Origin",r?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 J=new Set(["127.0.0.1","localhost","::1"]);function fn(t){if(!J.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(n)}const N=_(E.homedir(),".chatpanel","bridge-token");let S="";function mn(){try{xe(N)&&(S=Y(N,"utf8").trim()),S||(S=Ee(32).toString("hex"),Ce(_(E.homedir(),".chatpanel"),{recursive:!0}),Ae(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ue=ln({random:()=>ve(0,1e6)/1e6});function gn(t){if(!S)return a(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ue.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),a(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function yn(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=ue.claim(n?.code);return r.ok?(u("info",`paired a ${$(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${$(t)} caller`),a(e,403,{error:r.reason}))}function wn(t,e){const n=$(t);return a(e,200,{ok:!0,trust:n,paired:I(n),version:g})}let H=null;async function he(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(E.homedir(),".chatpanel"),dataDir:_(E.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function pe(t,e,n){try{const r=await he(),o=t.method==="POST"?await m(t):{};if(n==="status")return a(e,200,await r.status());if(n==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return n==="pair"?a(e,200,await r.pair()):n==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?a(e,200,await r.update(o)):n==="disconnect"?a(e,200,await r.stop({forget:!!o.forget})):a(e,404,{error:"unknown channel action"})}catch(r){return a(e,400,{error:r?.message||String(r)})}}function fe(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 r=Buffer.from(n),o=Buffer.from(S);return r.length===o.length&&Oe(r,o)}const bn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/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"]),Sn=new Set(["/debug"]),kn=t=>Sn.has(t),Tn=(t,e)=>t!=="GET"&&t!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function En(t,e){if(!fn(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!de(n))return"forbidden origin";const r=t.method==="POST"&&bn.has(e)||t.method==="GET"&&kn(e)||Tn(t.method,e);return r&&!(hn(n)||fe(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I($(t))&&!On.has(e)?vn:null}const vn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",On=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(t,e,n){const r=$(t),o=gt(sn(n,r));if(!cn(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=o.reach,s=I(r)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="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 → Coding Agents to unlock them.";return{options:o,note:s}}function a(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function m(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function Cn(t){const e=await Promise.all(Object.entries(O).filter(([,s])=>!s.hidden).map(async([s,{engine:d,label:c,tools:l}])=>{const h=await d.available().catch(p=>({ok:!1,reason:String(p?.message||p)})),y=await Ue(s).catch(()=>[]);return{id:s,label:c,available:h.ok,reason:h.reason,connectors:y,...l===!1?{tools:!1}:{}}})),n=Mt()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Ht(g).catch(()=>({current:g,updateAvailable:!1})),r=await Xe().catch(()=>null),o=await rt().catch(()=>null),i=await ee().status().catch(s=>({enabled:!1,reason:s.message}));a(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ut,sandbox:i,localMcp:Wt(),processes:bt(),worktrees:re,secretBackend:ne(),warm:Jt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{},...o?{agentDefs:o}:{}})}async function An(t,e,n){const{index:r,problems:o}=await G({extraDirs:e,workdir:n});a(t,200,{ok:!0,skills:je(r),problems:o})}async function xn(t,e,n){a(t,200,{ok:!0,quarantined:await ze(e,n)})}async function Pn(t,e,n,r){const{index:o}=await G({extraDirs:n,workdir:r}),i=Fe(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown skill"});a(t,200,{ok:!0,skill:i})}async function Rn(t,e,n,r,o){const{index:i}=await G({extraDirs:r,workdir:o}),s=await Je(i,e,n);if(s.error)return a(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(t,200,{ok:!0,...s})}async function In(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{const r=await Ke({skill:n?.skill,files:n?.files||[],overwrite:!!n?.overwrite});return L(),a(e,200,r)}catch(r){return a(e,z(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function $n(t,e,n,r){let o;try{o=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}try{const i=await Ve({name:n,path:r,text:o?.text??""});return L(),a(e,200,i)}catch(i){return a(e,z(i),{ok:!1,error:i.message,code:i.code||"ERROR"})}}async function Nn(t,e){try{const n=await Ye({name:e});return L(),a(t,200,n)}catch(n){return a(t,z(n),{ok:!1,error:n.message,code:n.code||"ERROR"})}}function z(t){return t instanceof Qe?t.code==="NOT_FOUND"?404:t.code==="EXISTS"||t.code==="FULL"?409:t.code==="REFUSED"||t.code==="OUTSIDE"?403:400:400}async function me(t,e){return qe({roots:Ze(process.env,E.homedir(),t,e)})}async function Dn(t,e,n){const{index:r,quarantined:o,problems:i}=await me(e,n);a(t,200,{ok:!0,agents:et(r),...o.length?{quarantined:o.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...i.length?{problems:i}:{}})}async function _n(t,e,n,r){const{index:o}=await me(n,r),i=tt(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown agent definition"});a(t,200,{ok:!0,...i})}async function Hn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,{ok:!0,...await nt({agent:n?.agent,to:n?.to})})}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function Mn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,await ot({agent:n?.agent,to:n?.to,overwrite:!!n?.overwrite}))}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function ge(t){if(t instanceof at){if(t.code==="NOT_OURS")return 409;if(t.code==="TARGET")return 400}return 400}async function Un(){return(await Promise.all(Object.entries(O).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 ye(t,e=""){const n=await Un();if(e){const r=n.find(o=>o.id===e);return r?a(t,200,r):a(t,404,b(new R(`Model "${e}" not found`,404,"model")))}return a(t,200,{object:"list",data:n})}async function Wn(t){try{const e=await ie(g);a(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>Q(),400))}catch(e){a(t,400,{ok:!1,error:String(e?.message||e)})}}async function Bn(t,e){let n;try{n=await m(t)}catch(f){return a(e,400,{error:"Bad JSON: "+f.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=X(t,n.agent,n.options||{});if(o.error)return a(e,403,{error:o.error});n.options=o.options,Array.isArray(n.images)&&n.images.length&&u("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 i=f=>{e.writableEnded||e.write(`data: ${JSON.stringify(f)}
2
+ import{createServer as Oe}from"node:http";import v from"node:os";import{randomBytes as Ae,randomInt as Ce,timingSafeEqual as xe}from"node:crypto";import{mkdirSync as Pe,writeFileSync as $e,readFileSync as Q,existsSync as Re}from"node:fs";import{join as _}from"node:path";import*as Ie from"./engines/claude.js";import*as Ne from"./engines/codex.js";import*as De from"./engines/antigravity.js";import{pi as _e,opencode as He,kiro as Be,copilot as Me,deepseek as Ue,hermes as We}from"./engines/cli-agents.js";import{connectorsFor as Ge}from"./connectors.js";import*as Le from"./engines/custom.js";import{installService as je,uninstallService as Fe,serviceStatus as Je,restartService as Z}from"./service.js";import{skillIndex as G,listRecords as Xe,readRecord as ze,readPackageFile as Ke,skillsHealth as Ye,quarantinedSkills as Ve,clearSkillCache as L}from"./skills.js";import{writeSkillPackage as Qe,writeSkillFile as Ze,deleteSkillPackage as qe,SkillWriteError as et}from"./skill-write.js";import{agentDefRoots as tt,scanAgentDefs as nt,listAgentDefs as ot,readAgentDef as rt,planAgentExport as at,exportAgentDef as it,agentDefsHealth as st,AgentDefError as ct}from"./agent-defs.js";import{capabilityToolSpecs as lt,runCapabilityTool as dt}from"./mcp-capabilities.js";import{createSession as ut,deleteSession as q,getSession as ee,activeSession as ht,relayToolCall as pt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ft,isDefaultWorkdir as mt,resolveWorkdir as gt,writeScopeNote as yt}from"./workdir.js";import{sandbox as te,runSandboxCli as wt,withGrant as ne,withoutOutsideWhenCapped as St,grantedWriteRoots as bt,acceptRefusalReport as kt,liveProcesses as Tt}from"./sandbox.js";import{gitState as Et,gitDelta as vt}from"./scm.js";import{listConnections as Ot,putConnection as At,removeConnection as Ct,runEnvFor as xt,testConnection as Pt,secretBackend as oe}from"./connections.js";import{worktreeFor as re,listWorktrees as $t,removeWorktree as Rt,withHook as It,WORKTREE_ROOT as ae}from"./worktree.js";import{AGENT_CLIS as Nt,agentAvailable as Dt,agentInstallDirs as _t,enrichPath as Ht,enrichAgentEnv as Bt,findAgentBin as Mt,resolveCommand as ie}from"./env.js";import"./sanitize.js";import{checkForUpdate as Ut,selfUpdate as se,isEmbedded as Wt}from"./update.js";import{callLocalMcp as Gt,localMcpStatus as Lt,signInLocalMcp as jt,signInStatusLocalMcp as Ft}from"./mcp-local.js";import{assertPublicHttpUrl as ce,assertPublicWebUrl as le}from"./ssrf.js";import{startRun as de,endRun as j,cancelRun as Jt,cancelAll as Xt}from"./runs.js";import{closeWarmPools as zt,warmStatus as Kt}from"./warm.js";import{SESSION_AGENTS as ue,listSessions as Yt,readSession as Vt,adoptSession as Qt,catchUp as Zt}from"./agent-sessions.js";import{normalizeThread as he}from"./events/agent-thread.js";import{portClashPlan as qt,serviceManagerOf as en,STANDBY_POLL_MS as tn}from"./events/service-standby.js";import{holdThread as pe}from"./threads.js";import{CompatError as R,anthropicError as F,anthropicStream as nn,chatCompletionStream as on,completionStream as rn,createAnthropicMessage as an,createChatCompletion as sn,createCompletion as cn,createResponse as ln,openAIError as S,parseAnthropicMessage as dn,parseChatCompletion as un,parseCompletion as hn,parseResponse as pn,responseStream as fn}from"./api-compat.js";import{callerTrust as mn,isPaired as I,parseExtensionIds as gn,capRunOptions as yn,engineHonoursReach as wn,createPairingStore as Sn,formatPairingCode as bn}from"./pii/trust.js";const g="0.42.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",b=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:Ie,label:"Claude Code"},codex:{engine:Ne,label:"Codex"},antigravity:{engine:De,label:"Antigravity",tools:!1},pi:{engine:_e,label:"Pi"},opencode:{engine:He,label:"OpenCode"},hermes:{engine:We,label:"Hermes"},kiro:{engine:Be,label:"Kiro"},copilot:{engine:Me,label:"GitHub Copilot"},deepseek:{engine:Ue,label:"DeepSeek Harness"},custom:{engine:Le,label:"Custom",hidden:!0}};function fe(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]")}const kn=gn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=mn({origin:n.headers.origin||"",hasToken:we(n),extensionIds:kn})),n.chatpanelTrust}function Tn(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 En(n,e){const t=n.headers.origin||"",o=fe(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 J=new Set(["127.0.0.1","localhost","::1"]);function vn(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const D=_(v.homedir(),".chatpanel","bridge-token");let T="";function On(){try{Re(D)&&(T=Q(D,"utf8").trim()),T||(T=Ae(32).toString("hex"),Pe(_(v.homedir(),".chatpanel"),{recursive:!0}),$e(D,T,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const me=Sn({random:()=>Ce(0,1e6)/1e6});function An(n){if(!T)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=me.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Cn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=me.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:T})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function xn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:g})}let H=null;async function ge(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(v.homedir(),".chatpanel"),dataDir:_(v.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${b}`,token:T},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function ye(n,e,t){try{const o=await ge(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="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 we(n){if(!T)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(T);return o.length===r.length&&xe(o,r)}const Pn=new Set(["/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/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"]),$n=new Set(["/debug"]),Rn=n=>$n.has(n),In=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Nn(n,e){if(!vn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!fe(t))return"forbidden origin";const o=n.method==="POST"&&Pn.has(e)||n.method==="GET"&&Rn(e)||In(n.method,e);return o&&!(Tn(t)||we(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!_n.has(e)?Dn:null}const Dn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",_n=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(n,e,t){const o=N(n),r=St(yn(t,o));if(!wn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=r.reach,s=I(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 → Coding Agents to unlock them.";return{options:r,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(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 Hn(n){const e=await Promise.all(Object.entries(O).filter(([,s])=>!s.hidden).map(async([s,{engine:d,label:c,tools:l}])=>{const h=await d.available().catch(p=>({ok:!1,reason:String(p?.message||p)})),y=await Ge(s).catch(()=>[]);return{id:s,label:c,available:h.ok,reason:h.reason,connectors:y,...l===!1?{tools:!1}:{}}})),t=Wt()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Ut(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ye().catch(()=>null),r=await st().catch(()=>null),a=await te().status().catch(s=>({enabled:!1,reason:s.message}));i(n,200,{ok:!0,version:g,agents:e,update:t,workspace:ft,sandbox:a,localMcp:Lt(),processes:Tt(),worktrees:ae,secretBackend:oe(),warm:Kt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{},...r?{agentDefs:r}:{}})}async function Bn(n,e,t){const{index:o,problems:r}=await G({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Xe(o),problems:r})}async function Mn(n,e,t){i(n,200,{ok:!0,quarantined:await Ve(e,t)})}async function Un(n,e,t,o){const{index:r}=await G({extraDirs:t,workdir:o}),a=ze(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function Wn(n,e,t,o,r){const{index:a}=await G({extraDirs:o,workdir:r}),s=await Ke(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function Gn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await Qe({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return L(),i(e,200,o)}catch(o){return i(e,z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function Ln(n,e,t,o){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await Ze({name:t,path:o,text:r?.text??""});return L(),i(e,200,a)}catch(a){return i(e,z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function jn(n,e){try{const t=await qe({name:e});return L(),i(n,200,t)}catch(t){return i(n,z(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function z(n){return n instanceof et?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Se(n,e){return nt({roots:tt(process.env,v.homedir(),n,e)})}async function Fn(n,e,t){const{index:o,quarantined:r,problems:a}=await Se(e,t);i(n,200,{ok:!0,agents:ot(o),...r.length?{quarantined:r.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function Jn(n,e,t,o){const{index:r}=await Se(t,o),a=rt(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function Xn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,{ok:!0,...await at({agent:t?.agent,to:t?.to})})}catch(o){return i(e,be(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function zn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,await it({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,be(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function be(n){if(n instanceof ct){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function Kn(){return(await Promise.all(Object.entries(O).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 ke(n,e=""){const t=await Kn();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new R(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function Yn(n){try{const e=await se(g);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>Z(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function Vn(n,e){let t;try{t=await m(n)}catch(f){return i(e,400,{error:"Bad JSON: "+f.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=X(n,t.agent,t.options||{});if(r.error)return i(e,403,{error:r.error});t.options=r.options,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 a=f=>{e.writableEnded||e.write(`data: ${JSON.stringify(f)}
3
3
 
4
- `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=le(d),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};t.on("close",h),e.on("close",h),e.on("error",h);const y=f=>{s||i(f)};i({type:"run",id:d}),o.note&&i({type:"status",text:o.note});let p=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const f=n.options.workspace;if(p=await oe({repo:f.repo,projectId:f.projectId,jobId:f.jobId,base:f.base||null}),p.error){i({type:"error",error:`workspace: ${p.error}`}),j(d),e.writableEnded||e.end();return}}const K=p?p.path:pt(n.options?.workingDir);let C=null;{const f=K,A=!!p||!ht(n.options?.workingDir),w=ft(n.agent,n.options?.permissionMode,f,yt(f,{grant:n.options?.sandbox}));i({type:"workdir",path:f,isDefault:!A,writeScope:w||void 0}),i({type:"status",text:`Working in ${f}${A?"":" (default)"}`}),w&&i({type:"status",text:w}),C=await St(f),C&&i({type:"scm",phase:"before",...C})}let B=null;if(C||p){const f=Array.isArray(n.options?.grants)?n.options.grants:[],{env:A,connection:w}=Ot({remote:C?.remote||null,grants:f,branch:p?.branch||null,connectionId:n.options?.connectionId||null});B=Pt(A),p&&i({type:"workspace",path:p.path,branch:p.branch,base:p.base,created:p.created,repo:p.repo,...w?{connection:w}:{}}),w&&i({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${A.CHATPANEL_SCM_PUSH==="own"?`${p?.branch} only`:A.CHATPANEL_SCM_PUSH}`})}const V=n.approvals===!0,D={...n.options||{},...p?{workingDir:p.path}:{},...B?{runEnv:B}:{},approvals:V};let P=null;(n.pageTools?.specs?.length||V)&&(P=ct(y,n.pageTools?.specs||[]),D.permissionSession=P,n.pageTools?.specs?.length&&(D.mcp={url:`http://${k}:${v}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs}));try{await te(D.sandbox,()=>r.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:D,images:Array.isArray(n.images)?n.images:[]},y,{signal:l.signal}))}catch(f){u("error",`${n.agent} chat failed: ${f?.message||f}`),i({type:"error",error:f?.message||String(f)})}finally{if(!s){const f=await kt(K,C).catch(()=>null);f&&y({type:"scm",phase:"after",...f})}j(d),P&&Z(P.id),e.writableEnded||e.end()}}async function Gn(t,e,n){if(t.method==="GET"&&n==="/connections")return a(e,200,{ok:!0,connections:Tt(),secretBackend:ne()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await m(t);if(n==="/connections")try{return a(e,200,{ok:!0,connection:Et(r.connection||r,{token:r.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return o?o[2]==="delete"?a(e,200,{ok:vt(o[1])}):a(e,200,Ct(o[1],r.remote||"")):a(e,404,{error:"Not found"})}async function Ln(t,e,n){if(t.method==="GET"&&n==="/worktrees")return a(e,200,{ok:!0,root:re,worktrees:await At()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await m(t);if(n==="/worktrees"){const o=await oe({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return a(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(n==="/worktrees/remove"){const o=await xt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return a(e,o.ok?200:400,o)}return a(e,404,{error:"Not found"})}async function T(t,e,n){const r=O[t.agent];if(!r||r.hidden)throw new R(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new R(o.reason||`${t.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,s=le(i),d=()=>s.cancel("disconnected");n.on("close",d);let c="";try{return await te(t.options?.sandbox,()=>r.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{n.off("close",d),j(i)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
4
+ `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=de(d),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};n.on("close",h),e.on("close",h),e.on("error",h);const y=f=>{s||a(f)};a({type:"run",id:d}),r.note&&a({type:"status",text:r.note});let p=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const f=t.options.workspace;if(p=await re({repo:f.repo,projectId:f.projectId,jobId:f.jobId,base:f.base||null}),p.error){a({type:"error",error:`workspace: ${p.error}`}),j(d),e.writableEnded||e.end();return}}const Y=p?p.path:gt(t.options?.workingDir);let A=null;{const f=Y,C=!!p||!mt(t.options?.workingDir),w=yt(t.agent,t.options?.permissionMode,f,bt(f,{grant:t.options?.sandbox}));a({type:"workdir",path:f,isDefault:!C,writeScope:w||void 0}),a({type:"status",text:`Working in ${f}${C?"":" (default)"}`}),w&&a({type:"status",text:w}),A=await Et(f),A&&a({type:"scm",phase:"before",...A})}let W=null;if(A||p){const f=Array.isArray(t.options?.grants)?t.options.grants:[],{env:C,connection:w}=xt({remote:A?.remote||null,grants:f,branch:p?.branch||null,connectionId:t.options?.connectionId||null});W=It(C),p&&a({type:"workspace",path:p.path,branch:p.branch,base:p.base,created:p.created,repo:p.repo,...w?{connection:w}:{}}),w&&a({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${C.CHATPANEL_SCM_PUSH==="own"?`${p?.branch} only`:C.CHATPANEL_SCM_PUSH}`})}const V=t.approvals===!0,P={...t.options||{},...p?{workingDir:p.path}:{},...W?{runEnv:W}:{},approvals:V};let $=null;(t.pageTools?.specs?.length||V)&&($=ut(y,t.pageTools?.specs||[]),P.permissionSession=$,t.pageTools?.specs?.length&&(P.mcp={url:`http://${k}:${b}/mcp/${$.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await ne(P.sandbox,()=>pe(t.agent,P,l.signal,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:P,images:Array.isArray(t.images)?t.images:[]},y,{signal:l.signal})))}catch(f){u("error",`${t.agent} chat failed: ${f?.message||f}`),a({type:"error",error:f?.message||String(f)})}finally{if(!s){const f=await vt(Y,A).catch(()=>null);f&&y({type:"scm",phase:"after",...f})}j(d),$&&q($.id),e.writableEnded||e.end()}}async function Qn(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:Ot(),secretBackend:oe()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:At(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(t);return r?r[2]==="delete"?i(e,200,{ok:Ct(r[1])}):i(e,200,Pt(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function Zn(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ae,worktrees:await $t()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/worktrees"){const r=await re({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(t==="/worktrees/remove"){const r=await Rt({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 E(n,e,t){const o=O[n.agent];if(!o||o.hidden)throw new R(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!r.ok)throw new R(r.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=de(a),d=()=>s.cancel("disconnected");t.on("close",d);let c="";try{return await ne(n.options?.sandbox,()=>pe(n.agent,n.options,s.signal,()=>o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal}))),c}finally{t.off("close",d),j(a)}}function B(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5
 
6
- `)}function U(t,e,n){t.writableEnded||t.write(`event: ${e}
7
- data: ${JSON.stringify(n)}
6
+ `)}function M(n,e,t){n.writableEnded||n.write(`event: ${e}
7
+ data: ${JSON.stringify(t)}
8
8
 
9
- `)}async function W(t,e,n,r){try{const o=n(await m(t)),i=X(t,o.agent,o.options||{});if(i.error)throw new R(i.error,403,"permission");return o.options=i.options,o}catch(o){return a(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${o.message}`):o)),null}}async function jn(t,e){const n=await W(t,e,en,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Yt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=zt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function Fn(t,e){const n=await W(t,e,tn,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Qt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=Kt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function Jn(t,e){const n=await W(t,e,nn,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Zt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=on(n.requestedModel,o=>U(e,o.type,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){const i={type:"error",sequence_number:0,...b(o)};U(e,"error",i)}e.end()}async function Xn(t,e){const n=await W(t,e,qt,F);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Vt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,F(o))}M(e);const r=Xt(n.requestedModel,(o,i)=>U(e,o,i));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",F(o))}e.end()}async function zn(t,e){let n={};try{n=await m(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?Lt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),a(e,200,{ok:!0,cancelled:o})}async function we(t,e,n){let r;try{r=await m(t)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?q(n):lt(),i=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),a(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return i({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=it();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await st(r.params?.name,r.params?.arguments||{});if(c)return i(c);if(!o)return s(-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 dt(o,r.params?.name,r.params?.arguments||{}))}catch(l){return i({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Kn(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{},o=n.message;if(!r.command||!o)return a(e,400,{error:"need server.command and message"});try{const i=await Ut({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function Vn(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{};if(!r.command)return a(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return a(e,200,n.status?Gt(o):await Bt(o))}catch(i){return a(e,200,{state:"failed",error:String(i?.message||i)})}}async function Yn(t,e){let n;try{n=await m(t)}catch(h){return a(e,400,{error:"Bad JSON: "+h.message})}const{url:r,headers:o,message:i}=n||{};if(!r||!i)return a(e,400,{error:"need url and message"});let s;try{s=se(r)}catch(h){return a(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[h,y]of Object.entries(o)){const p=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(p)||p.startsWith("x-"))&&(d[h]=String(y))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&se(h.url)}catch(p){return a(e,400,{error:String(p?.message||p)})}const y=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")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const be=256*1024,Qn=5,Zn=8e3;async function qn(t){let e=ce(t);const n=new AbortController,r=setTimeout(()=>n.abort(),Zn);try{for(let o=0;o<=Qn;o++){const i=await fetch(e.href,{method:"GET",redirect:"manual",signal:n.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=ce(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 s=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:no(await eo(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function eo(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,be);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:i,value:s}=await e.read();if(i||(o+=s.byteLength,r+=n.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=be))break}}finally{try{await e.cancel()}catch{}}return r}function to(t){return String(t).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,n)=>{try{return String.fromCodePoint(+n)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,n)=>{try{return String.fromCodePoint(parseInt(n,16))}catch{return""}})}function no(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?to(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function oo(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=n&&n.url;if(!r||typeof r!="string")return a(e,400,{error:"need url"});try{const o=await qn(r);return a(e,200,{title:o.title||null,url:o.url||r})}catch(o){const i=o?.name==="AbortError"?"timed out":String(o?.message||o);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function ro(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=q(n.session);if(!r)return a(e,404,{error:"no such session"});const o=r.pending.get(n.id);return o?(r.pending.delete(n.id),o.resolve(n.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function ao(t,e){let n;try{n=await m(t)}catch(c){return a(e,400,{error:"Bad JSON: "+c.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=String(n.prompt||"").slice(0,6e3);if(!o)return a(e,400,{error:"Empty prompt"});const i=n.model||"",s=X(t,n.agent,{model:i});if(s.error)return a(e,403,{error:s.error});const d=String(n.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 c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:i}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),a(e,200,{text:(c||"").trim()})}catch(c){return a(e,502,{error:c?.message||String(c)})}}async function io(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof r.engine.listModels!="function")return a(e,200,{models:[]});try{const o=await r.engine.listModels(n.options||{});return a(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return a(e,502,{error:o?.message||String(o)})}}async function so(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=String(n.command||"").trim();if(!r)return a(e,400,{error:"No command"});let o=null;try{o=ae(r)}catch{o=null}return a(e,200,{ok:!!o,via:o?o.kind:null})}const Se=Te(async(t,e)=>{if(pn(t,e),t.method==="OPTIONS")return e.writeHead(204),e.end();let n;try{n=new URL(t.url,`http://${t.headers.host||"127.0.0.1"}`)}catch{return a(e,400,{error:"bad request"})}const r=En(t,n.pathname);if(r)return a(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return Cn(e);const o=n.searchParams.getAll("dir"),i=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return An(e,o,i);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return xn(e,o,i);if(t.method==="GET"&&n.pathname==="/agent-defs")return Dn(e,o,i);if(t.method==="POST"&&n.pathname==="/agent-defs/export-plan")return Hn(t,e);if(t.method==="POST"&&n.pathname==="/agent-defs/export")return Mn(t,e);if(t.method==="GET"&&n.pathname.startsWith("/agent-defs/"))return _n(e,decodeURIComponent(n.pathname.slice(12)),o,i);if(t.method==="POST"&&n.pathname==="/skills")return In(t,e);if((t.method==="PUT"||t.method==="POST"||t.method==="DELETE")&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?t.method==="DELETE"?Nn(e,decodeURIComponent(s)):a(e,405,{ok:!1,error:"use POST /skills to save a skill"}):t.method==="DELETE"?a(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):$n(t,e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)))}if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?Pn(e,decodeURIComponent(s),o,i):Rn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,i)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return Gn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return Ln(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return ye(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return ye(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(Rt.map(d=>[d,s?_t(d)||ae(d)?.kind||null:It(d)])),...s?{home:E.homedir(),path:process.env.PATH,installDirs:$t(E.homedir())}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return Bn(t,e);if(t.method==="POST"&&n.pathname==="/pair")return yn(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return gn(e);if(t.method==="POST"&&n.pathname==="/whoami")return wn(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return jn(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return Fn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return Jn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return Xn(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return we(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const s=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return we(t,e,s);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return Z(s),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return pe(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return pe(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return zn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return ro(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await m(t)}catch{s=null}const d=wt(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return Kn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local/signin")return Vn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return Yn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return oo(t,e);if(t.method==="POST"&&n.pathname==="/complete")return ao(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return io(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return so(t,e);if(t.method==="POST"&&n.pathname==="/update")return Wn(e);a(e,404,{error:"Not found"})}catch(o){a(e,500,{error:o?.message||String(o)})}});function u(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function co(t){let e="";const n=[];let r=!1,o=!1;const i=()=>{o&&!r&&!n.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;n.length;){const d=n.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
9
+ `)}async function U(n,e,t,o){try{const r=t(await m(n)),a=X(n,r.agent,r.options||{});if(a.error)throw new R(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${r.message}`):r)),null}}async function qn(n,e){const t=await U(n,e,un,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,sn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}B(e);const o=on(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function eo(n,e){const t=await U(n,e,hn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,cn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}B(e);const o=rn(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function to(n,e){const t=await U(n,e,pn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,ln(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}B(e);const o=fn(t.requestedModel,r=>M(e,r.type,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...S(r)};M(e,"error",a)}e.end()}async function no(n,e){const t=await U(n,e,dn,F);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,an(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,F(r))}B(e);const o=nn(t.requestedModel,(r,a)=>M(e,r,a));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){M(e,"error",F(r))}e.end()}async function oo(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?Jt(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Te(n,e,t){let o;try{o=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?ee(t):ht(),a=c=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:c,message:l}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return a({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=lt();if(o.method==="tools/list"){const c=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(o.method==="tools/call"){const c=await dt(o.params?.name,o.params?.arguments||{});if(c)return a(c);if(!r)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await pt(r,o.params?.name,o.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function ro(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await Gt({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox},r);return r.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function ao(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{};if(!o.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const r={key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox};try{return i(e,200,t.status?Ft(r):await jt(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function io(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:a}=t||{};if(!o||!a)return i(e,400,{error:"need url and message"});let s;try{s=ce(o)}catch(h){return i(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,y]of Object.entries(r)){const p=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(p)||p.startsWith("x-"))&&(d[h]=String(y))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{h.url&&ce(h.url)}catch(p){return i(e,400,{error:String(p?.message||p)})}const y=await h.text().catch(()=>"");return i(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const Ee=256*1024,so=5,co=8e3;async function lo(n){let e=le(n);const t=new AbortController,o=setTimeout(()=>t.abort(),co);try{for(let r=0;r<=so;r++){const a=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(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=le(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:po(await uo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function uo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ee);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=Ee))break}}finally{try{await e.cancel()}catch{}}return o}function ho(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 po(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?ho(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function fo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await lo(o);return i(e,200,{title:r.title||null,url:r.url||o})}catch(r){const a=r?.name==="AbortError"?"timed out":String(r?.message||r);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function mo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=ee(t.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function go(n,e){let t;try{t=await m(n)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=X(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=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 c="";return typeof o.engine.complete=="function"?c=await o.engine.complete({prompt:r,system:d,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function yo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function wo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(t.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=ie(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function So(n,e,t){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(o?.agent||"");if(!ue.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${ue.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await Yt(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await Vt(r,String(o.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=he({id:o.thread?.id??o.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const s=await Qt(r,String(o.id||""),a.id);return s?i(e,200,{session:s}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=he({id:o.thread?.id??o.thread});return a?i(e,200,await Zt(r,a.id,Array.isArray(o.messages)?o.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const K=Oe(async(n,e)=>{if(En(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 i(e,400,{error:"bad request"})}const o=Nn(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return Hn(e);const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return Bn(e,r,a);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Mn(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return Fn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return Xn(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return zn(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return Jn(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return Gn(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),d=s.indexOf("/file/");return d===-1?n.method==="DELETE"?jn(e,decodeURIComponent(s)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):Ln(n,e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),d=s.indexOf("/file/");return d===-1?Un(e,decodeURIComponent(s),r,a):Wn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Qn(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Zn(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return ke(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return ke(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:g,agents:Object.fromEntries(Nt.map(d=>[d,s?Mt(d)||ie(d)?.kind||null:Dt(d)])),...s?{home:v.homedir(),path:process.env.PATH,installDirs:_t(v.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return So(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return Vn(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Cn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return An(e);if(n.method==="POST"&&t.pathname==="/whoami")return xn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return qn(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return eo(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return to(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return no(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Te(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return Te(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return q(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ye(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ye(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return oo(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return mo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const d=kt(s||{});return e.writeHead(d?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return ro(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return ao(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return io(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return fo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return go(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return yo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return wo(n,e);if(n.method==="POST"&&t.pathname==="/update")return Yn(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function bo(n){let e="";const t=[];let o=!1,r=!1;const a=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const d=t.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
10
10
  `)}catch(l){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(l?.message||l)}})+`
11
- `)}}r=!1,i()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
12
- `))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&n.push(l)}s()}),process.stdin.on("end",()=>{o=!0,i()}),process.stdin.resume()}function lo(){Nt(),Dt(),mn(),Se.on("error",t=>{t&&t.code==="EADDRINUSE"&&(u("error",`Port ${v} 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: ${t?.message||t}`),process.exit(1)});for(const t of["SIGINT","SIGTERM"])process.on(t,()=>{const e=jt("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=Ft("shutdown");n&&u("info",`shutdown: closed ${n} warm agent process${n===1?"":"es"}`),ee().close(),setTimeout(()=>process.exit(0),e||n?300:0).unref?.(),!e&&!n&&process.exit(0)});Se.listen(v,k,async()=>{u("info",`listening on http://${k}:${v}`),J.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:t,label:e,hidden:n}]of Object.entries(O)){if(n)continue;const r=await t.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),he().then(t=>t.startIfConfigured()).then(t=>{t?.skipped||(t?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${t?.error||"unknown error"}`))}).catch(t=>u("error",`channels: ${t?.message||t}`))})}function uo(){console.log(`ChatPanel Bridge v${g}
11
+ `)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
12
+ `))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function ko(){Ht(),Bt(),On();let n=!1;K.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${b}/health`,{signal:AbortSignal.timeout(1500)}).then(t=>t.ok?t.json():null).catch(()=>null).then(t=>{const o=!!(t?.version&&Array.isArray(t.agents)),r=qt({name:"bridge",self:g,holder:o?{ours:o,version:t.version}:null,managedBy:en(process.env),port:b});if(r.action==="standby"||n&&!t){if(!n)for(const a of r.lines)u("info",a);n=!0,setTimeout(()=>K.listen(b,k),tn);return}if(o)for(const a of r.lines)u("error",a);else u("error",`Port ${b} 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)});return}u("error",`bridge server error: ${e?.message||e}`),process.exit(1)});for(const e of["SIGINT","SIGTERM"])process.on(e,()=>{const t=Xt("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const o=zt("shutdown");o&&u("info",`shutdown: closed ${o} warm agent process${o===1?"":"es"}`),te().close(),setTimeout(()=>process.exit(0),t||o?300:0).unref?.(),!t&&!o&&process.exit(0)});K.listen(b,k,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${k}:${b}`),J.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:e,label:t,hidden:o}]of Object.entries(O)){if(o)continue;const r=await e.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${t}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),ge().then(e=>e.startIfConfigured()).then(e=>{e?.skipped||(e?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${e?.error||"unknown error"}`))}).catch(e=>u("error",`channels: ${e?.message||e}`))})}function To(){console.log(`ChatPanel Bridge v${g}
13
13
 
14
14
  Usage:
15
- chatpanel-bridge start the bridge (foreground) on ${k}:${v}
15
+ chatpanel-bridge start the bridge (foreground) on ${k}:${b}
16
16
  chatpanel-bridge --install run automatically at login, in the background
17
17
  chatpanel-bridge --uninstall remove the login auto-start
18
18
  chatpanel-bridge --status show whether auto-start is set up
@@ -21,4 +21,4 @@ Usage:
21
21
  chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
22
22
  chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
23
23
 
24
- Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function ho(){const t=process.argv,e=(...n)=>n.some(r=>t.includes(r));if(e("--help","-h"))return uo(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let n="";try{n=Y(N,"utf8").trim()}catch{}const r=`http://${k}:${v}`;try{if(!n)throw new Error(`no token at ${N} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(2500)}),i=await o.json().catch(()=>({}));if(!o.ok)throw new Error(i.error||`HTTP ${o.status}`);console.log(`Pairing code: ${dn(i.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(t.includes("sandbox"))return mt(t.slice(t.indexOf("sandbox")+1)).then(n=>{process.exitCode=n}),!0;if(e("--install")){try{Be(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(n){u("error","Install failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--uninstall")){try{Ge(),u("info","Removed the login auto-start.")}catch(n){u("error","Uninstall failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--status")){let n=!1;try{n=Le()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const ke=process.argv.indexOf("--mcp-stdio");if(ke>=0){const t=process.argv[ke+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),co(t)}else process.argv.includes("--update")?(async()=>{try{const t=await ie(g);u("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),Q()}catch(t){u("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():ho()||lo();
24
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function Eo(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return To(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=Q(D,"utf8").trim()}catch{}const o=`http://${k}:${b}`;try{if(!t)throw new Error(`no token at ${D} — is the bridge running?`);const r=await fetch(`${o}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await r.json().catch(()=>({}));if(!r.ok)throw new Error(a.error||`HTTP ${r.status}`);console.log(`Pairing code: ${bn(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(r){u("error",`could not get a pairing code from the bridge at ${o}: ${r?.message||r}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return wt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{je(),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{Fe(),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=Je()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const ve=process.argv.indexOf("--mcp-stdio");if(ve>=0){const n=process.argv[ve+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),bo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await se(g);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),Z()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():Eo()||ko();
package/src/service.js CHANGED
@@ -1,4 +1,4 @@
1
- import u from"node:os";import e from"node:path";import{mkdirSync as l,writeFileSync as p,rmSync as b,existsSync as v}from"node:fs";import{spawn as f,spawnSync as P}from"node:child_process";const d="net.chatpanel.bridge",I="ChatPanel Bridge";function m(){const t=process.execPath,r=e.basename(t).toLowerCase();return(r.startsWith("node")||r.startsWith("bun"))&&process.argv[1]?{program:t,args:[e.resolve(process.argv[1])]}:{program:t,args:[]}}function E(){const t=e.join(u.homedir(),".chatpanel");return l(t,{recursive:!0}),{out:e.join(t,"bridge.log"),err:e.join(t,"bridge.err.log")}}function n(t,r,s={}){return P(t,r,{encoding:"utf8",...s})}const S=()=>e.join(u.homedir(),"Library","LaunchAgents",`${d}.plist`);function L(){const{program:t,args:r}=m(),{out:s,err:i}=E(),a=[t,...r].map($=>` <string>${$}</string>`).join(`
1
+ import l from"node:os";import e from"node:path";import{mkdirSync as u,writeFileSync as p,rmSync as b,existsSync as k}from"node:fs";import{spawn as m,spawnSync as P}from"node:child_process";const d="net.chatpanel.bridge",$="ChatPanel Bridge";function f(){const t=process.execPath,r=e.basename(t).toLowerCase();return(r.startsWith("node")||r.startsWith("bun"))&&process.argv[1]?{program:t,args:[e.resolve(process.argv[1])]}:{program:t,args:[]}}function A(){const t=e.join(l.homedir(),".chatpanel");return u(t,{recursive:!0}),{out:e.join(t,"bridge.log"),err:e.join(t,"bridge.err.log")}}function n(t,r,s={}){return P(t,r,{encoding:"utf8",...s})}const v=()=>e.join(l.homedir(),"Library","LaunchAgents",`${d}.plist`);function I(){const{program:t,args:r}=f(),{out:s,err:i}=A(),a=[t,...r].map(E=>` <string>${E}</string>`).join(`
2
2
  `),c=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4
4
  <plist version="1.0">
@@ -8,21 +8,26 @@ import u from"node:os";import e from"node:path";import{mkdirSync as l,writeFileS
8
8
  <array>
9
9
  ${a}
10
10
  </array>
11
+ <key>EnvironmentVariables</key>
12
+ <dict>
13
+ <key>CHATPANEL_SERVICE</key><string>1</string>
14
+ </dict>
11
15
  <key>RunAtLoad</key><true/>
12
16
  <key>KeepAlive</key><true/>
13
17
  <key>StandardOutPath</key><string>${s}</string>
14
18
  <key>StandardErrorPath</key><string>${i}</string>
15
19
  </dict>
16
20
  </plist>
17
- `,o=S();l(e.dirname(o),{recursive:!0}),p(o,c),n("launchctl",["unload",o]);const y=n("launchctl",["load","-w",o]);if(y.status!==0)throw new Error((y.stderr||"").trim()||"launchctl load failed")}function j(){const t=S();n("launchctl",["unload","-w",t]),v(t)&&b(t)}function A(){return(n("launchctl",["list"]).stdout||"").includes(d)}const g="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",h="ChatPanelBridge",k=()=>e.join(u.homedir(),".chatpanel","launch.vbs");function U(){const{program:t,args:r}=m(),s=[t,...r].map(c=>`""${c}""`).join(" "),i=k();l(e.dirname(i),{recursive:!0}),p(i,`CreateObject("WScript.Shell").Run "${s}", 0, False\r
18
- `);const a=n("reg",["add",g,"/v",h,"/t","REG_SZ","/d",`wscript.exe "${i}"`,"/f"]);if(a.status!==0)throw new Error((a.stderr||"").trim()||"reg add failed");n("wscript.exe",[i])}function C(){n("reg",["delete",g,"/v",h,"/f"]),n("taskkill",["/IM","chatpanel-bridge.exe","/F"])}function D(){return n("reg",["query",g,"/v",h]).status===0}const x=()=>e.join(u.homedir(),".config","systemd","user","chatpanel-bridge.service");function R(){const{program:t,args:r}=m(),s=[t,...r].map(o=>/\s/.test(o)?`"${o}"`:o).join(" "),i=`[Unit]
19
- Description=${I}
21
+ `,o=v();u(e.dirname(o),{recursive:!0}),p(o,c),n("launchctl",["unload",o]);const w=n("launchctl",["load","-w",o]);if(w.status!==0)throw new Error((w.stderr||"").trim()||"launchctl load failed")}function L(){const t=v();n("launchctl",["unload","-w",t]),k(t)&&b(t)}function C(){return(n("launchctl",["list"]).stdout||"").includes(d)}const g="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",h="ChatPanelBridge",S=()=>e.join(l.homedir(),".chatpanel","launch.vbs");function j(){const{program:t,args:r}=f(),s=[t,...r].map(c=>`""${c}""`).join(" "),i=S();u(e.dirname(i),{recursive:!0}),p(i,`CreateObject("WScript.Shell").Run "${s}", 0, False\r
22
+ `);const a=n("reg",["add",g,"/v",h,"/t","REG_SZ","/d",`wscript.exe "${i}"`,"/f"]);if(a.status!==0)throw new Error((a.stderr||"").trim()||"reg add failed");n("wscript.exe",[i])}function U(){n("reg",["delete",g,"/v",h,"/f"]),n("taskkill",["/IM","chatpanel-bridge.exe","/F"])}function R(){return n("reg",["query",g,"/v",h]).status===0}const x=()=>e.join(l.homedir(),".config","systemd","user","chatpanel-bridge.service");function N(){const{program:t,args:r}=f(),s=[t,...r].map(o=>/\s/.test(o)?`"${o}"`:o).join(" "),i=`[Unit]
23
+ Description=${$}
20
24
  After=network.target
21
25
 
22
26
  [Service]
23
27
  ExecStart=${s}
28
+ Environment=CHATPANEL_SERVICE=1
24
29
  Restart=on-failure
25
30
 
26
31
  [Install]
27
32
  WantedBy=default.target
28
- `,a=x();l(e.dirname(a),{recursive:!0}),p(a,i),n("systemctl",["--user","daemon-reload"]);const c=n("systemctl",["--user","enable","--now","chatpanel-bridge"]);if(c.status!==0)throw new Error((c.stderr||"").trim()||"systemctl enable failed")}function W(){n("systemctl",["--user","disable","--now","chatpanel-bridge"]);const t=x();v(t)&&b(t)}function N(){return(n("systemctl",["--user","is-enabled","chatpanel-bridge"]).stdout||"").trim()==="enabled"}function w(t,r,s){if(process.platform==="darwin")return t();if(process.platform==="win32")return r();if(process.platform==="linux")return s();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the bridge directly.`)}function M(){return w(L,U,R)}function K(){return w(j,C,W)}function O(){return w(A,D,N)}function Y(){try{if(process.platform==="darwin"){const t=typeof process.getuid=="function"?process.getuid():0;return f("launchctl",["kickstart","-k",`gui/${t}/${d}`],{detached:!0,stdio:"ignore"}).unref(),!0}if(process.platform==="linux")return f("systemctl",["--user","restart","chatpanel-bridge"],{detached:!0,stdio:"ignore"}).unref(),!0;if(process.platform==="win32"){const t=k(),r=e.dirname(process.execPath),s=`taskkill /IM chatpanel-bridge.exe /F >nul 2>&1 & timeout /t 2 >nul & wscript.exe "${t}" & del /q "${e.join(r,"chatpanel-bridge.old-*.exe")}" >nul 2>&1`;return f("cmd",["/c",s],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),!0}}catch{}return!1}export{M as installService,m as resolveLaunch,Y as restartService,O as serviceStatus,K as uninstallService};
33
+ `,a=x();u(e.dirname(a),{recursive:!0}),p(a,i),n("systemctl",["--user","daemon-reload"]);const c=n("systemctl",["--user","enable","--now","chatpanel-bridge"]);if(c.status!==0)throw new Error((c.stderr||"").trim()||"systemctl enable failed")}function D(){n("systemctl",["--user","disable","--now","chatpanel-bridge"]);const t=x();k(t)&&b(t)}function T(){return(n("systemctl",["--user","is-enabled","chatpanel-bridge"]).stdout||"").trim()==="enabled"}function y(t,r,s){if(process.platform==="darwin")return t();if(process.platform==="win32")return r();if(process.platform==="linux")return s();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the bridge directly.`)}function V(){return y(I,j,N)}function H(){return y(L,U,D)}function M(){return y(C,R,T)}function K(){try{if(process.platform==="darwin"){const t=typeof process.getuid=="function"?process.getuid():0;return m("launchctl",["kickstart","-k",`gui/${t}/${d}`],{detached:!0,stdio:"ignore"}).unref(),!0}if(process.platform==="linux")return m("systemctl",["--user","restart","chatpanel-bridge"],{detached:!0,stdio:"ignore"}).unref(),!0;if(process.platform==="win32"){const t=S(),r=e.dirname(process.execPath),s=`taskkill /IM chatpanel-bridge.exe /F >nul 2>&1 & timeout /t 2 >nul & wscript.exe "${t}" & del /q "${e.join(r,"chatpanel-bridge.old-*.exe")}" >nul 2>&1`;return m("cmd",["/c",s],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),!0}}catch{}return!1}export{V as installService,f as resolveLaunch,K as restartService,M as serviceStatus,H as uninstallService};
package/src/threads.js ADDED
@@ -0,0 +1 @@
1
+ import{readFileSync as A,writeFileSync as $,renameSync as b,mkdirSync as v}from"node:fs";import{createHmac as g,randomBytes as N}from"node:crypto";import O from"node:os";import w from"node:path";import{normalizeThread as y,legacyThreadIds as k,threadPlan as _,turnSeen as j,historySplit as E,historyExtension as I}from"./events/agent-thread.js";const P=w.join(O.homedir(),".chatpanel","agent-threads.json");function B({file:l=P,now:c=Date.now,max:d=2e3}={}){let i=null;function n(){if(i)return i;try{const t=JSON.parse(A(l,"utf8"));t?.v===1&&/^[0-9a-f]{64}$/.test(t.key)&&t.links&&typeof t.links=="object"&&(i={v:1,key:t.key,links:t.links})}catch{}return i||(i={v:1,key:N(32).toString("hex"),links:{}}),i}function a(){const t=n(),e=Object.keys(t.links);if(e.length>d){e.sort((r,o)=>(t.links[r].at||0)-(t.links[o].at||0));for(const r of e.slice(0,e.length-d))delete t.links[r]}try{v(w.dirname(l),{recursive:!0,mode:448});const r=`${l}.${process.pid}.tmp`;$(r,JSON.stringify(t),{mode:384}),b(r,l)}catch{}}const s=(t,e)=>`${t}|${e}`,u=(t,e)=>[e,...k(e)].map(r=>n().links[s(t,r)]).find(Boolean),f=(t,e)=>{for(const r of k(e))delete n().links[s(t,r)]};return{digest(t){const e=Array.isArray(t?.users)?t.users:[];return g("sha256",Buffer.from(n().key,"hex")).update(JSON.stringify([e,Number(t?.answers)||0])).digest("hex")},mark(t){return g("sha256",Buffer.from(n().key,"hex")).update(`last\0${String(t??"")}`).digest("hex")},unseen(t,e){return this.extension(t,e)?.tail||null},extension(t,e){if(!t||!Array.isArray(t.last))return null;if(Number.isInteger(t.n)&&Number.isInteger(t.answers)){const o=I(e,{n:t.n,answers:t.answers});return o&&t.digest===this.digest(o.prefix)&&t.last.includes(this.mark(o.last))?{tail:o.tail,answered:o.answered}:null}const r=E(e);return r.last!=null&&t.digest===this.digest(r)&&t.last.includes(this.mark(r.last))?{tail:e.slice(-1),answered:!0}:null},get(t,e){const r=u(t,e);return r&&typeof r.sessionId=="string"?{...r}:null},put(t,e,{sessionId:r,cwd:o="",seen:h}){if(!t||!e||typeof r!="string"||!r)return;const x=(Array.isArray(h?.last)?h.last:[]).map(T=>this.mark(T)),S=Array.isArray(h?.users)?h.users.length:0;f(t,e),n().links[s(t,e)]={sessionId:r,cwd:String(o||""),digest:this.digest(h),last:x,n:S,answers:Number(h?.answers)||0,at:c()},a()},drop(t,e){u(t,e)&&(delete n().links[s(t,e)],f(t,e),a())},list(){return Object.entries(n().links).map(([t,e])=>{const r=t.lastIndexOf("|"),o=t.slice(r+1);return{agent:t.slice(0,r),thread:y({id:o})?.id||o,sessionId:e.sessionId,cwd:e.cwd,at:e.at}}).sort((t,e)=>(e.at||0)-(t.at||0))}}}function U(l,c,d={},{cwd:i="",links:n=L()}={}){const a=y(d?.thread);if(!a||d?.ephemeral===!0)return null;const s=`${l}|${d.reach||"local"}`,u=n.get(s,a.id),f=n.unseen(u,c),t=_({link:u,digest:f?u.digest:"",cwd:i,hasHistory:(c?.length||0)>1});return t.mode==="resume"&&(t.tail=f),{thread:a,plan:t,record(e,{answered:r=!0}={}){typeof e=="string"&&e&&n.put(s,a.id,{sessionId:e,cwd:i,seen:j(c,{answered:r})})},forget(){n.drop(s,a.id)},restart(){return{...this,plan:{mode:"start",sessionId:null,seed:(c?.length||0)>1,why:"the session could not be resumed"}}}}}let p=null;function L(){return p||(p=B())}function W(l){p=l}const D="This chat is answering a message from another device right now. Send again when it finishes.",m=new Map,F=15e3;async function Y(l,c,d,i,{waitMs:n=F}={}){const a=y(c?.thread);if(!a||c?.ephemeral===!0)return i();const s=`${l}|${c?.reach||"local"}|${a.id}`,u=m.get(s);if(u){if(!u.signal?.aborted)throw new Error(D);await Promise.race([u.done,new Promise(e=>setTimeout(e,n).unref?.())])}let f;const t={signal:d,done:new Promise(e=>{f=e})};m.set(s,t);try{return await i()}finally{m.get(s)===t&&m.delete(s),f()}}export{P as THREADS_FILE,D as THREAD_BUSY,W as _setThreadLinksForTest,B as createThreadLinks,Y as holdThread,L as threadLinks,U as threadTurn};
package/src/warm-pool.js CHANGED
@@ -1 +1 @@
1
- import{treeRssBytes as R,totalMemoryBytes as B}from"./proc.js";const v=1024**3,A=B(),D=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(A>=16*v?10*6e4:5*6e4),S=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(A*.2),3*v),U=400*1024**2;function N(n,a,o=U){const p=Math.floor(a/o),l=n>=48*v?4:n>=24*v?3:n>=12*v?2:1;return Math.max(1,Math.min(p,l))}const k=Number(process.env.CHATPANEL_WARM_MAX)||N(A,S),z=new Set;function x(n=[]){const o=(Array.isArray(n)?n:[]).slice(0,-1),p=o.filter(c=>c?.role==="user").map(c=>String(c.content||"").trim()),l=o.filter(c=>c?.role==="assistant").length;return{users:p,answers:l}}function y(n,a){if(n.answers!==a.answers||n.users.length!==a.users.length)return!1;for(let o=0;o<n.users.length;o++)if(n.users[o]!==a.users[o])return!1;return!0}function W({max:n=k,idleMs:a=D,budgetBytes:o=S,group:p=z,now:l=Date.now,measure:c=r=>R(r?.pid),log:h=()=>{}}={}){const r=new Set;let m=null;const $=()=>{let e=0;for(const s of p)e+=s.bytes;return e};let M=0;const f=e=>`${Math.round(e/1024**2)} MB`;function d(e,s="dropped"){if(r.has(e)){r.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}h(`warm ${e.label}: ${s} (${r.size} live)`),!r.size&&m&&(clearInterval(m),m=null)}}function _(){const e=l();for(const s of[...r])!s.busy&&e-s.lastUsed>a&&d(s,"idle")}function L(){m||!Number.isFinite(a)||a<=0||(m=setInterval(_,Math.min(a,6e4)),m.unref?.())}const E={get size(){return r.size},get bytes(){let e=0;for(const s of r)e+=s.bytes||0;return e},peek({key:e,messages:s}){const i=x(s);for(const t of r)if(!t.busy&&t.alive&&t.key===e&&y(t.shape,i))return!0;return!1},acquire({key:e,messages:s}){const i=x(s);for(const t of r)if(!(t.busy||!t.alive||t.key!==e)){if(!y(t.shape,i)){h(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${i.users.length}u/${i.answers}a)`);continue}return t.busy=!0,t.lastUsed=l(),h(`warm ${t.label}: reused`),t}return null},reserve({key:e,label:s=e,evict:i=!0}){const t=()=>{let u=null;for(const b of r)!b.busy&&(!u||b.lastUsed<u.lastUsed)&&(u=b);return u};if(r.size>=n){const u=i?t():null;if(!u)return null;d(u,"evicted")}const w=M||U;for(;$()+w>o;){const u=i?t():null;if(!u)return h(`warm ${s}: not kept — ${f($())} warm + ~${f(w)} would pass the ${f(o)} budget`),null;d(u,`evicted for memory (${f($())} warm)`)}const T={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:l(),bytes:w};return r.add(T),h(`warm ${s}: starting (${r.size} live, ~${f($())} of ${f(o)})`),L(),T},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&d(e,"process exited")}),e},release(e,{user:s,answered:i}){e.alive&&(typeof s=="string"&&(e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(i?1:0)}),e.busy=!1,e.lastUsed=l(),setImmediate(()=>{if(!e.alive)return;const t=c(e.session);t>0&&(e.bytes=t,M=t,h(`warm ${e.label}: ${f(t)} resident`))}))},drop:d,closeAll(e="shutdown"){for(const s of[...r])d(s,e)},keys(){return[...r].map(e=>e.key)},reap:_};return p.add(E),E}export{S as WARM_BUDGET_BYTES,W as createWarmPool,x as historyShape,N as warmMaxFor};
1
+ import{treeRssBytes as B,totalMemoryBytes as D}from"./proc.js";import{historyShape as $,userTextMatches as N}from"./events/agent-thread.js";const d=1024**3,b=D(),k=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(b>=16*d?10*6e4:5*6e4),U=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(b*.2),3*d),x=400*1024**2;function z(n,o,a=x){const l=Math.floor(o/a),f=n>=48*d?4:n>=24*d?3:n>=12*d?2:1;return Math.max(1,Math.min(l,f))}const I=Number(process.env.CHATPANEL_WARM_MAX)||z(b,U),W=new Set;function S(n,o){if(n.answers!==o.answers||n.users.length!==o.users.length)return!1;const a=n.users.length;for(let l=0;l<a-1;l++)if(n.users[l]!==o.users[l])return!1;return a===0||N(n.users[a-1],o.users[a-1])}function P({max:n=I,idleMs:o=k,budgetBytes:a=U,group:l=W,now:f=Date.now,measure:L=r=>B(r?.pid),log:p=()=>{}}={}){const r=new Set;let h=null;const v=()=>{let e=0;for(const s of l)e+=s.bytes;return e};let A=0;const c=e=>`${Math.round(e/1024**2)} MB`;function m(e,s="dropped"){if(r.has(e)){r.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}p(`warm ${e.label}: ${s} (${r.size} live)`),!r.size&&h&&(clearInterval(h),h=null)}}function _(){const e=f();for(const s of[...r])!s.busy&&e-s.lastUsed>o&&m(s,"idle")}function R(){h||!Number.isFinite(o)||o<=0||(h=setInterval(_,Math.min(o,6e4)),h.unref?.())}const E={get size(){return r.size},get bytes(){let e=0;for(const s of r)e+=s.bytes||0;return e},peek({key:e,messages:s}){const u=$(s);for(const t of r)if(!t.busy&&t.alive&&t.key===e&&S(t.shape,u))return!0;return!1},acquire({key:e,messages:s}){const u=$(s);for(const t of r)if(!(t.busy||!t.alive||t.key!==e)){if(!S(t.shape,u)){p(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${u.users.length}u/${u.answers}a)`);continue}return t.busy=!0,t.lastUsed=f(),p(`warm ${t.label}: reused`),t}return null},reserve({key:e,label:s=e,evict:u=!0}){const t=()=>{let i=null;for(const w of r)!w.busy&&(!i||w.lastUsed<i.lastUsed)&&(i=w);return i};if(r.size>=n){const i=u?t():null;if(!i)return null;m(i,"evicted")}const M=A||x;for(;v()+M>a;){const i=u?t():null;if(!i)return p(`warm ${s}: not kept — ${c(v())} warm + ~${c(M)} would pass the ${c(a)} budget`),null;m(i,`evicted for memory (${c(v())} warm)`)}const T={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:f(),bytes:M};return r.add(T),p(`warm ${s}: starting (${r.size} live, ~${c(v())} of ${c(a)})`),R(),T},holds(e,s){return e.shape=$(s),e},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&m(e,"process exited")}),e},release(e,{user:s,answered:u}){e.alive&&(typeof s=="string"&&(e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(u?1:0)}),e.busy=!1,e.lastUsed=f(),setImmediate(()=>{if(!e.alive)return;const t=L(e.session);t>0&&(e.bytes=t,A=t,p(`warm ${e.label}: ${c(t)} resident`))}))},drop:m,closeAll(e="shutdown"){for(const s of[...r])m(s,e)},keys(){return[...r].map(e=>e.key)},reap:_};return l.add(E),E}export{U as WARM_BUDGET_BYTES,P as createWarmPool,$ as historyShape,z as warmMaxFor};