@chatpanel/bridge 0.20.2 → 0.21.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 +1 -1
- package/src/engines/claude.js +6 -6
- package/src/server.js +1 -1
- package/src/warm-pool.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.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/engines/claude.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`)}catch{}};
|
|
3
|
-
`))>=0;){const
|
|
4
|
-
`):(
|
|
1
|
+
import{spawn as F}from"node:child_process";import{writeFile as W,unlink as H}from"node:fs/promises";import P from"node:os";import R from"node:path";import{resolveClaude as S,buildSpawnSpec as q,isCompiledBinary as ae,selfMcpStdio as ie}from"../env.js";import{signInStatus as le,signInMessage as z,loginRequired as ce}from"../sign-in.js";import{buildCliPrompt as U}from"./prompt.js";import{summarizeCliError as ue}from"../cli-errors.js";import{killOnAbort as pe}from"../proc.js";import{sandbox as de,noteSandbox as fe,track as he}from"../sandbox.js";import{pushExtraArgs as me,FORBIDDEN as ye}from"./args.js";import{relayTimeoutMax as _e}from"../relay-timeout.js";import{displayPath as be,resolveWorkdir as B}from"../workdir.js";import{connectorsFor as we}from"../connectors.js";import{chatWarm as Te}from"./claude-warm.js";import{claudePermissionResponse as ge,permissionAnswer as xe}from"../events/agent-permission.js";import{relayPermission as Ee}from"../mcp-sessions.js";async function Ce(e,t){const r=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const o=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",n=R.join(P.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await W(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const G=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,J=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],K=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),ke=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch"])}),Se=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),Ae=Object.freeze(["remember","forget"]),ve=Object.freeze(["ask_model","ask_status"]),Y=Object.freeze({device:Object.freeze([]),trusted:Se});function Ne(e,t=[]){const r=Y[e]||Y.device,i=(t||[]).filter(n=>typeof n=="string"&&/^chatpanel/i.test(n)),s=[],o=[];for(const n of i){for(const a of r)s.push(`mcp__${n}__${a}`);for(const a of[...Ae,...ve])o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function Pe(e){if(!e||e==="any")return null;const t=K[e]?e:"device";return{allow:[...K[t]],deny:[...ke[t]]}}let M="Claude Code not found.",X=0,E=!1;async function st(){if(Date.now()-X>(E?3e4:4e3)){X=Date.now();try{S()||!ae()&&await j()?E=!0:(E=!1,M=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{E=!1}}return E?await le("claude",S()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:z("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:M}}async function at(){return["opus","sonnet","haiku"]}function Me(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=ie(e.url),s=[...new Set(e.specs.map(o=>o?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:r,args:i}}},allowedTools:s.map(o=>`mcp__${t}__${o}`)}}async function Oe(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):xe("deny","This run has no approval surface.");return r(ge(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function Q({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:u=null}){const f=S();if(!f)return null;const[y,_,b]=q(f,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((m,p)=>{de().wrap(y,_,b,{engine:"claude",cwd:r}).then(c=>{fe(s,c.record);let l;try{l=he(F(c.bin,c.argv,c.opts),c,{kind:"agent"})}catch(d){return p(new Error(`Failed to start claude: ${d.message}`))}const w=pe(l,o);let h="",T="",v=!1,g=null;const oe={sawText:!1,tail:"",boundary:!1,harnessChars:n};let O="",C,L=0;const N=()=>{clearTimeout(C),!L&&(C=setTimeout(()=>{l.kill("SIGKILL"),p(new Error(`Claude Code timed out — no output for ${Math.round(G/1e3)}s.`))},G))};N();const se=d=>{try{l.stdin.write(`${JSON.stringify(d)}
|
|
2
|
+
`)}catch{}};l.stdout.on("data",d=>{N(),h+=d.toString();let $;for(;($=h.indexOf(`
|
|
3
|
+
`))>=0;){const D=h.slice(0,$).trim();if(h=h.slice($+1),!D.startsWith("{"))continue;let x;try{x=JSON.parse(D)}catch{continue}if(x.type==="control_request"){L++,clearTimeout(C),Oe(x,u,se).catch(()=>{}).finally(()=>{L--,N()});continue}if(x.type==="control_response")continue;const k=ee(x,s,v,r,oe);k.streamed&&(v=!0),k.result!=null&&(O=k.result),k.apiError&&(g=k.apiError),a&&x.type==="result"&&l.stdin.end()}}),l.stderr.on("data",d=>{N(),T+=d.toString()}),l.on("error",d=>{clearTimeout(C),w(),p(new Error(`Failed to start claude (${y}): ${d.message}`))}),l.on("close",d=>{if(clearTimeout(C),w(),o?.aborted){m({streamedAny:v,resultText:O});return}if(g&&ce(g))return p(new Error(z("Claude Code","claude")));if(d===0&&g)return p(new Error(`Claude Code reported an error: ${g}`));d===0?m({streamedAny:v,resultText:O}):p(new Error(ue("Claude Code",d,T,g||"",{agentId:"claude"})))}),a?l.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
|
|
4
|
+
`):(l.stdin.write(e),l.stdin.end())}).catch(p)})}function Le(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(r=>typeof r=="string"?r:r?.text||"").filter(Boolean).join(`
|
|
5
5
|
`)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function V(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
|
|
6
6
|
|
|
7
7
|
`}),e.boundary=!1)}function Z(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function ee(e,t,r,i="",s=null){const o={streamed:!1,result:null};if(e.type==="stream_event"){const n=e.event;n?.type==="content_block_delta"&&(n.delta?.type==="text_delta"?(o.streamed=!0,V(s,t),t({type:"delta",text:n.delta.text}),Z(s,n.delta.text)):n.delta?.type==="thinking_delta"&&t({type:"reasoning",text:n.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return o.apiError=(e.message?.content||[]).filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
8
|
-
`)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:
|
|
8
|
+
`)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:De(n,i)})):n.type==="text"&&!r&&(o.streamed=!0,V(s,t),t({type:"delta",text:n.text}),Z(s,n.text))}else if(e.type==="user")for(const n of e.message?.content||[])n.type==="tool_result"&&t({type:"tool",phase:"done",callId:n.tool_use_id,status:n.is_error?"error":"ok",result:Le(n.content)});else if(e.type==="result"){e.is_error?o.apiError=o.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?o.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const n=e.usage||e.message?.usage;if(n){const a=Number.isFinite(Number(e.total_cost_usd))?Number(e.total_cost_usd):null,u=Number(s?.costUsdBefore)||0;s&&a!=null&&(s.costUsdTotal=a),t({type:"usage",provider:"bridge",inputTokens:n.input_tokens||0,outputTokens:n.output_tokens||0,cacheReadTokens:n.cache_read_input_tokens||0,cacheWriteTokens:n.cache_creation_input_tokens||0,costUsd:a!=null?Math.max(0,a-u):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return o}const te=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let A=null;function re({probe:e=null}={}){return A||(A=(async()=>{try{return String(await(e?e():new Promise(t=>{const[r,i,s]=q(S(),["--help"],null),o=F(r,i,{...s,stdio:["ignore","pipe","pipe"]});let n="";o.stdout.on("data",a=>{n+=a}),o.on("error",()=>t("")),o.on("close",()=>t(n)),setTimeout(()=>{try{o.kill()}catch{}t(n)},8e3).unref?.()}))||"")}catch{return""}})(),A)}async function $e(e={}){return/--effort\b/.test(await re(e))}async function We(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await re(e))}function it(){A=null}async function Re({system:e,options:t,tag:r}){const i=t.permissionMode||"default",s=B(t.workingDir),o=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];te&&await $e()&&o.push("--effort",te);const n=[],a=[],u=Me(t.mcp);if(u){const c=R.join(P.tmpdir(),`chatpanel-mcp-${r}.json`);await W(c,JSON.stringify(u.config)),n.push(c),o.push("--mcp-config",c),a.push(...u.allowedTools)}const f=Pe(t.reach);if(f){const c=Ne(t.reach,await we("claude").catch(()=>[]));o.push("--allowedTools",...f.allow,...a,...c.allow),o.push("--disallowedTools",...f.deny,...c.deny)}else i==="bypassPermissions"?o.push("--permission-mode","bypassPermissions"):i==="acceptEdits"?(o.push("--permission-mode","acceptEdits"),a.length&&o.push("--allowedTools",...a)):o.push("--allowedTools",...J,...a);const y=!f&&t.approvals===!0;if(y&&o.push("--permission-prompt-tool","stdio"),e)if(S()?.kind!=="wsl"&&await We()){const l=R.join(P.tmpdir(),`chatpanel-system-${r}.md`);await W(l,e,{mode:384}),n.push(l),o.push("--append-system-prompt-file",l)}else o.push("--append-system-prompt",e);t.model&&o.push("--model",t.model),t.useLocalConfig===!1&&o.push("--setting-sources","");const _=u&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(_e(t.mcp?.specs))}:null,b=t.askDepth?{CHATPANEL_ASK_DEPTH:String(Math.max(0,Math.min(8,Number(t.askDepth)||0)))}:null,m=_||b||t.runEnv?{...t.runEnv||{},..._||{},...b||{}}:null;return{args:o,cwd:s,runEnv:m,cleanup:()=>n.forEach(c=>H(c).catch(()=>{})),hasMcp:!!u,approvals:y}}function ne({prompt:e="",system:t="",specs:r=null}={}){const i=Array.isArray(r)&&r.length?JSON.stringify(r).length:0;return String(e).length+String(t).length+i}function Ie(e,t=[],r=""){let i=U(e,r);return t.length&&(i+=`
|
|
9
9
|
|
|
10
|
-
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function
|
|
10
|
+
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function lt({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=await Te({messages:e,system:t,options:r,images:i},s,{signal:o}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!n.handled&&!o?.aborted){if(n.thrown)throw new Error(n.reason);return je({messages:e,system:t,options:r,images:i},s,{signal:o})}}async function je({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await Re({system:t,options:r,tag:n}),{args:u,cwd:f,runEnv:y}=a,_=await Ce(i,n),b=()=>{_.forEach(l=>H(l).catch(()=>{})),a.cleanup()},m=Ie(e,_);me(u,r.extraArgs,ye.claude,s);const p=a.approvals&&r.permissionSession?l=>Ee(r.permissionSession,l):null,c=Q({prompt:m,args:u,cwd:f,env:y,emit:s,signal:o,harness:ne({prompt:m,system:t,specs:r.mcp?.specs}),host:a.approvals,ask:p});if(c===null)return b(),Fe({messages:e,system:t,options:r},s,{signal:o});try{const{streamedAny:l,resultText:w}=await c;s({type:"done",text:l?"":w})}finally{b()}}async function ct({prompt:e,system:t,model:r}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",r||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const o=Q({prompt:e,args:i,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(o===null)return He({prompt:e,system:t,model:r});const{resultText:n}=await o;return(s||n||"").trim()}function De(e,t=""){const r=e.input||{};return r.command?String(r.command).slice(0,60):r.file_path?be(r.file_path,t):r.pattern?r.pattern:r.url?r.url:r.description?String(r.description).slice(0,80):r.query?String(r.query).slice(0,80):r.prompt?String(r.prompt).slice(0,80):""}let I=null;function j(){return I||(I=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),I}async function Fe({messages:e,system:t,options:r},i,{signal:s}={}){const o=await j();if(!o)throw new Error(M);const{query:n}=o,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const u=r.permissionMode||"default",f=B(r.workingDir),y=u==="acceptEdits"||u==="bypassPermissions",_=new Set(J),b=async h=>_.has(h)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${h} blocked — set this agent's permission mode in ChatPanel to enable it.`};let m=!1;const p=U(e),c={sawText:!1,tail:"",boundary:!1,harnessChars:ne({prompt:p,system:t})};let l="";const w=n({prompt:p,options:{cwd:f,permissionMode:u,includePartialMessages:!0,canUseTool:b,abortController:a,settingSources:r.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...r.model?{model:r.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const h of w){const T=ee(h,i,m,f,c);T.streamed&&(m=!0),T.result!=null&&(l=T.result)}}catch(h){if(s?.aborted||a.signal.aborted)return;throw h}i({type:"done",text:m?"":l})}async function He({prompt:e,system:t,model:r}){const i=await j();if(!i)throw new Error(M);const{query:s}=i;let o="";const n=s({prompt:e,options:{cwd:P.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:r||"haiku"}});for await(const a of n)if(a.type==="assistant")for(const u of a.message.content)u.type==="text"&&(o+=u.text);else a.type==="result"&&a.subtype==="success"&&!o&&(o=a.result||"");return o.trim()}export{it as _resetEffortProbe,Oe as answerControlRequest,st as available,Re as buildClaudeLaunch,Ne as channelMcpTools,Pe as channelToolPolicy,lt as chat,je as chatCold,Me as claudeMcpConfig,Ie as claudePrompt,$e as claudeSupportsEffort,We as claudeSupportsSystemPromptFile,ct as complete,ee as handleMessage,ne as harnessChars,at as listModels,Ce as writeImages};
|
package/src/server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as ye}from"node:http";import P from"node:os";import{randomBytes as be,randomInt as Se,timingSafeEqual as ke}from"node:crypto";import{mkdirSync as Te,writeFileSync as ve,readFileSync as K,existsSync as Ce}from"node:fs";import{join as H}from"node:path";import*as Ee from"./engines/claude.js";import*as Oe from"./engines/codex.js";import*as xe from"./engines/antigravity.js";import{pi as Ae,opencode as Pe,kiro as $e,copilot as Ie,deepseek as Ne,hermes as Re}from"./engines/cli-agents.js";import{connectorsFor as _e}from"./connectors.js";import*as He from"./engines/custom.js";import{installService as Me,uninstallService as Be,serviceStatus as Ge,restartService as V}from"./service.js";import{skillIndex as W,listRecords as De,readRecord as Ue,readPackageFile as We,skillsHealth as Le,quarantinedSkills as je}from"./skills.js";import{capabilityToolSpecs as Je,runCapabilityTool as Fe}from"./mcp-capabilities.js";import{createSession as Xe,deleteSession as Y,getSession as Q,activeSession as ze,relayToolCall as Ke}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ve,isDefaultWorkdir as Ye,resolveWorkdir as Qe,writeScopeNote as Ze}from"./workdir.js";import{sandbox as Z,runSandboxCli as qe,withGrant as q,acceptRefusalReport as et,liveProcesses as tt}from"./sandbox.js";import{gitState as nt,gitDelta as ot}from"./scm.js";import{listConnections as rt,putConnection as at,removeConnection as it,runEnvFor as st,testConnection as ct,secretBackend as ee}from"./connections.js";import{worktreeFor as te,listWorktrees as lt,removeWorktree as dt,withHook as ut,WORKTREE_ROOT as ne}from"./worktree.js";import{AGENT_CLIS as pt,enrichPath as ht,enrichAgentEnv as mt,findAgentBin as oe,resolveCommand as ft}from"./env.js";import"./sanitize.js";import{checkForUpdate as gt,selfUpdate as re,isEmbedded as wt}from"./update.js";import{callLocalMcp as yt,localMcpStatus as bt,signInLocalMcp as St,signInStatusLocalMcp as kt}from"./mcp-local.js";import{assertPublicHttpUrl as ae,assertPublicWebUrl as ie}from"./ssrf.js";import{startRun as se,endRun as L,cancelRun as Tt,cancelAll as vt}from"./runs.js";import{closeWarmPools as Ct,warmStatus as Et}from"./warm.js";import{CompatError as $,anthropicError as j,anthropicStream as Ot,chatCompletionStream as xt,completionStream as At,createAnthropicMessage as Pt,createChatCompletion as $t,createCompletion as It,createResponse as Nt,openAIError as b,parseAnthropicMessage as Rt,parseChatCompletion as _t,parseCompletion as Ht,parseResponse as Mt,responseStream as Bt}from"./api-compat.js";import{callerTrust as Gt,isPaired as I,parseExtensionIds as Dt,capRunOptions as Ut,engineHonoursReach as Wt,createPairingStore as Lt,formatPairingCode as jt}from"./pii/trust.js";const w="0.20.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ee,label:"Claude Code"},codex:{engine:Oe,label:"Codex"},antigravity:{engine:xe,label:"Antigravity",tools:!1},pi:{engine:Ae,label:"Pi"},opencode:{engine:Pe,label:"OpenCode"},hermes:{engine:Re,label:"Hermes"},kiro:{engine:$e,label:"Kiro"},copilot:{engine:Ie,label:"GitHub Copilot"},deepseek:{engine:Ne,label:"DeepSeek Harness"},custom:{engine:He,label:"Custom",hidden:!0}};function ce(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 Jt=Dt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gt({origin:n.headers.origin||"",hasToken:pe(n),extensionIds:Jt})),n.chatpanelTrust}function Ft(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 Xt(n,e){const t=n.headers.origin||"",r=ce(t);e.setHeader("Access-Control-Allow-Origin",r?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 zt(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 R=H(P.homedir(),".chatpanel","bridge-token");let S="";function Kt(){try{Ce(R)&&(S=K(R,"utf8").trim()),S||(S=be(32).toString("hex"),Te(H(P.homedir(),".chatpanel"),{recursive:!0}),ve(R,S,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const le=Lt({random:()=>Se(0,1e6)/1e6});function Vt(n){if(!S)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=le.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 Yt(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=le.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function Qt(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:w})}let M=null;async function de(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(P.homedir(),".chatpanel"),dataDir:H(P.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)}}),M}async function ue(n,e,t){try{const r=await de(),o=n.method==="POST"?await f(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function pe(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(S);return r.length===o.length&&ke(r,o)}const Zt=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"]),qt=new Set(["/debug"]),en=n=>qt.has(n);function tn(n,e){if(!zt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ce(t))return"forbidden origin";const r=n.method==="POST"&&Zt.has(e)||n.method==="GET"&&en(e);return r&&!(Ft(t)||pe(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!on.has(e)?nn:null}const nn="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 F(n,e,t){const r=N(n),o=Ut(t,r);if(!Wt(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 a=o.reach,s=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}async function rn(n){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),p=await _e(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:p,...c===!1?{tools:!1}:{}}})),t=wt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await gt(w).catch(()=>({current:w,updateAvailable:!1})),r=await Le().catch(()=>null),o=await Z().status().catch(a=>({enabled:!1,reason:a.message}));i(n,200,{ok:!0,version:w,agents:e,update:t,workspace:Ve,sandbox:o,localMcp:bt(),processes:tt(),worktrees:ne,secretBackend:ee(),warm:Et(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function an(n,e,t){const{index:r,problems:o}=await W({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:De(r),problems:o})}async function sn(n,e,t){i(n,200,{ok:!0,quarantined:await je(e,t)})}async function cn(n,e,t,r){const{index:o}=await W({extraDirs:t,workdir:r}),a=Ue(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ln(n,e,t,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await We(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 dn(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function he(n,e=""){const t=await dn();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,b(new $(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function un(n){try{const e=await re(w);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function pn(n,e){let t;try{t=await f(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=F(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.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)}
|
|
2
|
+
import{createServer as ye}from"node:http";import P from"node:os";import{randomBytes as be,randomInt as Se,timingSafeEqual as ke}from"node:crypto";import{mkdirSync as Te,writeFileSync as ve,readFileSync as K,existsSync as Ce}from"node:fs";import{join as H}from"node:path";import*as Ee from"./engines/claude.js";import*as Oe from"./engines/codex.js";import*as xe from"./engines/antigravity.js";import{pi as Ae,opencode as Pe,kiro as $e,copilot as Ie,deepseek as Ne,hermes as Re}from"./engines/cli-agents.js";import{connectorsFor as _e}from"./connectors.js";import*as He from"./engines/custom.js";import{installService as Me,uninstallService as Be,serviceStatus as Ge,restartService as V}from"./service.js";import{skillIndex as W,listRecords as De,readRecord as Ue,readPackageFile as We,skillsHealth as Le,quarantinedSkills as je}from"./skills.js";import{capabilityToolSpecs as Je,runCapabilityTool as Fe}from"./mcp-capabilities.js";import{createSession as Xe,deleteSession as Y,getSession as Q,activeSession as ze,relayToolCall as Ke}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ve,isDefaultWorkdir as Ye,resolveWorkdir as Qe,writeScopeNote as Ze}from"./workdir.js";import{sandbox as Z,runSandboxCli as qe,withGrant as q,acceptRefusalReport as et,liveProcesses as tt}from"./sandbox.js";import{gitState as nt,gitDelta as ot}from"./scm.js";import{listConnections as rt,putConnection as at,removeConnection as it,runEnvFor as st,testConnection as ct,secretBackend as ee}from"./connections.js";import{worktreeFor as te,listWorktrees as lt,removeWorktree as dt,withHook as ut,WORKTREE_ROOT as ne}from"./worktree.js";import{AGENT_CLIS as pt,enrichPath as ht,enrichAgentEnv as mt,findAgentBin as oe,resolveCommand as ft}from"./env.js";import"./sanitize.js";import{checkForUpdate as gt,selfUpdate as re,isEmbedded as wt}from"./update.js";import{callLocalMcp as yt,localMcpStatus as bt,signInLocalMcp as St,signInStatusLocalMcp as kt}from"./mcp-local.js";import{assertPublicHttpUrl as ae,assertPublicWebUrl as ie}from"./ssrf.js";import{startRun as se,endRun as L,cancelRun as Tt,cancelAll as vt}from"./runs.js";import{closeWarmPools as Ct,warmStatus as Et}from"./warm.js";import{CompatError as $,anthropicError as j,anthropicStream as Ot,chatCompletionStream as xt,completionStream as At,createAnthropicMessage as Pt,createChatCompletion as $t,createCompletion as It,createResponse as Nt,openAIError as b,parseAnthropicMessage as Rt,parseChatCompletion as _t,parseCompletion as Ht,parseResponse as Mt,responseStream as Bt}from"./api-compat.js";import{callerTrust as Gt,isPaired as I,parseExtensionIds as Dt,capRunOptions as Ut,engineHonoursReach as Wt,createPairingStore as Lt,formatPairingCode as jt}from"./pii/trust.js";const w="0.21.1",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ee,label:"Claude Code"},codex:{engine:Oe,label:"Codex"},antigravity:{engine:xe,label:"Antigravity",tools:!1},pi:{engine:Ae,label:"Pi"},opencode:{engine:Pe,label:"OpenCode"},hermes:{engine:Re,label:"Hermes"},kiro:{engine:$e,label:"Kiro"},copilot:{engine:Ie,label:"GitHub Copilot"},deepseek:{engine:Ne,label:"DeepSeek Harness"},custom:{engine:He,label:"Custom",hidden:!0}};function ce(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 Jt=Dt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gt({origin:n.headers.origin||"",hasToken:pe(n),extensionIds:Jt})),n.chatpanelTrust}function Ft(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 Xt(n,e){const t=n.headers.origin||"",r=ce(t);e.setHeader("Access-Control-Allow-Origin",r?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 zt(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 R=H(P.homedir(),".chatpanel","bridge-token");let S="";function Kt(){try{Ce(R)&&(S=K(R,"utf8").trim()),S||(S=be(32).toString("hex"),Te(H(P.homedir(),".chatpanel"),{recursive:!0}),ve(R,S,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const le=Lt({random:()=>Se(0,1e6)/1e6});function Vt(n){if(!S)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=le.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 Yt(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=le.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function Qt(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:w})}let M=null;async function de(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(P.homedir(),".chatpanel"),dataDir:H(P.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)}}),M}async function ue(n,e,t){try{const r=await de(),o=n.method==="POST"?await f(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function pe(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(S);return r.length===o.length&&ke(r,o)}const Zt=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"]),qt=new Set(["/debug"]),en=n=>qt.has(n);function tn(n,e){if(!zt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ce(t))return"forbidden origin";const r=n.method==="POST"&&Zt.has(e)||n.method==="GET"&&en(e);return r&&!(Ft(t)||pe(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!on.has(e)?nn:null}const nn="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 F(n,e,t){const r=N(n),o=Ut(t,r);if(!Wt(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 a=o.reach,s=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}async function rn(n){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),p=await _e(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:p,...c===!1?{tools:!1}:{}}})),t=wt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await gt(w).catch(()=>({current:w,updateAvailable:!1})),r=await Le().catch(()=>null),o=await Z().status().catch(a=>({enabled:!1,reason:a.message}));i(n,200,{ok:!0,version:w,agents:e,update:t,workspace:Ve,sandbox:o,localMcp:bt(),processes:tt(),worktrees:ne,secretBackend:ee(),warm:Et(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function an(n,e,t){const{index:r,problems:o}=await W({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:De(r),problems:o})}async function sn(n,e,t){i(n,200,{ok:!0,quarantined:await je(e,t)})}async function cn(n,e,t,r){const{index:o}=await W({extraDirs:t,workdir:r}),a=Ue(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ln(n,e,t,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await We(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 dn(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function he(n,e=""){const t=await dn();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,b(new $(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function un(n){try{const e=await re(w);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function pn(n,e){let t;try{t=await f(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=F(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.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)}
|
|
3
3
|
|
|
4
4
|
`)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=se(d),l={signal:c.signal,abort:()=>c.cancel("client")},p=()=>{s=!0,c.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const g=h=>{s||a(h)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(m=await te({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(d),e.writableEnded||e.end();return}}const X=m?m.path:Qe(t.options?.workingDir);let E=null;{const h=X,O=!!m||!Ye(t.options?.workingDir),y=Ze(t.agent,t.options?.permissionMode,h);a({type:"workdir",path:h,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${h}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await nt(h),E&&a({type:"scm",phase:"before",...E})}let U=null;if(E||m){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:y}=st({remote:E?.remote||null,grants:h,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=ut(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z=t.approvals===!0,_={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{},approvals:z};let A=null;(t.pageTools?.specs?.length||z)&&(A=Xe(g,t.pageTools?.specs||[]),_.permissionSession=A,t.pageTools?.specs?.length&&(_.mcp={url:`http://${k}:${v}/mcp/${A.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await q(_.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:_,images:Array.isArray(t.images)?t.images:[]},g,{signal:l.signal}))}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),a({type:"error",error:h?.message||String(h)})}finally{if(!s){const h=await ot(X,E).catch(()=>null);h&&g({type:"scm",phase:"after",...h})}L(d),A&&Y(A.id),e.writableEnded||e.end()}}async function hn(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:rt(),secretBackend:ee()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:at(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return o?o[2]==="delete"?i(e,200,{ok:it(o[1])}):i(e,200,ct(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function mn(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ne,worktrees:await lt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/worktrees"){const o=await te({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(t==="/worktrees/remove"){const o=await dt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function T(n,e,t){const r=C[n.agent];if(!r||r.hidden)throw new $(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new $(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=se(a),d=()=>s.cancel("disconnected");t.on("close",d);let c="";try{return await q(n.options?.sandbox,()=>r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{t.off("close",d),L(a)}}function B(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
|
|
package/src/warm-pool.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{treeRssBytes as
|
|
1
|
+
import{treeRssBytes as R,totalMemoryBytes as B}from"./proc.js";const v=1024**3,A=B(),D=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(A>=16*v?10*6e4:5*6e4),S=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(A*.2),3*v),U=400*1024**2;function N(n,a,o=U){const p=Math.floor(a/o),l=n>=48*v?4:n>=24*v?3:n>=12*v?2:1;return Math.max(1,Math.min(p,l))}const k=Number(process.env.CHATPANEL_WARM_MAX)||N(A,S),z=new Set;function x(n=[]){const o=(Array.isArray(n)?n:[]).slice(0,-1),p=o.filter(c=>c?.role==="user").map(c=>String(c.content||"").trim()),l=o.filter(c=>c?.role==="assistant").length;return{users:p,answers:l}}function y(n,a){if(n.answers!==a.answers||n.users.length!==a.users.length)return!1;for(let o=0;o<n.users.length;o++)if(n.users[o]!==a.users[o])return!1;return!0}function W({max:n=k,idleMs:a=D,budgetBytes:o=S,group:p=z,now:l=Date.now,measure:c=r=>R(r?.pid),log:h=()=>{}}={}){const r=new Set;let m=null;const $=()=>{let e=0;for(const s of p)e+=s.bytes;return e};let M=0;const f=e=>`${Math.round(e/1024**2)} MB`;function d(e,s="dropped"){if(r.has(e)){r.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}h(`warm ${e.label}: ${s} (${r.size} live)`),!r.size&&m&&(clearInterval(m),m=null)}}function _(){const e=l();for(const s of[...r])!s.busy&&e-s.lastUsed>a&&d(s,"idle")}function L(){m||!Number.isFinite(a)||a<=0||(m=setInterval(_,Math.min(a,6e4)),m.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 i=x(s);for(const t of r)if(!t.busy&&t.alive&&t.key===e&&y(t.shape,i))return!0;return!1},acquire({key:e,messages:s}){const i=x(s);for(const t of r)if(!(t.busy||!t.alive||t.key!==e)){if(!y(t.shape,i)){h(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${i.users.length}u/${i.answers}a)`);continue}return t.busy=!0,t.lastUsed=l(),h(`warm ${t.label}: reused`),t}return null},reserve({key:e,label:s=e,evict:i=!0}){const t=()=>{let u=null;for(const b of r)!b.busy&&(!u||b.lastUsed<u.lastUsed)&&(u=b);return u};if(r.size>=n){const u=i?t():null;if(!u)return null;d(u,"evicted")}const w=M||U;for(;$()+w>o;){const u=i?t():null;if(!u)return h(`warm ${s}: not kept — ${f($())} warm + ~${f(w)} would pass the ${f(o)} budget`),null;d(u,`evicted for memory (${f($())} warm)`)}const T={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:l(),bytes:w};return r.add(T),h(`warm ${s}: starting (${r.size} live, ~${f($())} of ${f(o)})`),L(),T},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&d(e,"process exited")}),e},release(e,{user:s,answered:i}){e.alive&&(typeof s=="string"&&(e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(i?1:0)}),e.busy=!1,e.lastUsed=l(),setImmediate(()=>{if(!e.alive)return;const t=c(e.session);t>0&&(e.bytes=t,M=t,h(`warm ${e.label}: ${f(t)} resident`))}))},drop:d,closeAll(e="shutdown"){for(const s of[...r])d(s,e)},keys(){return[...r].map(e=>e.key)},reap:_};return p.add(E),E}export{S as WARM_BUDGET_BYTES,W as createWarmPool,x as historyShape,N as warmMaxFor};
|