@chatpanel/bridge 0.53.0 → 0.53.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 +1 -1
- package/src/events/agent-permission.js +2 -2
- package/src/origins.js +1 -0
- package/src/server.js +7 -7
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.53.
|
|
3
|
+
"version": "0.53.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": [
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const T="permission_request",
|
|
2
|
-
`);let
|
|
1
|
+
const T="permission_request",h=Object.freeze({ALLOW:"allow",ALLOW_CHAT:"allow_chat",DENY:"deny"}),k=600*1e3,L="permission_prompt";function N(){return{name:L,description:"Chap-internal: the person answers the agent's permission prompt. Not for the model.",parameters:{type:"object",properties:{tool:{type:"string"},input:{type:"object"},description:{type:"string"},path:{type:"string"},rules:{type:"array"}}}}}const C=t=>t===L,c=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),a=t=>typeof t=="string"?t:t==null?"":String(t);function P(t={}){const e=c(t)?t:{},o=a(e.tool_name||e.toolName||e.tool),n=[];for(const s of Array.isArray(e.permission_suggestions)?e.permission_suggestions:[])if(!(!c(s)||s.type!=="addRules"||s.behavior==="deny"))for(const r of Array.isArray(s.rules)?s.rules:[]){if(!c(r))continue;const p=a(r.toolName||o),l=a(r.ruleContent);p&&!n.some(u=>u.tool===p&&u.content===l)&&n.push({tool:p,content:l})}return{tool:o,displayName:a(e.display_name||e.displayName)||o,input:c(e.input)?e.input:{},description:a(e.description),path:a(e.blocked_path||e.path)||null,rules:n,toolUseId:a(e.tool_use_id||e.toolUseId)||null}}function A(t={}){const e=Array.isArray(t.rules)?t.rules.filter(o=>o&&o.tool):[];return e.length?e.map(o=>o.content?`${o.tool}(${o.content})`:o.tool):t.tool?[String(t.tool)]:[]}function S(t={}){const e=a(t.tool),o=c(t.input)?t.input:{},n=(i,m=240)=>i.length>m?`${i.slice(0,m-1)}…`:i;let s,r;if(e==="Bash")s="Run a command",r=n(a(o.command).trim()||a(t.description)||"a shell command");else if(e==="Edit"||e==="MultiEdit"||e==="NotebookEdit")s="Edit a file",r=a(o.file_path||o.notebook_path||t.path)||"a file";else if(e==="Write"){s="Write a file";const i=a(o.file_path||t.path)||"a file",m=a(o.content).length;r=m?`${i} (${m.toLocaleString()} chars)`:i}else if(/^mcp__/.test(e))s="Use a connected server",r=e.replace(/^mcp__/,"").replace(/__/," › ");else{s=`Use ${t.displayName||e||"a tool"}`;let i="";try{i=JSON.stringify(o)}catch{i=""}r=a(t.description)||(i&&i!=="{}"?n(i,200):e)}const p=A(t),l=Array.isArray(t.rules)?t.rules.filter(i=>i?.content):[],u=l.length&&l.some(i=>i.content!==r)?l.map(i=>i.content).join(", "):p.length&&!l.length?`every ${e} call`:null,f=c(t.access)?a(t.access.folder):"",d=f?`This works in ${f}, outside the folders it may change. Allowing it opens ${f} to it for the rest of this chat.`:null;return{title:s,detail:r,scope:u,description:a(t.description)||null,access:d}}function y(t,e=""){return t===h.ALLOW?{behavior:"allow",scope:"once"}:t===h.ALLOW_CHAT?{behavior:"allow",scope:"chat"}:{behavior:"deny",scope:"once",...e?{message:String(e)}:{}}}function _(t){return c(t)&&t.behavior==="allow"}function E(t,e){const o=new Set(Array.isArray(t)?t:[]);for(const n of A(e))o.add(n);return[...o].sort()}const b="*";function O(t,e){const o=new Set(Array.isArray(t)?t:[]);if(o.has(b))return y(h.ALLOW);const n=A(e);return n.length&&n.every(s=>o.has(s))?y(h.ALLOW):null}function R(t,e,o={}){const n=c(o)?o:{},s=_(e);let r;if(s){if(r={behavior:"allow",updatedInput:c(n.input)?n.input:{}},e.scope==="chat"){const p=(Array.isArray(n.permission_suggestions)?n.permission_suggestions:[]).filter(l=>c(l)&&l.type==="addRules"&&l.behavior!=="deny"&&Array.isArray(l.rules)&&l.rules.length).map(l=>({type:"addRules",rules:l.rules,behavior:"allow",destination:"session"}));p.length&&(r.updatedPermissions=p)}}else r={behavior:"deny",message:a(e?.message)||"The user declined this action in Chap. Continue without it, or explain what it was for and ask."};return{type:"control_response",response:{subtype:"success",request_id:String(t),response:r}}}function I(t,e){const{detail:o}=S(t),n=_(e),s=n&&e.scope==="chat"?" for this chat":"";return`${n?"Allowed":"Declined"}${s}: ${o}`}function $(t){return t==="Bash"?"code":/^(Edit|MultiEdit|NotebookEdit)$/.test(String(t))?"pencil":t==="Write"?"file":/^mcp__/.test(String(t))?"plug":"bot"}const W=4e5;function M(t={},e=null){if(!_(e)||!c(t))return null;const o=c(t.input)?t.input:{};if(!["Write","Create","write_file"].includes(String(t.tool||"")))return null;const n=String(o.file_path||o.path||""),s=typeof o.content=="string"?o.content:"";return!/\.svg$/i.test(n)||!/<svg[\s>]/i.test(s)||s.length>W?null:{kind:"svg",title:n.split(/[\\/]/).pop()||"picture.svg",text:s}}function v({memory:t=new Map}={}){const e=t;async function o(n,{convId:s=null,confirm:r,agentName:p="The agent"}={}){const l=c(n.access)?null:O(await e.get(s)||[],n);if(l)return l;const{title:u,detail:f,scope:d,description:i,access:m}=S(n),x=[m,f,i&&i!==f?i:"",d?`“Allow for this chat” also covers: ${d}`:""].filter(Boolean).join(`
|
|
2
|
+
`);let g;try{if(typeof r!="function")throw new Error("no card");g=await r(x,{title:`${p} asks — ${u.toLowerCase()}?`,iconName:$(n.tool),scopeLabel:"Allow for this chat",allLabel:"Allow all in this chat"})}catch(w){return y(h.DENY,`Chap could not show the permission card (${w?.message||w}).`)}return g==="all"?(await e.set(s,[b]),y(h.ALLOW_CHAT)):g==="site"||g==="always"?(await e.set(s,E(await e.get(s)||[],n)),y(h.ALLOW_CHAT)):y(g==="allow"?h.ALLOW:h.DENY)}return{ask:o,forget(n){e.delete(n)},standing(n){return e.get(n)||[]},provider({convId:n=null,confirm:s,agentName:r="The agent",onAnswered:p=null}={}){return{id:"permission",specs:[N()],execute:async(l,u)=>{const f=u&&typeof u=="object"?u:{},d=await o(f,{convId:n,confirm:s,agentName:r});try{p?.(f,d)}catch{}return JSON.stringify(d)}}}}}export{b as ALLOW_ALL,W as MAX_SHOWN_PICTURE,h as PERMISSION_ANSWERS,T as PERMISSION_EVENT,k as PERMISSION_TIMEOUT_MS,L as PERMISSION_TOOL_NAME,R as claudePermissionResponse,v as createPermissionDesk,S as describePermission,C as isPermissionTool,_ as permissionAllowed,y as permissionAnswer,$ as permissionIcon,A as permissionKeys,I as permissionLine,P as permissionRequestFromClaude,N as permissionToolSpec,M as pictureFromPermission,O as recallPermission,E as rememberPermission};
|
package/src/origins.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o=/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?$/,e=/^(chrome|moz)-extension:\/\/[A-Za-z0-9-]+$/;function r(t){const n=String(t||"");return e.test(n)||o.test(n)}function s(t){return!t||r(t)}export{r as isExtensionOrigin,s as originAllowed};
|
package/src/server.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:
|
|
2
|
+
import{originAllowed as ae,isExtensionOrigin as Le}from"./origins.js";import{createServer as We}from"node:http";import O from"node:os";import{randomBytes as je,randomInt as Fe,timingSafeEqual as Je}from"node:crypto";import{mkdirSync as Xe,writeFileSync as Ke,readFileSync as ie,existsSync as Ye}from"node:fs";import{join as M}from"node:path";import*as ze from"./engines/claude.js";import*as Ve from"./engines/codex.js";import*as Qe from"./engines/antigravity.js";import{pi as Ze,opencode as qe,kiro as et,copilot as tt,deepseek as nt,hermes as ot}from"./engines/cli-agents.js";import{connectorsFor as rt}from"./connectors.js";import{agentServersFor as at,resolveAgentServer as se,builtinRefusal as it,narrowBuiltinList as st}from"./agent-mcp.js";import*as ct from"./engines/custom.js";import{installService as lt,uninstallService as dt,serviceStatus as ut,restartService as ce}from"./service.js";import{skillIndex as J,listRecords as ht,readRecord as pt,readPackageFile as ft,skillsHealth as mt,quarantinedSkills as gt,clearSkillCache as X,preferredIndex as K}from"./skills.js";import{writeSkillPackage as wt,writeSkillFile as yt,deleteSkillPackage as bt,SkillWriteError as St}from"./skill-write.js";import{agentDefRoots as kt,scanAgentDefs as Tt,listAgentDefs as vt,readAgentDef as Et,planAgentExport as xt,exportAgentDef as At,agentDefsHealth as Ot,AgentDefError as Ct}from"./agent-defs.js";import{capabilityToolSpecs as Pt,runCapabilityTool as $t}from"./mcp-capabilities.js";import{createSession as Rt,deleteSession as le,getSession as de,activeSession as It,relayToolCall as Nt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Dt,isDefaultWorkdir as _t,resolveWorkdir as Ht,writeScopeNote as Mt}from"./workdir.js";import{sandbox as Y,runSandboxCli as Bt,withGrant as ue,withAgentGrant as Gt,withoutOutsideWhenCapped as Ut,grantedWriteRoots as he,acceptRefusalReport as Lt,liveProcesses as Wt,sandboxConfigFromEnv as jt}from"./sandbox.js";import{createAccessGate as Ft,chatKeyOf as Jt,chatFolders as Xt}from"./access-gate.js";import{signInDenial as Kt}from"./events/sandbox-policy.js";import{gitState as Yt,gitDelta as zt}from"./scm.js";import{listConnections as Vt,putConnection as Qt,removeConnection as Zt,runEnvFor as qt,testConnection as en,secretBackend as pe}from"./connections.js";import{worktreeFor as fe,listWorktrees as tn,removeWorktree as nn,withHook as on,WORKTREE_ROOT as me}from"./worktree.js";import{AGENT_CLIS as rn,agentAvailable as an,agentInstallDirs as sn,enrichPath as cn,enrichAgentEnv as ln,findAgentBin as dn,forgetMisses as un,primeAgentLookups as hn,resolveCommand as ge,isCompiledBinary as pn}from"./env.js";import"./sanitize.js";import{checkForUpdate as fn,selfUpdate as we,isEmbedded as ye}from"./update.js";import{callLocalMcp as mn,localMcpStatus as gn,signInLocalMcp as wn,signInStatusLocalMcp as yn}from"./mcp-local.js";import{assertPublicHttpUrl as be,assertPublicWebUrl as Se}from"./ssrf.js";import{startRun as ke,endRun as z,cancelRun as bn,cancelAll as Sn}from"./runs.js";import{closeWarmPools as kn,warmStatus as Tn}from"./warm.js";import{SESSION_AGENTS as Te,listSessions as vn,readSession as En,adoptSession as xn,catchUp as An}from"./agent-sessions.js";import{agentContext as On}from"./agent-context.js";import{normalizeThread as ve}from"./events/agent-thread.js";import{portClashPlan as Cn,serviceManagerOf as Pn,STANDBY_POLL_MS as $n}from"./events/service-standby.js";import{holdThread as Ee}from"./threads.js";import{oneReply as Rn}from"./one-reply.js";import{createSnapshot as In}from"./health-snapshot.js";import{CompatError as P,anthropicError as V,anthropicStream as Nn,chatCompletionStream as Dn,completionStream as _n,createAnthropicMessage as Hn,createChatCompletion as Mn,createCompletion as Bn,createResponse as Gn,openAIError as S,parseAnthropicMessage as Un,parseChatCompletion as Ln,parseCompletion as Wn,parseResponse as jn,responseStream as Fn}from"./api-compat.js";import{callerTrust as Jn,isPaired as I,parseExtensionIds as Xn,capRunOptions as Kn,engineHonoursReach as Yn,createPairingStore as zn,formatPairingCode as Vn}from"./pii/trust.js";const y="0.53.1",v=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:ze,label:"Claude Code"},codex:{engine:Ve,label:"Codex"},antigravity:{engine:Qe,label:"Antigravity",tools:!1},pi:{engine:Ze,label:"Pi"},opencode:{engine:qe,label:"OpenCode"},hermes:{engine:ot,label:"Hermes"},kiro:{engine:et,label:"Kiro"},copilot:{engine:tt,label:"GitHub Copilot"},deepseek:{engine:nt,label:"DeepSeek Harness"},custom:{engine:ct,label:"Custom",hidden:!0}},Qn=Xn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Jn({origin:n.headers.origin||"",hasToken:Ce(n),extensionIds:Qn})),n.chatpanelTrust}function Zn(n,e){const t=n.headers.origin||"",r=ae(t);e.setHeader("Access-Control-Allow-Origin",r?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 Q=new Set(["127.0.0.1","localhost","::1"]);function qn(n){if(!Q.has(v))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return Q.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let x="";function eo(){try{Ye(D)&&(x=ie(D,"utf8").trim()),x||(x=je(32).toString("hex"),Xe(M(O.homedir(),".chatpanel"),{recursive:!0}),Ke(D,x,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=zn({random:()=>Fe(0,1e6)/1e6});function to(n){if(!x)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 no(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=xe.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:x})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function oo(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ae(){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:x},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function Oe(n,e,t){try{const r=await Ae(),o=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function Ce(n){if(!x)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 r=Buffer.from(t),o=Buffer.from(x);return r.length===o.length&&Je(r,o)}const ro=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"]),ao=new Set(["/debug"]),io=n=>ao.has(n),so=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function co(n,e){if(!qn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ae(t))return"forbidden origin";const r=n.method==="POST"&&ro.has(e)||n.method==="GET"&&io(e)||so(n.method,e);return r&&!(Le(t)||Ce(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!uo.has(e)?lo:null}const Pe=()=>ye()?"chatpanel-gateway pair":"chatpanel-bridge pair",lo=`forbidden: this client is not paired with the bridge — run \`${Pe()}\` and enter the code in ChatPanel Settings`,uo=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Z(n,e,t){const r=N(n),o=Gt(e,Ut(Kn(t,r)));if(!Yn(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":`pair this client (${Pe()})`} to use ${e}`};const a=o.reach,c=I(r)?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:o,note:c}}async function $e(n,e,t){const r=e?.message||String(e);try{const o=await Y().status(),a=!!(o.enabled&&o.runtime)&&t?.outside!==!0,c=Kt(`${r}
|
|
3
|
+
${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:E[n]?.label||n||"This agent"});if(c)return c.line}catch{}return r}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 r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}const Re=In({compute:ho});async function ho(){await hn();const n=await Promise.all(Object.entries(E).filter(([,a])=>!a.hidden).map(async([a,{engine:c,label:l,tools:s}])=>{const d=await c.available().catch(f=>({ok:!1,reason:String(f?.message||f)})),p=await rt(a).catch(()=>[]),w=await at(a,{available:d.ok}).catch(()=>[]);return{id:a,label:l,available:d.ok,reason:d.reason,connectors:p,...w.length?{mcpServers:w}:{},...s===!1?{tools:!1}:{}}})),e=ye()?{current:y,updateAvailable:!1,embedded:"gateway"}:await fn(y).catch(()=>({current:y,updateAvailable:!1})),t=await mt().catch(()=>null),r=await Ot().catch(()=>null),o=await Y().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:r,sandboxStatus:o}}async function po(n,{fresh:e=!1}={}){e&&un();const{at:t,value:{agents:r,update:o,skills:a,agentDefs:c,sandboxStatus:l}}=await Re.get({fresh:e});i(n,200,{ok:!0,version:y,agents:r,update:o,checkedAt:t,workspace:Dt,sandbox:l,localMcp:gn(),processes:Wt(),worktrees:me,secretBackend:pe(),warm:Tn(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...c?{agentDefs:c}:{}})}async function fo(n,e,t,r={}){const o=await J({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:ht(K(o,r)),problems:o.problems})}async function mo(n,e,t){i(n,200,{ok:!0,quarantined:await gt(e,t)})}async function go(n,e,t,r,o={}){const a=pt(K(await J({extraDirs:t,workdir:r}),o),e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function wo(n,e,t,r,o,a={}){const c=await ft(K(await J({extraDirs:r,workdir:o}),a),e,t);if(c.error)return i(n,c.error==="unknown skill"?404:400,{ok:!1,error:c.error});i(n,200,{ok:!0,...c})}async function yo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{const r=await wt({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return X(),i(e,200,r)}catch(r){return i(e,q(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function bo(n,e,t,r){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await yt({name:t,path:r,text:o?.text??""});return X(),i(e,200,a)}catch(a){return i(e,q(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function So(n,e){try{const t=await bt({name:e});return X(),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 St?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Ie(n,e){return Tt({roots:kt(process.env,O.homedir(),n,e)})}async function ko(n,e,t){const{index:r,quarantined:o,problems:a}=await Ie(e,t);i(n,200,{ok:!0,agents:vt(r),...o.length?{quarantined:o.map(c=>({id:c.agent.id,path:c.relPath,source:c.source,verdict:c.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function To(n,e,t,r){const{index:o}=await Ie(t,r),a=Et(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function vo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{return i(e,200,{ok:!0,...await xt({agent:t?.agent,to:t?.to})})}catch(r){return i(e,Ne(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function Eo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{return i(e,200,await At({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(r){return i(e,Ne(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function Ne(n){if(n instanceof Ct){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function xo(){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 De(n,e=""){const t=await xo();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,S(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function Ao(n){try{const e=await we(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>ce(),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(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=E[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=Z(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.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 c=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,s=
|
|
5
|
+
`)};let c=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,s=ke(l),d={signal:s.signal,abort:()=>s.cancel("client")},p=()=>{c=!0,s.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const w=h=>{c||a(h)};a({type:"run",id:l}),o.note&&a({type:"status",text:o.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(f=await fe({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),z(l),e.writableEnded||e.end();return}}const _=f?f.path:Ht(t.options?.workingDir),W=Jt(t.agent,t.options),te=W?Xt(W):[];te.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...te])]}});let C=null;{const h=_,T=!!f||!_t(t.options?.workingDir),g=Mt(t.agent,t.options?.permissionMode,h,he(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 Yt(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}=qt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=on(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=Rt(w,t.pageTools?.specs||[]),b.permissionSession=R,t.pageTools?.specs?.length&&(b.mcp={url:`http://${v}:${k}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const Ge=jt();let ne=b.sandbox||null;F&&Ge.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&b.sandbox?.outside!==!0&&(b.accessGate=Ft({agent:t.agent,label:E[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>he(_,{grant:ne})}));try{const h=Rn(w),T=(g,H)=>ue(g.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:H,options:g,images:Array.isArray(t.images)?t.images:[]},h.emit,{signal:d.signal}));await Ee(t.agent,b,d.signal,async()=>{await T(b,t.system||"");let g=b;for(let H=0;H<2&&b.accessGate?.restart().length&&!d.signal.aborted;H++){const oe=b.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...oe])]}},ne=g.sandbox;const re=oe.map(Ue=>b.accessGate.short(Ue)).join(", ");h.seam(),w({type:"status",text:`Restarted with write access to ${re} — carrying on`}),await T(g,`${t.system||""}
|
|
6
6
|
|
|
7
|
-
[ChatPanel] The person has just allowed writing in ${re}, 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 $e(t.agent,h,b.sandbox)})}finally{if(!c){const h=await zt(_,C).catch(()=>null);h&&w({type:"scm",phase:"after",...h})}
|
|
7
|
+
[ChatPanel] The person has just allowed writing in ${re}, 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 $e(t.agent,h,b.sandbox)})}finally{if(!c){const h=await zt(_,C).catch(()=>null);h&&w({type:"scm",phase:"after",...h})}z(l),R&&le(R.id),e.writableEnded||e.end()}}async function Co(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:Vt(),secretBackend:pe()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:Qt(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return o?o[2]==="delete"?i(e,200,{ok:Zt(o[1])}):i(e,200,en(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function Po(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:me,worktrees:await tn()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/worktrees"){const o=await fe({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(t==="/worktrees/remove"){const o=await nn({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function A(n,e,t){const r=E[n.agent];if(!r||r.hidden)throw new P(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(d=>({ok:!1,reason:d?.message||String(d)}));if(!o.ok)throw new P(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,c=ke(a),l=()=>c.cancel("disconnected");t.on("close",l);let s="";try{return await ue(n.options?.sandbox,()=>Ee(n.agent,n.options,c.signal,()=>r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},d=>{d?.type==="delta"&&d.text?(s+=d.text,e(d.text)):d?.type==="done"&&d.text&&!s&&(s=d.text,e(d.text))},{signal:c.signal}))),s}catch(d){throw d instanceof Error&&!(d instanceof P)&&(d.message=await $e(n.agent,d,n.options?.sandbox)),d}finally{t.off("close",l),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
9
|
`)}function U(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
10
10
|
data: ${JSON.stringify(t)}
|
|
11
11
|
|
|
12
|
-
`)}async function L(n,e,t,r){try{const o=t(await m(n)),a=Z(n,o.agent,o.options||{});if(a.error)throw new P(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${o.message}`):o)),null}}async function $o(n,e){const t=await L(n,e,Un,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Hn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Nn(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Ro(n,e){const t=await L(n,e,Ln,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Mn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Dn(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Io(n,e){const t=await L(n,e,Wn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Bn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=jn(t.requestedModel,o=>U(e,o.type,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...S(o)};U(e,"error",a)}e.end()}async function No(n,e){const t=await L(n,e,Gn,V);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,_n(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,V(o))}G(e);const r=In(t.requestedModel,(o,a)=>U(e,o,a));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",V(o))}e.end()}async function Do(n,e){let t={};try{t=await m(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?yn(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function _e(n,e,t){let r;try{r=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?le(t):Rt(),a=s=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:s})},c=(s,d)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:s,message:d}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:y}});const l=Ct();if(r.method==="tools/list"){const s=o?o.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...l,...s]})}if(r.method==="tools/call"){const s=await Pt(r.params?.name,r.params?.arguments||{});if(s)return a(s);if(!o)return c(-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 It(o,r.params?.name,r.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return c(-32601,`Method not found: ${r.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 r=t.server||{},o=t.message;if(!r.command&&!r.from||!o)return i(e,400,{error:"need server.command (or server.from) and message"});try{let a;if(r.from){if(a=await ie(r),a.builtin&&o.method==="tools/call"){const l=await at(a.builtin,o);if(l)return i(e,200,{jsonrpc:"2.0",id:o.id??null,result:{content:[{type:"text",text:`Refused: ${l}`}],isError:!0}})}}else a={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};let c=await fn(a,o);return a.builtin&&o.method==="tools/list"&&(c=it(a.builtin,c)),o.id==null?(e.writeHead(202),e.end()):i(e,200,c)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Ho(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t.server||{};if(!r.command&&!r.from)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});try{const o=r.from?await ie(r):{key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};return i(e,200,t.status?wn(o):await gn(o))}catch(o){return i(e,200,{state:"failed",error:String(o?.message||o)})}}async function Mo(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:a}=t||{};if(!r||!a)return i(e,400,{error:"need url and message"});let c;try{c=ye(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const l={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,w]of Object.entries(o)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(l[p]=String(w))}const s=new AbortController,d=setTimeout(()=>s.abort(),3e4);try{const p=await fetch(c.href,{method:"POST",headers:l,body:JSON.stringify(a),redirect:"follow",signal:s.signal});try{p.url&&ye(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 ${c.host}: ${w}`})}finally{clearTimeout(d)}}const He=256*1024,Bo=5,Go=8e3;async function Uo(n){let e=be(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Go);try{for(let o=0;o<=Bo;o++){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=be(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 c=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(c)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:jo(await Lo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Lo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,He);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:c}=await e.read();if(a||(o+=c.byteLength,r+=t.decode(c,{stream:!0}),/<\/title\s*>/i.test(r)||o>=He))break}}finally{try{await e.cancel()}catch{}}return r}function Wo(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 jo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Wo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Fo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await Uo(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Jo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=le(t.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Xo(n,e){let t;try{t=await m(n)}catch(s){return i(e,400,{error:"Bad JSON: "+s.message})}const r=x[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=t.model||"",c=Z(n,t.agent,{model:a});if(c.error)return i(e,403,{error:c.error});const l=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let s="";return typeof r.engine.complete=="function"?s=await r.engine.complete({prompt:o,system:l,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:l,options:c.options},d=>{d.type==="delta"?s+=d.text||"":d.type==="done"&&d.text&&(s+=d.text)}),i(e,200,{text:(s||"").trim()})}catch(s){return i(e,502,{error:s?.message||String(s)})}}async function Ko(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=x[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function zo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(t.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=me(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}async function Yo(n,e,t){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(r?.agent||"");if(!ke.includes(o))return i(e,404,{error:`${o||"that agent"} keeps no sessions Chap can read (it can: ${ke.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await Tn(o,{limit:r.limit})});if(t==="/agent-sessions/read"){const a=await vn(o,String(r.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=Te({id:r.thread?.id??r.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const c=await xn(o,String(r.id||""),a.id);return c?i(e,200,{session:c}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=Te({id:r.thread?.id??r.thread});return a?i(e,200,await En(o,a.id,Array.isArray(r.messages)?r.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 ee=Le(async(n,e)=>{if(Zn(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 r=co(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return po(e,{fresh:t.searchParams.get("fresh")==="1"});const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"",c={agent:t.searchParams.get("agent")||"",source:t.searchParams.get("source")||""};if(n.method==="GET"&&t.pathname==="/skills")return fo(e,o,a,c);if(n.method==="POST"&&t.pathname==="/agent-context"){const l=await m(n).catch(()=>({})),s=l?.options&&typeof l.options=="object"?l.options:{},d={...s.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof s.permissionMode=="string"?{permissionMode:s.permissionMode}:{},...typeof s.workingDir=="string"&&s.workingDir?{workingDir:s.workingDir}:{},...typeof s.model=="string"&&s.model?{model:s.model}:{}};return i(e,200,await An({agent:typeof l?.agent=="string"?l.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return mo(e,o,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return ko(e,o,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return vo(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return xo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return To(e,decodeURIComponent(t.pathname.slice(12)),o,a);if(n.method==="POST"&&t.pathname==="/skills")return yo(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?n.method==="DELETE"?So(e,decodeURIComponent(l)):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"}):bo(n,e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?go(e,decodeURIComponent(l),o,a,c):wo(e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)),o,a,c)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Co(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Po(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return De(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return De(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const l=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:y,agents:Object.fromEntries(on.map(s=>[s,l?ln(s)||me(s)?.kind||null:rn(s)])),...l?{home:O.homedir(),path:process.env.PATH,installDirs:an(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Yo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/pair")return no(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return to(e);if(n.method==="POST"&&t.pathname==="/whoami")return oo(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return $o(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Ro(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return Io(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return No(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return _e(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const l=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return _e(n,e,l);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return ce(l),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return Oe(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return Oe(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Do(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Jo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let l=null;try{l=await m(n)}catch{l=null}const s=Ut(l||{});return e.writeHead(s?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 Ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Mo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Fo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Xo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Ko(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return zo(n,e);if(n.method==="POST"&&t.pathname==="/update")return Ao(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Vo(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},c=async()=>{if(!r){for(r=!0;t.length;){const l=t.shift();let s;try{s=JSON.parse(l)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:l});if(s.id==null)continue;const p=(await d.text()).trim();p&&process.stdout.write(p+`
|
|
12
|
+
`)}async function L(n,e,t,r){try{const o=t(await m(n)),a=Z(n,o.agent,o.options||{});if(a.error)throw new P(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${o.message}`):o)),null}}async function $o(n,e){const t=await L(n,e,Ln,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Mn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Dn(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Ro(n,e){const t=await L(n,e,Wn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Bn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=_n(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Io(n,e){const t=await L(n,e,jn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Gn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Fn(t.requestedModel,o=>U(e,o.type,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...S(o)};U(e,"error",a)}e.end()}async function No(n,e){const t=await L(n,e,Un,V);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Hn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,V(o))}G(e);const r=Nn(t.requestedModel,(o,a)=>U(e,o,a));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",V(o))}e.end()}async function Do(n,e){let t={};try{t=await m(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?bn(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function _e(n,e,t){let r;try{r=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?de(t):It(),a=s=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:s})},c=(s,d)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:s,message:d}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:y}});const l=Pt();if(r.method==="tools/list"){const s=o?o.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...l,...s]})}if(r.method==="tools/call"){const s=await $t(r.params?.name,r.params?.arguments||{});if(s)return a(s);if(!o)return c(-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 Nt(o,r.params?.name,r.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return c(-32601,`Method not found: ${r.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 r=t.server||{},o=t.message;if(!r.command&&!r.from||!o)return i(e,400,{error:"need server.command (or server.from) and message"});try{let a;if(r.from){if(a=await se(r),a.builtin&&o.method==="tools/call"){const l=await it(a.builtin,o);if(l)return i(e,200,{jsonrpc:"2.0",id:o.id??null,result:{content:[{type:"text",text:`Refused: ${l}`}],isError:!0}})}}else a={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};let c=await mn(a,o);return a.builtin&&o.method==="tools/list"&&(c=st(a.builtin,c)),o.id==null?(e.writeHead(202),e.end()):i(e,200,c)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Ho(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t.server||{};if(!r.command&&!r.from)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});try{const o=r.from?await se(r):{key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};return i(e,200,t.status?yn(o):await wn(o))}catch(o){return i(e,200,{state:"failed",error:String(o?.message||o)})}}async function Mo(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:a}=t||{};if(!r||!a)return i(e,400,{error:"need url and message"});let c;try{c=be(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const l={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,w]of Object.entries(o)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(l[p]=String(w))}const s=new AbortController,d=setTimeout(()=>s.abort(),3e4);try{const p=await fetch(c.href,{method:"POST",headers:l,body:JSON.stringify(a),redirect:"follow",signal:s.signal});try{p.url&&be(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 ${c.host}: ${w}`})}finally{clearTimeout(d)}}const He=256*1024,Bo=5,Go=8e3;async function Uo(n){let e=Se(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Go);try{for(let o=0;o<=Bo;o++){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=Se(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 c=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(c)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:jo(await Lo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Lo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,He);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:c}=await e.read();if(a||(o+=c.byteLength,r+=t.decode(c,{stream:!0}),/<\/title\s*>/i.test(r)||o>=He))break}}finally{try{await e.cancel()}catch{}}return r}function Wo(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 jo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Wo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Fo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await Uo(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Jo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=de(t.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Xo(n,e){let t;try{t=await m(n)}catch(s){return i(e,400,{error:"Bad JSON: "+s.message})}const r=E[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=t.model||"",c=Z(n,t.agent,{model:a});if(c.error)return i(e,403,{error:c.error});const l=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let s="";return typeof r.engine.complete=="function"?s=await r.engine.complete({prompt:o,system:l,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:l,options:c.options},d=>{d.type==="delta"?s+=d.text||"":d.type==="done"&&d.text&&(s+=d.text)}),i(e,200,{text:(s||"").trim()})}catch(s){return i(e,502,{error:s?.message||String(s)})}}async function Ko(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=E[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Yo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(t.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=ge(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}async function zo(n,e,t){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(r?.agent||"");if(!Te.includes(o))return i(e,404,{error:`${o||"that agent"} keeps no sessions Chap can read (it can: ${Te.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await vn(o,{limit:r.limit})});if(t==="/agent-sessions/read"){const a=await En(o,String(r.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=ve({id:r.thread?.id??r.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const c=await xn(o,String(r.id||""),a.id);return c?i(e,200,{session:c}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=ve({id:r.thread?.id??r.thread});return a?i(e,200,await An(o,a.id,Array.isArray(r.messages)?r.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 ee=We(async(n,e)=>{if(Zn(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 r=co(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return po(e,{fresh:t.searchParams.get("fresh")==="1"});const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"",c={agent:t.searchParams.get("agent")||"",source:t.searchParams.get("source")||""};if(n.method==="GET"&&t.pathname==="/skills")return fo(e,o,a,c);if(n.method==="POST"&&t.pathname==="/agent-context"){const l=await m(n).catch(()=>({})),s=l?.options&&typeof l.options=="object"?l.options:{},d={...s.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof s.permissionMode=="string"?{permissionMode:s.permissionMode}:{},...typeof s.workingDir=="string"&&s.workingDir?{workingDir:s.workingDir}:{},...typeof s.model=="string"&&s.model?{model:s.model}:{}};return i(e,200,await On({agent:typeof l?.agent=="string"?l.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return mo(e,o,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return ko(e,o,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return vo(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 To(e,decodeURIComponent(t.pathname.slice(12)),o,a);if(n.method==="POST"&&t.pathname==="/skills")return yo(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?n.method==="DELETE"?So(e,decodeURIComponent(l)):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"}):bo(n,e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?go(e,decodeURIComponent(l),o,a,c):wo(e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)),o,a,c)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Co(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Po(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return De(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return De(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const l=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:y,agents:Object.fromEntries(rn.map(s=>[s,l?dn(s)||ge(s)?.kind||null:an(s)])),...l?{home:O.homedir(),path:process.env.PATH,installDirs:sn(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return zo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/pair")return no(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return to(e);if(n.method==="POST"&&t.pathname==="/whoami")return oo(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return $o(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Ro(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return Io(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return No(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return _e(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const l=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return _e(n,e,l);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return le(l),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return Oe(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return Oe(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Do(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Jo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let l=null;try{l=await m(n)}catch{l=null}const s=Lt(l||{});return e.writeHead(s?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 Ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Mo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Fo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Xo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Ko(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Yo(n,e);if(n.method==="POST"&&t.pathname==="/update")return Ao(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Vo(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},c=async()=>{if(!r){for(r=!0;t.length;){const l=t.shift();let s;try{s=JSON.parse(l)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:l});if(s.id==null)continue;const p=(await d.text()).trim();p&&process.stdout.write(p+`
|
|
13
13
|
`)}catch(d){s.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:s.id,error:{code:-32e3,message:String(d?.message||d)}})+`
|
|
14
14
|
`)}}r=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",l=>{e+=l;let s;for(;(s=e.indexOf(`
|
|
15
|
-
`))>=0;){const d=e.slice(0,s).trim();e=e.slice(s+1),d&&t.push(d)}c()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Qo(){
|
|
15
|
+
`))>=0;){const d=e.slice(0,s).trim();e=e.slice(s+1),d&&t.push(d)}c()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Qo(){cn(),ln(),eo();let n=!1;ee.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 r=!!(t?.version&&Array.isArray(t.agents)),o=Cn({name:"bridge",self:y,holder:r?{ours:r,version:t.version}:null,managedBy:Pn(process.env),port:k});if(o.action==="standby"||n&&!t){if(!n)for(const a of o.lines)u("info",a);n=!0,setTimeout(()=>ee.listen(k,v),$n);return}if(r)for(const a of o.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=Sn("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const r=kn("shutdown");r&&u("info",`shutdown: closed ${r} warm agent process${r===1?"":"es"}`),Y().close(),setTimeout(()=>process.exit(0),t||r?300:0).unref?.(),!t&&!r&&process.exit(0)});ee.listen(k,v,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${v}:${k}`),Re.warm(),Q.has(v)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${v}. 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:r}]of Object.entries(E)){if(r)continue;const o=await e.available().catch(()=>({ok:!1}));u("info",` ${o.ok?"✓":"✕"} ${t}${o.ok?"":" — "+(o.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),Ae().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 Zo(){console.log(`ChatPanel Bridge v${y}
|
|
16
16
|
|
|
17
17
|
Usage:
|
|
18
18
|
chatpanel-bridge start the bridge (foreground) on ${v}:${k}
|
|
@@ -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 qo(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return Zo(),!0;if(e("--version","-v"))return console.log(y),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=
|
|
27
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function qo(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return Zo(),!0;if(e("--version","-v"))return console.log(y),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=ie(D,"utf8").trim()}catch{}const r=`http://${v}:${k}`;try{if(!t)throw new Error(`no token at ${D} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${Vn(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return Bt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{lt(),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{dt(),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=ut()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const Me=process.argv.indexOf("--mcp-stdio"),Be=process.argv.indexOf("--sandbox-host");if(Be>=0){const{runSandboxHost:n}=await import("./sandbox-host.js");await n(process.argv[Be+1],{compiled:pn()})}else if(Me>=0){const n=process.argv[Me+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Vo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await we(y);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),ce()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():qo()||Qo();
|