@chatpanel/bridge 0.46.0 → 0.46.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.46.0",
3
+ "version": "0.46.1",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -0,0 +1,3 @@
1
+ const c=["inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","harnessChars"];function o(t,n){if(!t)return n;if(!n)return t;const s={...t,...n};for(const u of c)(t[u]!=null||n[u]!=null)&&(s[u]=(Number(t[u])||0)+(Number(n[u])||0));return s.costUsd=t.costUsd!=null&&n.costUsd!=null?Number(t.costUsd)+Number(n.costUsd):null,s}function f(t){let n=!1,s=null,u=null,l=null;const r=e=>{e&&(n=!0,t({type:"delta",text:e}))};return{emit(e){if(e?.type==="done"){s=e;return}if(e?.type==="usage"){u=e;return}e?.type==="delta"&&e.text&&(n=!0),t(e)},seam(){r(s?.text),n&&r(`
2
+
3
+ `),s=null,l=o(l,u),u=null},finish(){const e=o(l,u);e&&t(e),s&&(n&&s.text?(r(s.text),t({...s,text:""})):t(s))}}}export{o as addUsage,f as oneReply};
package/src/server.js CHANGED
@@ -1,21 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as Be}from"node:http";import O from"node:os";import{randomBytes as Ge,randomInt as Ue,timingSafeEqual as Le}from"node:crypto";import{mkdirSync as We,writeFileSync as je,readFileSync as oe,existsSync as Fe}from"node:fs";import{join as H}from"node:path";import*as Je from"./engines/claude.js";import*as Xe from"./engines/codex.js";import*as Ke from"./engines/antigravity.js";import{pi as ze,opencode as Ye,kiro as Ve,copilot as Qe,deepseek as Ze,hermes as qe}from"./engines/cli-agents.js";import{connectorsFor as et}from"./connectors.js";import*as tt from"./engines/custom.js";import{installService as nt,uninstallService as ot,serviceStatus as rt,restartService as re}from"./service.js";import{skillIndex as F,listRecords as at,readRecord as it,readPackageFile as st,skillsHealth as ct,quarantinedSkills as lt,clearSkillCache as J}from"./skills.js";import{writeSkillPackage as dt,writeSkillFile as ut,deleteSkillPackage as ht,SkillWriteError as pt}from"./skill-write.js";import{agentDefRoots as ft,scanAgentDefs as mt,listAgentDefs as gt,readAgentDef as wt,planAgentExport as yt,exportAgentDef as bt,agentDefsHealth as St,AgentDefError as kt}from"./agent-defs.js";import{capabilityToolSpecs as Tt,runCapabilityTool as xt}from"./mcp-capabilities.js";import{createSession as Et,deleteSession as ae,getSession as ie,activeSession as vt,relayToolCall as At}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ot,isDefaultWorkdir as Ct,resolveWorkdir as Pt,writeScopeNote as $t}from"./workdir.js";import{sandbox as X,runSandboxCli as Rt,withGrant as se,withAgentGrant as It,withoutOutsideWhenCapped as Nt,grantedWriteRoots as ce,acceptRefusalReport as Dt,liveProcesses as _t,sandboxConfigFromEnv as Ht}from"./sandbox.js";import{createAccessGate as Mt,chatKeyOf as Bt,chatFolders as Gt}from"./access-gate.js";import{signInDenial as Ut}from"./events/sandbox-policy.js";import{gitState as Lt,gitDelta as Wt}from"./scm.js";import{listConnections as jt,putConnection as Ft,removeConnection as Jt,runEnvFor as Xt,testConnection as Kt,secretBackend as le}from"./connections.js";import{worktreeFor as de,listWorktrees as zt,removeWorktree as Yt,withHook as Vt,WORKTREE_ROOT as ue}from"./worktree.js";import{AGENT_CLIS as Qt,agentAvailable as Zt,agentInstallDirs as qt,enrichPath as en,enrichAgentEnv as tn,findAgentBin as nn,forgetMisses as on,primeAgentLookups as rn,resolveCommand as he,isCompiledBinary as an}from"./env.js";import"./sanitize.js";import{checkForUpdate as sn,selfUpdate as pe,isEmbedded as fe}from"./update.js";import{callLocalMcp as cn,localMcpStatus as ln,signInLocalMcp as dn,signInStatusLocalMcp as un}from"./mcp-local.js";import{assertPublicHttpUrl as me,assertPublicWebUrl as ge}from"./ssrf.js";import{startRun as we,endRun as K,cancelRun as hn,cancelAll as pn}from"./runs.js";import{closeWarmPools as fn,warmStatus as mn}from"./warm.js";import{SESSION_AGENTS as ye,listSessions as gn,readSession as wn,adoptSession as yn,catchUp as bn}from"./agent-sessions.js";import{agentContext as Sn}from"./agent-context.js";import{normalizeThread as be}from"./events/agent-thread.js";import{portClashPlan as kn,serviceManagerOf as Tn,STANDBY_POLL_MS as xn}from"./events/service-standby.js";import{holdThread as Se}from"./threads.js";import{createSnapshot as En}from"./health-snapshot.js";import{CompatError as P,anthropicError as z,anthropicStream as vn,chatCompletionStream as An,completionStream as On,createAnthropicMessage as Cn,createChatCompletion as Pn,createCompletion as $n,createResponse as Rn,openAIError as k,parseAnthropicMessage as In,parseChatCompletion as Nn,parseCompletion as Dn,parseResponse as _n,responseStream as Hn}from"./api-compat.js";import{callerTrust as Mn,isPaired as I,parseExtensionIds as Bn,capRunOptions as Gn,engineHonoursReach as Un,createPairingStore as Ln,formatPairingCode as Wn}from"./pii/trust.js";const b="0.46.0",x=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",T=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Je,label:"Claude Code"},codex:{engine:Xe,label:"Codex"},antigravity:{engine:Ke,label:"Antigravity",tools:!1},pi:{engine:ze,label:"Pi"},opencode:{engine:Ye,label:"OpenCode"},hermes:{engine:qe,label:"Hermes"},kiro:{engine:Ve,label:"Kiro"},copilot:{engine:Qe,label:"GitHub Copilot"},deepseek:{engine:Ze,label:"DeepSeek Harness"},custom:{engine:tt,label:"Custom",hidden:!0}};function ke(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 jn=Bn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Mn({origin:n.headers.origin||"",hasToken:ve(n),extensionIds:jn})),n.chatpanelTrust}function Fn(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 Jn(n,e){const t=n.headers.origin||"",o=ke(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 Y=new Set(["127.0.0.1","localhost","::1"]);function Xn(n){if(!Y.has(x))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return Y.has(t)}const D=H(O.homedir(),".chatpanel","bridge-token");let v="";function Kn(){try{Fe(D)&&(v=oe(D,"utf8").trim()),v||(v=Ge(32).toString("hex"),We(H(O.homedir(),".chatpanel"),{recursive:!0}),je(D,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const Te=Ln({random:()=>Ue(0,1e6)/1e6});function zn(n){if(!v)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=Te.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 Yn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=Te.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:v})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Vn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:b})}let M=null;async function xe(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(O.homedir(),".chatpanel"),dataDir:H(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${T}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),M}async function Ee(n,e,t){try{const o=await xe(),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 ve(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&Le(o,r)}const Qn=new Set(["/agent-context","/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"]),Zn=new Set(["/debug"]),qn=n=>Zn.has(n),eo=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function to(n,e){if(!Xn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ke(t))return"forbidden origin";const o=n.method==="POST"&&Qn.has(e)||n.method==="GET"&&qn(e)||eo(n.method,e);return o&&!(Fn(t)||ve(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!oo.has(e)?no:null}const Ae=()=>fe()?"chatpanel-gateway pair":"chatpanel-bridge pair",no=`forbidden: this client is not paired with the bridge — run \`${Ae()}\` and enter the code in ChatPanel Settings`,oo=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function V(n,e,t){const o=N(n),r=It(e,Nt(Gn(t,o)));if(!Un(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 (${Ae()})`} 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}}async function Oe(n,e,t){const o=e?.message||String(e);try{const r=await X().status(),a=!!(r.enabled&&r.runtime)&&t?.outside!==!0,s=Ut(`${o}
3
- ${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:E[n]?.label||n||"This agent"});if(s)return s.line}catch{}return o}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)})}const Ce=En({compute:ro});async function ro(){await rn();const n=await Promise.all(Object.entries(E).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:d}])=>{const l=await s.available().catch(y=>({ok:!1,reason:String(y?.message||y)})),p=await et(a).catch(()=>[]);return{id:a,label:c,available:l.ok,reason:l.reason,connectors:p,...d===!1?{tools:!1}:{}}})),e=fe()?{current:b,updateAvailable:!1,embedded:"gateway"}:await sn(b).catch(()=>({current:b,updateAvailable:!1})),t=await ct().catch(()=>null),o=await St().catch(()=>null),r=await X().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function ao(n,{fresh:e=!1}={}){e&&on();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await Ce.get({fresh:e});i(n,200,{ok:!0,version:b,agents:o,update:r,checkedAt:t,workspace:Ot,sandbox:c,localMcp:ln(),processes:_t(),worktrees:ue,secretBackend:le(),warm:mn(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...s?{agentDefs:s}:{}})}async function io(n,e,t){const{index:o,problems:r}=await F({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:at(o),problems:r})}async function so(n,e,t){i(n,200,{ok:!0,quarantined:await lt(e,t)})}async function co(n,e,t,o){const{index:r}=await F({extraDirs:t,workdir:o}),a=it(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function lo(n,e,t,o,r){const{index:a}=await F({extraDirs:o,workdir:r}),s=await st(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 uo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await dt({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return J(),i(e,200,o)}catch(o){return i(e,Q(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function ho(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 ut({name:t,path:o,text:r?.text??""});return J(),i(e,200,a)}catch(a){return i(e,Q(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function po(n,e){try{const t=await ht({name:e});return J(),i(n,200,t)}catch(t){return i(n,Q(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function Q(n){return n instanceof pt?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Pe(n,e){return mt({roots:ft(process.env,O.homedir(),n,e)})}async function fo(n,e,t){const{index:o,quarantined:r,problems:a}=await Pe(e,t);i(n,200,{ok:!0,agents:gt(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 mo(n,e,t,o){const{index:r}=await Pe(t,o),a=wt(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function go(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 yt({agent:t?.agent,to:t?.to})})}catch(o){return i(e,$e(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function wo(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 bt({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,$e(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function $e(n){if(n instanceof kt){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function yo(){return(await Promise.all(Object.entries(E).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function Re(n,e=""){const t=await yo();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,k(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function bo(n){try{const e=await pe(b);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>re(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function So(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=V(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=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
2
+ import{createServer as Ge}from"node:http";import O from"node:os";import{randomBytes as Ue,randomInt as Le,timingSafeEqual as We}from"node:crypto";import{mkdirSync as je,writeFileSync as Fe,readFileSync as re,existsSync as Je}from"node:fs";import{join as M}from"node:path";import*as Xe from"./engines/claude.js";import*as Ke from"./engines/codex.js";import*as ze from"./engines/antigravity.js";import{pi as Ye,opencode as Ve,kiro as Qe,copilot as Ze,deepseek as qe,hermes as et}from"./engines/cli-agents.js";import{connectorsFor as tt}from"./connectors.js";import*as nt from"./engines/custom.js";import{installService as ot,uninstallService as rt,serviceStatus as at,restartService as ae}from"./service.js";import{skillIndex as J,listRecords as it,readRecord as st,readPackageFile as ct,skillsHealth as lt,quarantinedSkills as dt,clearSkillCache as X}from"./skills.js";import{writeSkillPackage as ut,writeSkillFile as ht,deleteSkillPackage as pt,SkillWriteError as ft}from"./skill-write.js";import{agentDefRoots as mt,scanAgentDefs as gt,listAgentDefs as wt,readAgentDef as yt,planAgentExport as bt,exportAgentDef as St,agentDefsHealth as kt,AgentDefError as Tt}from"./agent-defs.js";import{capabilityToolSpecs as xt,runCapabilityTool as Et}from"./mcp-capabilities.js";import{createSession as vt,deleteSession as ie,getSession as se,activeSession as At,relayToolCall as Ot}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ct,isDefaultWorkdir as Pt,resolveWorkdir as $t,writeScopeNote as Rt}from"./workdir.js";import{sandbox as K,runSandboxCli as It,withGrant as ce,withAgentGrant as Nt,withoutOutsideWhenCapped as Dt,grantedWriteRoots as le,acceptRefusalReport as _t,liveProcesses as Ht,sandboxConfigFromEnv as Mt}from"./sandbox.js";import{createAccessGate as Bt,chatKeyOf as Gt,chatFolders as Ut}from"./access-gate.js";import{signInDenial as Lt}from"./events/sandbox-policy.js";import{gitState as Wt,gitDelta as jt}from"./scm.js";import{listConnections as Ft,putConnection as Jt,removeConnection as Xt,runEnvFor as Kt,testConnection as zt,secretBackend as de}from"./connections.js";import{worktreeFor as ue,listWorktrees as Yt,removeWorktree as Vt,withHook as Qt,WORKTREE_ROOT as he}from"./worktree.js";import{AGENT_CLIS as Zt,agentAvailable as qt,agentInstallDirs as en,enrichPath as tn,enrichAgentEnv as nn,findAgentBin as on,forgetMisses as rn,primeAgentLookups as an,resolveCommand as pe,isCompiledBinary as sn}from"./env.js";import"./sanitize.js";import{checkForUpdate as cn,selfUpdate as fe,isEmbedded as me}from"./update.js";import{callLocalMcp as ln,localMcpStatus as dn,signInLocalMcp as un,signInStatusLocalMcp as hn}from"./mcp-local.js";import{assertPublicHttpUrl as ge,assertPublicWebUrl as we}from"./ssrf.js";import{startRun as ye,endRun as z,cancelRun as pn,cancelAll as fn}from"./runs.js";import{closeWarmPools as mn,warmStatus as gn}from"./warm.js";import{SESSION_AGENTS as be,listSessions as wn,readSession as yn,adoptSession as bn,catchUp as Sn}from"./agent-sessions.js";import{agentContext as kn}from"./agent-context.js";import{normalizeThread as Se}from"./events/agent-thread.js";import{portClashPlan as Tn,serviceManagerOf as xn,STANDBY_POLL_MS as En}from"./events/service-standby.js";import{holdThread as ke}from"./threads.js";import{oneReply as vn}from"./one-reply.js";import{createSnapshot as An}from"./health-snapshot.js";import{CompatError as P,anthropicError as Y,anthropicStream as On,chatCompletionStream as Cn,completionStream as Pn,createAnthropicMessage as $n,createChatCompletion as Rn,createCompletion as In,createResponse as Nn,openAIError as S,parseAnthropicMessage as Dn,parseChatCompletion as _n,parseCompletion as Hn,parseResponse as Mn,responseStream as Bn}from"./api-compat.js";import{callerTrust as Gn,isPaired as I,parseExtensionIds as Un,capRunOptions as Ln,engineHonoursReach as Wn,createPairingStore as jn,formatPairingCode as Fn}from"./pii/trust.js";const y="0.46.1",x=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Xe,label:"Claude Code"},codex:{engine:Ke,label:"Codex"},antigravity:{engine:ze,label:"Antigravity",tools:!1},pi:{engine:Ye,label:"Pi"},opencode:{engine:Ve,label:"OpenCode"},hermes:{engine:et,label:"Hermes"},kiro:{engine:Qe,label:"Kiro"},copilot:{engine:Ze,label:"GitHub Copilot"},deepseek:{engine:qe,label:"DeepSeek Harness"},custom:{engine:nt,label:"Custom",hidden:!0}};function Te(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 Jn=Un(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gn({origin:n.headers.origin||"",hasToken:Ae(n),extensionIds:Jn})),n.chatpanelTrust}function Xn(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 Kn(n,e){const t=n.headers.origin||"",o=Te(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 V=new Set(["127.0.0.1","localhost","::1"]);function zn(n){if(!V.has(x))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return V.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let v="";function Yn(){try{Je(D)&&(v=re(D,"utf8").trim()),v||(v=Ue(32).toString("hex"),je(M(O.homedir(),".chatpanel"),{recursive:!0}),Fe(D,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=jn({random:()=>Le(0,1e6)/1e6});function Vn(n){if(!v)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=xe.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 Qn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=xe.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:v})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Zn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ee(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function ve(n,e,t){try{const o=await Ee(),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 Ae(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&We(o,r)}const qn=new Set(["/agent-context","/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"]),eo=new Set(["/debug"]),to=n=>eo.has(n),no=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function oo(n,e){if(!zn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!Te(t))return"forbidden origin";const o=n.method==="POST"&&qn.has(e)||n.method==="GET"&&to(e)||no(n.method,e);return o&&!(Xn(t)||Ae(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!ao.has(e)?ro:null}const Oe=()=>me()?"chatpanel-gateway pair":"chatpanel-bridge pair",ro=`forbidden: this client is not paired with the bridge — run \`${Oe()}\` and enter the code in ChatPanel Settings`,ao=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Q(n,e,t){const o=N(n),r=Nt(e,Dt(Ln(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 (${Oe()})`} 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}}async function Ce(n,e,t){const o=e?.message||String(e);try{const r=await K().status(),a=!!(r.enabled&&r.runtime)&&t?.outside!==!0,s=Lt(`${o}
3
+ ${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:E[n]?.label||n||"This agent"});if(s)return s.line}catch{}return o}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)})}const Pe=An({compute:io});async function io(){await an();const n=await Promise.all(Object.entries(E).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:d}])=>{const l=await s.available().catch(w=>({ok:!1,reason:String(w?.message||w)})),p=await tt(a).catch(()=>[]);return{id:a,label:c,available:l.ok,reason:l.reason,connectors:p,...d===!1?{tools:!1}:{}}})),e=me()?{current:y,updateAvailable:!1,embedded:"gateway"}:await cn(y).catch(()=>({current:y,updateAvailable:!1})),t=await lt().catch(()=>null),o=await kt().catch(()=>null),r=await K().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function so(n,{fresh:e=!1}={}){e&&rn();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await Pe.get({fresh:e});i(n,200,{ok:!0,version:y,agents:o,update:r,checkedAt:t,workspace:Ct,sandbox:c,localMcp:dn(),processes:Ht(),worktrees:he,secretBackend:de(),warm:gn(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...s?{agentDefs:s}:{}})}async function co(n,e,t){const{index:o,problems:r}=await J({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:it(o),problems:r})}async function lo(n,e,t){i(n,200,{ok:!0,quarantined:await dt(e,t)})}async function uo(n,e,t,o){const{index:r}=await J({extraDirs:t,workdir:o}),a=st(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ho(n,e,t,o,r){const{index:a}=await J({extraDirs:o,workdir:r}),s=await ct(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 po(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await ut({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return X(),i(e,200,o)}catch(o){return i(e,Z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function fo(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 ht({name:t,path:o,text:r?.text??""});return X(),i(e,200,a)}catch(a){return i(e,Z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function mo(n,e){try{const t=await pt({name:e});return X(),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 ft?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function $e(n,e){return gt({roots:mt(process.env,O.homedir(),n,e)})}async function go(n,e,t){const{index:o,quarantined:r,problems:a}=await $e(e,t);i(n,200,{ok:!0,agents:wt(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 wo(n,e,t,o){const{index:r}=await $e(t,o),a=yt(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function yo(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 bt({agent:t?.agent,to:t?.to})})}catch(o){return i(e,Re(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function bo(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 St({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,Re(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function Re(n){if(n instanceof Tt){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function So(){return(await Promise.all(Object.entries(E).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 Ie(n,e=""){const t=await So();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function ko(n){try{const e=await fe(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>ae(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function To(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=Q(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=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
4
4
 
5
- `)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,d=we(c),l={signal:d.signal,abort:()=>d.cancel("client")},p=()=>{s=!0,d.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const y=h=>{s||a(h)};a({type:"run",id:c}),r.note&&a({type:"status",text:r.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(f=await de({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),K(c),e.writableEnded||e.end();return}}const _=f?f.path:Pt(t.options?.workingDir),L=Bt(t.agent,t.options),q=L?Gt(L):[];q.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...q])]}});let C=null;{const h=_,g=!!f||!Ct(t.options?.workingDir),w=$t(t.agent,t.options?.permissionMode,h,ce(h,{grant:t.options?.sandbox}));a({type:"workdir",path:h,isDefault:!g,writeScope:w||void 0}),a({type:"status",text:`Working in ${h}${g?"":" (default)"}`}),w&&a({type:"status",text:w}),C=await Lt(h),C&&a({type:"scm",phase:"before",...C})}let W=null;if(C||f){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:g,connection:w}=Xt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});W=Vt(g),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...w?{connection:w}:{}}),w&&a({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${g.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:g.CHATPANEL_SCM_PUSH}`})}const j=t.approvals===!0,S={...t.options||{},...f?{workingDir:f.path}:{},...W?{runEnv:W}:{},approvals:j};let R=null;(t.pageTools?.specs?.length||j)&&(R=Et(y,t.pageTools?.specs||[]),S.permissionSession=R,t.pageTools?.specs?.length&&(S.mcp={url:`http://${x}:${T}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const He=Ht();let ee=S.sandbox||null;j&&He.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&S.sandbox?.outside!==!0&&(S.accessGate=Mt({agent:t.agent,label:E[t.agent]?.label||t.agent,key:L,cwd:_,roots:()=>ce(_,{grant:ee})}));try{const h=(g,w)=>se(g.sandbox,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:w,options:g,images:Array.isArray(t.images)?t.images:[]},y,{signal:l.signal}));await Se(t.agent,S,l.signal,async()=>{await h(S,t.system||"");let g=S;for(let w=0;w<2&&S.accessGate?.restart().length&&!l.signal.aborted;w++){const te=S.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...te])]}},ee=g.sandbox;const ne=te.map(Me=>S.accessGate.short(Me)).join(", ");y({type:"status",text:`Restarted with write access to ${ne} — carrying on`}),await h(g,`${t.system||""}
5
+ `)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,d=ye(c),l={signal:d.signal,abort:()=>d.cancel("client")},p=()=>{s=!0,d.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const w=h=>{s||a(h)};a({type:"run",id:c}),r.note&&a({type:"status",text:r.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(f=await ue({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),z(c),e.writableEnded||e.end();return}}const _=f?f.path:$t(t.options?.workingDir),W=Gt(t.agent,t.options),ee=W?Ut(W):[];ee.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...ee])]}});let C=null;{const h=_,T=!!f||!Pt(t.options?.workingDir),g=Rt(t.agent,t.options?.permissionMode,h,le(h,{grant:t.options?.sandbox}));a({type:"workdir",path:h,isDefault:!T,writeScope:g||void 0}),a({type:"status",text:`Working in ${h}${T?"":" (default)"}`}),g&&a({type:"status",text:g}),C=await Wt(h),C&&a({type:"scm",phase:"before",...C})}let j=null;if(C||f){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:T,connection:g}=Kt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=Qt(T),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...g?{connection:g}:{}}),g&&a({type:"status",text:`Git credential: ${g.kind} · ${g.host}${g.hasSecret?"":" (no token stored)"} · push: ${T.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:T.CHATPANEL_SCM_PUSH}`})}const F=t.approvals===!0,b={...t.options||{},...f?{workingDir:f.path}:{},...j?{runEnv:j}:{},approvals:F};let R=null;(t.pageTools?.specs?.length||F)&&(R=vt(w,t.pageTools?.specs||[]),b.permissionSession=R,t.pageTools?.specs?.length&&(b.mcp={url:`http://${x}:${k}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const Me=Mt();let te=b.sandbox||null;F&&Me.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&b.sandbox?.outside!==!0&&(b.accessGate=Bt({agent:t.agent,label:E[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>le(_,{grant:te})}));try{const h=vn(w),T=(g,H)=>ce(g.sandbox,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:H,options:g,images:Array.isArray(t.images)?t.images:[]},h.emit,{signal:l.signal}));await ke(t.agent,b,l.signal,async()=>{await T(b,t.system||"");let g=b;for(let H=0;H<2&&b.accessGate?.restart().length&&!l.signal.aborted;H++){const ne=b.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...ne])]}},te=g.sandbox;const oe=ne.map(Be=>b.accessGate.short(Be)).join(", ");h.seam(),w({type:"status",text:`Restarted with write access to ${oe} — carrying on`}),await T(g,`${t.system||""}
6
6
 
7
- [ChatPanel] The person has just allowed writing in ${ne}, and you were restarted with that access. Carry on with their request: do the step that was blocked. Do not ask again.`.trim())}})}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),h?.detail&&u("error",`${t.agent} said: ${h.detail}`),a({type:"error",error:await Oe(t.agent,h,S.sandbox)})}finally{if(!s){const h=await Wt(_,C).catch(()=>null);h&&y({type:"scm",phase:"after",...h})}K(c),R&&ae(R.id),e.writableEnded||e.end()}}async function ko(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:jt(),secretBackend:le()});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:Ft(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:Jt(r[1])}):i(e,200,Kt(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function To(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ue,worktrees:await zt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/worktrees"){const r=await de({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 Yt({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 A(n,e,t){const o=E[n.agent];if(!o||o.hidden)throw new P(`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 P(r.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=we(a),c=()=>s.cancel("disconnected");t.on("close",c);let d="";try{return await se(n.options?.sandbox,()=>Se(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?(d+=l.text,e(l.text)):l?.type==="done"&&l.text&&!d&&(d=l.text,e(l.text))},{signal:s.signal}))),d}catch(l){throw l instanceof Error&&!(l instanceof P)&&(l.message=await Oe(n.agent,l,n.options?.sandbox)),l}finally{t.off("close",c),K(a)}}function B(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function $(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
7
+ [ChatPanel] The person has just allowed writing in ${oe}, and you were restarted with that access. Carry on with their request: do the step that was blocked. Do not ask again.`.trim())}h.finish()})}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),h?.detail&&u("error",`${t.agent} said: ${h.detail}`),a({type:"error",error:await Ce(t.agent,h,b.sandbox)})}finally{if(!s){const h=await jt(_,C).catch(()=>null);h&&w({type:"scm",phase:"after",...h})}z(c),R&&ie(R.id),e.writableEnded||e.end()}}async function xo(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:Ft(),secretBackend:de()});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:Jt(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:Xt(r[1])}):i(e,200,zt(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function Eo(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:he,worktrees:await Yt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/worktrees"){const r=await ue({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 Vt({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 A(n,e,t){const o=E[n.agent];if(!o||o.hidden)throw new P(`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 P(r.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=ye(a),c=()=>s.cancel("disconnected");t.on("close",c);let d="";try{return await ce(n.options?.sandbox,()=>ke(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?(d+=l.text,e(l.text)):l?.type==="done"&&l.text&&!d&&(d=l.text,e(l.text))},{signal:s.signal}))),d}catch(l){throw l instanceof Error&&!(l instanceof P)&&(l.message=await Ce(n.agent,l,n.options?.sandbox)),l}finally{t.off("close",c),z(a)}}function G(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function $(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
8
8
 
9
- `)}function G(n,e,t){n.writableEnded||n.write(`event: ${e}
9
+ `)}function U(n,e,t){n.writableEnded||n.write(`event: ${e}
10
10
  data: ${JSON.stringify(t)}
11
11
 
12
- `)}async function U(n,e,t,o){try{const r=t(await m(n)),a=V(n,r.agent,r.options||{});if(a.error)throw new P(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${r.message}`):r)),null}}async function xo(n,e){const t=await U(n,e,Nn,k);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Pn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,k(r))}B(e);const o=An(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,k(r))}$(e,"[DONE]"),e.end()}async function Eo(n,e){const t=await U(n,e,Dn,k);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,$n(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,k(r))}B(e);const o=On(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,k(r))}$(e,"[DONE]"),e.end()}async function vo(n,e){const t=await U(n,e,_n,k);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Rn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,k(r))}B(e);const o=Hn(t.requestedModel,r=>G(e,r.type,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...k(r)};G(e,"error",a)}e.end()}async function Ao(n,e){const t=await U(n,e,In,z);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Cn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,z(r))}B(e);const o=vn(t.requestedModel,(r,a)=>G(e,r,a));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){G(e,"error",z(r))}e.end()}async function Oo(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?hn(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Ie(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?ie(t):vt(),a=d=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:d})},s=(d,l)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:d,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:b}});const c=Tt();if(o.method==="tools/list"){const d=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...d]})}if(o.method==="tools/call"){const d=await xt(o.params?.name,o.params?.arguments||{});if(d)return a(d);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 At(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 Co(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 cn({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 Po(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?un(r):await dn(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function $o(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.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=me(o)}catch(p){return i(e,400,{error:String(p?.message||p)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[p,y]of Object.entries(r)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[p]=String(y))}const d=new AbortController,l=setTimeout(()=>d.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:d.signal});try{p.url&&me(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const y=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:y})}catch(p){const y=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const Ne=256*1024,Ro=5,Io=8e3;async function No(n){let e=ge(n);const t=new AbortController,o=setTimeout(()=>t.abort(),Io);try{for(let r=0;r<=Ro;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/${b} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ge(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:Ho(await Do(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function Do(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ne);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>=Ne))break}}finally{try{await e.cancel()}catch{}}return o}function _o(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 Ho(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?_o(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Mo(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 No(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 Bo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=ie(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(d){return i(e,400,{error:"Bad JSON: "+d.message})}const o=E[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=V(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const c=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let d="";return typeof o.engine.complete=="function"?d=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},l=>{l.type==="delta"?d+=l.text||"":l.type==="done"&&l.text&&(d+=l.text)}),i(e,200,{text:(d||"").trim()})}catch(d){return i(e,502,{error:d?.message||String(d)})}}async function Uo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=E[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 Lo(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=he(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function Wo(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(!ye.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${ye.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await gn(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await wn(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=be({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 yn(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=be({id:o.thread?.id??o.thread});return a?i(e,200,await bn(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 Z=Be(async(n,e)=>{if(Jn(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=to(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return ao(e,{fresh:t.searchParams.get("fresh")==="1"});const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return io(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-context"){const s=await m(n).catch(()=>({})),c=s?.options&&typeof s.options=="object"?s.options:{},d={...c.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof c.permissionMode=="string"?{permissionMode:c.permissionMode}:{},...typeof c.workingDir=="string"&&c.workingDir?{workingDir:c.workingDir}:{},...typeof c.model=="string"&&c.model?{model:c.model}:{}};return i(e,200,await Sn({agent:typeof s?.agent=="string"?s.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return so(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return fo(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return go(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return wo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return mo(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return uo(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?n.method==="DELETE"?po(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"}):ho(n,e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?co(e,decodeURIComponent(s),r,a):lo(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return ko(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return To(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return Re(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return Re(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:b,agents:Object.fromEntries(Qt.map(c=>[c,s?nn(c)||he(c)?.kind||null:Zt(c)])),...s?{home:O.homedir(),path:process.env.PATH,installDirs:qt(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Wo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return So(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Yn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return zn(e);if(n.method==="POST"&&t.pathname==="/whoami")return Vn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return xo(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Eo(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return vo(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Ao(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Ie(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 Ie(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return ae(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return Ee(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return Ee(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 Bo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=Dt(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return Co(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Po(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return $o(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Mo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Go(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Uo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Lo(n,e);if(n.method==="POST"&&t.pathname==="/update")return bo(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 jo(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 c=t.shift();let d;try{d=JSON.parse(c)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(d.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
12
+ `)}async function L(n,e,t,o){try{const r=t(await m(n)),a=Q(n,r.agent,r.options||{});if(a.error)throw new P(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${r.message}`):r)),null}}async function vo(n,e){const t=await L(n,e,_n,S);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Rn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}G(e);const o=Cn(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,S(r))}$(e,"[DONE]"),e.end()}async function Ao(n,e){const t=await L(n,e,Hn,S);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,In(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}G(e);const o=Pn(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,S(r))}$(e,"[DONE]"),e.end()}async function Oo(n,e){const t=await L(n,e,Mn,S);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Nn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}G(e);const o=Bn(t.requestedModel,r=>U(e,r.type,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...S(r)};U(e,"error",a)}e.end()}async function Co(n,e){const t=await L(n,e,Dn,Y);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,$n(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,Y(r))}G(e);const o=On(t.requestedModel,(r,a)=>U(e,r,a));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){U(e,"error",Y(r))}e.end()}async function Po(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?pn(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Ne(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?se(t):At(),a=d=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:d})},s=(d,l)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:d,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:y}});const c=xt();if(o.method==="tools/list"){const d=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...d]})}if(o.method==="tools/call"){const d=await Et(o.params?.name,o.params?.arguments||{});if(d)return a(d);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 Ot(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 $o(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 ln({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 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||{};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?hn(r):await un(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(p){return i(e,400,{error:"Bad JSON: "+p.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=ge(o)}catch(p){return i(e,400,{error:String(p?.message||p)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[p,w]of Object.entries(r)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[p]=String(w))}const d=new AbortController,l=setTimeout(()=>d.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:d.signal});try{p.url&&ge(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const w=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:w})}catch(p){const w=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${w}`})}finally{clearTimeout(l)}}const De=256*1024,No=5,Do=8e3;async function _o(n){let e=we(n);const t=new AbortController,o=setTimeout(()=>t.abort(),Do);try{for(let r=0;r<=No;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/${y} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=we(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:Bo(await Ho(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function Ho(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,De);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>=De))break}}finally{try{await e.cancel()}catch{}}return o}function Mo(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 Bo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Mo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Go(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 _o(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 Uo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=se(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 Lo(n,e){let t;try{t=await m(n)}catch(d){return i(e,400,{error:"Bad JSON: "+d.message})}const o=E[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=Q(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const c=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let d="";return typeof o.engine.complete=="function"?d=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},l=>{l.type==="delta"?d+=l.text||"":l.type==="done"&&l.text&&(d+=l.text)}),i(e,200,{text:(d||"").trim()})}catch(d){return i(e,502,{error:d?.message||String(d)})}}async function Wo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=E[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 jo(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=pe(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function Fo(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(!be.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${be.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await wn(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await yn(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=Se({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 bn(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=Se({id:o.thread?.id??o.thread});return a?i(e,200,await Sn(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 q=Ge(async(n,e)=>{if(Kn(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=oo(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return so(e,{fresh:t.searchParams.get("fresh")==="1"});const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return co(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-context"){const s=await m(n).catch(()=>({})),c=s?.options&&typeof s.options=="object"?s.options:{},d={...c.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof c.permissionMode=="string"?{permissionMode:c.permissionMode}:{},...typeof c.workingDir=="string"&&c.workingDir?{workingDir:c.workingDir}:{},...typeof c.model=="string"&&c.model?{model:c.model}:{}};return i(e,200,await kn({agent:typeof s?.agent=="string"?s.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return lo(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return go(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return yo(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return bo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return wo(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return po(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?n.method==="DELETE"?mo(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"}):fo(n,e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?uo(e,decodeURIComponent(s),r,a):ho(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return xo(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Eo(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return Ie(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return Ie(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:y,agents:Object.fromEntries(Zt.map(c=>[c,s?on(c)||pe(c)?.kind||null:qt(c)])),...s?{home:O.homedir(),path:process.env.PATH,installDirs:en(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Fo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return To(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Qn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Vn(e);if(n.method==="POST"&&t.pathname==="/whoami")return Zn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return vo(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Ao(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Co(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Ne(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 Ne(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return ie(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ve(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ve(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Po(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Uo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=_t(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return $o(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Ro(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Io(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Go(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Lo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Wo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return jo(n,e);if(n.method==="POST"&&t.pathname==="/update")return ko(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 Jo(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 c=t.shift();let d;try{d=JSON.parse(c)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(d.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
13
13
  `)}catch(l){d.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:d.id,error:{code:-32e3,message:String(l?.message||l)}})+`
14
14
  `)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",c=>{e+=c;let d;for(;(d=e.indexOf(`
15
- `))>=0;){const l=e.slice(0,d).trim();e=e.slice(d+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function Fo(){en(),tn(),Kn();let n=!1;Z.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${T}/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=kn({name:"bridge",self:b,holder:o?{ours:o,version:t.version}:null,managedBy:Tn(process.env),port:T});if(r.action==="standby"||n&&!t){if(!n)for(const a of r.lines)u("info",a);n=!0,setTimeout(()=>Z.listen(T,x),xn);return}if(o)for(const a of r.lines)u("error",a);else u("error",`Port ${T} 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=pn("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const o=fn("shutdown");o&&u("info",`shutdown: closed ${o} warm agent process${o===1?"":"es"}`),X().close(),setTimeout(()=>process.exit(0),t||o?300:0).unref?.(),!t&&!o&&process.exit(0)});Z.listen(T,x,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${x}:${T}`),Ce.warm(),Y.has(x)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${x}. 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(E)){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."),xe().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 Jo(){console.log(`ChatPanel Bridge v${b}
15
+ `))>=0;){const l=e.slice(0,d).trim();e=e.slice(d+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function Xo(){tn(),nn(),Yn();let n=!1;q.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${k}/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=Tn({name:"bridge",self:y,holder:o?{ours:o,version:t.version}:null,managedBy:xn(process.env),port:k});if(r.action==="standby"||n&&!t){if(!n)for(const a of r.lines)u("info",a);n=!0,setTimeout(()=>q.listen(k,x),En);return}if(o)for(const a of r.lines)u("error",a);else u("error",`Port ${k} 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=fn("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const o=mn("shutdown");o&&u("info",`shutdown: closed ${o} warm agent process${o===1?"":"es"}`),K().close(),setTimeout(()=>process.exit(0),t||o?300:0).unref?.(),!t&&!o&&process.exit(0)});q.listen(k,x,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${x}:${k}`),Pe.warm(),V.has(x)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${x}. 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(E)){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."),Ee().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 Ko(){console.log(`ChatPanel Bridge v${y}
16
16
 
17
17
  Usage:
18
- chatpanel-bridge start the bridge (foreground) on ${x}:${T}
18
+ chatpanel-bridge start the bridge (foreground) on ${x}:${k}
19
19
  chatpanel-bridge --install run automatically at login, in the background
20
20
  chatpanel-bridge --uninstall remove the login auto-start
21
21
  chatpanel-bridge --status show whether auto-start is set up
@@ -24,4 +24,4 @@ Usage:
24
24
  chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
25
25
  chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
26
26
 
27
- Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function Xo(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return Jo(),!0;if(e("--version","-v"))return console.log(b),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=oe(D,"utf8").trim()}catch{}const o=`http://${x}:${T}`;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: ${Wn(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 Rt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{nt(),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{ot(),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=rt()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const De=process.argv.indexOf("--mcp-stdio"),_e=process.argv.indexOf("--sandbox-host");if(_e>=0){const{runSandboxHost:n}=await import("./sandbox-host.js");await n(process.argv[_e+1],{compiled:an()})}else if(De>=0){const n=process.argv[De+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),jo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await pe(b);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),re()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():Xo()||Fo();
27
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function zo(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return Ko(),!0;if(e("--version","-v"))return console.log(y),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=re(D,"utf8").trim()}catch{}const o=`http://${x}:${k}`;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: ${Fn(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 It(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{ot(),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{rt(),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=at()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const _e=process.argv.indexOf("--mcp-stdio"),He=process.argv.indexOf("--sandbox-host");if(He>=0){const{runSandboxHost:n}=await import("./sandbox-host.js");await n(process.argv[He+1],{compiled:sn()})}else if(_e>=0){const n=process.argv[_e+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Jo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await fe(y);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),ae()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():zo()||Xo();
package/src/threads.js CHANGED
@@ -1 +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};
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 still working on its last message (here or on another device). 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};