@chatpanel/bridge 0.49.0 → 0.49.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.49.0",
3
+ "version": "0.49.1",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
package/src/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as Ge}from"node:http";import O from"node:os";import{randomBytes as Ue,randomInt as Le,timingSafeEqual as We}from"node:crypto";import{mkdirSync as je,writeFileSync as Fe,readFileSync as re,existsSync as Je}from"node:fs";import{join as M}from"node:path";import*as Xe from"./engines/claude.js";import*as Ke from"./engines/codex.js";import*as ze from"./engines/antigravity.js";import{pi as Ye,opencode as Ve,kiro as Qe,copilot as Ze,deepseek as qe,hermes as et}from"./engines/cli-agents.js";import{connectorsFor as tt}from"./connectors.js";import*as nt from"./engines/custom.js";import{installService as ot,uninstallService as rt,serviceStatus as at,restartService as ae}from"./service.js";import{skillIndex as J,listRecords as it,readRecord as st,readPackageFile as ct,skillsHealth as lt,quarantinedSkills as dt,clearSkillCache as X}from"./skills.js";import{writeSkillPackage as ut,writeSkillFile as ht,deleteSkillPackage as pt,SkillWriteError as ft}from"./skill-write.js";import{agentDefRoots as mt,scanAgentDefs as gt,listAgentDefs as wt,readAgentDef as yt,planAgentExport as bt,exportAgentDef as St,agentDefsHealth as kt,AgentDefError as Tt}from"./agent-defs.js";import{capabilityToolSpecs as xt,runCapabilityTool as Et}from"./mcp-capabilities.js";import{createSession as vt,deleteSession as ie,getSession as se,activeSession as At,relayToolCall as Ot}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ct,isDefaultWorkdir as Pt,resolveWorkdir as $t,writeScopeNote as Rt}from"./workdir.js";import{sandbox as K,runSandboxCli as It,withGrant as ce,withAgentGrant as Nt,withoutOutsideWhenCapped as Dt,grantedWriteRoots as le,acceptRefusalReport as _t,liveProcesses as Ht,sandboxConfigFromEnv as Mt}from"./sandbox.js";import{createAccessGate as Bt,chatKeyOf as Gt,chatFolders as Ut}from"./access-gate.js";import{signInDenial as Lt}from"./events/sandbox-policy.js";import{gitState as Wt,gitDelta as jt}from"./scm.js";import{listConnections as Ft,putConnection as Jt,removeConnection as Xt,runEnvFor as Kt,testConnection as zt,secretBackend as de}from"./connections.js";import{worktreeFor as ue,listWorktrees as Yt,removeWorktree as Vt,withHook as Qt,WORKTREE_ROOT as he}from"./worktree.js";import{AGENT_CLIS as Zt,agentAvailable as qt,agentInstallDirs as en,enrichPath as tn,enrichAgentEnv as nn,findAgentBin as on,forgetMisses as rn,primeAgentLookups as an,resolveCommand as pe,isCompiledBinary as sn}from"./env.js";import"./sanitize.js";import{checkForUpdate as cn,selfUpdate as fe,isEmbedded as me}from"./update.js";import{callLocalMcp as ln,localMcpStatus as dn,signInLocalMcp as un,signInStatusLocalMcp as hn}from"./mcp-local.js";import{assertPublicHttpUrl as ge,assertPublicWebUrl as we}from"./ssrf.js";import{startRun as ye,endRun as z,cancelRun as pn,cancelAll as fn}from"./runs.js";import{closeWarmPools as mn,warmStatus as gn}from"./warm.js";import{SESSION_AGENTS as be,listSessions as wn,readSession as yn,adoptSession as bn,catchUp as Sn}from"./agent-sessions.js";import{agentContext as kn}from"./agent-context.js";import{normalizeThread as Se}from"./events/agent-thread.js";import{portClashPlan as Tn,serviceManagerOf as xn,STANDBY_POLL_MS as En}from"./events/service-standby.js";import{holdThread as ke}from"./threads.js";import{oneReply as vn}from"./one-reply.js";import{createSnapshot as An}from"./health-snapshot.js";import{CompatError as P,anthropicError as Y,anthropicStream as On,chatCompletionStream as Cn,completionStream as Pn,createAnthropicMessage as $n,createChatCompletion as Rn,createCompletion as In,createResponse as Nn,openAIError as S,parseAnthropicMessage as Dn,parseChatCompletion as _n,parseCompletion as Hn,parseResponse as Mn,responseStream as Bn}from"./api-compat.js";import{callerTrust as Gn,isPaired as I,parseExtensionIds as Un,capRunOptions as Ln,engineHonoursReach as Wn,createPairingStore as jn,formatPairingCode as Fn}from"./pii/trust.js";const y="0.49.0",x=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Xe,label:"Claude Code"},codex:{engine:Ke,label:"Codex"},antigravity:{engine:ze,label:"Antigravity",tools:!1},pi:{engine:Ye,label:"Pi"},opencode:{engine:Ve,label:"OpenCode"},hermes:{engine:et,label:"Hermes"},kiro:{engine:Qe,label:"Kiro"},copilot:{engine:Ze,label:"GitHub Copilot"},deepseek:{engine:qe,label:"DeepSeek Harness"},custom:{engine:nt,label:"Custom",hidden:!0}};function Te(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Jn=Un(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gn({origin:n.headers.origin||"",hasToken:Ae(n),extensionIds:Jn})),n.chatpanelTrust}function Xn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Kn(n,e){const t=n.headers.origin||"",o=Te(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const V=new Set(["127.0.0.1","localhost","::1"]);function zn(n){if(!V.has(x))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return V.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let v="";function Yn(){try{Je(D)&&(v=re(D,"utf8").trim()),v||(v=Ue(32).toString("hex"),je(M(O.homedir(),".chatpanel"),{recursive:!0}),Fe(D,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=jn({random:()=>Le(0,1e6)/1e6});function Vn(n){if(!v)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=xe.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Qn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=xe.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:v})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Zn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ee(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function ve(n,e,t){try{const o=await Ee(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function Ae(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&We(o,r)}const qn=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),eo=new Set(["/debug"]),to=n=>eo.has(n),no=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function oo(n,e){if(!zn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!Te(t))return"forbidden origin";const o=n.method==="POST"&&qn.has(e)||n.method==="GET"&&to(e)||no(n.method,e);return o&&!(Xn(t)||Ae(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!ao.has(e)?ro:null}const Oe=()=>me()?"chatpanel-gateway pair":"chatpanel-bridge pair",ro=`forbidden: this client is not paired with the bridge — run \`${Oe()}\` and enter the code in ChatPanel Settings`,ao=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Q(n,e,t){const o=N(n),r=Nt(e,Dt(Ln(t,o)));if(!Wn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":`pair this client (${Oe()})`} to use ${e}`};const a=r.reach,s=I(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:r,note:s}}async function Ce(n,e,t){const o=e?.message||String(e);try{const r=await K().status(),a=!!(r.enabled&&r.runtime)&&t?.outside!==!0,s=Lt(`${o}
2
+ import{createServer as Ge}from"node:http";import O from"node:os";import{randomBytes as Ue,randomInt as Le,timingSafeEqual as We}from"node:crypto";import{mkdirSync as je,writeFileSync as Fe,readFileSync as re,existsSync as Je}from"node:fs";import{join as M}from"node:path";import*as Xe from"./engines/claude.js";import*as Ke from"./engines/codex.js";import*as ze from"./engines/antigravity.js";import{pi as Ye,opencode as Ve,kiro as Qe,copilot as Ze,deepseek as qe,hermes as et}from"./engines/cli-agents.js";import{connectorsFor as tt}from"./connectors.js";import*as nt from"./engines/custom.js";import{installService as ot,uninstallService as rt,serviceStatus as at,restartService as ae}from"./service.js";import{skillIndex as J,listRecords as it,readRecord as st,readPackageFile as ct,skillsHealth as lt,quarantinedSkills as dt,clearSkillCache as X}from"./skills.js";import{writeSkillPackage as ut,writeSkillFile as ht,deleteSkillPackage as pt,SkillWriteError as ft}from"./skill-write.js";import{agentDefRoots as mt,scanAgentDefs as gt,listAgentDefs as wt,readAgentDef as yt,planAgentExport as bt,exportAgentDef as St,agentDefsHealth as kt,AgentDefError as Tt}from"./agent-defs.js";import{capabilityToolSpecs as xt,runCapabilityTool as Et}from"./mcp-capabilities.js";import{createSession as vt,deleteSession as ie,getSession as se,activeSession as At,relayToolCall as Ot}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ct,isDefaultWorkdir as Pt,resolveWorkdir as $t,writeScopeNote as Rt}from"./workdir.js";import{sandbox as K,runSandboxCli as It,withGrant as ce,withAgentGrant as Nt,withoutOutsideWhenCapped as Dt,grantedWriteRoots as le,acceptRefusalReport as _t,liveProcesses as Ht,sandboxConfigFromEnv as Mt}from"./sandbox.js";import{createAccessGate as Bt,chatKeyOf as Gt,chatFolders as Ut}from"./access-gate.js";import{signInDenial as Lt}from"./events/sandbox-policy.js";import{gitState as Wt,gitDelta as jt}from"./scm.js";import{listConnections as Ft,putConnection as Jt,removeConnection as Xt,runEnvFor as Kt,testConnection as zt,secretBackend as de}from"./connections.js";import{worktreeFor as ue,listWorktrees as Yt,removeWorktree as Vt,withHook as Qt,WORKTREE_ROOT as he}from"./worktree.js";import{AGENT_CLIS as Zt,agentAvailable as qt,agentInstallDirs as en,enrichPath as tn,enrichAgentEnv as nn,findAgentBin as on,forgetMisses as rn,primeAgentLookups as an,resolveCommand as pe,isCompiledBinary as sn}from"./env.js";import"./sanitize.js";import{checkForUpdate as cn,selfUpdate as fe,isEmbedded as me}from"./update.js";import{callLocalMcp as ln,localMcpStatus as dn,signInLocalMcp as un,signInStatusLocalMcp as hn}from"./mcp-local.js";import{assertPublicHttpUrl as ge,assertPublicWebUrl as we}from"./ssrf.js";import{startRun as ye,endRun as z,cancelRun as pn,cancelAll as fn}from"./runs.js";import{closeWarmPools as mn,warmStatus as gn}from"./warm.js";import{SESSION_AGENTS as be,listSessions as wn,readSession as yn,adoptSession as bn,catchUp as Sn}from"./agent-sessions.js";import{agentContext as kn}from"./agent-context.js";import{normalizeThread as Se}from"./events/agent-thread.js";import{portClashPlan as Tn,serviceManagerOf as xn,STANDBY_POLL_MS as En}from"./events/service-standby.js";import{holdThread as ke}from"./threads.js";import{oneReply as vn}from"./one-reply.js";import{createSnapshot as An}from"./health-snapshot.js";import{CompatError as P,anthropicError as Y,anthropicStream as On,chatCompletionStream as Cn,completionStream as Pn,createAnthropicMessage as $n,createChatCompletion as Rn,createCompletion as In,createResponse as Nn,openAIError as S,parseAnthropicMessage as Dn,parseChatCompletion as _n,parseCompletion as Hn,parseResponse as Mn,responseStream as Bn}from"./api-compat.js";import{callerTrust as Gn,isPaired as I,parseExtensionIds as Un,capRunOptions as Ln,engineHonoursReach as Wn,createPairingStore as jn,formatPairingCode as Fn}from"./pii/trust.js";const y="0.49.1",x=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Xe,label:"Claude Code"},codex:{engine:Ke,label:"Codex"},antigravity:{engine:ze,label:"Antigravity",tools:!1},pi:{engine:Ye,label:"Pi"},opencode:{engine:Ve,label:"OpenCode"},hermes:{engine:et,label:"Hermes"},kiro:{engine:Qe,label:"Kiro"},copilot:{engine:Ze,label:"GitHub Copilot"},deepseek:{engine:qe,label:"DeepSeek Harness"},custom:{engine:nt,label:"Custom",hidden:!0}};function Te(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Jn=Un(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gn({origin:n.headers.origin||"",hasToken:Ae(n),extensionIds:Jn})),n.chatpanelTrust}function Xn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Kn(n,e){const t=n.headers.origin||"",o=Te(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const V=new Set(["127.0.0.1","localhost","::1"]);function zn(n){if(!V.has(x))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return V.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let v="";function Yn(){try{Je(D)&&(v=re(D,"utf8").trim()),v||(v=Ue(32).toString("hex"),je(M(O.homedir(),".chatpanel"),{recursive:!0}),Fe(D,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=jn({random:()=>Le(0,1e6)/1e6});function Vn(n){if(!v)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=xe.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Qn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=xe.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:v})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Zn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ee(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function ve(n,e,t){try{const o=await Ee(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function Ae(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&We(o,r)}const qn=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),eo=new Set(["/debug"]),to=n=>eo.has(n),no=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function oo(n,e){if(!zn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!Te(t))return"forbidden origin";const o=n.method==="POST"&&qn.has(e)||n.method==="GET"&&to(e)||no(n.method,e);return o&&!(Xn(t)||Ae(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!ao.has(e)?ro:null}const Oe=()=>me()?"chatpanel-gateway pair":"chatpanel-bridge pair",ro=`forbidden: this client is not paired with the bridge — run \`${Oe()}\` and enter the code in ChatPanel Settings`,ao=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Q(n,e,t){const o=N(n),r=Nt(e,Dt(Ln(t,o)));if(!Wn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":`pair this client (${Oe()})`} to use ${e}`};const a=r.reach,s=I(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:r,note:s}}async function Ce(n,e,t){const o=e?.message||String(e);try{const r=await K().status(),a=!!(r.enabled&&r.runtime)&&t?.outside!==!0,s=Lt(`${o}
3
3
  ${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:E[n]?.label||n||"This agent"});if(s)return s.line}catch{}return o}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}const Pe=An({compute:io});async function io(){await an();const n=await Promise.all(Object.entries(E).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:d}])=>{const l=await s.available().catch(w=>({ok:!1,reason:String(w?.message||w)})),p=await tt(a).catch(()=>[]);return{id:a,label:c,available:l.ok,reason:l.reason,connectors:p,...d===!1?{tools:!1}:{}}})),e=me()?{current:y,updateAvailable:!1,embedded:"gateway"}:await cn(y).catch(()=>({current:y,updateAvailable:!1})),t=await lt().catch(()=>null),o=await kt().catch(()=>null),r=await K().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function so(n,{fresh:e=!1}={}){e&&rn();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await Pe.get({fresh:e});i(n,200,{ok:!0,version:y,agents:o,update:r,checkedAt:t,workspace:Ct,sandbox:c,localMcp:dn(),processes:Ht(),worktrees:he,secretBackend:de(),warm:gn(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...s?{agentDefs:s}:{}})}async function co(n,e,t){const{index:o,problems:r}=await J({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:it(o),problems:r})}async function lo(n,e,t){i(n,200,{ok:!0,quarantined:await dt(e,t)})}async function uo(n,e,t,o){const{index:r}=await J({extraDirs:t,workdir:o}),a=st(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ho(n,e,t,o,r){const{index:a}=await J({extraDirs:o,workdir:r}),s=await ct(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function po(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await ut({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return X(),i(e,200,o)}catch(o){return i(e,Z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function fo(n,e,t,o){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await ht({name:t,path:o,text:r?.text??""});return X(),i(e,200,a)}catch(a){return i(e,Z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function mo(n,e){try{const t=await pt({name:e});return X(),i(n,200,t)}catch(t){return i(n,Z(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function Z(n){return n instanceof ft?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function $e(n,e){return gt({roots:mt(process.env,O.homedir(),n,e)})}async function go(n,e,t){const{index:o,quarantined:r,problems:a}=await $e(e,t);i(n,200,{ok:!0,agents:wt(o),...r.length?{quarantined:r.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function wo(n,e,t,o){const{index:r}=await $e(t,o),a=yt(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function yo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,{ok:!0,...await bt({agent:t?.agent,to:t?.to})})}catch(o){return i(e,Re(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function bo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,await St({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,Re(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function Re(n){if(n instanceof Tt){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function So(){return(await Promise.all(Object.entries(E).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function Ie(n,e=""){const t=await So();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function ko(n){try{const e=await fe(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>ae(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function To(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=Q(n,t.agent,t.options||{});if(r.error)return i(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
4
4
 
5
5
  `)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,d=ye(c),l={signal:d.signal,abort:()=>d.cancel("client")},p=()=>{s=!0,d.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const w=h=>{s||a(h)};a({type:"run",id:c}),r.note&&a({type:"status",text:r.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(f=await ue({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),z(c),e.writableEnded||e.end();return}}const _=f?f.path:$t(t.options?.workingDir),W=Gt(t.agent,t.options),ee=W?Ut(W):[];ee.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...ee])]}});let C=null;{const h=_,T=!!f||!Pt(t.options?.workingDir),g=Rt(t.agent,t.options?.permissionMode,h,le(h,{grant:t.options?.sandbox}));a({type:"workdir",path:h,isDefault:!T,writeScope:g||void 0}),a({type:"status",text:`Working in ${h}${T?"":" (default)"}`}),g&&a({type:"status",text:g}),C=await Wt(h),C&&a({type:"scm",phase:"before",...C})}let j=null;if(C||f){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:T,connection:g}=Kt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=Qt(T),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...g?{connection:g}:{}}),g&&a({type:"status",text:`Git credential: ${g.kind} · ${g.host}${g.hasSecret?"":" (no token stored)"} · push: ${T.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:T.CHATPANEL_SCM_PUSH}`})}const F=t.approvals===!0,b={...t.options||{},...f?{workingDir:f.path}:{},...j?{runEnv:j}:{},approvals:F};let R=null;(t.pageTools?.specs?.length||F)&&(R=vt(w,t.pageTools?.specs||[]),b.permissionSession=R,t.pageTools?.specs?.length&&(b.mcp={url:`http://${x}:${k}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const Me=Mt();let te=b.sandbox||null;F&&Me.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&b.sandbox?.outside!==!0&&(b.accessGate=Bt({agent:t.agent,label:E[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>le(_,{grant:te})}));try{const h=vn(w),T=(g,H)=>ce(g.sandbox,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:H,options:g,images:Array.isArray(t.images)?t.images:[]},h.emit,{signal:l.signal}));await ke(t.agent,b,l.signal,async()=>{await T(b,t.system||"");let g=b;for(let H=0;H<2&&b.accessGate?.restart().length&&!l.signal.aborted;H++){const ne=b.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...ne])]}},te=g.sandbox;const oe=ne.map(Be=>b.accessGate.short(Be)).join(", ");h.seam(),w({type:"status",text:`Restarted with write access to ${oe} — carrying on`}),await T(g,`${t.system||""}
package/src/warm-pool.js CHANGED
@@ -1 +1 @@
1
- import{treeRssBytes as L,totalMemoryBytes as B}from"./proc.js";import{historyShape as k,userTextMatches as D,idsSeen as z,idsExtension as g}from"./events/agent-thread.js";const w=1024**3,x=B(),F=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(x>=16*w?10*6e4:5*6e4),U=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(x*.2),3*w),N=400*1024**2;function G(u,l,a=N){const c=Math.floor(l/a),d=u>=48*w?4:u>=24*w?3:u>=12*w?2:1;return Math.max(1,Math.min(c,d))}const P=Number(process.env.CHATPANEL_WARM_MAX)||G(x,U),C=new Set;function W(u,l){if(u.answers!==l.answers||u.users.length!==l.users.length)return!1;const a=u.users.length;for(let c=0;c<a-1;c++)if(u.users[c]!==l.users[c])return!1;return a===0||D(u.users[a-1],l.users[a-1])}const H=2*6e4;function Y({max:u=P,idleMs:l=F,budgetBytes:a=U,group:c=C,now:d=Date.now,measure:I=o=>L(o?.pid),log:p=()=>{}}={}){const o=new Set;let b=null;const $=()=>{let e=0;for(const s of c)e+=s.bytes;return e};let M=0;const h=e=>`${Math.round(e/1024**2)} MB`,v=new Set;function T(e){for(const s of[...v])s.key===e&&(v.delete(s),s.resolve())}function m(e,s="dropped"){if(o.has(e)){o.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}p(`warm ${e.label}: ${s} (${o.size} live)`),!o.size&&b&&(clearInterval(b),b=null),e.worker&&T(e.key)}}const _=e=>Number(e.session?.expiresAt)>0&&d()>=e.session.expiresAt-H;function S(){const e=d();for(const s of[...o])!s.busy&&e-s.lastUsed>l&&m(s,"idle")}function R(){b||!Number.isFinite(l)||l<=0||(b=setInterval(S,Math.min(l,6e4)),b.unref?.())}const A={get size(){return o.size},get bytes(){let e=0;for(const s of o)e+=s.bytes||0;return e},peek({key:e,messages:s}){const n=k(s);for(const r of o)if(!r.busy&&r.alive&&!r.worker&&r.key===e&&!_(r)&&W(r.shape,n))return!0;return!1},acquire({key:e,messages:s,thread:n=null}){const r=k(s);for(const t of o){if(t.busy||!t.alive||t.worker||t.key!==e)continue;if(_(t)){m(t,"its sign-in is about to expire");continue}const i=n?.id&&t.thread===n.id&&t.seenIds?g(s,n,t.seenIds):null;if(!i&&!W(t.shape,r)){p(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${r.users.length}u/${r.answers}a)`);continue}return t.busy=!0,t.lastUsed=d(),t.unseen=i&&i.tail.length>1?i.tail:null,p(`warm ${t.label}: reused${i?` by id (${i.tail.length} unseen)`:""}`),t}return null},reserve({key:e,label:s=e,evict:n=!0}){const r=()=>{let f=null;for(const E of o)!E.busy&&(!f||E.lastUsed<f.lastUsed)&&(f=E);return f};if(o.size>=u){const f=n?r():null;if(!f)return null;m(f,"evicted")}const t=M||N;for(;$()+t>a;){const f=n?r():null;if(!f)return p(`warm ${s}: not kept — ${h($())} warm + ~${h(t)} would pass the ${h(a)} budget`),null;m(f,`evicted for memory (${h($())} warm)`)}const i={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:d(),bytes:t};return o.add(i),p(`warm ${s}: starting (${o.size} live, ~${h($())} of ${h(a)})`),R(),i},holds(e,s){return e.shape=k(s),e},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&m(e,"process exited")}),e},release(e,{user:s,answered:n,messages:r=null,thread:t=null}){if(e.alive){if(typeof s=="string"){e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(n?1:0)};const i=t?.id?z(r,t,{answered:n}):null;i&&(e.thread=t.id,e.seenIds=i)}e.unseen=null,e.busy=!1,e.lastUsed=d(),setImmediate(()=>{if(!e.alive)return;const i=I(e.session);i>0&&(e.bytes=i,M=i,p(`warm ${e.label}: ${h(i)} resident`))})}},acquireWorker({key:e,thread:s=null}){let n=null;for(const r of o){if(r.busy||!r.alive||!r.worker||r.key!==e)continue;if(_(r)){m(r,"its sign-in is about to expire");continue}const t=(s&&r.thread===s?-1e6:0)+(r.uses||0);(!n||t<n.rank)&&(n={e:r,rank:t})}return n?(n.e.busy=!0,n.e.lastUsed=d(),p(`warm ${n.e.label}: worker reused (${n.e.uses||0} turns so far)`),n.e):null},reserveWorker({key:e,label:s=e,cap:n=2}){let r=0;for(const i of o)i.worker&&i.key===e&&r++;if(r>=n)return null;const t=A.reserve({key:e,label:`${s} (worker)`,evict:!1});return t&&(t.worker=!0),t},workerFree(e,s){return new Promise(n=>{const r={key:e,resolve:()=>{clearTimeout(r.timer),n(!0)}};r.timer=setTimeout(()=>{v.delete(r),n(!1)},s),r.timer.unref?.(),v.add(r)})},releaseWorker(e,{thread:s=null,maxUses:n=12}={}){if(e.alive){if(e.uses=(e.uses||0)+1,e.thread=s,e.busy=!1,e.lastUsed=d(),e.uses>=n){m(e,`worker retired after ${e.uses} turns`);return}setImmediate(()=>{if(!e.alive)return;const r=I(e.session);r>0&&(e.bytes=r,M=r,p(`warm ${e.label}: ${h(r)} resident`))}),T(e.key)}},drop:m,closeAll(e="shutdown"){for(const s of[...o])m(s,e)},keys(){return[...o].map(e=>e.key)},reap:S};return c.add(A),A}export{U as WARM_BUDGET_BYTES,Y as createWarmPool,k as historyShape,G as warmMaxFor};
1
+ import{treeRssBytes as L,totalMemoryBytes as B}from"./proc.js";import{historyShape as k,userTextMatches as D,idsSeen as z,idsExtension as g}from"./events/agent-thread.js";const w=1024**3,x=B(),F=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(x>=16*w?10*6e4:5*6e4),U=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(x*.2),3*w),N=400*1024**2;function G(u,l,a=N){const c=Math.floor(l/a),d=u>=48*w?4:u>=24*w?3:u>=12*w?2:1;return Math.max(1,Math.min(c,d))}const P=Number(process.env.CHATPANEL_WARM_MAX)||G(x,U),C=new Set;function W(u,l){if(u.answers!==l.answers||u.users.length!==l.users.length)return!1;const a=u.users.length;for(let c=0;c<a-1;c++)if(u.users[c]!==l.users[c])return!1;return a===0||D(u.users[a-1],l.users[a-1])}const H=2*6e4;function Y({max:u=P,idleMs:l=F,budgetBytes:a=U,group:c=C,now:d=Date.now,measure:I=i=>L(i?.pid),log:m=()=>{}}={}){const i=new Set;let b=null;const $=()=>{let e=0;for(const s of c)e+=s.bytes;return e};let M=0;const h=e=>`${Math.round(e/1024**2)} MB`,v=new Set;function T(e){for(const s of[...v])s.key===e&&(v.delete(s),s.resolve())}function p(e,s="dropped"){if(i.has(e)){i.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}m(`warm ${e.label}: ${s} (${i.size} live)`),!i.size&&b&&(clearInterval(b),b=null),e.worker&&T(e.key)}}const _=e=>Number(e.session?.expiresAt)>0&&d()>=e.session.expiresAt-H;function S(){const e=d();for(const s of[...i])!s.busy&&e-s.lastUsed>l&&p(s,"idle")}function R(){b||!Number.isFinite(l)||l<=0||(b=setInterval(S,Math.min(l,6e4)),b.unref?.())}const A={get size(){return i.size},get bytes(){let e=0;for(const s of i)e+=s.bytes||0;return e},peek({key:e,messages:s}){const n=k(s);for(const r of i)if(!r.busy&&r.alive&&!r.worker&&r.key===e&&!_(r)&&W(r.shape,n))return!0;return!1},acquire({key:e,messages:s,thread:n=null}){const r=k(s);for(const t of i){if(t.busy||!t.alive||t.worker||t.key!==e)continue;if(_(t)){p(t,"its sign-in is about to expire");continue}const o=n?.id&&t.thread===n.id&&t.seenIds?g(s,n,t.seenIds):null;if(!o&&!W(t.shape,r)){m(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${r.users.length}u/${r.answers}a)`);continue}return t.busy=!0,t.lastUsed=d(),t.unseen=o&&o.tail.length>1?o.tail:null,m(`warm ${t.label}: reused${o?` by id (${o.tail.length} unseen)`:""}`),t}return null},reserve({key:e,label:s=e,evict:n=!0}){const r=()=>{let f=null;for(const E of i)!E.busy&&(!f||E.lastUsed<f.lastUsed)&&(f=E);return f};if(i.size>=u){const f=n?r():null;if(!f)return null;p(f,"evicted")}const t=M||N;for(;$()+t>a;){const f=n?r():null;if(!f)return m(`warm ${s}: not kept — ${h($())} warm + ~${h(t)} would pass the ${h(a)} budget`),null;p(f,`evicted for memory (${h($())} warm)`)}const o={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:d(),bytes:t};return i.add(o),m(`warm ${s}: starting (${i.size} live, ~${h($())} of ${h(a)})`),R(),o},holds(e,s){return e.shape=k(s),e},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&p(e,"process exited")}),e},release(e,{user:s,answered:n,messages:r=null,thread:t=null}){if(e.alive){if(typeof s=="string"){e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(n?1:0)};const o=t?.id?z(r,t,{answered:n}):null;o&&(e.thread=t.id,e.seenIds=o)}e.unseen=null,e.busy=!1,e.lastUsed=d(),setImmediate(()=>{if(!e.alive)return;const o=I(e.session);o>0&&(e.bytes=o,M=o,m(`warm ${e.label}: ${h(o)} resident`))})}},acquireWorker({key:e,thread:s=null}){let n=null;for(const r of i){if(r.busy||!r.alive||!r.worker||r.key!==e)continue;if(_(r)){p(r,"its sign-in is about to expire");continue}const t=(s&&r.thread===s?-1e6:0)+(r.uses||0);(!n||t<n.rank)&&(n={e:r,rank:t})}return n?(n.e.busy=!0,n.e.lastUsed=d(),m(`warm ${n.e.label}: worker reused (${n.e.uses||0} turns so far)`),n.e):null},reserveWorker({key:e,label:s=e,cap:n=2}){let r=0;for(const o of i)o.worker&&o.key===e&&r++;if(r>=n)return null;const t=A.reserve({key:e,label:`${s} (worker)`,evict:!1});return t&&(t.worker=!0),t},workerFree(e,s){return new Promise(n=>{const r={key:e,resolve:()=>{clearTimeout(r.timer),n(!0)}};r.timer=setTimeout(()=>{v.delete(r),n(!1)},s),v.add(r)})},releaseWorker(e,{thread:s=null,maxUses:n=12}={}){if(e.alive){if(e.uses=(e.uses||0)+1,e.thread=s,e.busy=!1,e.lastUsed=d(),e.uses>=n){p(e,`worker retired after ${e.uses} turns`);return}setImmediate(()=>{if(!e.alive)return;const r=I(e.session);r>0&&(e.bytes=r,M=r,m(`warm ${e.label}: ${h(r)} resident`))}),T(e.key)}},drop:p,closeAll(e="shutdown"){for(const s of[...i])p(s,e)},keys(){return[...i].map(e=>e.key)},reap:S};return c.add(A),A}export{U as WARM_BUDGET_BYTES,Y as createWarmPool,k as historyShape,G as warmMaxFor};