@chatpanel/bridge 0.44.2 → 0.46.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/package.json +1 -1
- package/scripts/sync-events.mjs +2 -2
- package/src/access-gate.js +1 -0
- package/src/aws-credentials.js +4 -0
- package/src/cli-errors.js +6 -5
- package/src/engines/claude-warm.js +3 -3
- package/src/engines/claude.js +6 -6
- package/src/engines/codex-appserver.js +5 -5
- package/src/env.js +2 -2
- package/src/events/access-request.js +1 -0
- package/src/events/agent-permission.js +2 -2
- package/src/events/harness-cards.js +1 -1
- package/src/events/policy.js +1 -0
- package/src/events/runtime-host.js +1 -0
- package/src/events/sandbox-choice.js +1 -0
- package/src/events/sandbox-grant.js +1 -1
- package/src/events/sandbox-policy.js +1 -1
- package/src/pii/pii-detect.js +2 -2
- package/src/pii/tool-harness.js +1 -1
- package/src/sandbox-command.js +1 -0
- package/src/sandbox-host.js +1 -1
- package/src/sandbox-srt.js +1 -1
- package/src/sandbox.js +1 -1
- package/src/server.js +12 -9
- package/src/warm-pool.js +1 -1
package/src/server.js
CHANGED
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as xe}from"node:http";import v from"node:os";import{randomBytes as Pe,randomInt as $e,timingSafeEqual as Re}from"node:crypto";import{mkdirSync as Ie,writeFileSync as Ne,readFileSync as Q,existsSync as De}from"node:fs";import{join as _}from"node:path";import*as _e from"./engines/claude.js";import*as He from"./engines/codex.js";import*as Me from"./engines/antigravity.js";import{pi as Be,opencode as Ue,kiro as We,copilot as Le,deepseek as Ge,hermes as je}from"./engines/cli-agents.js";import{connectorsFor as Fe}from"./connectors.js";import*as Je from"./engines/custom.js";import{installService as Xe,uninstallService as ze,serviceStatus as Ke,restartService as Z}from"./service.js";import{skillIndex as L,listRecords as Ye,readRecord as Ve,readPackageFile as Qe,skillsHealth as Ze,quarantinedSkills as qe,clearSkillCache as G}from"./skills.js";import{writeSkillPackage as et,writeSkillFile as tt,deleteSkillPackage as nt,SkillWriteError as ot}from"./skill-write.js";import{agentDefRoots as rt,scanAgentDefs as at,listAgentDefs as it,readAgentDef as st,planAgentExport as ct,exportAgentDef as lt,agentDefsHealth as dt,AgentDefError as ut}from"./agent-defs.js";import{capabilityToolSpecs as ht,runCapabilityTool as pt}from"./mcp-capabilities.js";import{createSession as ft,deleteSession as q,getSession as ee,activeSession as mt,relayToolCall as gt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as yt,isDefaultWorkdir as wt,resolveWorkdir as St,writeScopeNote as bt}from"./workdir.js";import{sandbox as te,runSandboxCli as kt,withGrant as ne,withoutOutsideWhenCapped as Tt,grantedWriteRoots as Et,acceptRefusalReport as vt,liveProcesses as Ot}from"./sandbox.js";import{gitState as At,gitDelta as Ct}from"./scm.js";import{listConnections as xt,putConnection as Pt,removeConnection as $t,runEnvFor as Rt,testConnection as It,secretBackend as oe}from"./connections.js";import{worktreeFor as re,listWorktrees as Nt,removeWorktree as Dt,withHook as _t,WORKTREE_ROOT as ae}from"./worktree.js";import{AGENT_CLIS as Ht,agentAvailable as Mt,agentInstallDirs as Bt,enrichPath as Ut,enrichAgentEnv as Wt,findAgentBin as Lt,forgetMisses as Gt,primeAgentLookups as jt,resolveCommand as ie}from"./env.js";import"./sanitize.js";import{checkForUpdate as Ft,selfUpdate as se,isEmbedded as ce}from"./update.js";import{callLocalMcp as Jt,localMcpStatus as Xt,signInLocalMcp as zt,signInStatusLocalMcp as Kt}from"./mcp-local.js";import{assertPublicHttpUrl as le,assertPublicWebUrl as de}from"./ssrf.js";import{startRun as ue,endRun as j,cancelRun as Yt,cancelAll as Vt}from"./runs.js";import{closeWarmPools as Qt,warmStatus as Zt}from"./warm.js";import{SESSION_AGENTS as he,listSessions as qt,readSession as en,adoptSession as tn,catchUp as nn}from"./agent-sessions.js";import{agentContext as on}from"./agent-context.js";import{normalizeThread as pe}from"./events/agent-thread.js";import{portClashPlan as rn,serviceManagerOf as an,STANDBY_POLL_MS as sn}from"./events/service-standby.js";import{holdThread as fe}from"./threads.js";import{createSnapshot as cn}from"./health-snapshot.js";import{CompatError as R,anthropicError as F,anthropicStream as ln,chatCompletionStream as dn,completionStream as un,createAnthropicMessage as hn,createChatCompletion as pn,createCompletion as fn,createResponse as mn,openAIError as S,parseAnthropicMessage as gn,parseChatCompletion as yn,parseCompletion as wn,parseResponse as Sn,responseStream as bn}from"./api-compat.js";import{callerTrust as kn,isPaired as I,parseExtensionIds as Tn,capRunOptions as En,engineHonoursReach as vn,createPairingStore as On,formatPairingCode as An}from"./pii/trust.js";const g="0.44.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",b=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:_e,label:"Claude Code"},codex:{engine:He,label:"Codex"},antigravity:{engine:Me,label:"Antigravity",tools:!1},pi:{engine:Be,label:"Pi"},opencode:{engine:Ue,label:"OpenCode"},hermes:{engine:je,label:"Hermes"},kiro:{engine:We,label:"Kiro"},copilot:{engine:Le,label:"GitHub Copilot"},deepseek:{engine:Ge,label:"DeepSeek Harness"},custom:{engine:Je,label:"Custom",hidden:!0}};function me(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 Cn=Tn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=kn({origin:n.headers.origin||"",hasToken:Se(n),extensionIds:Cn})),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 Pn(n,e){const t=n.headers.origin||"",o=me(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 $n(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 Rn(){try{De(D)&&(T=Q(D,"utf8").trim()),T||(T=Pe(32).toString("hex"),Ie(_(v.homedir(),".chatpanel"),{recursive:!0}),Ne(D,T,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const ge=On({random:()=>$e(0,1e6)/1e6});function In(n){if(!T)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ge.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 Nn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ge.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 Dn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:g})}let H=null;async function ye(){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 we(n,e,t){try{const o=await ye(),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 Se(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&&Re(o,r)}const _n=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"]),Hn=new Set(["/debug"]),Mn=n=>Hn.has(n),Bn=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Un(n,e){if(!$n(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!me(t))return"forbidden origin";const o=n.method==="POST"&&_n.has(e)||n.method==="GET"&&Mn(e)||Bn(n.method,e);return o&&!(xn(t)||Se(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!Ln.has(e)?Wn:null}const be=()=>ce()?"chatpanel-gateway pair":"chatpanel-bridge pair",Wn=`forbidden: this client is not paired with the bridge — run \`${be()}\` and enter the code in ChatPanel Settings`,Ln=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=Tt(En(t,o));if(!vn(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 (${be()})`} 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)})}const ke=cn({compute:Gn});async function Gn(){await jt();const n=await Promise.all(Object.entries(O).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:l}])=>{const d=await s.available().catch(y=>({ok:!1,reason:String(y?.message||y)})),h=await Fe(a).catch(()=>[]);return{id:a,label:c,available:d.ok,reason:d.reason,connectors:h,...l===!1?{tools:!1}:{}}})),e=ce()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Ft(g).catch(()=>({current:g,updateAvailable:!1})),t=await Ze().catch(()=>null),o=await dt().catch(()=>null),r=await te().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function jn(n,{fresh:e=!1}={}){e&&Gt();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await ke.get({fresh:e});i(n,200,{ok:!0,version:g,agents:o,update:r,checkedAt:t,workspace:yt,sandbox:c,localMcp:Xt(),processes:Ot(),worktrees:ae,secretBackend:oe(),warm:Zt(),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 Fn(n,e,t){const{index:o,problems:r}=await L({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Ye(o),problems:r})}async function Jn(n,e,t){i(n,200,{ok:!0,quarantined:await qe(e,t)})}async function Xn(n,e,t,o){const{index:r}=await L({extraDirs:t,workdir:o}),a=Ve(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function zn(n,e,t,o,r){const{index:a}=await L({extraDirs:o,workdir:r}),s=await Qe(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 Kn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await et({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return G(),i(e,200,o)}catch(o){return i(e,z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function Yn(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 tt({name:t,path:o,text:r?.text??""});return G(),i(e,200,a)}catch(a){return i(e,z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function Vn(n,e){try{const t=await nt({name:e});return G(),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 ot?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Te(n,e){return at({roots:rt(process.env,v.homedir(),n,e)})}async function Qn(n,e,t){const{index:o,quarantined:r,problems:a}=await Te(e,t);i(n,200,{ok:!0,agents:it(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 Zn(n,e,t,o){const{index:r}=await Te(t,o),a=st(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function qn(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 ct({agent:t?.agent,to:t?.to})})}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function eo(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 lt({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function Ee(n){if(n instanceof ut){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function to(){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 ve(n,e=""){const t=await to();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 no(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 oo(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.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=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
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)}
|
|
3
4
|
|
|
4
|
-
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,
|
|
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
6
|
|
|
6
|
-
`)}function
|
|
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)}
|
|
8
|
+
|
|
9
|
+
`)}function G(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
7
10
|
data: ${JSON.stringify(t)}
|
|
8
11
|
|
|
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 io(n,e){const t=await U(n,e,yn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,pn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=dn(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 so(n,e){const t=await U(n,e,wn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,fn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=un(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 co(n,e){const t=await U(n,e,Sn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,mn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=bn(t.requestedModel,r=>B(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)};B(e,"error",a)}e.end()}async function lo(n,e){const t=await U(n,e,gn,F);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,hn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,F(r))}M(e);const o=ln(t.requestedModel,(r,a)=>B(e,r,a));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",F(r))}e.end()}async function uo(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?Yt(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Oe(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):mt(),a=l=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:l})},s=(l,d)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:l,message:d}});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 c=ht();if(o.method==="tools/list"){const l=r?r.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...l]})}if(o.method==="tools/call"){const l=await pt(o.params?.name,o.params?.arguments||{});if(l)return a(l);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 gt(r,o.params?.name,o.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function ho(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 Jt({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?Kt(r):await zt(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function fo(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=le(o)}catch(h){return i(e,400,{error:String(h?.message||h)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,y]of Object.entries(r)){const f=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[h]=String(y))}const l=new AbortController,d=setTimeout(()=>l.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:l.signal});try{h.url&&le(h.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}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(d)}}const Ae=256*1024,mo=5,go=8e3;async function yo(n){let e=de(n);const t=new AbortController,o=setTimeout(()=>t.abort(),go);try{for(let r=0;r<=mo;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=de(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 wo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function wo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ae);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=Ae))break}}finally{try{await e.cancel()}catch{}}return o}function So(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /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?So(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function ko(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 yo(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 To(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 Eo(n,e){let t;try{t=await m(n)}catch(l){return i(e,400,{error:"Bad JSON: "+l.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 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 l="";return typeof o.engine.complete=="function"?l=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},d=>{d.type==="delta"?l+=d.text||"":d.type==="done"&&d.text&&(l+=d.text)}),i(e,200,{text:(l||"").trim()})}catch(l){return i(e,502,{error:l?.message||String(l)})}}async function vo(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 Oo(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 Ao(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(!he.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${he.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await qt(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await en(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=pe({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 tn(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=pe({id:o.thread?.id??o.thread});return a?i(e,200,await nn(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=xe(async(n,e)=>{if(Pn(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=Un(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return jn(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 Fn(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:{},l={...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 on({agent:typeof s?.agent=="string"?s.agent:"claude",options:l}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Jn(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return Qn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return qn(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return eo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return Zn(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return Kn(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"?Vn(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"}):Yn(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?Xn(e,decodeURIComponent(s),r,a):zn(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return ro(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return ao(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return ve(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return ve(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(Ht.map(c=>[c,s?Lt(c)||ie(c)?.kind||null:Mt(c)])),...s?{home:v.homedir(),path:process.env.PATH,installDirs:Bt(v.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Ao(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return oo(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Nn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return In(e);if(n.method==="POST"&&t.pathname==="/whoami")return Dn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return io(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return so(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return co(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return lo(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Oe(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return Oe(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 we(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return we(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return uo(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return To(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=vt(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return po(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return fo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return ko(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Eo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return vo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/update")return no(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 Co(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 l;try{l=JSON.parse(c)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(l.id==null)continue;const h=(await d.text()).trim();h&&process.stdout.write(h+`
|
|
10
|
-
`)}catch(
|
|
11
|
-
`)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",c=>{e+=c;let
|
|
12
|
-
`))>=0;){const
|
|
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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /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+`
|
|
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
|
+
`)}}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}
|
|
13
16
|
|
|
14
17
|
Usage:
|
|
15
|
-
chatpanel-bridge start the bridge (foreground) on ${
|
|
18
|
+
chatpanel-bridge start the bridge (foreground) on ${x}:${T}
|
|
16
19
|
chatpanel-bridge --install run automatically at login, in the background
|
|
17
20
|
chatpanel-bridge --uninstall remove the login auto-start
|
|
18
21
|
chatpanel-bridge --status show whether auto-start is set up
|
|
@@ -21,4 +24,4 @@ Usage:
|
|
|
21
24
|
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
22
25
|
chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
|
|
23
26
|
|
|
24
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function
|
|
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();
|
package/src/warm-pool.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{treeRssBytes as
|
|
1
|
+
import{treeRssBytes as L,totalMemoryBytes as B}from"./proc.js";import{historyShape as v,userTextMatches as D}from"./events/agent-thread.js";const d=1024**3,b=B(),k=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(b>=16*d?10*6e4:5*6e4),N=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(b*.2),3*d),S=400*1024**2;function z(n,o,a=S){const l=Math.floor(o/a),c=n>=48*d?4:n>=24*d?3:n>=12*d?2:1;return Math.max(1,Math.min(l,c))}const g=Number(process.env.CHATPANEL_WARM_MAX)||z(b,N),G=new Set;function U(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||D(n.users[a-1],o.users[a-1])}const W=2*6e4;function P({max:n=g,idleMs:o=k,budgetBytes:a=N,group:l=G,now:c=Date.now,measure:I=r=>L(r?.pid),log:h=()=>{}}={}){const r=new Set;let m=null;const M=()=>{let e=0;for(const s of l)e+=s.bytes;return e};let A=0;const f=e=>`${Math.round(e/1024**2)} MB`;function p(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)}}const w=e=>Number(e.session?.expiresAt)>0&&c()>=e.session.expiresAt-W;function E(){const e=c();for(const s of[...r])!s.busy&&e-s.lastUsed>o&&p(s,"idle")}function R(){m||!Number.isFinite(o)||o<=0||(m=setInterval(E,Math.min(o,6e4)),m.unref?.())}const x={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=v(s);for(const t of r)if(!t.busy&&t.alive&&t.key===e&&!w(t)&&U(t.shape,i))return!0;return!1},acquire({key:e,messages:s}){const i=v(s);for(const t of r)if(!(t.busy||!t.alive||t.key!==e)){if(w(t)){p(t,"its sign-in is about to expire");continue}if(!U(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=c(),h(`warm ${t.label}: reused`),t}return null},reserve({key:e,label:s=e,evict:i=!0}){const t=()=>{let u=null;for(const $ of r)!$.busy&&(!u||$.lastUsed<u.lastUsed)&&(u=$);return u};if(r.size>=n){const u=i?t():null;if(!u)return null;p(u,"evicted")}const _=A||S;for(;M()+_>a;){const u=i?t():null;if(!u)return h(`warm ${s}: not kept — ${f(M())} warm + ~${f(_)} would pass the ${f(a)} budget`),null;p(u,`evicted for memory (${f(M())} warm)`)}const T={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:c(),bytes:_};return r.add(T),h(`warm ${s}: starting (${r.size} live, ~${f(M())} of ${f(a)})`),R(),T},holds(e,s){return e.shape=v(s),e},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&p(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=c(),setImmediate(()=>{if(!e.alive)return;const t=I(e.session);t>0&&(e.bytes=t,A=t,h(`warm ${e.label}: ${f(t)} resident`))}))},drop:p,closeAll(e="shutdown"){for(const s of[...r])p(s,e)},keys(){return[...r].map(e=>e.key)},reap:E};return l.add(x),x}export{N as WARM_BUDGET_BYTES,P as createWarmPool,v as historyShape,z as warmMaxFor};
|