@chatpanel/bridge 0.32.1 → 0.32.2

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.32.1",
3
+ "version": "0.32.2",
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 +1 @@
1
- import{restoreText as d,restoreWithAliases as p,redactResultShape as f}from"./pii-redact.js";import{narrowSpecs as y}from"./tool-rank.js";const O=e=>/^mcp[_-]/i.test(String(e||""));function i(e,a){if(!a)return e;if(typeof e=="string")return p(e,a);if(Array.isArray(e))return e.map(t=>i(t,a));if(e&&typeof e=="object"){const t={};for(const s of Object.keys(e))t[s]=i(e[s],a);return t}return e}function m(){return"PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], [[LOCATION_1]], [[ORG_1]] that stand in for the user's real private data. Treat each one as a CONCRETE, specific value you already have — not missing or unknown information. Do not ask what it stands for, do not say it is unresolved, and do not refuse on privacy grounds. Reason and write with the placeholder exactly as written; the real value is restored in your answer automatically."}function g({toolData:e="real",ownTools:a=!1}={}){const t="PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], [[LOCATION_1]], [[ORG_1]] that stand in for the user's real private data. ",s=e==="redactRemote"?"When you call a LOCAL tool the placeholder is automatically replaced with the real value before the tool runs; REMOTE (MCP) tools deliberately receive the placeholder to keep private data off third-party servers. ":"When you call ANY tool, these placeholders are AUTOMATICALLY replaced with the real values before the tool executes — the tool receives the TRUE value and returns correct results. ",n="So: treat each placeholder as a CONCRETE, specific value you already have — it is enough to act on, NOT missing or unknown information. CALL THE TOOL using the placeholder exactly as written, as if it were the real value. If answering needs the real data behind a placeholder (e.g. which city [[LOCATION_1]] is, who [[PERSON_1]] is, what [[ORG_1]] does), do NOT reply that you lack information or cannot answer. Instead pick the most relevant available tool for that placeholder's TYPE — LOCATION → geography / place lookups, PERSON → people lookups, ORG → company/org lookups, dates/IDs → the matching lookup — and pass the placeholder straight through as the argument. The harness restores the true value before the tool runs, so the lookup returns correct results. Make your best-guess tool call FIRST; only conclude you lack data AFTER a tool has actually returned nothing useful. Do NOT ask the user to re-type the value and do NOT refuse on privacy grounds — the lookup will work. The real values are restored in your final answer automatically, so write your answer using the placeholders too.",l=a?" ONLY THE TOOLS LISTED IN THIS CONVERSATION restore placeholders. Any tool you bring yourself — your own web search, shell, file or code tools — receives the placeholder text literally and will find nothing. So for ANY lookup that involves a placeholder, call the listed tool (for example `find` with action `web_search` or `history_search`) rather than your own. Prefer the listed tools for lookups in general — the user sees those as steps — and keep your own tools for what the listed ones cannot do.":"";return t+s+n+l}const T=new Set(["web_search","web_fetch","fetch_url"]);function w(e){return T.has(String(e||"").toLowerCase())}function N({vault:e=null,toolData:a="real",redactOpts:t=null,redactResults:s=!0,remoteTools:n=null}={}){const l=!!e,c=a==="redactRemote",h=typeof n=="function"?n:n instanceof Set?o=>n.has(o):O;return{enabled:l,isRemoteTool:h,selectTools(o,r,u={}){return y(o,r,u)},toTool(o,r){return!l||c&&h(o)?r:i(r,e)},toModelResult(o,r){return!l||!s||!t||w(o)?r:f(r,e,t)},toUser(o){return l?d(o,e):o}}}export{w as isPublicSourceTool,O as isRemoteToolName,N as makeToolHarness,m as placeholderNote,g as placeholderToolNote,i as restoreToolArgs};
1
+ import{restoreText as O,restoreWithAliases as T,redactResultShape as w}from"./pii-redact.js";import{narrowSpecs as R}from"./tool-rank.js";const N=e=>/^mcp[_-]/i.test(String(e||""));function h(e,t){if(!t)return e;if(typeof e=="string")return T(e,t);if(Array.isArray(e))return e.map(o=>h(o,t));if(e&&typeof e=="object"){const o={};for(const a of Object.keys(e))o[a]=h(e[a],t);return o}return e}function A(){return"PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], [[LOCATION_1]], [[ORG_1]] that stand in for the user's real private data. Treat each one as a CONCRETE, specific value you already have — not missing or unknown information. Do not ask what it stands for, do not say it is unresolved, and do not refuse on privacy grounds. Reason and write with the placeholder exactly as written; the real value is restored in your answer automatically."}function E({toolData:e="real",ownTools:t=!1}={}){const o="PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], [[LOCATION_1]], [[ORG_1]] that stand in for the user's real private data. ",a=e==="redactRemote"?"When you call a LOCAL tool the placeholder is automatically replaced with the real value before the tool runs; REMOTE (MCP) tools deliberately receive the placeholder to keep private data off third-party servers. ":"When you call ANY tool, these placeholders are AUTOMATICALLY replaced with the real values before the tool executes — the tool receives the TRUE value and returns correct results. ",l="So: treat each placeholder as a CONCRETE, specific value you already have — it is enough to act on, NOT missing or unknown information. CALL THE TOOL using the placeholder exactly as written, as if it were the real value. If answering needs the real data behind a placeholder (e.g. which city [[LOCATION_1]] is, who [[PERSON_1]] is, what [[ORG_1]] does), do NOT reply that you lack information or cannot answer. Instead pick the most relevant available tool for that placeholder's TYPE — LOCATION → geography / place lookups, PERSON → people lookups, ORG → company/org lookups, dates/IDs → the matching lookup — and pass the placeholder straight through as the argument. The harness restores the true value before the tool runs, so the lookup returns correct results. Make your best-guess tool call FIRST; only conclude you lack data AFTER a tool has actually returned nothing useful. Do NOT ask the user to re-type the value and do NOT refuse on privacy grounds — the lookup will work. The real values are restored in your final answer automatically, so write your answer using the placeholders too.",i=t?" ONLY THE TOOLS LISTED IN THIS CONVERSATION restore placeholders. Any tool you bring yourself — your own web search, shell, file or code tools — receives the placeholder text literally and will find nothing. So for ANY lookup that involves a placeholder, call the listed tool (for example `find` with action `web_search` or `history_search`) rather than your own. Prefer the listed tools for lookups in general — the user sees those as steps — and keep your own tools for what the listed ones cannot do.":"";return o+a+l+i}const k=new Set(["web_search","web_fetch","fetch_url"]);function m(e){return k.has(String(e||"").toLowerCase())}function f(e,t,o){const a=d(t);return!a||a===e?e:o instanceof Map&&o.get(a)===e?a:e}function d(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return""}const o=t&&typeof t=="object"?t.action:null;return typeof o=="string"?o:""}function L({vault:e=null,toolData:t="real",redactOpts:o=null,redactResults:a=!0,remoteTools:l=null,hiddenVia:i=null}={}){const c=!!e,y=t==="redactRemote",u=typeof l=="function"?l:l instanceof Set?r=>l.has(r):N,p=(r,n)=>{if(u(r))return!0;const s=d(n);return!!s&&s!==r&&u(s)};return{enabled:c,isRemoteTool:p,realToolName:(r,n)=>f(r,n,i),selectTools(r,n,s={}){return R(r,n,s)},toTool(r,n){return!c||y&&p(r,n)?n:h(n,e)},toModelResult(r,n,s){return!c||!a||!o||m(f(r,s,i))?n:w(n,e,o)},toUser(r){return c?O(r,e):r}}}export{m as isPublicSourceTool,N as isRemoteToolName,L as makeToolHarness,A as placeholderNote,E as placeholderToolNote,f as realToolName,h as restoreToolArgs};
package/src/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as Te}from"node:http";import E from"node:os";import{randomBytes as Ee,randomInt as ve,timingSafeEqual as Oe}from"node:crypto";import{mkdirSync as Ce,writeFileSync as Ae,readFileSync as Y,existsSync as xe}from"node:fs";import{join as _}from"node:path";import*as Pe from"./engines/claude.js";import*as Re from"./engines/codex.js";import*as Ie from"./engines/antigravity.js";import{pi as $e,opencode as Ne,kiro as De,copilot as _e,deepseek as He,hermes as Me}from"./engines/cli-agents.js";import{connectorsFor as Ue}from"./connectors.js";import*as We from"./engines/custom.js";import{installService as Be,uninstallService as Ge,serviceStatus as Le,restartService as Q}from"./service.js";import{skillIndex as G,listRecords as je,readRecord as Fe,readPackageFile as Je,skillsHealth as Xe,quarantinedSkills as ze,clearSkillCache as L}from"./skills.js";import{writeSkillPackage as Ke,writeSkillFile as Ve,deleteSkillPackage as Ye,SkillWriteError as Qe}from"./skill-write.js";import{agentDefRoots as Ze,scanAgentDefs as qe,listAgentDefs as et,readAgentDef as tt,planAgentExport as nt,exportAgentDef as ot,agentDefsHealth as rt,AgentDefError as at}from"./agent-defs.js";import{capabilityToolSpecs as it,runCapabilityTool as st}from"./mcp-capabilities.js";import{createSession as ct,deleteSession as Z,getSession as q,activeSession as lt,relayToolCall as dt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ut,isDefaultWorkdir as ht,resolveWorkdir as pt,writeScopeNote as ft}from"./workdir.js";import{sandbox as ee,runSandboxCli as mt,withGrant as te,withoutOutsideWhenCapped as gt,grantedWriteRoots as yt,acceptRefusalReport as wt,liveProcesses as bt}from"./sandbox.js";import{gitState as St,gitDelta as kt}from"./scm.js";import{listConnections as Tt,putConnection as Et,removeConnection as vt,runEnvFor as Ot,testConnection as Ct,secretBackend as ne}from"./connections.js";import{worktreeFor as oe,listWorktrees as At,removeWorktree as xt,withHook as Pt,WORKTREE_ROOT as re}from"./worktree.js";import{AGENT_CLIS as Rt,agentAvailable as It,agentInstallDirs as $t,enrichPath as Nt,enrichAgentEnv as Dt,findAgentBin as _t,resolveCommand as ae}from"./env.js";import"./sanitize.js";import{checkForUpdate as Ht,selfUpdate as ie,isEmbedded as Mt}from"./update.js";import{callLocalMcp as Ut,localMcpStatus as Wt,signInLocalMcp as Bt,signInStatusLocalMcp as Gt}from"./mcp-local.js";import{assertPublicHttpUrl as se,assertPublicWebUrl as ce}from"./ssrf.js";import{startRun as le,endRun as j,cancelRun as Lt,cancelAll as jt}from"./runs.js";import{closeWarmPools as Ft,warmStatus as Jt}from"./warm.js";import{CompatError as R,anthropicError as F,anthropicStream as Xt,chatCompletionStream as zt,completionStream as Kt,createAnthropicMessage as Vt,createChatCompletion as Yt,createCompletion as Qt,createResponse as Zt,openAIError as b,parseAnthropicMessage as qt,parseChatCompletion as en,parseCompletion as tn,parseResponse as nn,responseStream as on}from"./api-compat.js";import{callerTrust as rn,isPaired as I,parseExtensionIds as an,capRunOptions as sn,engineHonoursReach as cn,createPairingStore as ln,formatPairingCode as dn}from"./pii/trust.js";const g="0.32.1",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:Pe,label:"Claude Code"},codex:{engine:Re,label:"Codex"},antigravity:{engine:Ie,label:"Antigravity",tools:!1},pi:{engine:$e,label:"Pi"},opencode:{engine:Ne,label:"OpenCode"},hermes:{engine:Me,label:"Hermes"},kiro:{engine:De,label:"Kiro"},copilot:{engine:_e,label:"GitHub Copilot"},deepseek:{engine:He,label:"DeepSeek Harness"},custom:{engine:We,label:"Custom",hidden:!0}};function de(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const un=an(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function $(t){return t.chatpanelTrust||(t.chatpanelTrust=rn({origin:t.headers.origin||"",hasToken:fe(t),extensionIds:un})),t.chatpanelTrust}function hn(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function pn(t,e){const n=t.headers.origin||"",r=de(n);e.setHeader("Access-Control-Allow-Origin",r?n||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function fn(t){if(!J.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(n)}const N=_(E.homedir(),".chatpanel","bridge-token");let S="";function mn(){try{xe(N)&&(S=Y(N,"utf8").trim()),S||(S=Ee(32).toString("hex"),Ce(_(E.homedir(),".chatpanel"),{recursive:!0}),Ae(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ue=ln({random:()=>ve(0,1e6)/1e6});function gn(t){if(!S)return a(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ue.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),a(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function yn(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=ue.claim(n?.code);return r.ok?(u("info",`paired a ${$(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${$(t)} caller`),a(e,403,{error:r.reason}))}function wn(t,e){const n=$(t);return a(e,200,{ok:!0,trust:n,paired:I(n),version:g})}let H=null;async function he(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(E.homedir(),".chatpanel"),dataDir:_(E.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function pe(t,e,n){try{const r=await he(),o=t.method==="POST"?await m(t):{};if(n==="status")return a(e,200,await r.status());if(n==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return n==="pair"?a(e,200,await r.pair()):n==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?a(e,200,await r.update(o)):n==="disconnect"?a(e,200,await r.stop({forget:!!o.forget})):a(e,404,{error:"unknown channel action"})}catch(r){return a(e,400,{error:r?.message||String(r)})}}function fe(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const r=Buffer.from(n),o=Buffer.from(S);return r.length===o.length&&Oe(r,o)}const bn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Sn=new Set(["/debug"]),kn=t=>Sn.has(t),Tn=(t,e)=>t!=="GET"&&t!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function En(t,e){if(!fn(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!de(n))return"forbidden origin";const r=t.method==="POST"&&bn.has(e)||t.method==="GET"&&kn(e)||Tn(t.method,e);return r&&!(hn(n)||fe(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I($(t))&&!On.has(e)?vn:null}const vn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",On=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(t,e,n){const r=$(t),o=gt(sn(n,r));if(!cn(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=o.reach,s=I(r)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:o,note:s}}function a(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function m(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function Cn(t){const e=await Promise.all(Object.entries(O).filter(([,s])=>!s.hidden).map(async([s,{engine:d,label:c,tools:l}])=>{const h=await d.available().catch(p=>({ok:!1,reason:String(p?.message||p)})),y=await Ue(s).catch(()=>[]);return{id:s,label:c,available:h.ok,reason:h.reason,connectors:y,...l===!1?{tools:!1}:{}}})),n=Mt()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Ht(g).catch(()=>({current:g,updateAvailable:!1})),r=await Xe().catch(()=>null),o=await rt().catch(()=>null),i=await ee().status().catch(s=>({enabled:!1,reason:s.message}));a(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ut,sandbox:i,localMcp:Wt(),processes:bt(),worktrees:re,secretBackend:ne(),warm:Jt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{},...o?{agentDefs:o}:{}})}async function An(t,e,n){const{index:r,problems:o}=await G({extraDirs:e,workdir:n});a(t,200,{ok:!0,skills:je(r),problems:o})}async function xn(t,e,n){a(t,200,{ok:!0,quarantined:await ze(e,n)})}async function Pn(t,e,n,r){const{index:o}=await G({extraDirs:n,workdir:r}),i=Fe(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown skill"});a(t,200,{ok:!0,skill:i})}async function Rn(t,e,n,r,o){const{index:i}=await G({extraDirs:r,workdir:o}),s=await Je(i,e,n);if(s.error)return a(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(t,200,{ok:!0,...s})}async function In(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{const r=await Ke({skill:n?.skill,files:n?.files||[],overwrite:!!n?.overwrite});return L(),a(e,200,r)}catch(r){return a(e,z(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function $n(t,e,n,r){let o;try{o=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}try{const i=await Ve({name:n,path:r,text:o?.text??""});return L(),a(e,200,i)}catch(i){return a(e,z(i),{ok:!1,error:i.message,code:i.code||"ERROR"})}}async function Nn(t,e){try{const n=await Ye({name:e});return L(),a(t,200,n)}catch(n){return a(t,z(n),{ok:!1,error:n.message,code:n.code||"ERROR"})}}function z(t){return t instanceof Qe?t.code==="NOT_FOUND"?404:t.code==="EXISTS"||t.code==="FULL"?409:t.code==="REFUSED"||t.code==="OUTSIDE"?403:400:400}async function me(t,e){return qe({roots:Ze(process.env,E.homedir(),t,e)})}async function Dn(t,e,n){const{index:r,quarantined:o,problems:i}=await me(e,n);a(t,200,{ok:!0,agents:et(r),...o.length?{quarantined:o.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...i.length?{problems:i}:{}})}async function _n(t,e,n,r){const{index:o}=await me(n,r),i=tt(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown agent definition"});a(t,200,{ok:!0,...i})}async function Hn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,{ok:!0,...await nt({agent:n?.agent,to:n?.to})})}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function Mn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,await ot({agent:n?.agent,to:n?.to,overwrite:!!n?.overwrite}))}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function ge(t){if(t instanceof at){if(t.code==="NOT_OURS")return 409;if(t.code==="TARGET")return 400}return 400}async function Un(){return(await Promise.all(Object.entries(O).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function ye(t,e=""){const n=await Un();if(e){const r=n.find(o=>o.id===e);return r?a(t,200,r):a(t,404,b(new R(`Model "${e}" not found`,404,"model")))}return a(t,200,{object:"list",data:n})}async function Wn(t){try{const e=await ie(g);a(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>Q(),400))}catch(e){a(t,400,{ok:!1,error:String(e?.message||e)})}}async function Bn(t,e){let n;try{n=await m(t)}catch(f){return a(e,400,{error:"Bad JSON: "+f.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=X(t,n.agent,n.options||{});if(o.error)return a(e,403,{error:o.error});n.options=o.options,Array.isArray(n.images)&&n.images.length&&u("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const i=f=>{e.writableEnded||e.write(`data: ${JSON.stringify(f)}
2
+ import{createServer as Te}from"node:http";import E from"node:os";import{randomBytes as Ee,randomInt as ve,timingSafeEqual as Oe}from"node:crypto";import{mkdirSync as Ce,writeFileSync as Ae,readFileSync as Y,existsSync as xe}from"node:fs";import{join as _}from"node:path";import*as Pe from"./engines/claude.js";import*as Re from"./engines/codex.js";import*as Ie from"./engines/antigravity.js";import{pi as $e,opencode as Ne,kiro as De,copilot as _e,deepseek as He,hermes as Me}from"./engines/cli-agents.js";import{connectorsFor as Ue}from"./connectors.js";import*as We from"./engines/custom.js";import{installService as Be,uninstallService as Ge,serviceStatus as Le,restartService as Q}from"./service.js";import{skillIndex as G,listRecords as je,readRecord as Fe,readPackageFile as Je,skillsHealth as Xe,quarantinedSkills as ze,clearSkillCache as L}from"./skills.js";import{writeSkillPackage as Ke,writeSkillFile as Ve,deleteSkillPackage as Ye,SkillWriteError as Qe}from"./skill-write.js";import{agentDefRoots as Ze,scanAgentDefs as qe,listAgentDefs as et,readAgentDef as tt,planAgentExport as nt,exportAgentDef as ot,agentDefsHealth as rt,AgentDefError as at}from"./agent-defs.js";import{capabilityToolSpecs as it,runCapabilityTool as st}from"./mcp-capabilities.js";import{createSession as ct,deleteSession as Z,getSession as q,activeSession as lt,relayToolCall as dt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ut,isDefaultWorkdir as ht,resolveWorkdir as pt,writeScopeNote as ft}from"./workdir.js";import{sandbox as ee,runSandboxCli as mt,withGrant as te,withoutOutsideWhenCapped as gt,grantedWriteRoots as yt,acceptRefusalReport as wt,liveProcesses as bt}from"./sandbox.js";import{gitState as St,gitDelta as kt}from"./scm.js";import{listConnections as Tt,putConnection as Et,removeConnection as vt,runEnvFor as Ot,testConnection as Ct,secretBackend as ne}from"./connections.js";import{worktreeFor as oe,listWorktrees as At,removeWorktree as xt,withHook as Pt,WORKTREE_ROOT as re}from"./worktree.js";import{AGENT_CLIS as Rt,agentAvailable as It,agentInstallDirs as $t,enrichPath as Nt,enrichAgentEnv as Dt,findAgentBin as _t,resolveCommand as ae}from"./env.js";import"./sanitize.js";import{checkForUpdate as Ht,selfUpdate as ie,isEmbedded as Mt}from"./update.js";import{callLocalMcp as Ut,localMcpStatus as Wt,signInLocalMcp as Bt,signInStatusLocalMcp as Gt}from"./mcp-local.js";import{assertPublicHttpUrl as se,assertPublicWebUrl as ce}from"./ssrf.js";import{startRun as le,endRun as j,cancelRun as Lt,cancelAll as jt}from"./runs.js";import{closeWarmPools as Ft,warmStatus as Jt}from"./warm.js";import{CompatError as R,anthropicError as F,anthropicStream as Xt,chatCompletionStream as zt,completionStream as Kt,createAnthropicMessage as Vt,createChatCompletion as Yt,createCompletion as Qt,createResponse as Zt,openAIError as b,parseAnthropicMessage as qt,parseChatCompletion as en,parseCompletion as tn,parseResponse as nn,responseStream as on}from"./api-compat.js";import{callerTrust as rn,isPaired as I,parseExtensionIds as an,capRunOptions as sn,engineHonoursReach as cn,createPairingStore as ln,formatPairingCode as dn}from"./pii/trust.js";const g="0.32.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:Pe,label:"Claude Code"},codex:{engine:Re,label:"Codex"},antigravity:{engine:Ie,label:"Antigravity",tools:!1},pi:{engine:$e,label:"Pi"},opencode:{engine:Ne,label:"OpenCode"},hermes:{engine:Me,label:"Hermes"},kiro:{engine:De,label:"Kiro"},copilot:{engine:_e,label:"GitHub Copilot"},deepseek:{engine:He,label:"DeepSeek Harness"},custom:{engine:We,label:"Custom",hidden:!0}};function de(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const un=an(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function $(t){return t.chatpanelTrust||(t.chatpanelTrust=rn({origin:t.headers.origin||"",hasToken:fe(t),extensionIds:un})),t.chatpanelTrust}function hn(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function pn(t,e){const n=t.headers.origin||"",r=de(n);e.setHeader("Access-Control-Allow-Origin",r?n||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function fn(t){if(!J.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(n)}const N=_(E.homedir(),".chatpanel","bridge-token");let S="";function mn(){try{xe(N)&&(S=Y(N,"utf8").trim()),S||(S=Ee(32).toString("hex"),Ce(_(E.homedir(),".chatpanel"),{recursive:!0}),Ae(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ue=ln({random:()=>ve(0,1e6)/1e6});function gn(t){if(!S)return a(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ue.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),a(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function yn(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=ue.claim(n?.code);return r.ok?(u("info",`paired a ${$(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${$(t)} caller`),a(e,403,{error:r.reason}))}function wn(t,e){const n=$(t);return a(e,200,{ok:!0,trust:n,paired:I(n),version:g})}let H=null;async function he(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(E.homedir(),".chatpanel"),dataDir:_(E.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function pe(t,e,n){try{const r=await he(),o=t.method==="POST"?await m(t):{};if(n==="status")return a(e,200,await r.status());if(n==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return n==="pair"?a(e,200,await r.pair()):n==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?a(e,200,await r.update(o)):n==="disconnect"?a(e,200,await r.stop({forget:!!o.forget})):a(e,404,{error:"unknown channel action"})}catch(r){return a(e,400,{error:r?.message||String(r)})}}function fe(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const r=Buffer.from(n),o=Buffer.from(S);return r.length===o.length&&Oe(r,o)}const bn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Sn=new Set(["/debug"]),kn=t=>Sn.has(t),Tn=(t,e)=>t!=="GET"&&t!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function En(t,e){if(!fn(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!de(n))return"forbidden origin";const r=t.method==="POST"&&bn.has(e)||t.method==="GET"&&kn(e)||Tn(t.method,e);return r&&!(hn(n)||fe(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I($(t))&&!On.has(e)?vn:null}const vn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",On=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(t,e,n){const r=$(t),o=gt(sn(n,r));if(!cn(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=o.reach,s=I(r)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:o,note:s}}function a(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function m(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function Cn(t){const e=await Promise.all(Object.entries(O).filter(([,s])=>!s.hidden).map(async([s,{engine:d,label:c,tools:l}])=>{const h=await d.available().catch(p=>({ok:!1,reason:String(p?.message||p)})),y=await Ue(s).catch(()=>[]);return{id:s,label:c,available:h.ok,reason:h.reason,connectors:y,...l===!1?{tools:!1}:{}}})),n=Mt()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Ht(g).catch(()=>({current:g,updateAvailable:!1})),r=await Xe().catch(()=>null),o=await rt().catch(()=>null),i=await ee().status().catch(s=>({enabled:!1,reason:s.message}));a(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ut,sandbox:i,localMcp:Wt(),processes:bt(),worktrees:re,secretBackend:ne(),warm:Jt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{},...o?{agentDefs:o}:{}})}async function An(t,e,n){const{index:r,problems:o}=await G({extraDirs:e,workdir:n});a(t,200,{ok:!0,skills:je(r),problems:o})}async function xn(t,e,n){a(t,200,{ok:!0,quarantined:await ze(e,n)})}async function Pn(t,e,n,r){const{index:o}=await G({extraDirs:n,workdir:r}),i=Fe(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown skill"});a(t,200,{ok:!0,skill:i})}async function Rn(t,e,n,r,o){const{index:i}=await G({extraDirs:r,workdir:o}),s=await Je(i,e,n);if(s.error)return a(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(t,200,{ok:!0,...s})}async function In(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{const r=await Ke({skill:n?.skill,files:n?.files||[],overwrite:!!n?.overwrite});return L(),a(e,200,r)}catch(r){return a(e,z(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function $n(t,e,n,r){let o;try{o=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}try{const i=await Ve({name:n,path:r,text:o?.text??""});return L(),a(e,200,i)}catch(i){return a(e,z(i),{ok:!1,error:i.message,code:i.code||"ERROR"})}}async function Nn(t,e){try{const n=await Ye({name:e});return L(),a(t,200,n)}catch(n){return a(t,z(n),{ok:!1,error:n.message,code:n.code||"ERROR"})}}function z(t){return t instanceof Qe?t.code==="NOT_FOUND"?404:t.code==="EXISTS"||t.code==="FULL"?409:t.code==="REFUSED"||t.code==="OUTSIDE"?403:400:400}async function me(t,e){return qe({roots:Ze(process.env,E.homedir(),t,e)})}async function Dn(t,e,n){const{index:r,quarantined:o,problems:i}=await me(e,n);a(t,200,{ok:!0,agents:et(r),...o.length?{quarantined:o.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...i.length?{problems:i}:{}})}async function _n(t,e,n,r){const{index:o}=await me(n,r),i=tt(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown agent definition"});a(t,200,{ok:!0,...i})}async function Hn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,{ok:!0,...await nt({agent:n?.agent,to:n?.to})})}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function Mn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,await ot({agent:n?.agent,to:n?.to,overwrite:!!n?.overwrite}))}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function ge(t){if(t instanceof at){if(t.code==="NOT_OURS")return 409;if(t.code==="TARGET")return 400}return 400}async function Un(){return(await Promise.all(Object.entries(O).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function ye(t,e=""){const n=await Un();if(e){const r=n.find(o=>o.id===e);return r?a(t,200,r):a(t,404,b(new R(`Model "${e}" not found`,404,"model")))}return a(t,200,{object:"list",data:n})}async function Wn(t){try{const e=await ie(g);a(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>Q(),400))}catch(e){a(t,400,{ok:!1,error:String(e?.message||e)})}}async function Bn(t,e){let n;try{n=await m(t)}catch(f){return a(e,400,{error:"Bad JSON: "+f.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=X(t,n.agent,n.options||{});if(o.error)return a(e,403,{error:o.error});n.options=o.options,Array.isArray(n.images)&&n.images.length&&u("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const i=f=>{e.writableEnded||e.write(`data: ${JSON.stringify(f)}
3
3
 
4
4
  `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=le(d),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};t.on("close",h),e.on("close",h),e.on("error",h);const y=f=>{s||i(f)};i({type:"run",id:d}),o.note&&i({type:"status",text:o.note});let p=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const f=n.options.workspace;if(p=await oe({repo:f.repo,projectId:f.projectId,jobId:f.jobId,base:f.base||null}),p.error){i({type:"error",error:`workspace: ${p.error}`}),j(d),e.writableEnded||e.end();return}}const K=p?p.path:pt(n.options?.workingDir);let C=null;{const f=K,A=!!p||!ht(n.options?.workingDir),w=ft(n.agent,n.options?.permissionMode,f,yt(f,{grant:n.options?.sandbox}));i({type:"workdir",path:f,isDefault:!A,writeScope:w||void 0}),i({type:"status",text:`Working in ${f}${A?"":" (default)"}`}),w&&i({type:"status",text:w}),C=await St(f),C&&i({type:"scm",phase:"before",...C})}let B=null;if(C||p){const f=Array.isArray(n.options?.grants)?n.options.grants:[],{env:A,connection:w}=Ot({remote:C?.remote||null,grants:f,branch:p?.branch||null,connectionId:n.options?.connectionId||null});B=Pt(A),p&&i({type:"workspace",path:p.path,branch:p.branch,base:p.base,created:p.created,repo:p.repo,...w?{connection:w}:{}}),w&&i({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${A.CHATPANEL_SCM_PUSH==="own"?`${p?.branch} only`:A.CHATPANEL_SCM_PUSH}`})}const V=n.approvals===!0,D={...n.options||{},...p?{workingDir:p.path}:{},...B?{runEnv:B}:{},approvals:V};let P=null;(n.pageTools?.specs?.length||V)&&(P=ct(y,n.pageTools?.specs||[]),D.permissionSession=P,n.pageTools?.specs?.length&&(D.mcp={url:`http://${k}:${v}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs}));try{await te(D.sandbox,()=>r.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:D,images:Array.isArray(n.images)?n.images:[]},y,{signal:l.signal}))}catch(f){u("error",`${n.agent} chat failed: ${f?.message||f}`),i({type:"error",error:f?.message||String(f)})}finally{if(!s){const f=await kt(K,C).catch(()=>null);f&&y({type:"scm",phase:"after",...f})}j(d),P&&Z(P.id),e.writableEnded||e.end()}}async function Gn(t,e,n){if(t.method==="GET"&&n==="/connections")return a(e,200,{ok:!0,connections:Tt(),secretBackend:ne()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await m(t);if(n==="/connections")try{return a(e,200,{ok:!0,connection:Et(r.connection||r,{token:r.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return o?o[2]==="delete"?a(e,200,{ok:vt(o[1])}):a(e,200,Ct(o[1],r.remote||"")):a(e,404,{error:"Not found"})}async function Ln(t,e,n){if(t.method==="GET"&&n==="/worktrees")return a(e,200,{ok:!0,root:re,worktrees:await At()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await m(t);if(n==="/worktrees"){const o=await oe({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return a(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(n==="/worktrees/remove"){const o=await xt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return a(e,o.ok?200:400,o)}return a(e,404,{error:"Not found"})}async function T(t,e,n){const r=O[t.agent];if(!r||r.hidden)throw new R(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new R(o.reason||`${t.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,s=le(i),d=()=>s.cancel("disconnected");n.on("close",d);let c="";try{return await te(t.options?.sandbox,()=>r.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{n.off("close",d),j(i)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5