@chatpanel/bridge 0.13.3 → 0.13.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.13.3",
3
+ "version": "0.13.4",
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": [
package/src/server.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as fe}from"node:http";import P from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ce from"./engines/antigravity.js";import{pi as Ee,opencode as Oe,kiro as Ae,copilot as Pe,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{gitState as Ye,gitDelta as Qe}from"./scm.js";import{listConnections as Ze,putConnection as qe,removeConnection as et,runEnvFor as tt,testConnection as nt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as rt,removeWorktree as ot,withHook as at,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as it,enrichPath as st,enrichAgentEnv as ct,findAgentBin as ee,resolveCommand as lt}from"./env.js";import"./sanitize.js";import{checkForUpdate as dt,selfUpdate as te,isEmbedded as ut}from"./update.js";import{callLocalMcp as ht}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as pt,cancelAll as mt}from"./runs.js";import{closeWarmPools as ft,warmStatus as gt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as yt,chatCompletionStream as wt,completionStream as bt,createAnthropicMessage as St,createChatCompletion as kt,createCompletion as Tt,createResponse as vt,openAIError as w,parseAnthropicMessage as Ct,parseChatCompletion as Et,parseCompletion as Ot,parseResponse as At,responseStream as Pt}from"./api-compat.js";import{callerTrust as xt,isPaired as $,parseExtensionIds as $t,capRunOptions as It,engineHonoursReach as Nt,createPairingStore as Rt,formatPairingCode as _t}from"./pii/trust.js";const g="0.13.3",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ce,label:"Antigravity",tools:!1},pi:{engine:Ee,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Ae,label:"Kiro"},copilot:{engine:Pe,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const Ht=$t(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(t){return t.chatpanelTrust||(t.chatpanelTrust=xt({origin:t.headers.origin||"",hasToken:le(t),extensionIds:Ht})),t.chatpanelTrust}function Mt(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function Bt(t,e){const n=t.headers.origin||"",o=ae(n);e.setHeader("Access-Control-Allow-Origin",o?n||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const W=new Set(["127.0.0.1","localhost","::1"]);function Gt(t){if(!W.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(n)}const N=_(P.homedir(),".chatpanel","bridge-token");let S="";function Ut(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(P.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(t){d("error",`could not initialise bridge token: ${t?.message||t}`)}}const ie=Rt({random:()=>ye(0,1e6)/1e6});function Dt(t){if(!S)return i(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),i(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Lt(t,e){let n;try{n=await f(t)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(n?.code);return o.ok?(d("info",`paired a ${I(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(t)} caller`),i(e,403,{error:o.reason}))}function jt(t,e){const n=I(t);return i(e,200,{ok:!0,trust:n,paired:$(n),version:g})}let H=null;async function se(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(P.homedir(),".chatpanel"),dataDir:_(P.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(t,e,n){try{const o=await se(),r=t.method==="POST"?await f(t):{};if(n==="status")return i(e,200,await o.status());if(n==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return n==="pair"?i(e,200,await o.pair()):n==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):n==="settings"?i(e,200,await o.update(r)):n==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function le(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const o=Buffer.from(n),r=Buffer.from(S);return o.length===r.length&&we(o,r)}const Wt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Ft=new Set(["/debug"]),Jt=t=>Ft.has(t);function zt(t,e){if(!Gt(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!ae(n))return"forbidden origin";const o=t.method==="POST"&&Wt.has(e)||t.method==="GET"&&Jt(e);return o&&!(Mt(n)||le(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(t))&&!Vt.has(e)?Kt:null}const Kt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(t,e,n){const o=I(t),r=It(n,o);if(!Nt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=r.reach,l=$(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:r,note:l}}function i(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function f(t){return new Promise((e,n)=>{let o="";t.on("data",r=>{o+=r,o.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){n(r)}}),t.on("error",n)})}async function Xt(t){const e=await Promise.all(Object.entries(C).filter(([,r])=>!r.hidden).map(async([r,{engine:a,label:l,tools:m}])=>{const s=await a.available().catch(u=>({ok:!1,reason:String(u?.message||u)})),c=await Ie(r).catch(()=>[]);return{id:r,label:l,available:s.ok,reason:s.reason,connectors:c,...m===!1?{tools:!1}:{}}})),n=ut()?{current:g,updateAvailable:!1,embedded:"gateway"}:await dt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ue().catch(()=>null);i(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ze,worktrees:q,secretBackend:Q(),warm:gt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Yt(t,e){const{index:n,problems:o}=await D({extraDirs:e});i(t,200,{ok:!0,skills:Me(n),problems:o})}async function Qt(t,e){i(t,200,{ok:!0,quarantined:await De(e)})}async function Zt(t,e,n){const{index:o}=await D({extraDirs:n}),r=Be(o,e);if(!r)return i(t,404,{ok:!1,error:"unknown skill"});i(t,200,{ok:!0,skill:r})}async function qt(t,e,n,o){const{index:r}=await D({extraDirs:o}),a=await Ge(r,e,n);if(a.error)return i(t,a.error==="unknown skill"?404:400,{ok:!1,error:a.error});i(t,200,{ok:!0,...a})}async function en(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function de(t,e=""){const n=await en();if(e){const o=n.find(r=>r.id===e);return o?i(t,200,o):i(t,404,w(new x(`Model "${e}" not found`,404,"model")))}return i(t,200,{object:"list",data:n})}async function tn(t){try{const e=await te(g);i(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(t,400,{ok:!1,error:String(e?.message||e)})}}async function nn(t,e){let n;try{n=await f(t)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const o=C[n.agent];if(!o)return i(e,404,{error:`Unknown agent "${n.agent}"`});const r=F(t,n.agent,n.options||{});if(r.error)return i(e,403,{error:r.error});n.options=r.options,Array.isArray(n.images)&&n.images.length&&d("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
2
+ import{createServer as fe}from"node:http";import A from"node:os";import{randomBytes as ge,randomInt as ye,timingSafeEqual as we}from"node:crypto";import{mkdirSync as be,writeFileSync as Se,readFileSync as K,existsSync as ke}from"node:fs";import{join as _}from"node:path";import*as Te from"./engines/claude.js";import*as ve from"./engines/codex.js";import*as Ce from"./engines/antigravity.js";import{pi as Ee,opencode as Oe,kiro as Pe,copilot as Ae,deepseek as xe,hermes as $e}from"./engines/cli-agents.js";import{connectorsFor as Ie}from"./connectors.js";import*as Ne from"./engines/custom.js";import{installService as Re,uninstallService as _e,serviceStatus as He,restartService as V}from"./service.js";import{skillIndex as D,listRecords as Me,readRecord as Be,readPackageFile as Ge,skillsHealth as Ue,quarantinedSkills as De}from"./skills.js";import{capabilityToolSpecs as Le,runCapabilityTool as je}from"./mcp-capabilities.js";import{createSession as We,deleteSession as X,getSession as Y,activeSession as Fe,relayToolCall as Je}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ze,isDefaultWorkdir as Ke,resolveWorkdir as Ve,writeScopeNote as Xe}from"./workdir.js";import{gitState as Ye,gitDelta as Qe}from"./scm.js";import{listConnections as Ze,putConnection as qe,removeConnection as et,runEnvFor as tt,testConnection as nt,secretBackend as Q}from"./connections.js";import{worktreeFor as Z,listWorktrees as rt,removeWorktree as ot,withHook as at,WORKTREE_ROOT as q}from"./worktree.js";import{AGENT_CLIS as it,enrichPath as st,enrichAgentEnv as ct,findAgentBin as ee,resolveCommand as lt}from"./env.js";import"./sanitize.js";import{checkForUpdate as dt,selfUpdate as te,isEmbedded as ut}from"./update.js";import{callLocalMcp as ht}from"./mcp-local.js";import{assertPublicHttpUrl as ne,assertPublicWebUrl as re}from"./ssrf.js";import{startRun as oe,endRun as L,cancelRun as pt,cancelAll as mt}from"./runs.js";import{closeWarmPools as ft,warmStatus as gt}from"./warm.js";import{CompatError as x,anthropicError as j,anthropicStream as yt,chatCompletionStream as wt,completionStream as bt,createAnthropicMessage as St,createChatCompletion as kt,createCompletion as Tt,createResponse as vt,openAIError as w,parseAnthropicMessage as Ct,parseChatCompletion as Et,parseCompletion as Ot,parseResponse as Pt,responseStream as At}from"./api-compat.js";import{callerTrust as xt,isPaired as $,parseExtensionIds as $t,capRunOptions as It,engineHonoursReach as Nt,createPairingStore as Rt,formatPairingCode as _t}from"./pii/trust.js";const g="0.13.4",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Te,label:"Claude Code"},codex:{engine:ve,label:"Codex"},antigravity:{engine:Ce,label:"Antigravity",tools:!1},pi:{engine:Ee,label:"Pi"},opencode:{engine:Oe,label:"OpenCode"},hermes:{engine:$e,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:Ae,label:"GitHub Copilot"},deepseek:{engine:xe,label:"DeepSeek Harness"},custom:{engine:Ne,label:"Custom",hidden:!0}};function ae(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 Ht=$t(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(n){return n.chatpanelTrust||(n.chatpanelTrust=xt({origin:n.headers.origin||"",hasToken:le(n),extensionIds:Ht})),n.chatpanelTrust}function Mt(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 Bt(n,e){const t=n.headers.origin||"",o=ae(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 W=new Set(["127.0.0.1","localhost","::1"]);function Gt(n){if(!W.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return W.has(t)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function Ut(){try{ke(N)&&(S=K(N,"utf8").trim()),S||(S=ge(32).toString("hex"),be(_(A.homedir(),".chatpanel"),{recursive:!0}),Se(N,S,{mode:384}))}catch(n){d("error",`could not initialise bridge token: ${n?.message||n}`)}}const ie=Rt({random:()=>ye(0,1e6)/1e6});function Dt(n){if(!S)return a(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ie.issue();return d("info","pairing code issued — valid for 5 minutes, one use"),a(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Lt(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=ie.claim(t?.code);return o.ok?(d("info",`paired a ${I(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(d("info",`pairing refused (${o.reason}) from ${I(n)} caller`),a(e,403,{error:o.reason}))}function jt(n,e){const t=I(n);return a(e,200,{ok:!0,trust:t,paired:$(t),version:g})}let H=null;async function se(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>d("info",e),warn:e=>d("info",e),error:e=>d("error",e)}}),H}async function ce(n,e,t){try{const o=await se(),r=n.method==="POST"?await f(n):{};if(t==="status")return a(e,200,await o.status());if(t==="connect"){const i=await o.connect(r);return a(e,200,{ok:!0,...i})}return t==="pair"?a(e,200,await o.pair()):t==="unpair"?a(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?a(e,200,await o.update(r)):t==="disconnect"?a(e,200,await o.stop({forget:!!r.forget})):a(e,404,{error:"unknown channel action"})}catch(o){return a(e,400,{error:o?.message||String(o)})}}function le(n){if(!S)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(S);return o.length===r.length&&we(o,r)}const Wt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Ft=new Set(["/debug"]),Jt=n=>Ft.has(n);function zt(n,e){if(!Gt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ae(t))return"forbidden origin";const o=n.method==="POST"&&Wt.has(e)||n.method==="GET"&&Jt(e);return o&&!(Mt(t)||le(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!$(I(n))&&!Vt.has(e)?Kt:null}const Kt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const o=I(n),r=It(t,o);if(!Nt(e,r.reach))return{error:`${$(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(o)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=r.reach,s=$(o)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:r,note:s}}function a(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}async function Xt(n){const e=await Promise.all(Object.entries(C).filter(([,r])=>!r.hidden).map(async([r,{engine:i,label:s,tools:u}])=>{const c=await i.available().catch(h=>({ok:!1,reason:String(h?.message||h)})),l=await Ie(r).catch(()=>[]);return{id:r,label:s,available:c.ok,reason:c.reason,connectors:l,...u===!1?{tools:!1}:{}}})),t=ut()?{current:g,updateAvailable:!1,embedded:"gateway"}:await dt(g).catch(()=>({current:g,updateAvailable:!1})),o=await Ue().catch(()=>null);a(n,200,{ok:!0,version:g,agents:e,update:t,workspace:ze,worktrees:q,secretBackend:Q(),warm:gt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...o?{skills:o}:{}})}async function Yt(n,e,t){const{index:o,problems:r}=await D({extraDirs:e,workdir:t});a(n,200,{ok:!0,skills:Me(o),problems:r})}async function Qt(n,e,t){a(n,200,{ok:!0,quarantined:await De(e,t)})}async function Zt(n,e,t,o){const{index:r}=await D({extraDirs:t,workdir:o}),i=Be(r,e);if(!i)return a(n,404,{ok:!1,error:"unknown skill"});a(n,200,{ok:!0,skill:i})}async function qt(n,e,t,o,r){const{index:i}=await D({extraDirs:o,workdir:r}),s=await Ge(i,e,t);if(s.error)return a(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(n,200,{ok:!0,...s})}async function en(){return(await Promise.all(Object.entries(C).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 en();if(e){const o=t.find(r=>r.id===e);return o?a(n,200,o):a(n,404,w(new x(`Model "${e}" not found`,404,"model")))}return a(n,200,{object:"list",data:t})}async function tn(n){try{const e=await te(g);a(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){a(n,400,{ok:!1,error:String(e?.message||e)})}}async function nn(n,e){let t;try{t=await f(n)}catch(p){return a(e,400,{error:"Bad JSON: "+p.message})}const o=C[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=F(n,t.agent,t.options||{});if(r.error)return a(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&d("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 i=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
3
3
 
4
- `)};let l=!1;const m=`run_${Math.random().toString(36).slice(2,10)}`,s=oe(m),c={signal:s.signal,abort:()=>s.cancel("client")},u=()=>{l=!0,s.cancel("disconnected")};t.on("close",u),e.on("close",u),e.on("error",u);const b=h=>{l||a(h)};a({type:"run",id:m}),r.note&&a({type:"status",text:r.note});let p=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const h=n.options.workspace;if(p=await Z({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),p.error){a({type:"error",error:`workspace: ${p.error}`}),L(m),e.writableEnded||e.end();return}}const J=p?p.path:Ve(n.options?.workingDir);let E=null;{const h=J,O=!!p||!Ke(n.options?.workingDir),y=Xe(n.agent,n.options?.permissionMode,h);a({type:"workdir",path:h,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${h}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await Ye(h),E&&a({type:"scm",phase:"before",...E})}let U=null;if(E||p){const h=Array.isArray(n.options?.grants)?n.options.grants:[],{env:O,connection:y}=tt({remote:E?.remote||null,grants:h,branch:p?.branch||null,connectionId:n.options?.connectionId||null});U=at(O),p&&a({type:"workspace",path:p.path,branch:p.branch,base:p.base,created:p.created,repo:p.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${p?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z={...n.options||{},...p?{workingDir:p.path}:{},...U?{runEnv:U}:{}};let R=null;n.pageTools?.specs?.length&&(R=We(b,n.pageTools.specs),z.mcp={url:`http://${k}:${v}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs});try{await o.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:z,images:Array.isArray(n.images)?n.images:[]},b,{signal:c.signal})}catch(h){d("error",`${n.agent} chat failed: ${h?.message||h}`),a({type:"error",error:h?.message||String(h)})}finally{if(!l){const h=await Qe(J,E).catch(()=>null);h&&b({type:"scm",phase:"after",...h})}L(m),R&&X(R.id),e.writableEnded||e.end()}}async function rn(t,e,n){if(t.method==="GET"&&n==="/connections")return i(e,200,{ok:!0,connections:Ze(),secretBackend:Q()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await f(t);if(n==="/connections")try{return i(e,200,{ok:!0,connection:qe(o.connection||o,{token:o.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return r?r[2]==="delete"?i(e,200,{ok:et(r[1])}):i(e,200,nt(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function on(t,e,n){if(t.method==="GET"&&n==="/worktrees")return i(e,200,{ok:!0,root:q,worktrees:await rt()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await f(t);if(n==="/worktrees"){const r=await Z({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return i(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(n==="/worktrees/remove"){const r=await ot({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return i(e,r.ok?200:400,r)}return i(e,404,{error:"Not found"})}async function T(t,e,n){const o=C[t.agent];if(!o||o.hidden)throw new x(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const r=await o.engine.available().catch(c=>({ok:!1,reason:c?.message||String(c)}));if(!r.ok)throw new x(r.reason||`${t.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,l=oe(a),m=()=>l.cancel("disconnected");n.on("close",m);let s="";try{return await o.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},c=>{c?.type==="delta"&&c.text?(s+=c.text,e(c.text)):c?.type==="done"&&c.text&&!s&&(s=c.text,e(c.text))},{signal:l.signal}),s}finally{n.off("close",m),L(a)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function A(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
4
+ `)};let s=!1;const u=`run_${Math.random().toString(36).slice(2,10)}`,c=oe(u),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};n.on("close",h),e.on("close",h),e.on("error",h);const b=p=>{s||i(p)};i({type:"run",id:u}),r.note&&i({type:"status",text:r.note});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const p=t.options.workspace;if(m=await Z({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),m.error){i({type:"error",error:`workspace: ${m.error}`}),L(u),e.writableEnded||e.end();return}}const J=m?m.path:Ve(t.options?.workingDir);let E=null;{const p=J,O=!!m||!Ke(t.options?.workingDir),y=Xe(t.agent,t.options?.permissionMode,p);i({type:"workdir",path:p,isDefault:!O,writeScope:y||void 0}),i({type:"status",text:`Working in ${p}${O?"":" (default)"}`}),y&&i({type:"status",text:y}),E=await Ye(p),E&&i({type:"scm",phase:"before",...E})}let U=null;if(E||m){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:y}=tt({remote:E?.remote||null,grants:p,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=at(O),m&&i({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&i({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{}};let R=null;t.pageTools?.specs?.length&&(R=We(b,t.pageTools.specs),z.mcp={url:`http://${k}:${v}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs});try{await o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:z,images:Array.isArray(t.images)?t.images:[]},b,{signal:l.signal})}catch(p){d("error",`${t.agent} chat failed: ${p?.message||p}`),i({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await Qe(J,E).catch(()=>null);p&&b({type:"scm",phase:"after",...p})}L(u),R&&X(R.id),e.writableEnded||e.end()}}async function rn(n,e,t){if(n.method==="GET"&&t==="/connections")return a(e,200,{ok:!0,connections:Ze(),secretBackend:Q()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const o=await f(n);if(t==="/connections")try{return a(e,200,{ok:!0,connection:qe(o.connection||o,{token:o.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return r?r[2]==="delete"?a(e,200,{ok:et(r[1])}):a(e,200,nt(r[1],o.remote||"")):a(e,404,{error:"Not found"})}async function on(n,e,t){if(n.method==="GET"&&t==="/worktrees")return a(e,200,{ok:!0,root:q,worktrees:await rt()});if(n.method!=="POST")return a(e,405,{error:"method not allowed"});const o=await f(n);if(t==="/worktrees"){const r=await Z({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return a(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(t==="/worktrees/remove"){const r=await ot({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return a(e,r.ok?200:400,r)}return a(e,404,{error:"Not found"})}async function T(n,e,t){const o=C[n.agent];if(!o||o.hidden)throw new x(`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 x(r.reason||`${n.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,s=oe(i),u=()=>s.cancel("disconnected");t.on("close",u);let c="";try{return await o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal}),c}finally{t.off("close",u),L(i)}}function M(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function P(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5
 
6
- `)}function B(t,e,n){t.writableEnded||t.write(`event: ${e}
7
- data: ${JSON.stringify(n)}
6
+ `)}function B(n,e,t){n.writableEnded||n.write(`event: ${e}
7
+ data: ${JSON.stringify(t)}
8
8
 
9
- `)}async function G(t,e,n,o){try{const r=n(await f(t)),a=F(t,r.agent,r.options||{});if(a.error)throw new x(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new x(`Bad JSON: ${r.message}`):r)),null}}async function an(t,e){const n=await G(t,e,Et,w);if(!n)return;if(!n.stream)try{const r=await T(n,()=>{},e);return i(e,200,kt(n.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,w(r))}M(e);const o=wt(n.requestedModel,r=>A(e,r));try{await T(n,r=>o.delta(r),e),o.done()}catch(r){A(e,w(r))}A(e,"[DONE]"),e.end()}async function sn(t,e){const n=await G(t,e,Ot,w);if(!n)return;if(!n.stream)try{const r=await T(n,()=>{},e);return i(e,200,Tt(n.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,w(r))}M(e);const o=bt(n.requestedModel,r=>A(e,r));try{await T(n,r=>o.delta(r),e),o.done()}catch(r){A(e,w(r))}A(e,"[DONE]"),e.end()}async function cn(t,e){const n=await G(t,e,At,w);if(!n)return;if(!n.stream)try{const r=await T(n,()=>{},e);return i(e,200,vt(n.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,w(r))}M(e);const o=Pt(n.requestedModel,r=>B(e,r.type,r));try{await T(n,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...w(r)};B(e,"error",a)}e.end()}async function ln(t,e){const n=await G(t,e,Ct,j);if(!n)return;if(!n.stream)try{const r=await T(n,()=>{},e);return i(e,200,St(n.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,j(r))}M(e);const o=yt(n.requestedModel,(r,a)=>B(e,r,a));try{await T(n,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",j(r))}e.end()}async function dn(t,e){let n={};try{n=await f(t)||{}}catch{}const o=String(n.id||"").trim(),r=o?pt(o,"stopped"):!1;return r&&d("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function ue(t,e,n){let o;try{o=await f(t)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=n?Y(n):Fe(),a=s=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:s})},l=(s,c)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:s,message:c}});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 m=Le();if(o.method==="tools/list"){const s=r?r.specs.map(c=>({name:c.name,description:c.description,inputSchema:c.parameters||{type:"object",properties:{}}})):[];return a({tools:[...m,...s]})}if(o.method==="tools/call"){const s=await je(o.params?.name,o.params?.arguments||{});if(s)return a(s);if(!r)return l(-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 Je(r,o.params?.name,o.params?.arguments||{}))}catch(c){return a({content:[{type:"text",text:`error: ${c?.message||c}`}],isError:!0})}}return l(-32601,`Method not found: ${o.method}`)}async function un(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=n.server||{},r=n.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await ht({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd},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 hn(t,e){let n;try{n=await f(t)}catch(u){return i(e,400,{error:"Bad JSON: "+u.message})}const{url:o,headers:r,message:a}=n||{};if(!o||!a)return i(e,400,{error:"need url and message"});let l;try{l=ne(o)}catch(u){return i(e,400,{error:String(u?.message||u)})}const m={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[u,b]of Object.entries(r)){const p=u.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(p)||p.startsWith("x-"))&&(m[u]=String(b))}const s=new AbortController,c=setTimeout(()=>s.abort(),3e4);try{const u=await fetch(l.href,{method:"POST",headers:m,body:JSON.stringify(a),redirect:"follow",signal:s.signal});try{u.url&&ne(u.url)}catch(p){return i(e,400,{error:String(p?.message||p)})}const b=await u.text().catch(()=>"");return i(e,200,{status:u.status,sessionId:u.headers.get("Mcp-Session-Id")||null,contentType:u.headers.get("Content-Type")||"",body:b})}catch(u){const b=u?.name==="AbortError"?"timed out":String(u?.message||u);return i(e,502,{error:`couldn't reach MCP server ${l.host}: ${b}`})}finally{clearTimeout(c)}}const he=256*1024,pn=5,mn=8e3;async function fn(t){let e=re(t);const n=new AbortController,o=setTimeout(()=>n.abort(),mn);try{for(let r=0;r<=pn;r++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:n.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=re(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 l=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(l)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:wn(await gn(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function gn(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,he);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:l}=await e.read();if(a||(r+=l.byteLength,o+=n.decode(l,{stream:!0}),/<\/title\s*>/i.test(o)||r>=he))break}}finally{try{await e.cancel()}catch{}}return o}function yn(t){return String(t).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,n)=>{try{return String.fromCodePoint(+n)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,n)=>{try{return String.fromCodePoint(parseInt(n,16))}catch{return""}})}function wn(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?yn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function bn(t,e){let n;try{n=await f(t)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=n&&n.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await fn(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 Sn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=Y(n.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(n.id);return r?(o.pending.delete(n.id),r.resolve(n.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function kn(t,e){let n;try{n=await f(t)}catch(s){return i(e,400,{error:"Bad JSON: "+s.message})}const o=C[n.agent];if(!o)return i(e,404,{error:`Unknown agent "${n.agent}"`});const r=String(n.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=n.model||"",l=F(t,n.agent,{model:a});if(l.error)return i(e,403,{error:l.error});const m=String(n.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let s="";return typeof o.engine.complete=="function"?s=await o.engine.complete({prompt:r,system:m,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:m,options:l.options},c=>{c.type==="delta"?s+=c.text||"":c.type==="done"&&c.text&&(s+=c.text)}),i(e,200,{text:(s||"").trim()})}catch(s){return i(e,502,{error:s?.message||String(s)})}}async function Tn(t,e){let n;try{n=await f(t)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=C[n.agent];if(!o)return i(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(n.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function vn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(n.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=lt(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}const pe=fe(async(t,e)=>{if(Bt(t,e),t.method==="OPTIONS")return e.writeHead(204),e.end();let n;try{n=new URL(t.url,`http://${t.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const o=zt(t,n.pathname);if(o)return i(e,403,{error:o});try{if(t.method==="GET"&&n.pathname==="/health")return Xt(e);const r=n.searchParams.getAll("dir");if(t.method==="GET"&&n.pathname==="/skills")return Yt(e,r);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return Qt(e,r);if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const a=n.pathname.slice(8),l=a.indexOf("/file/");return l===-1?Zt(e,decodeURIComponent(a),r):qt(e,decodeURIComponent(a.slice(0,l)),decodeURIComponent(a.slice(l+6)),r)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return rn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return on(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return de(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return de(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const a=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:g,agents:Object.fromEntries(it.map(l=>[l,a?ee(l)||null:!!ee(l)])),...a?{home:P.homedir(),path:process.env.PATH}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return nn(t,e);if(t.method==="POST"&&n.pathname==="/pair")return Lt(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return Dt(e);if(t.method==="POST"&&n.pathname==="/whoami")return jt(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return an(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return sn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return cn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return ln(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return ue(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const a=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return ue(t,e,a);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return X(a),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return ce(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return ce(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return dn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return Sn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local")return un(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return hn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return bn(t,e);if(t.method==="POST"&&n.pathname==="/complete")return kn(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return Tn(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return vn(t,e);if(t.method==="POST"&&n.pathname==="/update")return tn(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function d(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Cn(t){let e="";const n=[];let o=!1,r=!1;const a=()=>{r&&!o&&!n.length&&process.exit(0)},l=async()=>{if(!o){for(o=!0;n.length;){const m=n.shift();let s;try{s=JSON.parse(m)}catch{continue}try{const c=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:m});if(s.id==null)continue;const u=(await c.text()).trim();u&&process.stdout.write(u+`
10
- `)}catch(c){s.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:s.id,error:{code:-32e3,message:String(c?.message||c)}})+`
11
- `)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",m=>{e+=m;let s;for(;(s=e.indexOf(`
12
- `))>=0;){const c=e.slice(0,s).trim();e=e.slice(s+1),c&&n.push(c)}l()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function En(){st(),ct(),Ut(),pe.on("error",t=>{t&&t.code==="EADDRINUSE"&&(d("error",`Port ${v} is already in use — another app (or a second bridge) has it.`),d("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)),d("error",`bridge server error: ${t?.message||t}`),process.exit(1)});for(const t of["SIGINT","SIGTERM"])process.on(t,()=>{const e=mt("shutdown");e&&d("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=ft("shutdown");n&&d("info",`shutdown: closed ${n} warm agent process${n===1?"":"es"}`),setTimeout(()=>process.exit(0),e||n?300:0).unref?.(),!e&&!n&&process.exit(0)});pe.listen(v,k,async()=>{d("info",`listening on http://${k}:${v}`),W.has(k)||d("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:t,label:e,hidden:n}]of Object.entries(C)){if(n)continue;const o=await t.available().catch(()=>({ok:!1}));d("info",` ${o.ok?"✓":"✕"} ${e}${o.ok?"":" — "+(o.reason||"unavailable")}`)}d("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),se().then(t=>t.startIfConfigured()).then(t=>{t?.skipped||(t?.ok?d("info","channels: telegram connected — polling for messages"):d("error",`channels: telegram not started — ${t?.error||"unknown error"}`))}).catch(t=>d("error",`channels: ${t?.message||t}`))})}function On(){console.log(`ChatPanel Bridge v${g}
9
+ `)}async function G(n,e,t,o){try{const r=t(await f(n)),i=F(n,r.agent,r.options||{});if(i.error)throw new x(i.error,403,"permission");return r.options=i.options,r}catch(r){return a(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new x(`Bad JSON: ${r.message}`):r)),null}}async function an(n,e){const t=await G(n,e,Et,w);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return a(e,200,kt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}M(e);const o=wt(t.requestedModel,r=>P(e,r));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){P(e,w(r))}P(e,"[DONE]"),e.end()}async function sn(n,e){const t=await G(n,e,Ot,w);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return a(e,200,Tt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}M(e);const o=bt(t.requestedModel,r=>P(e,r));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){P(e,w(r))}P(e,"[DONE]"),e.end()}async function cn(n,e){const t=await G(n,e,Pt,w);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return a(e,200,vt(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,w(r))}M(e);const o=At(t.requestedModel,r=>B(e,r.type,r));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){const i={type:"error",sequence_number:0,...w(r)};B(e,"error",i)}e.end()}async function ln(n,e){const t=await G(n,e,Ct,j);if(!t)return;if(!t.stream)try{const r=await T(t,()=>{},e);return a(e,200,St(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:a(e,r?.status||500,j(r))}M(e);const o=yt(t.requestedModel,(r,i)=>B(e,r,i));try{await T(t,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",j(r))}e.end()}async function dn(n,e){let t={};try{t=await f(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?pt(o,"stopped"):!1;return r&&d("info",`cancel: ${o} stopped by client`),a(e,200,{ok:!0,cancelled:r})}async function ue(n,e,t){let o;try{o=await f(n)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?Y(t):Fe(),i=c=>{r&&e.setHeader("Mcp-Session-Id",r.id),a(e,200,{jsonrpc:"2.0",id:o.id??null,result:c})},s=(c,l)=>a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:c,message:l}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return i({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const u=Le();if(o.method==="tools/list"){const c=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return i({tools:[...u,...c]})}if(o.method==="tools/call"){const c=await je(o.params?.name,o.params?.arguments||{});if(c)return i(c);if(!r)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return i(await Je(r,o.params?.name,o.params?.arguments||{}))}catch(l){return i({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function un(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return a(e,400,{error:"need server.command and message"});try{const i=await ht({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd},r);return r.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function hn(n,e){let t;try{t=await f(n)}catch(h){return a(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:i}=t||{};if(!o||!i)return a(e,400,{error:"need url and message"});let s;try{s=ne(o)}catch(h){return a(e,400,{error:String(h?.message||h)})}const u={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,b]of Object.entries(r)){const m=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(u[h]=String(b))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:u,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&ne(h.url)}catch(m){return a(e,400,{error:String(m?.message||m)})}const b=await h.text().catch(()=>"");return a(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",body:b})}catch(h){const b=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${s.host}: ${b}`})}finally{clearTimeout(l)}}const he=256*1024,pn=5,mn=8e3;async function fn(n){let e=re(n);const t=new AbortController,o=setTimeout(()=>t.abort(),mn);try{for(let r=0;r<=pn;r++){const i=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(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=re(new URL(i.headers.get("location"),e).href),i.body)try{await i.body.cancel()}catch{}continue}if(!i.ok){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}const s=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:wn(await gn(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function gn(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 o="",r=0;try{for(;;){const{done:i,value:s}=await e.read();if(i||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=he))break}}finally{try{await e.cancel()}catch{}}return o}function yn(n){return String(n).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function wn(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?yn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function bn(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return a(e,400,{error:"need url"});try{const r=await fn(o);return a(e,200,{title:r.title||null,url:r.url||o})}catch(r){const i=r?.name==="AbortError"?"timed out":String(r?.message||r);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function Sn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=Y(t.session);if(!o)return a(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function kn(n,e){let t;try{t=await f(n)}catch(c){return a(e,400,{error:"Bad JSON: "+c.message})}const o=C[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return a(e,400,{error:"Empty prompt"});const i=t.model||"",s=F(n,t.agent,{model:i});if(s.error)return a(e,403,{error:s.error});const u=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof o.engine.complete=="function"?c=await o.engine.complete({prompt:r,system:u,model:i}):await o.engine.chat({messages:[{role:"user",content:r}],system:u,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),a(e,200,{text:(c||"").trim()})}catch(c){return a(e,502,{error:c?.message||String(c)})}}async function Tn(n,e){let t;try{t=await f(n)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}const o=C[t.agent];if(!o)return a(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return a(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return a(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return a(e,502,{error:r?.message||String(r)})}}async function vn(n,e){let t;try{t=await f(n)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const o=String(t.command||"").trim();if(!o)return a(e,400,{error:"No command"});let r=null;try{r=lt(o)}catch{r=null}return a(e,200,{ok:!!r,via:r?r.kind:null})}const pe=fe(async(n,e)=>{if(Bt(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 a(e,400,{error:"bad request"})}const o=zt(n,t.pathname);if(o)return a(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return Xt(e);const r=t.searchParams.getAll("dir"),i=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return Yt(e,r,i);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Qt(e,r,i);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),u=s.indexOf("/file/");return u===-1?Zt(e,decodeURIComponent(s),r,i):qt(e,decodeURIComponent(s.slice(0,u)),decodeURIComponent(s.slice(u+6)),r,i)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return rn(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return on(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 s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(it.map(u=>[u,s?ee(u)||null:!!ee(u)])),...s?{home:A.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return nn(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Lt(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Dt(e);if(n.method==="POST"&&t.pathname==="/whoami")return jt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return an(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return sn(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return cn(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return ln(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return ue(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 ue(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return X(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ce(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ce(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return dn(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Sn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local")return un(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return hn(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return bn(n,e);if(n.method==="POST"&&t.pathname==="/complete")return kn(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Tn(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return vn(n,e);if(n.method==="POST"&&t.pathname==="/update")return tn(e);a(e,404,{error:"Not found"})}catch(r){a(e,500,{error:r?.message||String(r)})}});function d(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Cn(n){let e="";const t=[];let o=!1,r=!1;const i=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const u=t.shift();let c;try{c=JSON.parse(u)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:u});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
10
+ `)}catch(l){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(l?.message||l)}})+`
11
+ `)}}o=!1,i()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",u=>{e+=u;let c;for(;(c=e.indexOf(`
12
+ `))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{r=!0,i()}),process.stdin.resume()}function En(){st(),ct(),Ut(),pe.on("error",n=>{n&&n.code==="EADDRINUSE"&&(d("error",`Port ${v} is already in use — another app (or a second bridge) has it.`),d("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)),d("error",`bridge server error: ${n?.message||n}`),process.exit(1)});for(const n of["SIGINT","SIGTERM"])process.on(n,()=>{const e=mt("shutdown");e&&d("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const t=ft("shutdown");t&&d("info",`shutdown: closed ${t} warm agent process${t===1?"":"es"}`),setTimeout(()=>process.exit(0),e||t?300:0).unref?.(),!e&&!t&&process.exit(0)});pe.listen(v,k,async()=>{d("info",`listening on http://${k}:${v}`),W.has(k)||d("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:n,label:e,hidden:t}]of Object.entries(C)){if(t)continue;const o=await n.available().catch(()=>({ok:!1}));d("info",` ${o.ok?"✓":"✕"} ${e}${o.ok?"":" — "+(o.reason||"unavailable")}`)}d("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),se().then(n=>n.startIfConfigured()).then(n=>{n?.skipped||(n?.ok?d("info","channels: telegram connected — polling for messages"):d("error",`channels: telegram not started — ${n?.error||"unknown error"}`))}).catch(n=>d("error",`channels: ${n?.message||n}`))})}function On(){console.log(`ChatPanel Bridge v${g}
13
13
 
14
14
  Usage:
15
15
  chatpanel-bridge start the bridge (foreground) on ${k}:${v}
@@ -20,4 +20,4 @@ Usage:
20
20
  chatpanel-bridge --version print the version
21
21
  chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
22
22
 
23
- Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function An(){const t=process.argv,e=(...n)=>n.some(o=>t.includes(o));if(e("--help","-h"))return On(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let n="";try{n=K(N,"utf8").trim()}catch{}const o=`http://${k}:${v}`;try{if(!n)throw new Error(`no token at ${N} — is the bridge running?`);const r=await fetch(`${o}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(2500)}),a=await r.json().catch(()=>({}));if(!r.ok)throw new Error(a.error||`HTTP ${r.status}`);console.log(`Pairing code: ${_t(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(r){d("error",`could not get a pairing code from the bridge at ${o}: ${r?.message||r}`),process.exitCode=1}})(),!0;if(e("--install")){try{Re(),d("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(n){d("error","Install failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--uninstall")){try{_e(),d("info","Removed the login auto-start.")}catch(n){d("error","Uninstall failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--status")){let n=!1;try{n=He()}catch(o){d("error",String(o?.message||o))}return d("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const me=process.argv.indexOf("--mcp-stdio");if(me>=0){const t=process.argv[me+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Cn(t)}else process.argv.includes("--update")?(async()=>{try{const t=await te(g);d("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),V()}catch(t){d("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():An()||En();
23
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT`)}function Pn(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return On(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=K(N,"utf8").trim()}catch{}const o=`http://${k}:${v}`;try{if(!t)throw new Error(`no token at ${N} — is the bridge running?`);const r=await fetch(`${o}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),i=await r.json().catch(()=>({}));if(!r.ok)throw new Error(i.error||`HTTP ${r.status}`);console.log(`Pairing code: ${_t(i.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(r){d("error",`could not get a pairing code from the bridge at ${o}: ${r?.message||r}`),process.exitCode=1}})(),!0;if(e("--install")){try{Re(),d("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){d("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{_e(),d("info","Removed the login auto-start.")}catch(t){d("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=He()}catch(o){d("error",String(o?.message||o))}return d("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const me=process.argv.indexOf("--mcp-stdio");if(me>=0){const n=process.argv[me+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Cn(n)}else process.argv.includes("--update")?(async()=>{try{const n=await te(g);d("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),V()}catch(n){d("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():Pn()||En();
package/src/skills.js CHANGED
@@ -1 +1 @@
1
- import{readFile as b,readdir as K,stat as x,realpath as v}from"node:fs/promises";import{createHash as R}from"node:crypto";import S from"node:os";import{delimiter as M,isAbsolute as j,join as g,resolve as k,sep as E}from"node:path";import{isSafeSkillPath as A,normalizeSkill as H,SKILL_FILE_KINDS as _}from"./events/skill-manifest.js";import{scanSkill as q,admits as T}from"./events/skill-scan.js";const O=512*1024,W=4*1024*1024,L=500,X=3,B=new Set([".git",".svn",".hg",".cache",".DS_Store","node_modules"]),G=Object.freeze([{source:"local",label:"ChatPanel",segments:[".chatpanel","skills"],writable:!0},{source:"agents-dir",label:"Shared (~/.agents)",segments:[".agents","skills"]},{source:"claude",label:"Claude Code",segments:[".claude","skills"]},{source:"codex",label:"Codex",segments:[".codex","skills"]},{source:"copilot",label:"GitHub Copilot",segments:[".copilot","skills"]},{source:"gemini",label:"Antigravity / Gemini",segments:[".gemini","skills"]},{source:"opencode",label:"OpenCode",segments:[".opencode","skills"]},{source:"kiro",label:"Kiro",segments:[".kiro","skills"]},{source:"pi",label:"Pi",segments:[".pi","skills"]},{source:"hermes",label:"Hermes",segments:[".hermes","skills"]}]);function I(t){return(Array.isArray(t)?t:[]).map(e=>String(e||"").trim()).filter(Boolean).filter(e=>j(e)).slice(0,16)}function C(t=process.env,e=S.homedir(),s=[]){const n=String(t.CHATPANEL_SKILL_DIRS||"").split(/\r?\n/).flatMap(r=>r.split(M)).map(r=>r.trim()).filter(Boolean),i=[...new Set([...n,...I(s)])];return[...G.map(r=>({dir:g(e,...r.segments),source:r.source,label:r.label,writable:!!r.writable})),...i.map(r=>({dir:k(r),source:"external",label:"Custom folder",writable:!1}))]}function N(t){const e=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(String(t||""));if(!e)return{meta:{},body:String(t||"")};const s={},n=[{indent:-1,obj:s}];for(const i of e[1].split(/\r?\n/)){if(!i.trim()||i.trim().startsWith("#"))continue;const r=i.length-i.trimStart().length,c=i.trim(),a=/^([A-Za-z_][\w.-]*)\s*:\s*(.*)$/.exec(c);if(!a)continue;for(;n.length>1&&r<=n[n.length-1].indent;)n.pop();const u=n[n.length-1].obj,[,o,l]=a;if(l===""){const p={};u[o]=p,n.push({indent:r,obj:p});continue}u[o]=P(l)}return{meta:s,body:String(t).slice(e[0].length)}}function P(t){const e=t.trim().replace(/\s+#.*$/,"").trim();return/^\[.*\]$/.test(e)?e.slice(1,-1).split(",").map(s=>$(s.trim())).filter(Boolean):e==="true"?!0:e==="false"?!1:$(e)}const $=t=>/^(['"]).*\1$/.test(t)?t.slice(1,-1):t,z=/^[a-z0-9][a-z0-9_-]*$/;function Z({meta:t,body:e,dirName:s,relPath:n,source:i,files:r,hash:c}){const a=typeof t.name=="string"&&t.name.trim()?t.name.trim():s,u=z.test(String(a))?String(a):s,o={};for(const l of _){const p=r.filter(f=>f.startsWith(`${l}/`)).map(f=>f.slice(l.length+1));p.length&&(o[l]=p)}return H({id:u,name:String(a),command:z.test(u)?u:"",description:typeof t.description=="string"?t.description:"",prompt:e.trim(),...typeof t.version=="string"?{version:t.version}:{},...Array.isArray(t.platforms)?{platforms:t.platforms}:{},...Object.keys(o).length?{files:o}:{},origin:{source:i,id:n,hash:c}})}function J(t,e=process.platform){const s=t?.platforms;if(!Array.isArray(s)||!s.length)return!0;const n=e==="darwin"?"macos":e==="win32"?"windows":"linux";return s.includes(n)}async function D(t){try{return await K(t,{withFileTypes:!0})}catch{return[]}}async function Q(t){const e=[];for(const s of _)for(const n of await D(g(t,s))){if(!n.isFile())continue;const i=`${s}/${n.name}`;if(A(i)&&e.push(i),e.length>=200)return e}return e}async function U(t,e,s){let n;try{const p=await x(g(t,"SKILL.md"));if(!p.isFile()||p.size>O)return null;n=await b(g(t,"SKILL.md"),"utf8")}catch{return null}const{meta:i,body:r}=N(n),c=`sha256-${R("sha256").update(n).digest("hex").slice(0,32)}`,a=e.split("/").pop(),u=await Q(t),o=Z({meta:i,body:r,dirName:a,relPath:e,source:s,files:u,hash:c}),l=q({name:o.name,prompt:o.prompt,files:u||[]});return o.origin={...o.origin,scanned:{verdict:l.verdict,scanner:l.scanner,findings:l.findings.length}},{skill:o,dir:t,scan:l}}async function V({roots:t,extraDirs:e=[],platform:s=process.platform}={}){t=t||C(process.env,S.homedir(),e);const n=new Map,i=[],r=[];for(const{dir:c,source:a}of t){const u=async(o,l,p)=>{if(!(n.size>=L||p>X))for(const f of await D(o)){if(n.size>=L)return;if(!f.isDirectory()||B.has(f.name))continue;const h=l?`${l}/${f.name}`:f.name,w=g(o,f.name),m=f.name.startsWith(".")?null:await U(w,h,a).catch(y=>(i.push({path:h,reason:String(y?.message||y)}),null));m?T(m.scan?.verdict)?!n.has(m.skill.id)&&J(m.skill,s)&&n.set(m.skill.id,{...m,root:c,source:a}):r.push({id:m.skill.id,path:h,verdict:m.scan.verdict,findings:m.scan.findings}):await u(w,h,p+1)}};await u(c,"",1)}return{index:n,problems:i,quarantined:r}}function ot(t){return[...t.values()].map(({skill:e})=>{const{prompt:s,...n}=e;return{...n,promptChars:(s||"").length}})}function at(t,e){const s=t.get(String(e||""));return s?s.skill:null}async function lt(t,e,s){const n=t.get(String(e||""));if(!n)return{error:"unknown skill"};if(!A(s))return{error:"unsafe path"};if(String(s).split("/")[0]==="scripts")return{error:"scripts are not readable as text"};const i=k(n.dir,s);let r;try{r=await v(i)}catch{return{error:"not found"}}const c=await v(n.dir).catch(()=>n.dir);if(r!==c&&!r.startsWith(c+E))return{error:"outside package"};const a=await x(r).catch(()=>null);return a?.isFile()?a.size>W?{error:"file too large"}:{path:s,text:await b(r,"utf8")}:{error:"not found"}}const Y=5e3;let d=null;async function F({force:t=!1,now:e=Date.now,extraDirs:s=[]}={}){const n=e(),i=I(s).map(c=>k(c)).sort().join("|");if(!t&&d&&d.key===i&&n-d.at<Y)return d.value;const r=await V({extraDirs:s});return d={at:n,key:i,value:r},r}function ct(){d=null}async function ut(t=[]){const{index:e,problems:s,quarantined:n}=await F({extraDirs:t}),i=new Set([...e.values()].map(r=>r.root));return{count:e.size,roots:C(process.env,S.homedir(),t).filter(r=>i.has(r.dir)).map(r=>r.dir),sources:[...new Set([...e.values()].map(r=>r.source))].sort(),...s.length?{problems:s.length}:{},...n?.length?{quarantined:n.length}:{}}}async function pt(t=[]){const{quarantined:e}=await F({extraDirs:t});return e||[]}export{G as AGENT_SKILL_DIRS,ct as clearSkillCache,ot as listRecords,N as parseFrontmatter,J as platformOk,pt as quarantinedSkills,lt as readPackageFile,at as readRecord,V as scanSkills,F as skillIndex,Z as skillRecord,C as skillRoots,ut as skillsHealth};
1
+ import{readFile as v,readdir as H,stat as A,realpath as _}from"node:fs/promises";import{createHash as q}from"node:crypto";import w from"node:os";import{delimiter as T,isAbsolute as L,join as g,resolve as k,sep as O}from"node:path";import{isSafeSkillPath as j,normalizeSkill as W,SKILL_FILE_KINDS as I}from"./events/skill-manifest.js";import{scanSkill as X,admits as B}from"./events/skill-scan.js";const G=512*1024,N=4*1024*1024,C=500,P=3,Z=new Set([".git",".svn",".hg",".cache",".DS_Store","node_modules"]),R=Object.freeze([{source:"local",label:"ChatPanel",segments:[".chatpanel","skills"],writable:!0},{source:"agents-dir",label:"Shared (~/.agents)",segments:[".agents","skills"]},{source:"claude",label:"Claude Code",segments:[".claude","skills"]},{source:"codex",label:"Codex",segments:[".codex","skills"]},{source:"copilot",label:"GitHub Copilot",segments:[".copilot","skills"],projectSegments:[".github","skills"]},{source:"gemini",label:"Antigravity / Gemini",segments:[".gemini","skills"]},{source:"opencode",label:"OpenCode",segments:[".opencode","skills"]},{source:"kiro",label:"Kiro",segments:[".kiro","skills"]},{source:"pi",label:"Pi",segments:[".pi","skills"]},{source:"hermes",label:"Hermes",segments:[".hermes","skills"]}]);function $(t){return(Array.isArray(t)?t:[]).map(e=>String(e||"").trim()).filter(Boolean).filter(e=>L(e)).slice(0,16)}function z(t){const e=String(t||"").trim();if(!e||!L(e))return[];const n=k(e);return R.map(r=>({dir:g(n,...r.projectSegments||r.segments),source:r.source,label:r.label,writable:!1,project:n}))}function D(t=process.env,e=w.homedir(),n=[],r=""){const s=String(t.CHATPANEL_SKILL_DIRS||"").split(/\r?\n/).flatMap(o=>o.split(T)).map(o=>o.trim()).filter(Boolean),i=[...new Set([...s,...$(n)])];return[...z(r),...R.map(o=>({dir:g(e,...o.segments),source:o.source,label:o.label,writable:!!o.writable})),...i.map(o=>({dir:k(o),source:"external",label:"Custom folder",writable:!1}))]}function J(t){const e=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(String(t||""));if(!e)return{meta:{},body:String(t||"")};const n={},r=[{indent:-1,obj:n}];for(const s of e[1].split(/\r?\n/)){if(!s.trim()||s.trim().startsWith("#"))continue;const i=s.length-s.trimStart().length,o=s.trim(),l=/^([A-Za-z_][\w.-]*)\s*:\s*(.*)$/.exec(o);if(!l)continue;for(;r.length>1&&i<=r[r.length-1].indent;)r.pop();const c=r[r.length-1].obj,[,a,u]=l;if(u===""){const p={};c[a]=p,r.push({indent:i,obj:p});continue}c[a]=Q(u)}return{meta:n,body:String(t).slice(e[0].length)}}function Q(t){const e=t.trim().replace(/\s+#.*$/,"").trim();return/^\[.*\]$/.test(e)?e.slice(1,-1).split(",").map(n=>F(n.trim())).filter(Boolean):e==="true"?!0:e==="false"?!1:F(e)}const F=t=>/^(['"]).*\1$/.test(t)?t.slice(1,-1):t,K=/^[a-z0-9][a-z0-9_-]*$/;function U({meta:t,body:e,dirName:n,relPath:r,source:s,files:i,hash:o}){const l=typeof t.name=="string"&&t.name.trim()?t.name.trim():n,c=K.test(String(l))?String(l):n,a={};for(const u of I){const p=i.filter(m=>m.startsWith(`${u}/`)).map(m=>m.slice(u.length+1));p.length&&(a[u]=p)}return W({id:c,name:String(l),command:K.test(c)?c:"",description:typeof t.description=="string"?t.description:"",prompt:e.trim(),...typeof t.version=="string"?{version:t.version}:{},...Array.isArray(t.platforms)?{platforms:t.platforms}:{},...Object.keys(a).length?{files:a}:{},origin:{source:s,id:r,hash:o}})}function V(t,e=process.platform){const n=t?.platforms;if(!Array.isArray(n)||!n.length)return!0;const r=e==="darwin"?"macos":e==="win32"?"windows":"linux";return n.includes(r)}async function M(t){try{return await H(t,{withFileTypes:!0})}catch{return[]}}async function Y(t){const e=[];for(const n of I)for(const r of await M(g(t,n))){if(!r.isFile())continue;const s=`${n}/${r.name}`;if(j(s)&&e.push(s),e.length>=200)return e}return e}async function tt(t,e,n){let r;try{const p=await A(g(t,"SKILL.md"));if(!p.isFile()||p.size>G)return null;r=await v(g(t,"SKILL.md"),"utf8")}catch{return null}const{meta:s,body:i}=J(r),o=`sha256-${q("sha256").update(r).digest("hex").slice(0,32)}`,l=e.split("/").pop(),c=await Y(t),a=U({meta:s,body:i,dirName:l,relPath:e,source:n,files:c,hash:o}),u=X({name:a.name,prompt:a.prompt,files:c||[]});return a.origin={...a.origin,scanned:{verdict:u.verdict,scanner:u.scanner,findings:u.findings.length}},{skill:a,dir:t,scan:u}}async function et({roots:t,extraDirs:e=[],workdir:n="",platform:r=process.platform}={}){t=t||D(process.env,w.homedir(),e,n);const s=new Map,i=[],o=[];for(const{dir:l,source:c,project:a}of t){const u=async(p,m,b)=>{if(!(s.size>=C||b>P))for(const d of await M(p)){if(s.size>=C)return;if(!d.isDirectory()||Z.has(d.name))continue;const S=m?`${m}/${d.name}`:d.name,y=g(p,d.name),f=d.name.startsWith(".")?null:await tt(y,S,c).catch(x=>(i.push({path:S,reason:String(x?.message||x)}),null));f?B(f.scan?.verdict)?!s.has(f.skill.id)&&V(f.skill,r)&&(a&&(f.skill.origin={...f.skill.origin,project:a}),s.set(f.skill.id,{...f,root:l,source:c})):o.push({id:f.skill.id,path:S,verdict:f.scan.verdict,findings:f.scan.findings}):await u(y,S,b+1)}};await u(l,"",1)}return{index:s,problems:i,quarantined:o}}function ct(t){return[...t.values()].map(({skill:e})=>{const{prompt:n,...r}=e;return{...r,promptChars:(n||"").length}})}function ut(t,e){const n=t.get(String(e||""));return n?n.skill:null}async function pt(t,e,n){const r=t.get(String(e||""));if(!r)return{error:"unknown skill"};if(!j(n))return{error:"unsafe path"};if(String(n).split("/")[0]==="scripts")return{error:"scripts are not readable as text"};const s=k(r.dir,n);let i;try{i=await _(s)}catch{return{error:"not found"}}const o=await _(r.dir).catch(()=>r.dir);if(i!==o&&!i.startsWith(o+O))return{error:"outside package"};const l=await A(i).catch(()=>null);return l?.isFile()?l.size>N?{error:"file too large"}:{path:n,text:await v(i,"utf8")}:{error:"not found"}}const nt=5e3;let h=null;async function E({force:t=!1,now:e=Date.now,extraDirs:n=[],workdir:r=""}={}){const s=e(),o=[z(r)[0]?.project||"",...$(n).map(c=>k(c)).sort()].join("|");if(!t&&h&&h.key===o&&s-h.at<nt)return h.value;const l=await et({extraDirs:n,workdir:r});return h={at:s,key:o,value:l},l}function ft(){h=null}async function mt(t=[]){const{index:e,problems:n,quarantined:r}=await E({extraDirs:t}),s=new Set([...e.values()].map(i=>i.root));return{count:e.size,roots:D(process.env,w.homedir(),t).filter(i=>s.has(i.dir)).map(i=>i.dir),sources:[...new Set([...e.values()].map(i=>i.source))].sort(),...n.length?{problems:n.length}:{},...r?.length?{quarantined:r.length}:{}}}async function dt(t=[],e=""){const{quarantined:n}=await E({extraDirs:t,workdir:e});return n||[]}export{R as AGENT_SKILL_DIRS,ft as clearSkillCache,ct as listRecords,J as parseFrontmatter,V as platformOk,z as projectSkillRoots,dt as quarantinedSkills,pt as readPackageFile,ut as readRecord,et as scanSkills,E as skillIndex,U as skillRecord,D as skillRoots,mt as skillsHealth};