@chatpanel/bridge 0.47.1 → 0.47.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.47.1",
3
+ "version": "0.47.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": [
package/src/mcp-local.js CHANGED
@@ -1,6 +1,6 @@
1
- import{spawn as B}from"node:child_process";import{registryEnv as G,normalizeRegistries as H}from"./events/registries.js";function F(n){try{return H({npm:n.CHATPANEL_REGISTRY_NPM,pypi:n.CHATPANEL_REGISTRY_PYPI,models:n.CHATPANEL_REGISTRY_MODELS,github:n.CHATPANEL_REGISTRY_GITHUB})}catch{return{}}}import Y from"node:os";import k from"node:path";import{resolveCommand as U,buildSpawnSpec as J}from"./env.js";import{sandbox as q,refusalsFor as K,track as V}from"./sandbox.js";import{missingCommandMessage as W}from"./events/mcp-errors.js";import{parseSignInPrompt as Q,signInError as x,signInFromError as X}from"./events/mcp-signin.js";import{pickProbeTool as Z}from"./events/mcp-launcher.js";import{envLikeArgs as nn}from"./events/mcp-args-env.js";const d=new Map,b=new Map,C=10*6e4,en=6e4,tn=5*6e4,$=Object.freeze({protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"ChatPanel",version:"1.0"}}),rn=150,on=8*6e4,sn=16*6e4,S=4e3;function L(n){const e=Y.homedir(),t={};for(const[i,s]of Object.entries(n||{})){const o=String(s);t[i]=o==="~"?e:o.startsWith("~/")?k.join(e,o.slice(2)):o}return t}const A=n=>n.key||`${n.command}\0${(Array.isArray(n.args)?n.args.join(" "):n.args)||""}`,O=n=>JSON.stringify([n.command,Array.isArray(n.args)?n.args:String(n.args||""),n.env||{},n.cwd||null,n.sandbox||null]);function T(n,e){clearTimeout(n.idleTimer);for(const{reject:t,timer:i}of n.pending.values())clearTimeout(i),t(e);n.pending.clear(),d.get(n.key)===n&&d.delete(n.key);try{n.child.kill()}catch{}}function f(n){clearTimeout(n.idleTimer);const e=n.pendingSignIn?Math.max(C,sn):C;n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}d.delete(n.key)},e)}function an(n){const e=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
1
+ import{spawn as B}from"node:child_process";import{registryEnv as G,normalizeRegistries as H}from"./events/registries.js";function F(n){try{return H({npm:n.CHATPANEL_REGISTRY_NPM,pypi:n.CHATPANEL_REGISTRY_PYPI,models:n.CHATPANEL_REGISTRY_MODELS,github:n.CHATPANEL_REGISTRY_GITHUB})}catch{return{}}}import Y from"node:os";import k from"node:path";import{resolveCommand as U,buildSpawnSpec as J}from"./env.js";import{sandbox as q,refusalsFor as K,track as V}from"./sandbox.js";import{missingCommandMessage as W}from"./events/mcp-errors.js";import{parseSignInPrompt as Q,signInError as x,signInFromError as X}from"./events/mcp-signin.js";import{pickProbeTool as Z}from"./events/mcp-launcher.js";import{envLikeArgs as nn}from"./events/mcp-args-env.js";const c=new Map,b=new Map,C=10*6e4,en=6e4,tn=5*6e4,$=Object.freeze({protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"ChatPanel",version:"1.0"}}),rn=150,on=8*6e4,sn=16*6e4,S=4e3;function L(n){const e=Y.homedir(),t={};for(const[r,s]of Object.entries(n||{})){const o=String(s);t[r]=o==="~"?e:o.startsWith("~/")?k.join(e,o.slice(2)):o}return t}const T=n=>n.key||`${n.command}\0${(Array.isArray(n.args)?n.args.join(" "):n.args)||""}`,O=n=>JSON.stringify([n.command,Array.isArray(n.args)?n.args:String(n.args||""),n.env||{},n.cwd||null,n.sandbox||null]);function y(n,e){clearTimeout(n.idleTimer);for(const{reject:t,timer:r}of n.pending.values())clearTimeout(r),t(e);n.pending.clear(),c.get(n.key)===n&&c.delete(n.key);try{n.child.kill()}catch{}}function f(n){clearTimeout(n.idleTimer);const e=n.pendingSignIn?Math.max(C,sn):C;n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}c.delete(n.key)},e)}function an(n){const e=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
2
2
  `).split(`
3
3
  `).map(t=>t.trimEnd()).filter(Boolean).join(`
4
- `).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function y(n,e){const t=an(e?.stderr);return t?`${n}: ${t}`:n}const M=new Map,j=new Set;function Mn(){const n=[];for(const e of d.values())e.child.exitCode!=null||e.child.killed||n.push({id:e.key,command:k.basename(String(e.command||"")),pid:e.child.pid??null,sandbox:e.sandbox,commandId:e.commandId,since:e.startedAt,refused:K(e.commandId)});return n}async function z(n){const e=A(n),t=O(n);if(M.has(e)){const o=await M.get(e);if(o.sig===t)return o}const i=d.get(e);if(i&&i.child.exitCode==null&&!i.child.killed){if(i.sig===t)return f(i),i;T(i,new Error("local MCP server restarted: its configuration changed"))}const s=ln(n,e,t).finally(()=>M.delete(e));return M.set(e,s),s}async function ln(n,e,t=O(n)){const i=U(n.command);if(!i)throw new Error(W(n.command,{platform:process.platform}));const s=Array.isArray(n.args)?n.args:String(n.args||"").split(/\s+/).filter(Boolean),o={};for(const a of nn(s)){const l=a.indexOf("=");o[a.slice(0,l).trim()]=a.slice(l+1).trim()}const[p,h,u]=J(i,s,n.cwd||null);u.env={...u.env||process.env,...G(F(u.env||process.env)),...L(o),...L(n.env||{})},Object.keys(o).length&&console.error(`[bridge] local MCP "${n.command}": ${Object.keys(o).join(", ")} looked like environment variables in Arguments, so they were applied as env too`),u.stdio=["pipe","pipe","pipe"];const c=await q().wrap(p,h,u,{engine:"mcp",cwd:n.cwd||null,commandId:`mcp:${String(e).slice(0,48)}`,...n.sandbox?{grant:n.sandbox}:{}}),[N,R,D]=[c.bin,c.argv,c.opts];c.record.layer==="none"&&!j.has(c.record.reason)&&(j.add(c.record.reason),console.error(`[bridge] local MCP "${n.command}" runs outside a sandbox — ${c.record.reason}`));const g=V(B(N,R,D),c,{kind:"mcp",label:e}),r={key:e,sig:t,child:g,command:n.command,sandbox:c.record,commandId:c.commandId,startedAt:Date.now(),pending:new Map,buf:"",stderr:"",idleTimer:null,initialized:!1,handshake:null,pendingSignIn:null,pendingSignInAt:0,signInIds:null},v=a=>T(r,a);return g.stdout.setEncoding("utf8"),g.stdout.on("data",a=>{r.buf+=a;let l;for(;(l=r.buf.indexOf(`
5
- `))>=0;){const I=r.buf.slice(0,l).trim();if(r.buf=r.buf.slice(l+1),I[0]!=="{"&&I[0]!=="[")continue;let w;try{w=JSON.parse(I)}catch{continue}for(const m of Array.isArray(w)?w:[w]){m&&m.id!=null&&r.signInIds?.has(m.id)&&(r.signInIds.delete(m.id),r.signInIds.size||(r.pendingSignIn=null,r.signedInAt=Date.now(),f(r)));const P=m&&m.id!=null?r.pending.get(m.id):null;P&&(clearTimeout(P.timer),r.pending.delete(m.id),P.resolve(m))}}}),g.stderr.setEncoding("utf8"),g.stderr.on("data",a=>{r.stderr+=a,r.stderr.length>S*2&&(r.stderr=r.stderr.slice(-S*2)),r.pending.size&&(r.promptBuf=((r.promptBuf||"")+a).slice(-2e3),clearTimeout(r.promptTimer),r.promptTimer=setTimeout(()=>{const l=Q(r.promptBuf);l&&(r.promptBuf="",dn(r,l))},rn))}),g.on("error",a=>v(new Error(y(`local MCP "${n.command}" failed to start: ${a.message}`,r)))),g.on("close",(a,l)=>{const I=l?`exited with signal ${l}`:a==null?"exited":`exited with code ${a}`;v(new Error(y(`local MCP "${n.command}" ${I}`,r)))}),d.set(e,r),f(r),r}function dn(n,e){if(f(n),e.code&&(n.pendingSignIn=e,n.pendingSignInAt=Date.now(),n.signInIds=new Set(n.pending.keys()),f(n)),e.browser){for(const i of n.pending.values())clearTimeout(i.timer),i.timer=setTimeout(()=>{i.reject(new Error(y("local MCP call timed out waiting for the sign-in",n)))},tn);return}const t=x(e);for(const[i,s]of n.pending)clearTimeout(s.timer),n.pending.delete(i),s.resolve({jsonrpc:"2.0",id:i,error:t})}function _(n,e){const t=()=>n.child.stdin.write(JSON.stringify(e)+`
6
- `);return e.id==null?(t(),Promise.resolve(null)):new Promise((i,s)=>{const o=setTimeout(()=>{n.pending.delete(e.id),s(new Error(y("local MCP call timed out",n)))},en);n.pending.set(e.id,{resolve:i,reject:s,timer:o}),t()})}function cn(n,e){return n.initialized?Promise.resolve():(n.handshake||(n.handshake=(async()=>{const t=await _(n,{jsonrpc:"2.0",id:`cp-init-${Date.now()}`,method:"initialize",params:e});if(t?.error)throw new Error(`local MCP re-initialize failed: ${t.error.message||t.error.code}`);await _(n,{jsonrpc:"2.0",method:"notifications/initialized"}),n.initialized=!0})().finally(()=>{n.handshake=null})),n.handshake)}async function En(n,{initializeParams:e=$}={}){const t=await z(n);if(t.pendingSignIn)return{state:"prompt",signIn:t.pendingSignIn,since:t.pendingSignInAt};await E(n,{jsonrpc:"2.0",id:`cp-si-init-${Date.now()}`,method:"initialize",params:e}).catch(()=>{});const s=(await E(n,{jsonrpc:"2.0",id:`cp-si-list-${Date.now()}`,method:"tools/list",params:{}}).catch(()=>null))?.result?.tools||[],o=Z(s);if(!o)return{state:"unsupported",error:"This server declares no read-only tool that takes no arguments, so there is nothing safe to call to make it sign in."};const p=await E(n,{jsonrpc:"2.0",id:`cp-si-${Date.now()}`,method:"tools/call",params:{name:o,arguments:{}}}).catch(u=>({error:{message:String(u?.message||u)}})),h=X(p?.error);return h?{state:"prompt",signIn:h,since:d.get(A(n))?.pendingSignInAt||Date.now(),probe:o}:p?.error?{state:"failed",error:p.error.message||"the server refused",probe:o}:{state:"signed-in",probe:o}}function Pn(n){const e=d.get(A(n));return!e||e.child.exitCode!=null?{state:"gone"}:e.pendingSignIn?{state:"prompt",signIn:e.pendingSignIn,since:e.pendingSignInAt}:{state:e.signedInAt?"signed-in":"idle"}}function mn(n){const e=d.get(n);return e?(T(e,new Error("local MCP server stopped")),!0):!1}function bn(){let n=0;for(const e of[...d.keys()])mn(e)&&(n+=1);return n}function An(n){return d.get(n)||null}function _n(n){return b.has(n)}async function E(n,e){if(!n?.command)throw new Error("no command for local MCP server");const t=await z(n);if(f(t),e.method==="initialize")b.set(t.key,e.params||{}),t.initialized=!0;else if(e.method!=="notifications/initialized"){if(e.id!=null&&t.pendingSignIn&&Date.now()-t.pendingSignInAt<on)return{jsonrpc:"2.0",id:e.id,error:x(t.pendingSignIn)};if(e.id!=null&&t.pendingSignIn)return T(t,new Error("local MCP sign-in expired: starting a new one")),E(n,e);t.initialized||await cn(t,b.get(t.key)||$)}return _(t,e)}export{An as _procForTest,E as callLocalMcp,_n as hasInitParams,Mn as localMcpStatus,En as signInLocalMcp,Pn as signInStatusLocalMcp,bn as stopAllLocalMcp,mn as stopLocalMcp};
4
+ `).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function M(n,e){const t=an(e?.stderr);return t?`${n}: ${t}`:n}const A=new Map,j=new Set;function Mn(){const n=[];for(const e of c.values())e.child.exitCode!=null||e.child.killed||n.push({id:e.key,command:k.basename(String(e.command||"")),pid:e.child.pid??null,sandbox:e.sandbox,commandId:e.commandId,since:e.startedAt,refused:K(e.commandId)});return n}async function z(n){const e=T(n),t=O(n);if(A.has(e)){const o=await A.get(e);if(o.sig===t)return o}const r=c.get(e);if(r&&r.child.exitCode==null&&!r.child.killed){if(r.sig===t)return f(r),r;y(r,new Error("local MCP server restarted: its configuration changed"))}const s=ln(n,e,t).finally(()=>A.delete(e));return A.set(e,s),s}async function ln(n,e,t=O(n)){const r=U(n.command);if(!r)throw new Error(W(n.command,{platform:process.platform}));const s=Array.isArray(n.args)?n.args:String(n.args||"").split(/\s+/).filter(Boolean),o={};for(const a of nn(s)){const d=a.indexOf("=");o[a.slice(0,d).trim()]=a.slice(d+1).trim()}const[p,h,u]=J(r,s,n.cwd||null);u.env={...u.env||process.env,...G(F(u.env||process.env)),...L(o),...L(n.env||{})},Object.keys(o).length&&console.error(`[bridge] local MCP "${n.command}": ${Object.keys(o).join(", ")} looked like environment variables in Arguments, so they were applied as env too`),u.stdio=["pipe","pipe","pipe"];const l=await q().wrap(p,h,u,{engine:"mcp",cwd:n.cwd||null,commandId:`mcp:${String(e).slice(0,48)}`,...n.sandbox?{grant:n.sandbox}:{}}),[N,D,R]=[l.bin,l.argv,l.opts];l.record.layer==="none"&&!j.has(l.record.reason)&&(j.add(l.record.reason),console.error(`[bridge] local MCP "${n.command}" runs outside a sandbox — ${l.record.reason}`));const g=V(B(N,D,R),l,{kind:"mcp",label:e}),i={key:e,sig:t,child:g,command:n.command,sandbox:l.record,commandId:l.commandId,startedAt:Date.now(),pending:new Map,buf:"",stderr:"",idleTimer:null,initialized:!1,handshake:null,pendingSignIn:null,pendingSignInAt:0,signInIds:null},v=a=>y(i,a);return g.stdout.setEncoding("utf8"),g.stdout.on("data",a=>{i.buf+=a;let d;for(;(d=i.buf.indexOf(`
5
+ `))>=0;){const I=i.buf.slice(0,d).trim();if(i.buf=i.buf.slice(d+1),I[0]!=="{"&&I[0]!=="[")continue;let w;try{w=JSON.parse(I)}catch{continue}for(const m of Array.isArray(w)?w:[w]){m&&m.id!=null&&i.signInIds?.has(m.id)&&(i.signInIds.delete(m.id),i.signInIds.size||(i.pendingSignIn=null,i.signedInAt=Date.now(),f(i)));const P=m&&m.id!=null?i.pending.get(m.id):null;P&&(clearTimeout(P.timer),i.pending.delete(m.id),P.resolve(m))}}}),g.stderr.setEncoding("utf8"),g.stderr.on("data",a=>{i.stderr+=a,i.stderr.length>S*2&&(i.stderr=i.stderr.slice(-S*2)),i.pending.size&&(i.promptBuf=((i.promptBuf||"")+a).slice(-2e3),clearTimeout(i.promptTimer),i.promptTimer=setTimeout(()=>{const d=Q(i.promptBuf);d&&(i.promptBuf="",dn(i,d))},rn))}),g.on("error",a=>v(new Error(M(`local MCP "${n.command}" failed to start: ${a.message}`,i)))),g.on("close",(a,d)=>{const I=d?`exited with signal ${d}`:a==null?"exited":`exited with code ${a}`;v(new Error(M(`local MCP "${n.command}" ${I}`,i)))}),c.set(e,i),f(i),i}function dn(n,e){if(f(n),e.code&&(n.pendingSignIn=e,n.pendingSignInAt=Date.now(),n.signInIds=new Set(n.pending.keys()),f(n)),e.browser){for(const r of n.pending.values())clearTimeout(r.timer),r.timer=setTimeout(()=>{r.reject(new Error(M("local MCP call timed out waiting for the sign-in",n)))},tn);return}const t=x(e);for(const[r,s]of n.pending)clearTimeout(s.timer),n.pending.delete(r),s.resolve({jsonrpc:"2.0",id:r,error:t})}function _(n,e){const t=()=>n.child.stdin.write(JSON.stringify(e)+`
6
+ `);return e.id==null?(t(),Promise.resolve(null)):new Promise((r,s)=>{const o=setTimeout(()=>{n.pending.delete(e.id),s(new Error(M("local MCP call timed out",n)))},en);n.pending.set(e.id,{resolve:r,reject:s,timer:o}),t()})}function cn(n,e){return n.initialized?Promise.resolve():(n.handshake||(n.handshake=(async()=>{const t=await _(n,{jsonrpc:"2.0",id:`cp-init-${Date.now()}`,method:"initialize",params:e});if(t?.error)throw new Error(`local MCP re-initialize failed: ${t.error.message||t.error.code}`);await _(n,{jsonrpc:"2.0",method:"notifications/initialized"}),n.initialized=!0})().finally(()=>{n.handshake=null})),n.handshake)}async function An(n,{initializeParams:e=$}={}){const t=await z(n);if(t.pendingSignIn)return{state:"prompt",signIn:t.pendingSignIn,since:t.pendingSignInAt};await E(n,{jsonrpc:"2.0",id:`cp-si-init-${Date.now()}`,method:"initialize",params:e}).catch(()=>{});const s=(await E(n,{jsonrpc:"2.0",id:`cp-si-list-${Date.now()}`,method:"tools/list",params:{}}).catch(()=>null))?.result?.tools||[],o=Z(s);if(!o)return{state:"unsupported",error:"This server declares no read-only tool that takes no arguments, so there is nothing safe to call to make it sign in."};const p=await E(n,{jsonrpc:"2.0",id:`cp-si-${Date.now()}`,method:"tools/call",params:{name:o,arguments:{}}}).catch(l=>({error:{message:String(l?.message||l)}})),h=X(p?.error);if(h)return{state:"prompt",signIn:h,since:c.get(T(n))?.pendingSignInAt||Date.now(),probe:o};if(p?.error)return{state:"failed",error:p.error.message||"the server refused",probe:o};const u=c.get(T(n));return u&&(u.signedInAt=Date.now()),{state:"signed-in",probe:o}}function En(n){const e=c.get(T(n));return!e||e.child.exitCode!=null?{state:"gone"}:e.pendingSignIn?{state:"prompt",signIn:e.pendingSignIn,since:e.pendingSignInAt}:{state:e.signedInAt?"signed-in":"idle"}}function mn(n){const e=c.get(n);return e?(y(e,new Error("local MCP server stopped")),!0):!1}function Pn(){let n=0;for(const e of[...c.keys()])mn(e)&&(n+=1);return n}function bn(n){return c.get(n)||null}function _n(n){return b.has(n)}async function E(n,e){if(!n?.command)throw new Error("no command for local MCP server");const t=await z(n);if(f(t),e.method==="initialize")b.set(t.key,e.params||{}),t.initialized=!0;else if(e.method!=="notifications/initialized"){if(e.id!=null&&t.pendingSignIn&&Date.now()-t.pendingSignInAt<on)return{jsonrpc:"2.0",id:e.id,error:x(t.pendingSignIn)};if(e.id!=null&&t.pendingSignIn)return y(t,new Error("local MCP sign-in expired: starting a new one")),E(n,e);t.initialized||await cn(t,b.get(t.key)||$)}return _(t,e)}export{bn as _procForTest,E as callLocalMcp,_n as hasInitParams,Mn as localMcpStatus,An as signInLocalMcp,En as signInStatusLocalMcp,Pn as stopAllLocalMcp,mn as stopLocalMcp};
package/src/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as Ge}from"node:http";import O from"node:os";import{randomBytes as Ue,randomInt as Le,timingSafeEqual as We}from"node:crypto";import{mkdirSync as je,writeFileSync as Fe,readFileSync as re,existsSync as Je}from"node:fs";import{join as M}from"node:path";import*as Xe from"./engines/claude.js";import*as Ke from"./engines/codex.js";import*as ze from"./engines/antigravity.js";import{pi as Ye,opencode as Ve,kiro as Qe,copilot as Ze,deepseek as qe,hermes as et}from"./engines/cli-agents.js";import{connectorsFor as tt}from"./connectors.js";import*as nt from"./engines/custom.js";import{installService as ot,uninstallService as rt,serviceStatus as at,restartService as ae}from"./service.js";import{skillIndex as J,listRecords as it,readRecord as st,readPackageFile as ct,skillsHealth as lt,quarantinedSkills as dt,clearSkillCache as X}from"./skills.js";import{writeSkillPackage as ut,writeSkillFile as ht,deleteSkillPackage as pt,SkillWriteError as ft}from"./skill-write.js";import{agentDefRoots as mt,scanAgentDefs as gt,listAgentDefs as wt,readAgentDef as yt,planAgentExport as bt,exportAgentDef as St,agentDefsHealth as kt,AgentDefError as Tt}from"./agent-defs.js";import{capabilityToolSpecs as xt,runCapabilityTool as Et}from"./mcp-capabilities.js";import{createSession as vt,deleteSession as ie,getSession as se,activeSession as At,relayToolCall as Ot}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ct,isDefaultWorkdir as Pt,resolveWorkdir as $t,writeScopeNote as Rt}from"./workdir.js";import{sandbox as K,runSandboxCli as It,withGrant as ce,withAgentGrant as Nt,withoutOutsideWhenCapped as Dt,grantedWriteRoots as le,acceptRefusalReport as _t,liveProcesses as Ht,sandboxConfigFromEnv as Mt}from"./sandbox.js";import{createAccessGate as Bt,chatKeyOf as Gt,chatFolders as Ut}from"./access-gate.js";import{signInDenial as Lt}from"./events/sandbox-policy.js";import{gitState as Wt,gitDelta as jt}from"./scm.js";import{listConnections as Ft,putConnection as Jt,removeConnection as Xt,runEnvFor as Kt,testConnection as zt,secretBackend as de}from"./connections.js";import{worktreeFor as ue,listWorktrees as Yt,removeWorktree as Vt,withHook as Qt,WORKTREE_ROOT as he}from"./worktree.js";import{AGENT_CLIS as Zt,agentAvailable as qt,agentInstallDirs as en,enrichPath as tn,enrichAgentEnv as nn,findAgentBin as on,forgetMisses as rn,primeAgentLookups as an,resolveCommand as pe,isCompiledBinary as sn}from"./env.js";import"./sanitize.js";import{checkForUpdate as cn,selfUpdate as fe,isEmbedded as me}from"./update.js";import{callLocalMcp as ln,localMcpStatus as dn,signInLocalMcp as un,signInStatusLocalMcp as hn}from"./mcp-local.js";import{assertPublicHttpUrl as ge,assertPublicWebUrl as we}from"./ssrf.js";import{startRun as ye,endRun as z,cancelRun as pn,cancelAll as fn}from"./runs.js";import{closeWarmPools as mn,warmStatus as gn}from"./warm.js";import{SESSION_AGENTS as be,listSessions as wn,readSession as yn,adoptSession as bn,catchUp as Sn}from"./agent-sessions.js";import{agentContext as kn}from"./agent-context.js";import{normalizeThread as Se}from"./events/agent-thread.js";import{portClashPlan as Tn,serviceManagerOf as xn,STANDBY_POLL_MS as En}from"./events/service-standby.js";import{holdThread as ke}from"./threads.js";import{oneReply as vn}from"./one-reply.js";import{createSnapshot as An}from"./health-snapshot.js";import{CompatError as P,anthropicError as Y,anthropicStream as On,chatCompletionStream as Cn,completionStream as Pn,createAnthropicMessage as $n,createChatCompletion as Rn,createCompletion as In,createResponse as Nn,openAIError as S,parseAnthropicMessage as Dn,parseChatCompletion as _n,parseCompletion as Hn,parseResponse as Mn,responseStream as Bn}from"./api-compat.js";import{callerTrust as Gn,isPaired as I,parseExtensionIds as Un,capRunOptions as Ln,engineHonoursReach as Wn,createPairingStore as jn,formatPairingCode as Fn}from"./pii/trust.js";const y="0.47.1",x=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Xe,label:"Claude Code"},codex:{engine:Ke,label:"Codex"},antigravity:{engine:ze,label:"Antigravity",tools:!1},pi:{engine:Ye,label:"Pi"},opencode:{engine:Ve,label:"OpenCode"},hermes:{engine:et,label:"Hermes"},kiro:{engine:Qe,label:"Kiro"},copilot:{engine:Ze,label:"GitHub Copilot"},deepseek:{engine:qe,label:"DeepSeek Harness"},custom:{engine:nt,label:"Custom",hidden:!0}};function Te(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Jn=Un(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gn({origin:n.headers.origin||"",hasToken:Ae(n),extensionIds:Jn})),n.chatpanelTrust}function Xn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Kn(n,e){const t=n.headers.origin||"",o=Te(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const V=new Set(["127.0.0.1","localhost","::1"]);function zn(n){if(!V.has(x))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return V.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let v="";function Yn(){try{Je(D)&&(v=re(D,"utf8").trim()),v||(v=Ue(32).toString("hex"),je(M(O.homedir(),".chatpanel"),{recursive:!0}),Fe(D,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=jn({random:()=>Le(0,1e6)/1e6});function Vn(n){if(!v)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=xe.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Qn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=xe.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:v})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Zn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ee(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function ve(n,e,t){try{const o=await Ee(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function Ae(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&We(o,r)}const qn=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),eo=new Set(["/debug"]),to=n=>eo.has(n),no=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function oo(n,e){if(!zn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!Te(t))return"forbidden origin";const o=n.method==="POST"&&qn.has(e)||n.method==="GET"&&to(e)||no(n.method,e);return o&&!(Xn(t)||Ae(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!ao.has(e)?ro:null}const Oe=()=>me()?"chatpanel-gateway pair":"chatpanel-bridge pair",ro=`forbidden: this client is not paired with the bridge — run \`${Oe()}\` and enter the code in ChatPanel Settings`,ao=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Q(n,e,t){const o=N(n),r=Nt(e,Dt(Ln(t,o)));if(!Wn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":`pair this client (${Oe()})`} to use ${e}`};const a=r.reach,s=I(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:r,note:s}}async function Ce(n,e,t){const o=e?.message||String(e);try{const r=await K().status(),a=!!(r.enabled&&r.runtime)&&t?.outside!==!0,s=Lt(`${o}
2
+ import{createServer as Ge}from"node:http";import O from"node:os";import{randomBytes as Ue,randomInt as Le,timingSafeEqual as We}from"node:crypto";import{mkdirSync as je,writeFileSync as Fe,readFileSync as re,existsSync as Je}from"node:fs";import{join as M}from"node:path";import*as Xe from"./engines/claude.js";import*as Ke from"./engines/codex.js";import*as ze from"./engines/antigravity.js";import{pi as Ye,opencode as Ve,kiro as Qe,copilot as Ze,deepseek as qe,hermes as et}from"./engines/cli-agents.js";import{connectorsFor as tt}from"./connectors.js";import*as nt from"./engines/custom.js";import{installService as ot,uninstallService as rt,serviceStatus as at,restartService as ae}from"./service.js";import{skillIndex as J,listRecords as it,readRecord as st,readPackageFile as ct,skillsHealth as lt,quarantinedSkills as dt,clearSkillCache as X}from"./skills.js";import{writeSkillPackage as ut,writeSkillFile as ht,deleteSkillPackage as pt,SkillWriteError as ft}from"./skill-write.js";import{agentDefRoots as mt,scanAgentDefs as gt,listAgentDefs as wt,readAgentDef as yt,planAgentExport as bt,exportAgentDef as St,agentDefsHealth as kt,AgentDefError as Tt}from"./agent-defs.js";import{capabilityToolSpecs as xt,runCapabilityTool as Et}from"./mcp-capabilities.js";import{createSession as vt,deleteSession as ie,getSession as se,activeSession as At,relayToolCall as Ot}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ct,isDefaultWorkdir as Pt,resolveWorkdir as $t,writeScopeNote as Rt}from"./workdir.js";import{sandbox as K,runSandboxCli as It,withGrant as ce,withAgentGrant as Nt,withoutOutsideWhenCapped as Dt,grantedWriteRoots as le,acceptRefusalReport as _t,liveProcesses as Ht,sandboxConfigFromEnv as Mt}from"./sandbox.js";import{createAccessGate as Bt,chatKeyOf as Gt,chatFolders as Ut}from"./access-gate.js";import{signInDenial as Lt}from"./events/sandbox-policy.js";import{gitState as Wt,gitDelta as jt}from"./scm.js";import{listConnections as Ft,putConnection as Jt,removeConnection as Xt,runEnvFor as Kt,testConnection as zt,secretBackend as de}from"./connections.js";import{worktreeFor as ue,listWorktrees as Yt,removeWorktree as Vt,withHook as Qt,WORKTREE_ROOT as he}from"./worktree.js";import{AGENT_CLIS as Zt,agentAvailable as qt,agentInstallDirs as en,enrichPath as tn,enrichAgentEnv as nn,findAgentBin as on,forgetMisses as rn,primeAgentLookups as an,resolveCommand as pe,isCompiledBinary as sn}from"./env.js";import"./sanitize.js";import{checkForUpdate as cn,selfUpdate as fe,isEmbedded as me}from"./update.js";import{callLocalMcp as ln,localMcpStatus as dn,signInLocalMcp as un,signInStatusLocalMcp as hn}from"./mcp-local.js";import{assertPublicHttpUrl as ge,assertPublicWebUrl as we}from"./ssrf.js";import{startRun as ye,endRun as z,cancelRun as pn,cancelAll as fn}from"./runs.js";import{closeWarmPools as mn,warmStatus as gn}from"./warm.js";import{SESSION_AGENTS as be,listSessions as wn,readSession as yn,adoptSession as bn,catchUp as Sn}from"./agent-sessions.js";import{agentContext as kn}from"./agent-context.js";import{normalizeThread as Se}from"./events/agent-thread.js";import{portClashPlan as Tn,serviceManagerOf as xn,STANDBY_POLL_MS as En}from"./events/service-standby.js";import{holdThread as ke}from"./threads.js";import{oneReply as vn}from"./one-reply.js";import{createSnapshot as An}from"./health-snapshot.js";import{CompatError as P,anthropicError as Y,anthropicStream as On,chatCompletionStream as Cn,completionStream as Pn,createAnthropicMessage as $n,createChatCompletion as Rn,createCompletion as In,createResponse as Nn,openAIError as S,parseAnthropicMessage as Dn,parseChatCompletion as _n,parseCompletion as Hn,parseResponse as Mn,responseStream as Bn}from"./api-compat.js";import{callerTrust as Gn,isPaired as I,parseExtensionIds as Un,capRunOptions as Ln,engineHonoursReach as Wn,createPairingStore as jn,formatPairingCode as Fn}from"./pii/trust.js";const y="0.47.2",x=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Xe,label:"Claude Code"},codex:{engine:Ke,label:"Codex"},antigravity:{engine:ze,label:"Antigravity",tools:!1},pi:{engine:Ye,label:"Pi"},opencode:{engine:Ve,label:"OpenCode"},hermes:{engine:et,label:"Hermes"},kiro:{engine:Qe,label:"Kiro"},copilot:{engine:Ze,label:"GitHub Copilot"},deepseek:{engine:qe,label:"DeepSeek Harness"},custom:{engine:nt,label:"Custom",hidden:!0}};function Te(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Jn=Un(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gn({origin:n.headers.origin||"",hasToken:Ae(n),extensionIds:Jn})),n.chatpanelTrust}function Xn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Kn(n,e){const t=n.headers.origin||"",o=Te(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const V=new Set(["127.0.0.1","localhost","::1"]);function zn(n){if(!V.has(x))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return V.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let v="";function Yn(){try{Je(D)&&(v=re(D,"utf8").trim()),v||(v=Ue(32).toString("hex"),je(M(O.homedir(),".chatpanel"),{recursive:!0}),Fe(D,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=jn({random:()=>Le(0,1e6)/1e6});function Vn(n){if(!v)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=xe.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Qn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=xe.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:v})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Zn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ee(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function ve(n,e,t){try{const o=await Ee(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function Ae(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&We(o,r)}const qn=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),eo=new Set(["/debug"]),to=n=>eo.has(n),no=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function oo(n,e){if(!zn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!Te(t))return"forbidden origin";const o=n.method==="POST"&&qn.has(e)||n.method==="GET"&&to(e)||no(n.method,e);return o&&!(Xn(t)||Ae(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!ao.has(e)?ro:null}const Oe=()=>me()?"chatpanel-gateway pair":"chatpanel-bridge pair",ro=`forbidden: this client is not paired with the bridge — run \`${Oe()}\` and enter the code in ChatPanel Settings`,ao=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Q(n,e,t){const o=N(n),r=Nt(e,Dt(Ln(t,o)));if(!Wn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":`pair this client (${Oe()})`} to use ${e}`};const a=r.reach,s=I(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:r,note:s}}async function Ce(n,e,t){const o=e?.message||String(e);try{const r=await K().status(),a=!!(r.enabled&&r.runtime)&&t?.outside!==!0,s=Lt(`${o}
3
3
  ${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:E[n]?.label||n||"This agent"});if(s)return s.line}catch{}return o}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}const Pe=An({compute:io});async function io(){await an();const n=await Promise.all(Object.entries(E).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:d}])=>{const l=await s.available().catch(w=>({ok:!1,reason:String(w?.message||w)})),p=await tt(a).catch(()=>[]);return{id:a,label:c,available:l.ok,reason:l.reason,connectors:p,...d===!1?{tools:!1}:{}}})),e=me()?{current:y,updateAvailable:!1,embedded:"gateway"}:await cn(y).catch(()=>({current:y,updateAvailable:!1})),t=await lt().catch(()=>null),o=await kt().catch(()=>null),r=await K().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function so(n,{fresh:e=!1}={}){e&&rn();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await Pe.get({fresh:e});i(n,200,{ok:!0,version:y,agents:o,update:r,checkedAt:t,workspace:Ct,sandbox:c,localMcp:dn(),processes:Ht(),worktrees:he,secretBackend:de(),warm:gn(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...s?{agentDefs:s}:{}})}async function co(n,e,t){const{index:o,problems:r}=await J({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:it(o),problems:r})}async function lo(n,e,t){i(n,200,{ok:!0,quarantined:await dt(e,t)})}async function uo(n,e,t,o){const{index:r}=await J({extraDirs:t,workdir:o}),a=st(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ho(n,e,t,o,r){const{index:a}=await J({extraDirs:o,workdir:r}),s=await ct(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function po(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await ut({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return X(),i(e,200,o)}catch(o){return i(e,Z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function fo(n,e,t,o){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await ht({name:t,path:o,text:r?.text??""});return X(),i(e,200,a)}catch(a){return i(e,Z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function mo(n,e){try{const t=await pt({name:e});return X(),i(n,200,t)}catch(t){return i(n,Z(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function Z(n){return n instanceof ft?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function $e(n,e){return gt({roots:mt(process.env,O.homedir(),n,e)})}async function go(n,e,t){const{index:o,quarantined:r,problems:a}=await $e(e,t);i(n,200,{ok:!0,agents:wt(o),...r.length?{quarantined:r.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function wo(n,e,t,o){const{index:r}=await $e(t,o),a=yt(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function yo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,{ok:!0,...await bt({agent:t?.agent,to:t?.to})})}catch(o){return i(e,Re(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function bo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,await St({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,Re(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function Re(n){if(n instanceof Tt){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function So(){return(await Promise.all(Object.entries(E).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function Ie(n,e=""){const t=await So();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function ko(n){try{const e=await fe(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>ae(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function To(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=Q(n,t.agent,t.options||{});if(r.error)return i(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
4
4
 
5
5
  `)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,d=ye(c),l={signal:d.signal,abort:()=>d.cancel("client")},p=()=>{s=!0,d.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const w=h=>{s||a(h)};a({type:"run",id:c}),r.note&&a({type:"status",text:r.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(f=await ue({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),z(c),e.writableEnded||e.end();return}}const _=f?f.path:$t(t.options?.workingDir),W=Gt(t.agent,t.options),ee=W?Ut(W):[];ee.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...ee])]}});let C=null;{const h=_,T=!!f||!Pt(t.options?.workingDir),g=Rt(t.agent,t.options?.permissionMode,h,le(h,{grant:t.options?.sandbox}));a({type:"workdir",path:h,isDefault:!T,writeScope:g||void 0}),a({type:"status",text:`Working in ${h}${T?"":" (default)"}`}),g&&a({type:"status",text:g}),C=await Wt(h),C&&a({type:"scm",phase:"before",...C})}let j=null;if(C||f){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:T,connection:g}=Kt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=Qt(T),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...g?{connection:g}:{}}),g&&a({type:"status",text:`Git credential: ${g.kind} · ${g.host}${g.hasSecret?"":" (no token stored)"} · push: ${T.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:T.CHATPANEL_SCM_PUSH}`})}const F=t.approvals===!0,b={...t.options||{},...f?{workingDir:f.path}:{},...j?{runEnv:j}:{},approvals:F};let R=null;(t.pageTools?.specs?.length||F)&&(R=vt(w,t.pageTools?.specs||[]),b.permissionSession=R,t.pageTools?.specs?.length&&(b.mcp={url:`http://${x}:${k}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const Me=Mt();let te=b.sandbox||null;F&&Me.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&b.sandbox?.outside!==!0&&(b.accessGate=Bt({agent:t.agent,label:E[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>le(_,{grant:te})}));try{const h=vn(w),T=(g,H)=>ce(g.sandbox,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:H,options:g,images:Array.isArray(t.images)?t.images:[]},h.emit,{signal:l.signal}));await ke(t.agent,b,l.signal,async()=>{await T(b,t.system||"");let g=b;for(let H=0;H<2&&b.accessGate?.restart().length&&!l.signal.aborted;H++){const ne=b.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...ne])]}},te=g.sandbox;const oe=ne.map(Be=>b.accessGate.short(Be)).join(", ");h.seam(),w({type:"status",text:`Restarted with write access to ${oe} — carrying on`}),await T(g,`${t.system||""}