@chatpanel/bridge 0.32.3 → 0.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/scripts/sync-events.mjs +2 -2
- package/src/agent-context.js +1 -0
- package/src/agent-sessions.js +16 -0
- package/src/channels/adapters/telegram.js +3 -3
- package/src/cli-errors.js +6 -3
- package/src/engines/antigravity.js +4 -4
- package/src/engines/claude-warm.js +3 -3
- package/src/engines/claude.js +8 -8
- package/src/engines/codex-appserver.js +11 -11
- package/src/engines/codex.js +6 -6
- package/src/engines/custom.js +5 -5
- package/src/engines/prompt.js +8 -6
- package/src/events/agent-permission.js +2 -2
- package/src/events/agent-thread.js +5 -0
- package/src/events/compaction.js +11 -0
- package/src/events/context-breakdown.js +5 -0
- package/src/events/context-window.js +1 -0
- package/src/events/dialect-a2a.js +1 -1
- package/src/events/dialect-claude.js +1 -1
- package/src/events/harness-cards.js +1 -1
- package/src/events/mcp-signin.js +1 -1
- package/src/events/sandbox-policy.js +1 -1
- package/src/events/service-standby.js +1 -0
- package/src/health-snapshot.js +1 -0
- package/src/pii/pii-detect.js +2 -2
- package/src/sandbox-srt.js +1 -1
- package/src/sandbox.js +1 -1
- package/src/server.js +10 -10
- package/src/service.js +10 -5
- package/src/threads.js +1 -0
- package/src/warm-pool.js +1 -1
package/src/sandbox-srt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as
|
|
1
|
+
import{spawnSync as ke}from"node:child_process";import{writeFileSync as oe,mkdirSync as re,existsSync as De}from"node:fs";import{createHash as Ee,randomBytes as Oe}from"node:crypto";import{fileURLToPath as $e}from"node:url";import M from"node:os";import $ from"node:path";import{toSrtSettings as ie,sandboxRecord as Le,shellJoin as ae,sandboxEnvOverlay as F,windowsGrantsFor as Ce,windowsSandboxEnv as Re,withSrtWinEnv as Te,ENGINE_KITS as ce,DEVELOPER_HOSTS as de,SECRET_PATHS as Ne,COMMON_WRITE as He}from"./events/sandbox-policy.js";import{defineSandboxRuntime as _e,registerSandboxRuntime as Pe}from"./sandbox-runtime.js";function je(n=process.env.CHATPANEL_SRT_MODULE){if(!n)return"";try{const o=n.startsWith("file:")?$e(new URL("./cli.js",n)):$.join($.dirname(n),"cli.js");return De(o)?o:""}catch{return""}}const le=new Set;function ue(n,o=$.join(M.tmpdir(),"chatpanel-srt")){const y=JSON.stringify(n),p=$.join(o,`${Ee("sha256").update(y).digest("hex").slice(0,16)}.json`);return le.has(p)||(re(o,{recursive:!0,mode:448}),oe(p,y,{mode:384}),le.add(p)),p}function Me(){try{const n=ke(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return n.status===0&&String(n.stdout||"").trim().length>0}catch{return!1}}const z="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)";function Ue({config:n,platform:o=process.platform,home:y=M.homedir(),loopback:p=[],compiled:W=!1,selfFiles:he=[process.execPath,process.argv[1]||""],onExit:we=_=>process.on("exit",_),hostEntry:B=null,reportUrl:J="",mintReportToken:fe=()=>"",onRefusal:be=()=>{},parseRefusal:xe=()=>null,loadSrt:X=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:G=Me,cliEntry:K=je(),hostEntryFor:q=()=>"",log:L=()=>{}}={}){const _=new Set;let c=null,w=null,a=null,U=null,C=null,g=null,A=null;const R=new Set;let Q=!1;const me="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",pe="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function Se(){if(!n.windows){w=me;return}if(W){w=pe;return}try{a=await X()}catch(t){w=`sandbox-runtime is not installed — it ships with the gateway (${t.message})`;return}if(!a?.SandboxManager?.wrapWithSandboxArgv||typeof a.grantWindowsAcl!="function"||typeof a.getWindowsSandboxUserStatusAsync!="function"){w="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{g=a.resolveSrtWin({path:a.VENDORED_SRT_WIN_EXE})}catch(t){w=`Windows: srt-win.exe is not beside sandbox-runtime (${t.message})`;return}let e;try{e=await a.getWindowsSandboxUserStatusAsync({srtWin:g})}catch(t){A=!1,w=`Windows: srt-win could not be asked whether the sandbox account exists (${t.message}) — ${z}`;return}if(A=!!(e?.provisioned&&e.sid),!A){w=`Windows: the sandbox account is not installed — ${z}`;return}C=e.sid,c="srt-lib"}async function ye(){if(!(c||w)){if(!n.enabled){w="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(o==="win32")return Se();if(!W)try{if(a=await X(),a?.SandboxManager?.wrapWithSandboxArgv){c="srt-lib";return}}catch(e){L(`sandbox: library not available (${e.message})`)}if(G()){c="srt-cli";return}w=W?"srt is not on PATH — the compiled bridge cannot carry it: npm i -g @anthropic-ai/sandbox-runtime":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}}let Y=!1;function Z(e,{hosts:t=[],sockets:s=[]}={}){const r={...e.network};let i=!1;if((r.allowedDomains||[]).includes("*")){const d=r.allowedDomains.filter(l=>l.startsWith("127.0.0.1:"));r.allowedDomains=[...new Set([...Object.values(ce).flatMap(l=>l.hosts),...de,...n.extraHosts,...t,...d])],i=!0}return o==="darwin"&&s.length&&(r.allowUnixSockets=s),{settings:{...e,network:r},narrowed:i}}const ee=(e,{narrowed:t},s)=>(t&&(e.narrowed=`open → allowlist: the srt CLI refuses "*" — the gateway's embedded bridge runs open`),s.length&&o==="darwin"&&(e.sockets=s,delete e.socketsDropped),e);function I(){return K&&!W?{bin:process.execPath,argv:[K]}:c==="srt-cli"||G()?{bin:"srt",argv:[]}:null}function ge(){const e=Array.isArray(n.exactHosts)?n.exactHosts:n.mode==="open"?["*"]:n.mode==="none"?[]:[...new Set([...Object.values(ce).flatMap(r=>r.hosts),...de,...n.extraHosts])],t={id:`session:${n.mode}`,network:{mode:n.mode,allowedDomains:e},filesystem:{allowWrite:[M.tmpdir(),...He,...n.extraWrite],denyRead:[...Ne,...n.extraDenyRead]}},s=ie(t,{loopback:p,home:o==="linux"?y:"",platform:o});return o==="darwin"&&Array.isArray(n.exactSockets)&&n.exactSockets.length&&(s.network.allowUnixSockets=n.exactSockets),g?{...s,windows:{srtWin:{path:g.exe}}}:s}async function te(){return U||(U=a.SandboxManager.initialize(ge()).then(()=>{try{a.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(e=>{for(const t of e||[]){const s=xe(t?.line);if(!s||!t?.encodedCommand)continue;let r="";try{r=Buffer.from(t.encodedCommand,"base64").toString("utf8")}catch{continue}const i=`${r}|${s.host}|${t.timestamp instanceof Date?t.timestamp.getTime():String(t.timestamp)}`;_.has(i)||(_.add(i),be({commandId:r,...s,at:t.timestamp instanceof Date?t.timestamp.getTime():Date.now()}))}})}catch(e){L(`sandbox: violations not subscribed (${e.message})`)}})),U}function ve(e){const t=$.join(M.tmpdir(),"chatpanel-srt");re(t,{recursive:!0,mode:448});const s=$.join(t,`host-${Oe(8).toString("hex")}.json`);return oe(s,JSON.stringify(e),{mode:384}),s}function We(e,t){const s=(d,l)=>a.expandWindowsFsPaths(d,{mode:l}).filter(u=>!R.has(`${l}:${u.toLowerCase()}`)),r=s(e,"grant"),i=s(t,"grant");if(!(!r.length&&!i.length)){a.grantWindowsAcl({sandboxUserSid:C,read:r,write:i,srtWin:g});for(const d of r)R.add(`grant:${d.toLowerCase()}`);for(const d of i)R.add(`grant:${d.toLowerCase()}`);Q||(Q=!0,we(()=>{try{a.revokeWindowsAcl({sandboxUserSid:C,srtWin:g})}catch{}}))}}async function Ae(e,t,s,{engine:r,workdir:i,kit:d,settings:l,commandId:u,record:T,caBundle:S=""}){await te();const k=h=>typeof h=="string"&&/^[a-z]:\\/i.test(h),{read:P,write:D}=Ce({kit:d,files:[e,...k(t[0])?[t[0]]:[],...he].filter(Boolean),home:y});We(P,D);const f=ae(e,t,{platform:"win32"}),E=await a.SandboxManager.wrapWithSandboxArgv(f,void 0,{filesystem:{denyRead:l.filesystem.denyRead,denyWrite:l.filesystem.denyWrite}},void 0,i,{commandId:u,commandText:f}),x=s?.env||process.env,v={...Re({engine:r,home:y,env:x,base:process.env}),...F({},{platform:o,caBundle:S})},N=Te(E.argv,v),b={};for(const[h,H]of Object.entries(E.env||{}))process.env[h]!==H&&(b[h]=H);return{bin:N[0],argv:N.slice(1),opts:{...s,env:{...x,...b},shell:!1},record:T,commandId:u}}return _e({id:"srt",label:"Anthropic sandbox-runtime",async detect(){return await ye(),{ok:!!c,runtime:c,reason:w,ownSessions:!!(c&&(c==="srt-lib"&&(B??q(W))||o!=="win32"&&I())),...o==="win32"&&A!==null?{provisioned:A,...A?{}:{install:z}}:{}}},async wrap({kit:e,grant:t,bin:s,argv:r,opts:i,engine:d,workdir:l,commandId:u,caBundle:T=""}){const S=ie(e,{loopback:p,home:o==="linux"?y:"",platform:o}),k=ae(s,r),P=Array.isArray(n.exactHosts),D=n.mode==="allowlist"&&t.hosts.length>0&&!P,f=S.network.allowUnixSockets||[],E=f.length>0&&!P;delete S.network.allowUnixSockets;const x=(D||E)&&c==="srt-lib"?B??q(W):"",v=D&&!x&&o!=="win32"?I():null,N=!!(x||v),b=Le({layer:"process",runtime:x?"srt-host":v?"srt-cli":c,kitId:e.id,mode:e.network.mode,hosts:N||!D?t.hosts:[]});D&&!N&&(b.hostsDropped=t.hosts,Y||(Y=!0,L(`sandbox: hosts granted to ${d} (${t.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`))),E&&!x?b.socketsDropped=f:E&&(b.sockets=f);try{if(x){const m=fe(u),O={bin:s,argv:r,cwd:i?.cwd||null,engine:d,workdir:l,grant:t,commandId:u,config:{enabled:!0,mode:n.mode,extraHosts:[],extraWrite:n.extraWrite,extraDenyRead:n.extraDenyRead,windows:n.windows,exactHosts:e.network.allowedDomains,exactSockets:f},loopback:p,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:J?{url:J,token:m}:null},j={...i?.env||process.env};return{bin:process.execPath,argv:[x,ve(O)],opts:{...i,env:j,shell:!1},record:b,commandId:u}}if(v){const m={...i?.env||process.env};Object.assign(m,F(m,{platform:o,caBundle:T}));const O=Z(S,{hosts:t.hosts,sockets:f});return{bin:v.bin,argv:[...v.argv,"-s",ue(O.settings),"-c",k],opts:{...i,env:m,shell:!1},record:ee(b,O,f),commandId:u}}if(c==="srt-lib"&&o==="win32")return{...await Ae(s,r,i,{engine:d,workdir:l,kit:e,settings:S,commandId:u,record:b,caBundle:T})};if(c==="srt-lib"){await te();const m=await a.SandboxManager.wrapWithSandboxArgv(k,void 0,{filesystem:S.filesystem},void 0,l,{commandId:u,commandText:k}),O=i?.env||process.env,j={};for(const[ne,se]of Object.entries(m.env||{}))process.env[ne]!==se&&(j[ne]=se);const V={...O,...j};return Object.assign(V,F(V,{platform:o,caBundle:T})),{bin:m.argv[0],argv:m.argv.slice(1),opts:{...i,env:V,shell:!1},record:b,commandId:u}}const h=I(),H=Z(S,{hosts:t.hosts,sockets:f});return{bin:h.bin,argv:[...h.argv,"-s",ue(H.settings),"-c",k],opts:{...i,shell:!1},record:ee(b,H,f),commandId:u}}catch(h){return L(`sandbox: could not wrap ${s}: ${h.message}`),{passReason:h?.code==="SHAPE"?`the sandbox policy refused this run: ${h.message}`:`sandbox-runtime failed to wrap the command: ${h.message}`}}},violations(e){try{return a?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(e)||[]}catch{return[]}},close(){if(!(!C||!R.size)){try{a.revokeWindowsAcl({sandboxUserSid:C,srtWin:g})}catch(e){L(`sandbox: could not release the Windows grants: ${e.message}`)}R.clear()}}})}Pe("srt",n=>Ue(n));export{Ue as createSrtRuntime};
|
package/src/sandbox.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as
|
|
1
|
+
import{spawn as ae}from"node:child_process";import"node:fs";import{randomBytes as ie}from"node:crypto";import{AsyncLocalStorage as ue}from"node:async_hooks";import{fileURLToPath as ce}from"node:url";import N from"node:os";import le from"node:path";import{ensureCaBundle as de}from"./ca-bundle.js";import{kitFor as pe,sandboxRecord as fe,normalizeGrant as P,writableRoots as xe,NETWORK_MODES as me}from"./events/sandbox-policy.js";import{createSandboxRuntime as he,sandboxRuntimeIds as we}from"./sandbox-runtime.js";import"./sandbox-srt.js";const V=new ue,Se=new Set(["codex","claude","antigravity","custom"]);function Ve(e,t){let n;try{n=P(e)}catch{n=null}return V.run(n,t)}function Ye(e){const t=e&&typeof e=="object"?e:{};if(!t.reach||t.reach==="any"||!t.sandbox||typeof t.sandbox!="object"||!("outside"in t.sandbox))return t;const{outside:n,...s}=t.sandbox;return{...t,sandbox:s}}function Y(){return V.getStore()||null}function ze(e,{config:t=te(),grant:n=Y(),home:s=N.homedir()}={}){try{return xe({grant:n,extraWrite:t.extraWrite,cwd:e,home:s})}catch{return[]}}const be=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function z(e){const t=be.exec(String(e||""));return t?{host:t[1].toLowerCase(),port:Number(t[2])||0,reason:t[3]||""}:null}const g=new Map,R=[],O=new Map,Ae=new Set,ye=50;function J({commandId:e,host:t,port:n=0,reason:s="",at:a=Date.now()}){if(!e||!t)return;let o=g.get(e);for(o||(o=new Map,g.set(e,o)),o.set(t,{at:a,reason:s,port:n}),R.push({id:e,engine:O.get(e)||String(e).split(":")[0],host:t,at:a});R.length>ye;)R.shift()}function _e(e){const t=g.get(e);return t?[...t.entries()].sort((n,s)=>s[1].at-n[1].at).map(([n])=>n):[]}function Ne(e=20){return R.slice(-e).reverse()}function Je(){g.clear(),R.length=0,O.clear(),Ae.clear()}const q=new Map;function Q(e){const t=ie(16).toString("hex");return q.set(t,e),t}function qe(e={}){const t=q.get(String(e?.token||""));return!t||t!==e.commandId?!1:(J({commandId:t,host:String(e.host||"").toLowerCase().slice(0,253),port:Number(e.port)||0,reason:String(e.reason||"").slice(0,200)}),!0)}let Re=0;const Te=e=>`${e}:${(++Re).toString(36)}${Date.now().toString(36).slice(-4)}`,L=new Map;function Ee(e,t,{kind:n="agent",label:s=""}={}){if(!e||!t)return e;try{e.sandbox=t.record}catch{}if(typeof e.on!="function")return e;const a=t.commandId||"";L.set(e,{id:a,kind:n,engine:O.get(a)||String(a).split(":")[0]||"custom",command:t.label||"",label:s,pid:e.pid??null,since:Date.now(),sandbox:t.record});const o=()=>L.delete(e);return e.once("exit",o),e.once("error",o),e}function Qe(){return[...L.values()].map(e=>({...e,refused:_e(e.id)}))}function Ze(){L.clear()}function Z(e){if(e)return"";try{return ce(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}const ee="open",et="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",ge=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],W=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean);function te(e=process.env){const t=String(e.CHATPANEL_SANDBOX||ee).toLowerCase(),n=t!=="off"&&t!=="0"&&t!=="false",s=me.includes(t)?t:ee;return{enabled:n,mode:s,extraHosts:W(e.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:W(e.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:W(e.CHATPANEL_SANDBOX_DENY_READ),windows:e.CHATPANEL_SANDBOX_WINDOWS==="1",reads:e.CHATPANEL_SANDBOX_READS==="inverted"?"inverted":"enumerated"}}function Oe({config:e=te(),loadSrt:t=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:n=void 0,cliEntry:s=void 0,onRefusal:a=l=>J(l),reportUrl:o=process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT?`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT}/sandbox/refused`:"http://127.0.0.1:4319/sandbox/refused",hostEntry:p=null,compiled:u=!1,platform:i=process.platform,home:x=N.homedir(),loopback:$=ge(),selfFiles:B=[process.execPath,process.argv[1]||""],onExit:k=l=>process.on("exit",l),runtimeId:T=process.env.CHATPANEL_SANDBOX_RUNTIME||"srt",makeRuntime:M=null,log:m=()=>{}}={}){let l=null,E=null,d={ok:!1,runtime:null,reason:null,ownSessions:!1};function b(){if(l||E)return l;try{l=M?M({config:e,platform:i,home:x,loopback:$,compiled:u,selfFiles:B,onExit:k,hostEntry:p,reportUrl:o,mintReportToken:Q,onRefusal:a,parseRefusal:z,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:Z,log:m}):he(T,{config:e,platform:i,home:x,loopback:$,compiled:u,selfFiles:B,onExit:k,hostEntry:p,reportUrl:o,mintReportToken:Q,onRefusal:a,parseRefusal:z,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:Z,log:m})}catch(r){E=r?.message||String(r),m(`sandbox: ${E}`)}return l}async function X(){if(!e.enabled)return d={ok:!1,runtime:null,reason:"sandboxing is off (CHATPANEL_SANDBOX=off)",ownSessions:!1},d;const r=b();if(!r)return d={ok:!1,runtime:null,reason:E,ownSessions:!1},d;try{d={...d,...await r.detect()}}catch(c){d={ok:!1,runtime:null,reason:`the ${r.id} sandbox could not be started: ${c.message}`,ownSessions:!1}}return d}return{config:e,async status(){const r=await X(),c=b();return{enabled:e.enabled,mode:e.mode,runtime:r.runtime,platform:i,layer:c?.id||T,layers:we(),...r.reason?{reason:r.reason}:{},extras:{hosts:e.extraHosts,write:e.extraWrite,denyRead:e.extraDenyRead},ownSessions:!!r.ownSessions,refused:Ne(),...r.provisioned!==void 0?{provisioned:r.provisioned}:{},...r.install?{install:r.install}:{}}},close(){try{b()?.close()}catch(r){m(`sandbox: close failed: ${r.message}`)}},async wrap(r,c,A,{engine:f="custom",cwd:y=null,commandId:h=null,grant:F=Y(),readOnly:re=!1,peers:se=!0}={}){const G=await X();h=h||Te(f),O.set(h,f);const I=y||A?.cwd||process.cwd(),U=le.basename(String(r||"")),_=S=>({bin:r,argv:c,opts:A,record:fe({layer:"none",reason:S}),commandId:h,label:U});let j=!1;try{j=P(F).outside===!0}catch{}if(j&&Se.has(f))return _("you allowed this agent to run outside the ChatPanel sandbox (its own sandbox still applies)");if(!G.ok)return _(G.reason);const oe=await de({home:N.homedir(),log:m}).catch(()=>"");let K,D;try{D=P(F),K=pe({engine:f,cwd:I,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[N.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead,grant:D,home:N.homedir(),reads:e.reads,readOnly:re,peers:se})}catch(S){return _(`kit: ${S.message}`)}let w;try{w=await b().wrap({kit:K,grant:D,bin:r,argv:c,opts:A,engine:f,workdir:I,commandId:h,caBundle:oe})}catch(S){return m(`sandbox: could not wrap ${r}: ${S.message}`),_(`the ${T} sandbox failed to wrap the command: ${S.message}`)}return!w||w.passReason?_(w?.passReason||`the ${T} sandbox returned nothing`):{...w,commandId:w.commandId||h,label:U}},async wrapOwn(r,c,A,f={}){const y=await this.wrap(r,c(!1),A,f);return y.record.layer==="none"?{...y,argv:c(!0),inner:!0}:{...y,inner:!1}},violations(r){try{return b()?.violations(r)||[]}catch{return[]}}}}let C=null;function ne(){if(!C){const{isCompiledBinary:e}=Le();C=Oe({compiled:e(),log:t=>console.error(`[bridge] ${t}`)})}return C}function tt(e){C=e}let v=null;function Le(){return v||(v={isCompiledBinary:()=>{const e=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}}),v}const H=new Set;function nt(e,t){if(!t||t.layer!=="none"||typeof e!="function")return;const n=t.reason||"unknown";H.has(n)||(H.add(n),e({type:"status",text:`Running outside a sandbox — ${n}`}))}function rt(){H.clear()}const Ce=/sandbox_apply: Operation not permitted/;function st(e,t="This agent"){return Ce.test(String(e||""))?`${t} tried to start a sandbox of its own inside the ChatPanel sandbox, and macOS does not allow one inside another — so that tool could not run. To let it, turn on "Run outside the ChatPanel sandbox" in this agent's settings.`:null}async function ot(e,t,n,s={},{spawnImpl:a=ae,box:o=ne(),kind:p="agent",label:u=""}={}){const i=await o.wrap(e,t,n,s);return Ee(a(i.bin,i.argv,i.opts),i,{kind:p,label:u})}async function at(e,{box:t=ne(),platform:n=process.platform,loadSrt:s=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:a=console.log,err:o=console.error}={}){const p=e[0]||"status";if(p==="status")return a(JSON.stringify(await t.status(),null,2)),0;if(p!=="install")return o("usage: chatpanel-bridge sandbox [status|install]"),2;if(n!=="win32")return a("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let u;try{u=await s()}catch(i){return o(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${i.message})`),1}try{const i=u.resolveSrtWin({path:u.VENDORED_SRT_WIN_EXE}),x=await u.installWindowsSandboxAsync({srtWin:i});return x?.cancelled?(o("Cancelled at the administrator prompt — nothing was installed."),1):(a(`The sandbox account is installed${x?.user?.sid?` (${x.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(i){o(`install failed: ${i.message}`);try{o(u.windowsInstallInstructions())}catch{}return 1}}export{Ze as _resetLiveForTest,rt as _resetNotedForTest,Je as _resetRefusalsForTest,tt as _setSandboxForTest,qe as acceptRefusalReport,Oe as createSandbox,Y as currentGrant,ze as grantedWriteRoots,Qe as liveProcesses,st as nestedSandboxLine,nt as noteSandbox,z as parseRefusalLine,Ne as recentRefusals,J as recordRefusal,_e as refusalsFor,at as runSandboxCli,ne as sandbox,te as sandboxConfigFromEnv,ot as sandboxedSpawn,Ee as track,Ve as withGrant,Ye as withoutOutsideWhenCapped};
|
package/src/server.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
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.3",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 xe}from"node:http";import v from"node:os";import{randomBytes as Pe,randomInt as $e,timingSafeEqual as Re}from"node:crypto";import{mkdirSync as Ie,writeFileSync as Ne,readFileSync as Q,existsSync as De}from"node:fs";import{join as _}from"node:path";import*as _e from"./engines/claude.js";import*as He from"./engines/codex.js";import*as Me from"./engines/antigravity.js";import{pi as Be,opencode as Ue,kiro as We,copilot as Le,deepseek as Ge,hermes as je}from"./engines/cli-agents.js";import{connectorsFor as Fe}from"./connectors.js";import*as Je from"./engines/custom.js";import{installService as Xe,uninstallService as ze,serviceStatus as Ke,restartService as Z}from"./service.js";import{skillIndex as L,listRecords as Ye,readRecord as Ve,readPackageFile as Qe,skillsHealth as Ze,quarantinedSkills as qe,clearSkillCache as G}from"./skills.js";import{writeSkillPackage as et,writeSkillFile as tt,deleteSkillPackage as nt,SkillWriteError as ot}from"./skill-write.js";import{agentDefRoots as rt,scanAgentDefs as at,listAgentDefs as it,readAgentDef as st,planAgentExport as ct,exportAgentDef as lt,agentDefsHealth as dt,AgentDefError as ut}from"./agent-defs.js";import{capabilityToolSpecs as ht,runCapabilityTool as pt}from"./mcp-capabilities.js";import{createSession as ft,deleteSession as q,getSession as ee,activeSession as mt,relayToolCall as gt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as yt,isDefaultWorkdir as wt,resolveWorkdir as St,writeScopeNote as bt}from"./workdir.js";import{sandbox as te,runSandboxCli as kt,withGrant as ne,withoutOutsideWhenCapped as Tt,grantedWriteRoots as Et,acceptRefusalReport as vt,liveProcesses as Ot}from"./sandbox.js";import{gitState as At,gitDelta as Ct}from"./scm.js";import{listConnections as xt,putConnection as Pt,removeConnection as $t,runEnvFor as Rt,testConnection as It,secretBackend as oe}from"./connections.js";import{worktreeFor as re,listWorktrees as Nt,removeWorktree as Dt,withHook as _t,WORKTREE_ROOT as ae}from"./worktree.js";import{AGENT_CLIS as Ht,agentAvailable as Mt,agentInstallDirs as Bt,enrichPath as Ut,enrichAgentEnv as Wt,findAgentBin as Lt,resolveCommand as ie}from"./env.js";import"./sanitize.js";import{checkForUpdate as Gt,selfUpdate as se,isEmbedded as ce}from"./update.js";import{callLocalMcp as jt,localMcpStatus as Ft,signInLocalMcp as Jt,signInStatusLocalMcp as Xt}from"./mcp-local.js";import{assertPublicHttpUrl as le,assertPublicWebUrl as de}from"./ssrf.js";import{startRun as ue,endRun as j,cancelRun as zt,cancelAll as Kt}from"./runs.js";import{closeWarmPools as Yt,warmStatus as Vt}from"./warm.js";import{SESSION_AGENTS as he,listSessions as Qt,readSession as Zt,adoptSession as qt,catchUp as en}from"./agent-sessions.js";import{agentContext as tn}from"./agent-context.js";import{normalizeThread as pe}from"./events/agent-thread.js";import{portClashPlan as nn,serviceManagerOf as on,STANDBY_POLL_MS as rn}from"./events/service-standby.js";import{holdThread as fe}from"./threads.js";import{createSnapshot as an}from"./health-snapshot.js";import{CompatError as R,anthropicError as F,anthropicStream as sn,chatCompletionStream as cn,completionStream as ln,createAnthropicMessage as dn,createChatCompletion as un,createCompletion as hn,createResponse as pn,openAIError as S,parseAnthropicMessage as fn,parseChatCompletion as mn,parseCompletion as gn,parseResponse as yn,responseStream as wn}from"./api-compat.js";import{callerTrust as Sn,isPaired as I,parseExtensionIds as bn,capRunOptions as kn,engineHonoursReach as Tn,createPairingStore as En,formatPairingCode as vn}from"./pii/trust.js";const g="0.44.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",b=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:_e,label:"Claude Code"},codex:{engine:He,label:"Codex"},antigravity:{engine:Me,label:"Antigravity",tools:!1},pi:{engine:Be,label:"Pi"},opencode:{engine:Ue,label:"OpenCode"},hermes:{engine:je,label:"Hermes"},kiro:{engine:We,label:"Kiro"},copilot:{engine:Le,label:"GitHub Copilot"},deepseek:{engine:Ge,label:"DeepSeek Harness"},custom:{engine:Je,label:"Custom",hidden:!0}};function me(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const On=bn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Sn({origin:n.headers.origin||"",hasToken:Se(n),extensionIds:On})),n.chatpanelTrust}function An(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 Cn(n,e){const t=n.headers.origin||"",o=me(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function xn(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const D=_(v.homedir(),".chatpanel","bridge-token");let T="";function Pn(){try{De(D)&&(T=Q(D,"utf8").trim()),T||(T=Pe(32).toString("hex"),Ie(_(v.homedir(),".chatpanel"),{recursive:!0}),Ne(D,T,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const ge=En({random:()=>$e(0,1e6)/1e6});function $n(n){if(!T)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ge.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Rn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ge.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:T})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function In(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:g})}let H=null;async function ye(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(v.homedir(),".chatpanel"),dataDir:_(v.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${b}`,token:T},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function we(n,e,t){try{const o=await ye(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function Se(n){if(!T)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(T);return o.length===r.length&&Re(o,r)}const Nn=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"]),Dn=new Set(["/debug"]),_n=n=>Dn.has(n),Hn=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Mn(n,e){if(!xn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!me(t))return"forbidden origin";const o=n.method==="POST"&&Nn.has(e)||n.method==="GET"&&_n(e)||Hn(n.method,e);return o&&!(An(t)||Se(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!Un.has(e)?Bn:null}const be=()=>ce()?"chatpanel-gateway pair":"chatpanel-bridge pair",Bn=`forbidden: this client is not paired with the bridge — run \`${be()}\` and enter the code in ChatPanel Settings`,Un=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(n,e,t){const o=N(n),r=Tt(kn(t,o));if(!Tn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":`pair this client (${be()})`} to use ${e}`};const a=r.reach,s=I(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:r,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}const ke=an({compute:Wn});async function Wn(){const n=await Promise.all(Object.entries(O).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:l}])=>{const d=await s.available().catch(y=>({ok:!1,reason:String(y?.message||y)})),h=await Fe(a).catch(()=>[]);return{id:a,label:c,available:d.ok,reason:d.reason,connectors:h,...l===!1?{tools:!1}:{}}})),e=ce()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Gt(g).catch(()=>({current:g,updateAvailable:!1})),t=await Ze().catch(()=>null),o=await dt().catch(()=>null),r=await te().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function Ln(n,{fresh:e=!1}={}){const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await ke.get({fresh:e});i(n,200,{ok:!0,version:g,agents:o,update:r,checkedAt:t,workspace:yt,sandbox:c,localMcp:Ft(),processes:Ot(),worktrees:ae,secretBackend:oe(),warm:Vt(),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 Gn(n,e,t){const{index:o,problems:r}=await L({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Ye(o),problems:r})}async function jn(n,e,t){i(n,200,{ok:!0,quarantined:await qe(e,t)})}async function Fn(n,e,t,o){const{index:r}=await L({extraDirs:t,workdir:o}),a=Ve(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function Jn(n,e,t,o,r){const{index:a}=await L({extraDirs:o,workdir:r}),s=await Qe(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function Xn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await et({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return G(),i(e,200,o)}catch(o){return i(e,z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function zn(n,e,t,o){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await tt({name:t,path:o,text:r?.text??""});return G(),i(e,200,a)}catch(a){return i(e,z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function Kn(n,e){try{const t=await nt({name:e});return G(),i(n,200,t)}catch(t){return i(n,z(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function z(n){return n instanceof ot?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Te(n,e){return at({roots:rt(process.env,v.homedir(),n,e)})}async function Yn(n,e,t){const{index:o,quarantined:r,problems:a}=await Te(e,t);i(n,200,{ok:!0,agents:it(o),...r.length?{quarantined:r.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function Vn(n,e,t,o){const{index:r}=await Te(t,o),a=st(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function Qn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,{ok:!0,...await ct({agent:t?.agent,to:t?.to})})}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function Zn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,await lt({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function Ee(n){if(n instanceof ut){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function qn(){return(await Promise.all(Object.entries(O).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function ve(n,e=""){const t=await qn();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new R(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function eo(n){try{const e=await se(g);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>Z(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function to(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=X(n,t.agent,t.options||{});if(r.error)return i(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
3
3
|
|
|
4
|
-
`)};let s=!1;const
|
|
4
|
+
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,l=ue(c),d={signal:l.signal,abort:()=>l.cancel("client")},h=()=>{s=!0,l.cancel("disconnected")};n.on("close",h),e.on("close",h),e.on("error",h);const y=p=>{s||a(p)};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 p=t.options.workspace;if(f=await re({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),j(c),e.writableEnded||e.end();return}}const Y=f?f.path:St(t.options?.workingDir);let A=null;{const p=Y,C=!!f||!wt(t.options?.workingDir),w=bt(t.agent,t.options?.permissionMode,p,Et(p,{grant:t.options?.sandbox}));a({type:"workdir",path:p,isDefault:!C,writeScope:w||void 0}),a({type:"status",text:`Working in ${p}${C?"":" (default)"}`}),w&&a({type:"status",text:w}),A=await At(p),A&&a({type:"scm",phase:"before",...A})}let W=null;if(A||f){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:C,connection:w}=Rt({remote:A?.remote||null,grants:p,branch:f?.branch||null,connectionId:t.options?.connectionId||null});W=_t(C),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...w?{connection:w}:{}}),w&&a({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${C.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:C.CHATPANEL_SCM_PUSH}`})}const V=t.approvals===!0,P={...t.options||{},...f?{workingDir:f.path}:{},...W?{runEnv:W}:{},approvals:V};let $=null;(t.pageTools?.specs?.length||V)&&($=ft(y,t.pageTools?.specs||[]),P.permissionSession=$,t.pageTools?.specs?.length&&(P.mcp={url:`http://${k}:${b}/mcp/${$.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await ne(P.sandbox,()=>fe(t.agent,P,d.signal,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:P,images:Array.isArray(t.images)?t.images:[]},y,{signal:d.signal})))}catch(p){u("error",`${t.agent} chat failed: ${p?.message||p}`),p?.detail&&u("error",`${t.agent} said: ${p.detail}`),a({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await Ct(Y,A).catch(()=>null);p&&y({type:"scm",phase:"after",...p})}j(c),$&&q($.id),e.writableEnded||e.end()}}async function no(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:xt(),secretBackend:oe()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:Pt(o.connection||o,{token:o.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return r?r[2]==="delete"?i(e,200,{ok:$t(r[1])}):i(e,200,It(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function oo(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ae,worktrees:await Nt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/worktrees"){const r=await re({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return i(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(t==="/worktrees/remove"){const r=await Dt({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 E(n,e,t){const o=O[n.agent];if(!o||o.hidden)throw new R(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(d=>({ok:!1,reason:d?.message||String(d)}));if(!r.ok)throw new R(r.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=ue(a),c=()=>s.cancel("disconnected");t.on("close",c);let l="";try{return await ne(n.options?.sandbox,()=>fe(n.agent,n.options,s.signal,()=>o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},d=>{d?.type==="delta"&&d.text?(l+=d.text,e(d.text)):d?.type==="done"&&d.text&&!l&&(l=d.text,e(d.text))},{signal:s.signal}))),l}finally{t.off("close",c),j(a)}}function M(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
5
5
|
|
|
6
|
-
`)}function
|
|
7
|
-
data: ${JSON.stringify(
|
|
6
|
+
`)}function B(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
7
|
+
data: ${JSON.stringify(t)}
|
|
8
8
|
|
|
9
|
-
`)}async function W(t,e,n,r){try{const o=n(await m(t)),i=X(t,o.agent,o.options||{});if(i.error)throw new R(i.error,403,"permission");return o.options=i.options,o}catch(o){return a(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${o.message}`):o)),null}}async function jn(t,e){const n=await W(t,e,en,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Yt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=zt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function Fn(t,e){const n=await W(t,e,tn,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Qt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=Kt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function Jn(t,e){const n=await W(t,e,nn,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Zt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=on(n.requestedModel,o=>U(e,o.type,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){const i={type:"error",sequence_number:0,...b(o)};U(e,"error",i)}e.end()}async function Xn(t,e){const n=await W(t,e,qt,F);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Vt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,F(o))}M(e);const r=Xt(n.requestedModel,(o,i)=>U(e,o,i));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",F(o))}e.end()}async function zn(t,e){let n={};try{n=await m(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?Lt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),a(e,200,{ok:!0,cancelled:o})}async function we(t,e,n){let r;try{r=await m(t)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?q(n):lt(),i=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),a(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>a(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return i({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=it();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return i({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await st(r.params?.name,r.params?.arguments||{});if(c)return i(c);if(!o)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 dt(o,r.params?.name,r.params?.arguments||{}))}catch(l){return i({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Kn(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{},o=n.message;if(!r.command||!o)return a(e,400,{error:"need server.command and message"});try{const i=await Ut({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function Vn(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{};if(!r.command)return a(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return a(e,200,n.status?Gt(o):await Bt(o))}catch(i){return a(e,200,{state:"failed",error:String(i?.message||i)})}}async function Yn(t,e){let n;try{n=await m(t)}catch(h){return a(e,400,{error:"Bad JSON: "+h.message})}const{url:r,headers:o,message:i}=n||{};if(!r||!i)return a(e,400,{error:"need url and message"});let s;try{s=se(r)}catch(h){return a(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[h,y]of Object.entries(o)){const p=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(p)||p.startsWith("x-"))&&(d[h]=String(y))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&se(h.url)}catch(p){return a(e,400,{error:String(p?.message||p)})}const y=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")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const be=256*1024,Qn=5,Zn=8e3;async function qn(t){let e=ce(t);const n=new AbortController,r=setTimeout(()=>n.abort(),Zn);try{for(let o=0;o<=Qn;o++){const i=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(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=ce(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:no(await eo(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function eo(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,be);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:i,value:s}=await e.read();if(i||(o+=s.byteLength,r+=n.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=be))break}}finally{try{await e.cancel()}catch{}}return r}function to(t){return String(t).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /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 no(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?to(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function oo(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=n&&n.url;if(!r||typeof r!="string")return a(e,400,{error:"need url"});try{const o=await qn(r);return a(e,200,{title:o.title||null,url:o.url||r})}catch(o){const i=o?.name==="AbortError"?"timed out":String(o?.message||o);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function ro(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=q(n.session);if(!r)return a(e,404,{error:"no such session"});const o=r.pending.get(n.id);return o?(r.pending.delete(n.id),o.resolve(n.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function ao(t,e){let n;try{n=await m(t)}catch(c){return a(e,400,{error:"Bad JSON: "+c.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=String(n.prompt||"").slice(0,6e3);if(!o)return a(e,400,{error:"Empty prompt"});const i=n.model||"",s=X(t,n.agent,{model:i});if(s.error)return a(e,403,{error:s.error});const d=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 c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:i}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,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 io(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof r.engine.listModels!="function")return a(e,200,{models:[]});try{const o=await r.engine.listModels(n.options||{});return a(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return a(e,502,{error:o?.message||String(o)})}}async function so(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=String(n.command||"").trim();if(!r)return a(e,400,{error:"No command"});let o=null;try{o=ae(r)}catch{o=null}return a(e,200,{ok:!!o,via:o?o.kind:null})}const Se=Te(async(t,e)=>{if(pn(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 a(e,400,{error:"bad request"})}const r=En(t,n.pathname);if(r)return a(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return Cn(e);const o=n.searchParams.getAll("dir"),i=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return An(e,o,i);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return xn(e,o,i);if(t.method==="GET"&&n.pathname==="/agent-defs")return Dn(e,o,i);if(t.method==="POST"&&n.pathname==="/agent-defs/export-plan")return Hn(t,e);if(t.method==="POST"&&n.pathname==="/agent-defs/export")return Mn(t,e);if(t.method==="GET"&&n.pathname.startsWith("/agent-defs/"))return _n(e,decodeURIComponent(n.pathname.slice(12)),o,i);if(t.method==="POST"&&n.pathname==="/skills")return In(t,e);if((t.method==="PUT"||t.method==="POST"||t.method==="DELETE")&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?t.method==="DELETE"?Nn(e,decodeURIComponent(s)):a(e,405,{ok:!1,error:"use POST /skills to save a skill"}):t.method==="DELETE"?a(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):$n(t,e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)))}if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?Pn(e,decodeURIComponent(s),o,i):Rn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,i)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return Gn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return Ln(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return ye(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return ye(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return a(e,200,{version:g,agents:Object.fromEntries(Rt.map(d=>[d,s?_t(d)||ae(d)?.kind||null:It(d)])),...s?{home:E.homedir(),path:process.env.PATH,installDirs:$t(E.homedir())}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return Bn(t,e);if(t.method==="POST"&&n.pathname==="/pair")return yn(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return gn(e);if(t.method==="POST"&&n.pathname==="/whoami")return wn(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return jn(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return Fn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return Jn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return Xn(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return we(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const s=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return we(t,e,s);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return Z(s),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return pe(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return pe(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return zn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return ro(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await m(t)}catch{s=null}const d=wt(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return Kn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local/signin")return Vn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return Yn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return oo(t,e);if(t.method==="POST"&&n.pathname==="/complete")return ao(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return io(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return so(t,e);if(t.method==="POST"&&n.pathname==="/update")return Wn(e);a(e,404,{error:"Not found"})}catch(o){a(e,500,{error:o?.message||String(o)})}});function u(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function co(t){let e="";const n=[];let r=!1,o=!1;const i=()=>{o&&!r&&!n.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;n.length;){const d=n.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
|
|
10
|
-
`)}catch(
|
|
11
|
-
`)}}
|
|
12
|
-
`))>=0;){const
|
|
9
|
+
`)}async function U(n,e,t,o){try{const r=t(await m(n)),a=X(n,r.agent,r.options||{});if(a.error)throw new R(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${r.message}`):r)),null}}async function ro(n,e){const t=await U(n,e,mn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,un(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=cn(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function ao(n,e){const t=await U(n,e,gn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,hn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=ln(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function io(n,e){const t=await U(n,e,yn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,pn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=wn(t.requestedModel,r=>B(e,r.type,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...S(r)};B(e,"error",a)}e.end()}async function so(n,e){const t=await U(n,e,fn,F);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,dn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,F(r))}M(e);const o=sn(t.requestedModel,(r,a)=>B(e,r,a));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",F(r))}e.end()}async function co(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?zt(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Oe(n,e,t){let o;try{o=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?ee(t):mt(),a=l=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:l})},s=(l,d)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:l,message:d}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return a({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const c=ht();if(o.method==="tools/list"){const l=r?r.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...l]})}if(o.method==="tools/call"){const l=await pt(o.params?.name,o.params?.arguments||{});if(l)return a(l);if(!r)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await gt(r,o.params?.name,o.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function lo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await jt({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox},r);return r.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function uo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{};if(!o.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const r={key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox};try{return i(e,200,t.status?Xt(r):await Jt(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function ho(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:a}=t||{};if(!o||!a)return i(e,400,{error:"need url and message"});let s;try{s=le(o)}catch(h){return i(e,400,{error:String(h?.message||h)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,y]of Object.entries(r)){const f=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[h]=String(y))}const l=new AbortController,d=setTimeout(()=>l.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:l.signal});try{h.url&&le(h.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const y=await h.text().catch(()=>"");return i(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(d)}}const Ae=256*1024,po=5,fo=8e3;async function mo(n){let e=de(n);const t=new AbortController,o=setTimeout(()=>t.abort(),fo);try{for(let r=0;r<=po;r++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=de(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:wo(await go(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function go(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ae);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=Ae))break}}finally{try{await e.cancel()}catch{}}return o}function yo(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function wo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?yo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function So(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await mo(o);return i(e,200,{title:r.title||null,url:r.url||o})}catch(r){const a=r?.name==="AbortError"?"timed out":String(r?.message||r);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function bo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=ee(t.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function ko(n,e){let t;try{t=await m(n)}catch(l){return i(e,400,{error:"Bad JSON: "+l.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=X(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const c=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let l="";return typeof o.engine.complete=="function"?l=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},d=>{d.type==="delta"?l+=d.text||"":d.type==="done"&&d.text&&(l+=d.text)}),i(e,200,{text:(l||"").trim()})}catch(l){return i(e,502,{error:l?.message||String(l)})}}async function To(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function Eo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(t.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=ie(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function vo(n,e,t){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(o?.agent||"");if(!he.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${he.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await Qt(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await Zt(r,String(o.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=pe({id:o.thread?.id??o.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const s=await qt(r,String(o.id||""),a.id);return s?i(e,200,{session:s}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=pe({id:o.thread?.id??o.thread});return a?i(e,200,await en(r,a.id,Array.isArray(o.messages)?o.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const K=xe(async(n,e)=>{if(Cn(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const o=Mn(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return Ln(e,{fresh:t.searchParams.get("fresh")==="1"});const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return Gn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-context"){const s=await m(n).catch(()=>({})),c=s?.options&&typeof s.options=="object"?s.options:{},l={...c.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof c.permissionMode=="string"?{permissionMode:c.permissionMode}:{},...typeof c.workingDir=="string"&&c.workingDir?{workingDir:c.workingDir}:{},...typeof c.model=="string"&&c.model?{model:c.model}:{}};return i(e,200,await tn({agent:typeof s?.agent=="string"?s.agent:"claude",options:l}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return jn(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return Yn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return Qn(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return Zn(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return Vn(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return Xn(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?n.method==="DELETE"?Kn(e,decodeURIComponent(s)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):zn(n,e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?Fn(e,decodeURIComponent(s),r,a):Jn(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return no(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return oo(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return ve(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return ve(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:g,agents:Object.fromEntries(Ht.map(c=>[c,s?Lt(c)||ie(c)?.kind||null:Mt(c)])),...s?{home:v.homedir(),path:process.env.PATH,installDirs:Bt(v.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return vo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return to(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Rn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return $n(e);if(n.method==="POST"&&t.pathname==="/whoami")return In(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return ro(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return ao(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return io(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return so(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Oe(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return Oe(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return q(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return we(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return we(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return co(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return bo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=vt(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return lo(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return uo(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return ho(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return So(n,e);if(n.method==="POST"&&t.pathname==="/complete")return ko(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return To(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Eo(n,e);if(n.method==="POST"&&t.pathname==="/update")return eo(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Oo(n){let e="";const t=[];let o=!1,r=!1;const a=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const c=t.shift();let l;try{l=JSON.parse(c)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(l.id==null)continue;const h=(await d.text()).trim();h&&process.stdout.write(h+`
|
|
10
|
+
`)}catch(d){l.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:l.id,error:{code:-32e3,message:String(d?.message||d)}})+`
|
|
11
|
+
`)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",c=>{e+=c;let l;for(;(l=e.indexOf(`
|
|
12
|
+
`))>=0;){const d=e.slice(0,l).trim();e=e.slice(l+1),d&&t.push(d)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function Ao(){Ut(),Wt(),Pn();let n=!1;K.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${b}/health`,{signal:AbortSignal.timeout(1500)}).then(t=>t.ok?t.json():null).catch(()=>null).then(t=>{const o=!!(t?.version&&Array.isArray(t.agents)),r=nn({name:"bridge",self:g,holder:o?{ours:o,version:t.version}:null,managedBy:on(process.env),port:b});if(r.action==="standby"||n&&!t){if(!n)for(const a of r.lines)u("info",a);n=!0,setTimeout(()=>K.listen(b,k),rn);return}if(o)for(const a of r.lines)u("error",a);else u("error",`Port ${b} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings.");process.exit(1)});return}u("error",`bridge server error: ${e?.message||e}`),process.exit(1)});for(const e of["SIGINT","SIGTERM"])process.on(e,()=>{const t=Kt("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const o=Yt("shutdown");o&&u("info",`shutdown: closed ${o} warm agent process${o===1?"":"es"}`),te().close(),setTimeout(()=>process.exit(0),t||o?300:0).unref?.(),!t&&!o&&process.exit(0)});K.listen(b,k,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${k}:${b}`),ke.warm(),J.has(k)||u("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:e,label:t,hidden:o}]of Object.entries(O)){if(o)continue;const r=await e.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${t}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),ye().then(e=>e.startIfConfigured()).then(e=>{e?.skipped||(e?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${e?.error||"unknown error"}`))}).catch(e=>u("error",`channels: ${e?.message||e}`))})}function Co(){console.log(`ChatPanel Bridge v${g}
|
|
13
13
|
|
|
14
14
|
Usage:
|
|
15
|
-
chatpanel-bridge start the bridge (foreground) on ${k}:${
|
|
15
|
+
chatpanel-bridge start the bridge (foreground) on ${k}:${b}
|
|
16
16
|
chatpanel-bridge --install run automatically at login, in the background
|
|
17
17
|
chatpanel-bridge --uninstall remove the login auto-start
|
|
18
18
|
chatpanel-bridge --status show whether auto-start is set up
|
|
@@ -21,4 +21,4 @@ Usage:
|
|
|
21
21
|
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
22
22
|
chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
|
|
23
23
|
|
|
24
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function
|
|
24
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function xo(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return Co(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=Q(D,"utf8").trim()}catch{}const o=`http://${k}:${b}`;try{if(!t)throw new Error(`no token at ${D} — is the bridge running?`);const r=await fetch(`${o}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await r.json().catch(()=>({}));if(!r.ok)throw new Error(a.error||`HTTP ${r.status}`);console.log(`Pairing code: ${vn(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(r){u("error",`could not get a pairing code from the bridge at ${o}: ${r?.message||r}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return kt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{Xe(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){u("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{ze(),u("info","Removed the login auto-start.")}catch(t){u("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=Ke()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const Ce=process.argv.indexOf("--mcp-stdio");if(Ce>=0){const n=process.argv[Ce+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Oo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await se(g);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),Z()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():xo()||Ao();
|
package/src/service.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import l from"node:os";import e from"node:path";import{mkdirSync as u,writeFileSync as p,rmSync as b,existsSync as k}from"node:fs";import{spawn as m,spawnSync as P}from"node:child_process";const d="net.chatpanel.bridge",$="ChatPanel Bridge";function f(){const t=process.execPath,r=e.basename(t).toLowerCase();return(r.startsWith("node")||r.startsWith("bun"))&&process.argv[1]?{program:t,args:[e.resolve(process.argv[1])]}:{program:t,args:[]}}function A(){const t=e.join(l.homedir(),".chatpanel");return u(t,{recursive:!0}),{out:e.join(t,"bridge.log"),err:e.join(t,"bridge.err.log")}}function n(t,r,s={}){return P(t,r,{encoding:"utf8",...s})}const v=()=>e.join(l.homedir(),"Library","LaunchAgents",`${d}.plist`);function I(){const{program:t,args:r}=f(),{out:s,err:i}=A(),a=[t,...r].map(E=>` <string>${E}</string>`).join(`
|
|
2
2
|
`),c=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
4
4
|
<plist version="1.0">
|
|
@@ -8,21 +8,26 @@ import u from"node:os";import e from"node:path";import{mkdirSync as l,writeFileS
|
|
|
8
8
|
<array>
|
|
9
9
|
${a}
|
|
10
10
|
</array>
|
|
11
|
+
<key>EnvironmentVariables</key>
|
|
12
|
+
<dict>
|
|
13
|
+
<key>CHATPANEL_SERVICE</key><string>1</string>
|
|
14
|
+
</dict>
|
|
11
15
|
<key>RunAtLoad</key><true/>
|
|
12
16
|
<key>KeepAlive</key><true/>
|
|
13
17
|
<key>StandardOutPath</key><string>${s}</string>
|
|
14
18
|
<key>StandardErrorPath</key><string>${i}</string>
|
|
15
19
|
</dict>
|
|
16
20
|
</plist>
|
|
17
|
-
`,o=
|
|
18
|
-
`);const a=n("reg",["add",g,"/v",h,"/t","REG_SZ","/d",`wscript.exe "${i}"`,"/f"]);if(a.status!==0)throw new Error((a.stderr||"").trim()||"reg add failed");n("wscript.exe",[i])}function
|
|
19
|
-
Description=${
|
|
21
|
+
`,o=v();u(e.dirname(o),{recursive:!0}),p(o,c),n("launchctl",["unload",o]);const w=n("launchctl",["load","-w",o]);if(w.status!==0)throw new Error((w.stderr||"").trim()||"launchctl load failed")}function L(){const t=v();n("launchctl",["unload","-w",t]),k(t)&&b(t)}function C(){return(n("launchctl",["list"]).stdout||"").includes(d)}const g="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",h="ChatPanelBridge",S=()=>e.join(l.homedir(),".chatpanel","launch.vbs");function j(){const{program:t,args:r}=f(),s=[t,...r].map(c=>`""${c}""`).join(" "),i=S();u(e.dirname(i),{recursive:!0}),p(i,`CreateObject("WScript.Shell").Run "${s}", 0, False\r
|
|
22
|
+
`);const a=n("reg",["add",g,"/v",h,"/t","REG_SZ","/d",`wscript.exe "${i}"`,"/f"]);if(a.status!==0)throw new Error((a.stderr||"").trim()||"reg add failed");n("wscript.exe",[i])}function U(){n("reg",["delete",g,"/v",h,"/f"]),n("taskkill",["/IM","chatpanel-bridge.exe","/F"])}function R(){return n("reg",["query",g,"/v",h]).status===0}const x=()=>e.join(l.homedir(),".config","systemd","user","chatpanel-bridge.service");function N(){const{program:t,args:r}=f(),s=[t,...r].map(o=>/\s/.test(o)?`"${o}"`:o).join(" "),i=`[Unit]
|
|
23
|
+
Description=${$}
|
|
20
24
|
After=network.target
|
|
21
25
|
|
|
22
26
|
[Service]
|
|
23
27
|
ExecStart=${s}
|
|
28
|
+
Environment=CHATPANEL_SERVICE=1
|
|
24
29
|
Restart=on-failure
|
|
25
30
|
|
|
26
31
|
[Install]
|
|
27
32
|
WantedBy=default.target
|
|
28
|
-
`,a=x();
|
|
33
|
+
`,a=x();u(e.dirname(a),{recursive:!0}),p(a,i),n("systemctl",["--user","daemon-reload"]);const c=n("systemctl",["--user","enable","--now","chatpanel-bridge"]);if(c.status!==0)throw new Error((c.stderr||"").trim()||"systemctl enable failed")}function D(){n("systemctl",["--user","disable","--now","chatpanel-bridge"]);const t=x();k(t)&&b(t)}function T(){return(n("systemctl",["--user","is-enabled","chatpanel-bridge"]).stdout||"").trim()==="enabled"}function y(t,r,s){if(process.platform==="darwin")return t();if(process.platform==="win32")return r();if(process.platform==="linux")return s();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the bridge directly.`)}function V(){return y(I,j,N)}function H(){return y(L,U,D)}function M(){return y(C,R,T)}function K(){try{if(process.platform==="darwin"){const t=typeof process.getuid=="function"?process.getuid():0;return m("launchctl",["kickstart","-k",`gui/${t}/${d}`],{detached:!0,stdio:"ignore"}).unref(),!0}if(process.platform==="linux")return m("systemctl",["--user","restart","chatpanel-bridge"],{detached:!0,stdio:"ignore"}).unref(),!0;if(process.platform==="win32"){const t=S(),r=e.dirname(process.execPath),s=`taskkill /IM chatpanel-bridge.exe /F >nul 2>&1 & timeout /t 2 >nul & wscript.exe "${t}" & del /q "${e.join(r,"chatpanel-bridge.old-*.exe")}" >nul 2>&1`;return m("cmd",["/c",s],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),!0}}catch{}return!1}export{V as installService,f as resolveLaunch,K as restartService,M as serviceStatus,H as uninstallService};
|
package/src/threads.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFileSync as A,writeFileSync as $,renameSync as b,mkdirSync as v}from"node:fs";import{createHmac as g,randomBytes as N}from"node:crypto";import O from"node:os";import w from"node:path";import{normalizeThread as y,legacyThreadIds as k,threadPlan as _,turnSeen as j,historySplit as E,historyExtension as I}from"./events/agent-thread.js";const P=w.join(O.homedir(),".chatpanel","agent-threads.json");function B({file:l=P,now:c=Date.now,max:d=2e3}={}){let i=null;function n(){if(i)return i;try{const t=JSON.parse(A(l,"utf8"));t?.v===1&&/^[0-9a-f]{64}$/.test(t.key)&&t.links&&typeof t.links=="object"&&(i={v:1,key:t.key,links:t.links})}catch{}return i||(i={v:1,key:N(32).toString("hex"),links:{}}),i}function a(){const t=n(),e=Object.keys(t.links);if(e.length>d){e.sort((r,o)=>(t.links[r].at||0)-(t.links[o].at||0));for(const r of e.slice(0,e.length-d))delete t.links[r]}try{v(w.dirname(l),{recursive:!0,mode:448});const r=`${l}.${process.pid}.tmp`;$(r,JSON.stringify(t),{mode:384}),b(r,l)}catch{}}const s=(t,e)=>`${t}|${e}`,u=(t,e)=>[e,...k(e)].map(r=>n().links[s(t,r)]).find(Boolean),f=(t,e)=>{for(const r of k(e))delete n().links[s(t,r)]};return{digest(t){const e=Array.isArray(t?.users)?t.users:[];return g("sha256",Buffer.from(n().key,"hex")).update(JSON.stringify([e,Number(t?.answers)||0])).digest("hex")},mark(t){return g("sha256",Buffer.from(n().key,"hex")).update(`last\0${String(t??"")}`).digest("hex")},unseen(t,e){return this.extension(t,e)?.tail||null},extension(t,e){if(!t||!Array.isArray(t.last))return null;if(Number.isInteger(t.n)&&Number.isInteger(t.answers)){const o=I(e,{n:t.n,answers:t.answers});return o&&t.digest===this.digest(o.prefix)&&t.last.includes(this.mark(o.last))?{tail:o.tail,answered:o.answered}:null}const r=E(e);return r.last!=null&&t.digest===this.digest(r)&&t.last.includes(this.mark(r.last))?{tail:e.slice(-1),answered:!0}:null},get(t,e){const r=u(t,e);return r&&typeof r.sessionId=="string"?{...r}:null},put(t,e,{sessionId:r,cwd:o="",seen:h}){if(!t||!e||typeof r!="string"||!r)return;const x=(Array.isArray(h?.last)?h.last:[]).map(T=>this.mark(T)),S=Array.isArray(h?.users)?h.users.length:0;f(t,e),n().links[s(t,e)]={sessionId:r,cwd:String(o||""),digest:this.digest(h),last:x,n:S,answers:Number(h?.answers)||0,at:c()},a()},drop(t,e){u(t,e)&&(delete n().links[s(t,e)],f(t,e),a())},list(){return Object.entries(n().links).map(([t,e])=>{const r=t.lastIndexOf("|"),o=t.slice(r+1);return{agent:t.slice(0,r),thread:y({id:o})?.id||o,sessionId:e.sessionId,cwd:e.cwd,at:e.at}}).sort((t,e)=>(e.at||0)-(t.at||0))}}}function U(l,c,d={},{cwd:i="",links:n=L()}={}){const a=y(d?.thread);if(!a||d?.ephemeral===!0)return null;const s=`${l}|${d.reach||"local"}`,u=n.get(s,a.id),f=n.unseen(u,c),t=_({link:u,digest:f?u.digest:"",cwd:i,hasHistory:(c?.length||0)>1});return t.mode==="resume"&&(t.tail=f),{thread:a,plan:t,record(e,{answered:r=!0}={}){typeof e=="string"&&e&&n.put(s,a.id,{sessionId:e,cwd:i,seen:j(c,{answered:r})})},forget(){n.drop(s,a.id)},restart(){return{...this,plan:{mode:"start",sessionId:null,seed:(c?.length||0)>1,why:"the session could not be resumed"}}}}}let p=null;function L(){return p||(p=B())}function W(l){p=l}const D="This chat is answering a message from another device right now. Send again when it finishes.",m=new Map,F=15e3;async function Y(l,c,d,i,{waitMs:n=F}={}){const a=y(c?.thread);if(!a||c?.ephemeral===!0)return i();const s=`${l}|${c?.reach||"local"}|${a.id}`,u=m.get(s);if(u){if(!u.signal?.aborted)throw new Error(D);await Promise.race([u.done,new Promise(e=>setTimeout(e,n).unref?.())])}let f;const t={signal:d,done:new Promise(e=>{f=e})};m.set(s,t);try{return await i()}finally{m.get(s)===t&&m.delete(s),f()}}export{P as THREADS_FILE,D as THREAD_BUSY,W as _setThreadLinksForTest,B as createThreadLinks,Y as holdThread,L as threadLinks,U as threadTurn};
|
package/src/warm-pool.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{treeRssBytes as
|
|
1
|
+
import{treeRssBytes as B,totalMemoryBytes as D}from"./proc.js";import{historyShape as $,userTextMatches as N}from"./events/agent-thread.js";const d=1024**3,b=D(),k=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(b>=16*d?10*6e4:5*6e4),U=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(b*.2),3*d),x=400*1024**2;function z(n,o,a=x){const l=Math.floor(o/a),f=n>=48*d?4:n>=24*d?3:n>=12*d?2:1;return Math.max(1,Math.min(l,f))}const I=Number(process.env.CHATPANEL_WARM_MAX)||z(b,U),W=new Set;function S(n,o){if(n.answers!==o.answers||n.users.length!==o.users.length)return!1;const a=n.users.length;for(let l=0;l<a-1;l++)if(n.users[l]!==o.users[l])return!1;return a===0||N(n.users[a-1],o.users[a-1])}function P({max:n=I,idleMs:o=k,budgetBytes:a=U,group:l=W,now:f=Date.now,measure:L=r=>B(r?.pid),log:p=()=>{}}={}){const r=new Set;let h=null;const v=()=>{let e=0;for(const s of l)e+=s.bytes;return e};let A=0;const c=e=>`${Math.round(e/1024**2)} MB`;function m(e,s="dropped"){if(r.has(e)){r.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}p(`warm ${e.label}: ${s} (${r.size} live)`),!r.size&&h&&(clearInterval(h),h=null)}}function _(){const e=f();for(const s of[...r])!s.busy&&e-s.lastUsed>o&&m(s,"idle")}function R(){h||!Number.isFinite(o)||o<=0||(h=setInterval(_,Math.min(o,6e4)),h.unref?.())}const E={get size(){return r.size},get bytes(){let e=0;for(const s of r)e+=s.bytes||0;return e},peek({key:e,messages:s}){const u=$(s);for(const t of r)if(!t.busy&&t.alive&&t.key===e&&S(t.shape,u))return!0;return!1},acquire({key:e,messages:s}){const u=$(s);for(const t of r)if(!(t.busy||!t.alive||t.key!==e)){if(!S(t.shape,u)){p(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${u.users.length}u/${u.answers}a)`);continue}return t.busy=!0,t.lastUsed=f(),p(`warm ${t.label}: reused`),t}return null},reserve({key:e,label:s=e,evict:u=!0}){const t=()=>{let i=null;for(const w of r)!w.busy&&(!i||w.lastUsed<i.lastUsed)&&(i=w);return i};if(r.size>=n){const i=u?t():null;if(!i)return null;m(i,"evicted")}const M=A||x;for(;v()+M>a;){const i=u?t():null;if(!i)return p(`warm ${s}: not kept — ${c(v())} warm + ~${c(M)} would pass the ${c(a)} budget`),null;m(i,`evicted for memory (${c(v())} warm)`)}const T={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:f(),bytes:M};return r.add(T),p(`warm ${s}: starting (${r.size} live, ~${c(v())} of ${c(a)})`),R(),T},holds(e,s){return e.shape=$(s),e},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&m(e,"process exited")}),e},release(e,{user:s,answered:u}){e.alive&&(typeof s=="string"&&(e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(u?1:0)}),e.busy=!1,e.lastUsed=f(),setImmediate(()=>{if(!e.alive)return;const t=L(e.session);t>0&&(e.bytes=t,A=t,p(`warm ${e.label}: ${c(t)} resident`))}))},drop:m,closeAll(e="shutdown"){for(const s of[...r])m(s,e)},keys(){return[...r].map(e=>e.key)},reap:_};return l.add(E),E}export{U as WARM_BUDGET_BYTES,P as createWarmPool,$ as historyShape,z as warmMaxFor};
|