@chatpanel/bridge 0.46.0 → 0.47.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-warm.js +5 -3
- package/src/engines/claude.js +6 -6
- package/src/events/event.js +1 -1
- package/src/one-reply.js +3 -0
- package/src/server.js +9 -9
- package/src/threads.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.47.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": [
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
import{unlink as z}from"node:fs/promises";import{spawnRpcChild as
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import{unlink as z}from"node:fs/promises";import{spawnRpcChild as J}from"../rpc-child.js";import{spawn as Q}from"node:child_process";import{track as V,sandbox as Y}from"../sandbox.js";import{createWarmPool as Z}from"../warm-pool.js";import{registerWarmPool as ee}from"../warm.js";import{createSession as U,deleteSession as D,rebindSession as re,releaseSession as se,relayPermission as G}from"../mcp-sessions.js";import{resolveClaude as te,buildSpawnSpec as ae}from"../env.js";import{loginRequired as H,signInMessage as K}from"../sign-in.js";import{pushExtraArgs as O,FORBIDDEN as q}from"./args.js";import{normalizeThread as ne}from"../events/agent-thread.js";import{buildClaudeLaunch as B,claudePrompt as le,handleMessage as oe,harnessChars as ie,writeImages as ue,answerControlRequest as ce}from"./claude.js";const F=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,j=Math.max(1,Number(process.env.CHATPANEL_WORKERS)||2),de=Number(process.env.CHATPANEL_WORKER_WAIT_MS)||3e4,fe=Math.max(2,Number(process.env.CHATPANEL_WORKER_MAX_TURNS)||12),pe=`Note: this is a new, unrelated request. Disregard the earlier requests in this session, but follow the instructions given with this one.
|
|
2
|
+
|
|
3
|
+
`,me=5e3,i=ee("claude",Z({log:o=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${o}`)}}));function he(o={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||o.warm===!1)}async function X({spec:o,args:S,cwd:e,env:I,spawnImpl:A,log:E=()=>{},ask:T=null,peers:b=!0}){const m=[...S,"--input-format","stream-json"],[w,h,C]=ae(o,m,e,I),u=await Y().wrap(w,h,C,{engine:"claude",cwd:e,peers:b});u.record.layer==="none"&&E(`sandbox: claude session runs outside a sandbox — ${u.record.reason}`);const[c,x,a]=[u.bin,u.argv,u.opts];let r=null;const _=new Set;let n="",k=0,R=0,v=null;const g=J(c,x,{spawnOpts:a,spawnImpl:(s,d,t)=>V((A||Q)(s,d,t),u,{kind:"warm"}),jsonrpc:!1,onStderr:s=>{n=(n+s).slice(-2e3),r&&r.touch()},onExit:s=>{if(E(`claude exited: ${s.signal||s.code}${n?` — ${n.trim().split(`
|
|
4
|
+
`).pop()}`:""}`),r){const d=r.apiError&&H(r.apiError)?K("Claude Code","claude"):r.apiError?`Claude Code reported an error: ${r.apiError}`:`Claude Code exited (${s.signal||s.code})${n?`: ${n.trim().split(`
|
|
5
|
+
`).pop().slice(0,200)}`:""}`;r.finish({status:"died",error:d})}for(const d of _)try{d(s)}catch{}},onMessage:s=>{if(!r||(r.touch(),s.type==="control_response"))return;if(s.type==="control_request"){const t=r;t.asking++,t.touch(),ce(s,T,f=>{try{g.send(f)}catch{}}).catch(()=>{}).finally(()=>{t.asking--,r===t&&t.touch()});return}const d=oe(s,r.emit,r.streamedAny,e,r.flow);d.sessionId&&(v=d.sessionId),d.streamed&&(r.streamedAny=!0),d.result!=null&&(r.resultText=d.result),d.apiError&&(r.apiError=d.apiError),s.type==="result"&&(r.apiError&&H(r.apiError)?r.finish({status:"failed",error:K("Claude Code","claude")}):r.apiError?r.finish({status:"failed",error:`Claude Code reported an error: ${r.apiError}`}):r.finish({status:"completed",error:null}))}});return{get pid(){return g.pid},get alive(){return!g.exited},expiresAt:u.expiresAt||0,get sessionId(){return v},onExit(s){_.add(s)},close(){g.close()},async turn({prompt:s,emit:d,signal:t,harness:f=null}){if(g.exited)throw new Error("Claude Code process is gone");if(r)throw new Error("a turn is already running on this process");let p=null,M;const N=new Promise($=>{M=$}),l={emit:d,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:R,harnessChars:f},streamedAny:!1,resultText:"",apiError:null,asking:0,touch(){clearTimeout(p),!l.asking&&(p=setTimeout(()=>l.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(F/1e3)}s.`}),F))},finish($){r===l&&(clearTimeout(p),r=null,M($))}};r=l,l.touch();const W=()=>{if(r===l){l.interrupted=!0;try{g.send({type:"control_request",request_id:`stop_${++k}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{r===l&&(l.finish({status:"killed",error:null}),g.kill())},me).unref?.()}};if(t?.aborted)return l.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};t?.addEventListener("abort",W,{once:!0});try{g.send({type:"user",message:{role:"user",content:s}})}catch($){l.finish({status:"failed",error:$.message})}const y=await N;l.flow.costUsdTotal!=null&&(R=l.flow.costUsdTotal),t?.removeEventListener("abort",W),y.status==="timeout"&&g.kill();const P=y.status==="killed"?"killed":l.interrupted?"interrupted":y.status;return{streamedAny:l.streamedAny,resultText:l.resultText,status:P,error:y.error,sessionId:v}}}}const L=new Set;async function we({key:o,spec:S,options:e,label:I,launch:A=X,log:E=()=>{},force:T=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!T||!o||!S||e?.ephemeral===!0||L.has(o)||i.peek({key:o,messages:[{role:"user",content:""}]}))return!1;L.add(o);const b=i.reserve({key:o,label:`${I} (spare)`,evict:!1});if(!b)return L.delete(o),!1;let m=null,w=null;try{let h=e.mcp;const C=e.mcp?.specs||[];(h?.url&&C.length||e.approvals===!0)&&(m=U(()=>{},C),h?.url&&C.length&&(h={...h,url:`${h.url.replace(/\/[^/]*$/,"")}/${m.id}`})),w=await B({system:"",options:{...e,mcp:h},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const u=[...w.args];O(u,e.extraArgs,q.claude,()=>{});const c=m,x=await A({spec:S,args:u,cwd:w.cwd,env:w.runEnv,ask:w.approvals&&c?r=>G(c,r):null,peers:w.peers});x.mcpSession=m,x.systemSent="",i.attach(b,x);const a=w.cleanup;return x.onExit(()=>{m&&D(m.id),a()}),i.release(b,{user:null,answered:!1}),E(`warm ${I}: spare ready`),!0}catch(h){return m&&D(m.id),w?.cleanup?.(),i.drop(b,`spare launch failed: ${h.message}`),!1}finally{L.delete(o)}}async function ke({messages:o,system:S,options:e,images:I,thread:A=null},E,{signal:T,launch:b=X}={}){if(!he(e))return{handled:!1,reason:"not eligible"};const m=te();if(!m)return{handled:!1,reason:"claude not resolvable"};const w=`${Date.now()}-${Math.random().toString(36).slice(2)}`,h=(e.mcp?.specs||[]).map(t=>t?.name).filter(Boolean),C=[];O(C,e.extraArgs,q.claude,()=>{});const u=JSON.stringify({agent:"claude",cwd:e.workingDir||"",mode:e.permissionMode||"default",model:e.model||"",local:e.useLocalConfig!==!1,reach:e.reach||"",tools:[...h].sort(),extra:C,approvals:e.approvals===!0,env:e.runEnv?Object.keys(e.runEnv).sort().map(t=>`${t}=${e.runEnv[t]}`):[],hosts:e.sandbox?.hosts?(Array.isArray(e.sandbox.hosts)?e.sandbox.hosts:String(e.sandbox.hosts).split(/[\s,;]+/)).map(t=>String(t).trim().toLowerCase()).filter(Boolean).sort():[],outside:e.sandbox?.outside===!0,...Array.isArray(e.sandbox?.signIn)&&e.sandbox.signIn.length?{signIn:[...e.sandbox.signIn].sort()}:{},ephemeral:e.ephemeral===!0,...e.worker===!0?{worker:!0}:{},...Array.isArray(e.sandbox?.write)&&e.sandbox.write.length?{write:[...e.sandbox.write].map(String).sort()}:{}}),c=e.worker===!0,x=c&&ne(e.thread)?.id||null;let a=null;if(c){const t=Date.now()+de;for(;a=i.acquireWorker({key:u,thread:x}),!a;){if(a=i.reserveWorker({key:u,label:`claude ${e.workingDir||"home"}`,cap:j}),a){a.fresh=!0;break}const f=t-Date.now();if(f<=0||T?.aborted||!await i.workerFree(u,f))throw new Error(`Claude Code workers are all busy (${j} at most); try again shortly.`)}}else a=i.acquire({key:u,messages:o});let r=!1;const _=!a&&!c&&A?.plan.mode==="resume"?A.plan.sessionId:null;if(!a||c&&a.fresh&&!a.session){if(!c&&(a=i.reserve({key:u,label:`claude ${e.workingDir||"home"}`,evict:e.ephemeral!==!0}),!a))return{handled:!1,reason:"all warm slots busy"};r=!0;let t=null,f=null;try{let p=e.mcp;(p?.url&&h.length||e.approvals===!0)&&(t=U(E,p?.specs||[]),p?.url&&h.length&&(p={...p,url:`${p.url.replace(/\/[^/]*$/,"")}/${t.id}`})),f=await B({system:S,options:{...e,mcp:p},tag:w,resume:_,name:A?.thread.title||""});const M=[...f.args];O(M,e.extraArgs,q.claude,E);const N=t;let l=null;const W=f.approvals&&N?$=>l?.accessGate?l.accessGate.ask(N,$):G(N,$):null,y=await b({spec:m,args:M,cwd:f.cwd,env:f.runEnv,ask:W,peers:f.peers});l=y,y.mcpSession=t,y.systemSent=String(S||""),i.attach(a,y),_&&i.holds(a,o);const P=f.cleanup;y.onExit(()=>{t&&D(t.id),P()})}catch(p){if(t&&D(t.id),f?.cleanup(),i.drop(a,`launch failed: ${p.message}`),c)throw new Error(`Claude Code worker could not start: ${p.message}`);return{handled:!1,reason:p.message}}}const n=a.session;n.accessGate=e.accessGate||null,n.mcpSession&&re(n.mcpSession,E,e.mcp?.specs);const k=o[o.length-1],R=await ue(I,w),v=String(S||""),g=(c&&!r?pe:"")+le(c?[k]:r&&!_?o:_?A.plan.tail?.length?A.plan.tail:[k]:[k],R,!r&&(c||v!==n.systemSent)?v:"");n.systemSent=v;let s;try{s=await n.turn({prompt:g,emit:E,signal:T,harness:ie({prompt:g,system:r?v:"",specs:r?e.mcp?.specs:null})})}finally{R.forEach(t=>z(t).catch(()=>{})),n.mcpSession&&se(n.mcpSession)}if(T?.aborted||s.status==="interrupted")return!c&&s.status==="interrupted"&&n.alive?i.release(a,{user:String(k?.content||""),answered:s.streamedAny}):i.drop(a,"stopped"),{handled:!0};if(s.status!=="completed"){if(i.drop(a,s.error||s.status),!s.streamedAny&&!c)return{handled:!1,reason:s.error||s.status};throw new Error(s.error||`Claude Code ${s.status}`)}if(E({type:"done",text:s.streamedAny?"":s.resultText}),c)return i.releaseWorker(a,{thread:x,maxUses:fe}),{handled:!0,completed:!0,sessionId:null};if(e.accessGate?.restart().length)return i.drop(a,"a folder was opened to it"),n.accessGate=null,{handled:!0,completed:!0,sessionId:s.sessionId||n.sessionId||null};n.accessGate=null,i.release(a,{user:String(k?.content||""),answered:!0});const d=s.sessionId||n.sessionId||null;return setTimeout(()=>{we({key:u,spec:m,options:e,label:`claude ${e.workingDir||"home"}`,launch:b}).catch(()=>{})},250).unref?.(),{handled:!0,completed:!0,sessionId:d}}export{ke as chatWarm,X as launchClaudeSession,i as pool,we as prewarmClaude,he as warmEligible};
|
package/src/engines/claude.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{spawn as z}from"node:child_process";import{writeFile as R,unlink as G}from"node:fs/promises";import P from"node:os";import D from"node:path";import{resolveClaude as v,buildSpawnSpec as J,isCompiledBinary as
|
|
1
|
+
import{spawn as z}from"node:child_process";import{writeFile as R,unlink as G}from"node:fs/promises";import P from"node:os";import D from"node:path";import{resolveClaude as v,buildSpawnSpec as J,isCompiledBinary as fe,selfMcpStdio as he}from"../env.js";import{signInStatus as me,signInMessage as X,loginRequired as ye}from"../sign-in.js";import{buildCliPrompt as Y}from"./prompt.js";import{cliError as _e}from"../cli-errors.js";import{killOnAbort as be}from"../proc.js";import{sandbox as we,noteSandbox as Te,track as ge,grantedWriteRoots as Ee}from"../sandbox.js";import{harnessDirArgs as Ce,harnessSessionArgs as H}from"../events/harness-cards.js";import{threadTurn as xe}from"../threads.js";import{liveClaudeSessions as Se}from"../agent-sessions.js";import{pushExtraArgs as ke,FORBIDDEN as Ae}from"./args.js";import{relayTimeoutMax as ve}from"../relay-timeout.js";import{displayPath as Ne,resolveWorkdir as j}from"../workdir.js";import{connectorsFor as Me}from"../connectors.js";import{chatWarm as Pe}from"./claude-warm.js";import{claudePermissionResponse as Le,permissionAnswer as Oe}from"../events/agent-permission.js";import{relayPermission as Ie}from"../mcp-sessions.js";async function $e(e,t){const r=[];for(let i=0;i<(e?.length||0);i++){const o=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!o)continue;const s=(o[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",n=D.join(P.tmpdir(),`chatpanel-claude-img-${t}-${i}.${s}`);await R(n,Buffer.from(o[2],"base64")),r.push(n)}return r}const K=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,V=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task","ListAgents"],Q=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),We=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch","ListAgents","SendMessage"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch","SendMessage"])}),Re=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),De=Object.freeze(["remember","forget"]),He=Object.freeze(["ask_model","ask_status"]),Z=Object.freeze({device:Object.freeze([]),trusted:Re});function je(e,t=[]){const r=Z[e]||Z.device,i=(t||[]).filter(n=>typeof n=="string"&&/^chatpanel/i.test(n)),o=[],s=[];for(const n of i){for(const a of r)o.push(`mcp__${n}__${a}`);for(const a of[...De,...He])s.push(`mcp__${n}__${a}`)}return{allow:o,deny:s}}function Fe(e){if(!e||e==="any")return null;const t=Q[e]?e:"device";return{allow:[...Q[t]],deny:[...We[t]]}}let L="Claude Code not found.",ee=0,k=!1;async function gt(){if(Date.now()-ee>(k?3e4:4e3)){ee=Date.now();try{v({probe:"async"})||!fe()&&await q()?k=!0:(k=!1,L=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{k=!1}}return k?await me("claude",v()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:X("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:L}}async function Et(){return["opus","sonnet","haiku"]}function Ue(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=he(e.url),o=[...new Set(e.specs.map(s=>s?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:r,args:i}}},allowedTools:o.map(s=>`mcp__${t}__${s}`)}}async function qe(e,t,r){const i=e?.request_id,o=e?.request?.subtype;if(o==="can_use_tool"){const s=t?await t(e.request):Oe("deny","This run has no approval surface.");return r(Le(i,s,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${o||"unknown"}`}}),!1}function te({prompt:e,args:t,cwd:r,env:i=null,emit:o,signal:s,harness:n=null,host:a=!1,ask:c=null,peers:u=!0}){const d=v();if(!d)return null;const[y,g,w]=J(d,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((_,f)=>{we().wrap(y,g,w,{engine:"claude",cwd:r,peers:u}).then(T=>{Te(o,T.record);let l;try{l=ge(z(T.bin,T.argv,T.opts),T,{kind:"agent"})}catch(m){return f(new Error(`Failed to start claude: ${m.message}`))}const h=be(l,s);let b="",E="",p=!1,x=null;const de={sawText:!1,tail:"",boundary:!1,harnessChars:n};let O="",I=null,A,$=0;const M=()=>{clearTimeout(A),!$&&(A=setTimeout(()=>{l.kill("SIGKILL"),f(new Error(`Claude Code timed out — no output for ${Math.round(K/1e3)}s.`))},K))};M();const pe=m=>{try{l.stdin.write(`${JSON.stringify(m)}
|
|
2
2
|
`)}catch{}};l.stdout.on("data",m=>{M(),b+=m.toString();let W;for(;(W=b.indexOf(`
|
|
3
|
-
`))>=0;){const B=b.slice(0,W).trim();if(b=b.slice(W+1),!B.startsWith("{"))continue;let S;try{S=JSON.parse(B)}catch{continue}if(S.type==="control_request"){$++,clearTimeout(A),
|
|
4
|
-
`):(l.stdin.write(e),l.stdin.end())}).catch(f)})}function
|
|
3
|
+
`))>=0;){const B=b.slice(0,W).trim();if(b=b.slice(W+1),!B.startsWith("{"))continue;let S;try{S=JSON.parse(B)}catch{continue}if(S.type==="control_request"){$++,clearTimeout(A),qe(S,c,pe).catch(()=>{}).finally(()=>{$--,M()});continue}if(S.type==="control_response")continue;const C=oe(S,o,p,r,de);C.streamed&&(p=!0),C.result!=null&&(O=C.result),C.apiError&&(x=C.apiError),C.sessionId&&(I=C.sessionId),a&&S.type==="result"&&l.stdin.end()}}),l.stderr.on("data",m=>{M(),E+=m.toString()}),l.on("error",m=>{clearTimeout(A),h(),f(new Error(`Failed to start claude (${y}): ${m.message}`))}),l.on("close",m=>{if(clearTimeout(A),h(),s?.aborted){_({streamedAny:p,resultText:O,sessionId:I,stopped:!0});return}if(x&&ye(x))return f(new Error(X("Claude Code","claude")));if(m===0&&x)return f(new Error(`Claude Code reported an error: ${x}`));m===0?_({streamedAny:p,resultText:O,sessionId:I}):f(_e("Claude Code",m,E,x||"",{agentId:"claude"}))}),a?l.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
|
|
4
|
+
`):(l.stdin.write(e),l.stdin.end())}).catch(f)})}function Be(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 re(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
|
|
6
6
|
|
|
7
|
-
`}),e.boundary=!1)}function ne(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function
|
|
8
|
-
`)||String(e.error||"api error"),
|
|
7
|
+
`}),e.boundary=!1)}function ne(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function oe(e,t,r,i="",o=null){const s={streamed:!1,result:null};if(typeof e?.session_id=="string"&&e.session_id&&(s.sessionId=e.session_id),e.type==="stream_event"){const n=e.event;n?.type==="content_block_delta"&&(n.delta?.type==="text_delta"?(s.streamed=!0,re(o,t),t({type:"delta",text:n.delta.text}),ne(o,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 s.apiError=(e.message?.content||[]).filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
8
|
+
`)||String(e.error||"api error"),s;for(const n of e.message?.content||[])n.type==="tool_use"?(o&&(o.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:Qe(n,i),...typeof e.parent_tool_use_id=="string"&&e.parent_tool_use_id?{parent:e.parent_tool_use_id}:{}})):n.type==="text"&&!r&&(s.streamed=!0,re(o,t),t({type:"delta",text:n.text}),ne(o,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:Be(n.content)});else if(e.type==="result"){e.is_error?s.apiError=s.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?s.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,c=Number(o?.costUsdBefore)||0;o&&a!=null&&(o.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-c):null,costBasis:"list",...o?.harnessChars!=null?{harnessChars:o.harnessChars}:{}})}}return s}const se=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let N=null;function ae({probe:e=null}={}){return N||(N=(async()=>{try{return String(await(e?e():new Promise(t=>{const[r,i,o]=J(v(),["--help"],null),s=z(r,i,{...o,stdio:["ignore","pipe","pipe"]});let n="";s.stdout.on("data",a=>{n+=a}),s.on("error",()=>t("")),s.on("close",()=>t(n)),setTimeout(()=>{try{s.kill()}catch{}t(n)},8e3).unref?.()}))||"")}catch{return""}})(),N)}async function ze(e={}){return/--effort\b/.test(await ae(e))}async function Ge(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await ae(e))}function Ct(){N=null}async function Je({system:e,options:t,tag:r,resume:i=null,name:o=""}){const s=t.permissionMode||"default",n=j(t.workingDir),a=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];se&&await ze()&&a.push("--effort",se),a.push(...Ce({harness:"claude",roots:Ee(n),dirs:t.dirs}));const c=[],u=[],d=Ue(t.mcp);if(d){const l=D.join(P.tmpdir(),`chatpanel-mcp-${r}.json`);await R(l,JSON.stringify(d.config)),c.push(l),a.push("--mcp-config",l),u.push(...d.allowedTools)}const y=Fe(t.reach);if(y){const l=je(t.reach,await Me("claude").catch(()=>[]));a.push("--allowedTools",...y.allow,...u,...l.allow),a.push("--disallowedTools",...y.deny,...l.deny)}else s==="bypassPermissions"?a.push("--permission-mode","bypassPermissions"):s==="acceptEdits"?(a.push("--permission-mode","acceptEdits"),u.length&&a.push("--allowedTools",...u)):a.push("--allowedTools",...V,...u);const g=!y&&t.approvals===!0;if(g&&a.push("--permission-prompt-tool","stdio"),e)if(v()?.kind!=="wsl"&&await Ge()){const h=D.join(P.tmpdir(),`chatpanel-system-${r}.md`);await R(h,e,{mode:384}),c.push(h),a.push("--append-system-prompt-file",h)}else a.push("--append-system-prompt",e);t.model&&a.push("--model",t.model),t.useLocalConfig===!1&&a.push("--setting-sources",""),i?a.push(...H({harness:"claude",mode:"resume",id:i})):t.ephemeral===!0&&a.push(...H({harness:"claude",mode:"off"})),t.ephemeral||a.push(...H({harness:"claude",mode:"name",name:o}));const w=d&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(ve(t.mcp?.specs))}:null,_=t.askDepth?{CHATPANEL_ASK_DEPTH:String(Math.max(0,Math.min(8,Number(t.askDepth)||0)))}:null,f=w||_||t.runEnv?{...t.runEnv||{},...w||{},..._||{}}:null;return{args:a,cwd:n,runEnv:f,cleanup:()=>c.forEach(l=>G(l).catch(()=>{})),hasMcp:!!d,approvals:g,peers:!y}}function ie({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 Xe(e,t=[],r=""){let i=Y(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}const
|
|
10
|
+
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}const Ye="This Claude Code session is in the middle of a turn in another window (VS Code or a terminal). Send again when it finishes — both sides continue the same session.";async function xt({messages:e,system:t,options:r,images:i},o,{signal:s}={}){const n=xe("claude",e,r,{cwd:j(r.workingDir)}),a=n?.plan.mode==="resume"?Se().get(n.plan.sessionId):void 0;if(a==="busy")throw new Error(Ye);if(a){const d=await ce({messages:e,system:t,options:r,images:i,thread:n},o,{signal:s});d?.completed&&d.thread?.record(d.sessionId);return}const c=await Pe({messages:e,system:t,options:r,images:i,thread:n},o,{signal:s}).catch(d=>({handled:!1,reason:d?.message||String(d),thrown:!0}));if(c.handled){c.completed&&n?.record(c.sessionId);return}if(s?.aborted)return;if(c.thrown)throw new Error(c.reason);const u=await ce({messages:e,system:t,options:r,images:i,thread:n},o,{signal:s});u?.completed&&u.thread?.record(u.sessionId)}const Ke=Math.max(1,Number(process.env.CHATPANEL_CLAUDE_COLD_MAX)||2);let F=0;const le=[];async function Ve(e){for(;F>=Ke;){if(e?.aborted)throw new Error("stopped while waiting for a launch slot");await new Promise(t=>{le.push(t),e?.addEventListener("abort",t,{once:!0})})}return F++,()=>{F--,le.shift()?.()}}async function ce(e,t,r={}){const i=await Ve(r.signal);try{return await ue(e,t,r)}finally{i()}}async function ue({messages:e,system:t,options:r,images:i,thread:o=null},s,{signal:n}={}){const a=`${Date.now()}-${Math.random().toString(36).slice(2)}`,c=o?.plan.mode==="resume"?o.plan.sessionId:null,u=await Je({system:t,options:r,tag:a,resume:c,name:o?.thread.title||""}),{args:d,cwd:y,runEnv:g}=u,w=await $e(i,a),_=()=>{w.forEach(p=>G(p).catch(()=>{})),u.cleanup()},f=Xe(c?o.plan.tail?.length?o.plan.tail:e.slice(-1):e,w);ke(d,r.extraArgs,Ae.claude,s);const T=u.approvals&&r.permissionSession?p=>r.accessGate?r.accessGate.ask(r.permissionSession,p):Ie(r.permissionSession,p):null;let l=!1;const b=te({prompt:f,args:d,cwd:y,env:g,emit:c?p=>{(p?.type==="delta"||p?.type==="tool")&&(l=!0),s(p)}:s,signal:n,harness:ie({prompt:f,system:t,specs:r.mcp?.specs}),host:u.approvals,ask:T,peers:u.peers});if(b===null)return _(),await Ze({messages:e,system:t,options:r},s,{signal:n}),null;let E;try{E=await b}catch(p){if(_(),c&&!l&&!n?.aborted)return o.forget(),ue({messages:e,system:t,options:r,images:i,thread:o.restart()},s,{signal:n});throw p}return _(),E.stopped?{completed:!1,thread:o}:(s({type:"done",text:E.streamedAny?"":E.resultText}),{completed:!0,sessionId:E.sessionId,thread:o})}async function St({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.","--no-session-persistence"];let o="";const s=te({prompt:e,args:i,cwd:null,peers:!1,emit:a=>{a.type==="delta"&&(o+=a.text)}});if(s===null)return et({prompt:e,system:t,model:r});const{resultText:n}=await s;return(o||n||"").trim()}function Qe(e,t=""){const r=e.input||{};return r.command?String(r.command).slice(0,60):r.file_path?Ne(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 U=null;function q(){return U||(U=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),U}async function Ze({messages:e,system:t,options:r},i,{signal:o}={}){const s=await q();if(!s)throw new Error(L);const{query:n}=s,a=new AbortController;o&&(o.aborted?a.abort():o.addEventListener("abort",()=>a.abort(),{once:!0}));const c=r.permissionMode||"default",u=j(r.workingDir),d=c==="acceptEdits"||c==="bypassPermissions",y=new Set(V),g=async h=>y.has(h)||d?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${h} blocked — set this agent's permission mode in ChatPanel to enable it.`};let w=!1;const _=Y(e),f={sawText:!1,tail:"",boundary:!1,harnessChars:ie({prompt:_,system:t})};let T="";const l=n({prompt:_,options:{cwd:u,permissionMode:c,includePartialMessages:!0,canUseTool:g,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 l){const b=oe(h,i,w,u,f);b.streamed&&(w=!0),b.result!=null&&(T=b.result)}}catch(h){if(o?.aborted||a.signal.aborted)return;throw h}i({type:"done",text:w?"":T})}async function et({prompt:e,system:t,model:r}){const i=await q();if(!i)throw new Error(L);const{query:o}=i;let s="";const n=o({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 c of a.message.content)c.type==="text"&&(s+=c.text);else a.type==="result"&&a.subtype==="success"&&!s&&(s=a.result||"");return s.trim()}export{Ye as SESSION_BUSY,Ct as _resetEffortProbe,qe as answerControlRequest,gt as available,Je as buildClaudeLaunch,je as channelMcpTools,Fe as channelToolPolicy,xt as chat,ce as chatCold,Ue as claudeMcpConfig,Xe as claudePrompt,ze as claudeSupportsEffort,Ge as claudeSupportsSystemPromptFile,St as complete,oe as handleMessage,ie as harnessChars,Et as listModels,$e as writeImages};
|
package/src/events/event.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isRef as
|
|
1
|
+
import{isRef as o}from"./ref.js";const c=1,v=Object.freeze({turn:["started","ended"],assistant:["prompted","message","reasoning"],context:["assembled","attached","expanded","retrieved"],capability:["offered","granted","denied","activated","revoked","invoked","resulted"],privacy:["redacted","egress"],policy:["changed","guard_denied"],data:["created","updated","deleted"],automation:["fired","suppressed"],shim:["fired"],judge:["decided"]}),E=Object.freeze(Object.entries(v).flatMap(([e,r])=>r.map(d=>`${e}.${d}`))),w=Object.freeze(["user","rule","schedule","model","agent","channel"]),x=Object.freeze(["global","site","tab","session","agent"]),l=Object.freeze(["R","M","L","C","A","X","H"]),S=Object.freeze(["pure","idempotent","replay-safe","non-replayable"]),I=Object.freeze(["none","redacted","delegated"]);class a extends Error{constructor(r,d,i=null){super(d),this.name="EventError",this.code=r,this.detail=i}}const t=e=>typeof e=="string"&&e.length>0,n=e=>typeof e=="number"&&Number.isFinite(e),u=e=>Array.isArray(e);function s(e){return!!e&&w.includes(e.kind)&&t(e.id)}function j(e){return!!e&&x.includes(e.kind)&&t(e.id)}const A={"turn.started":e=>t(e.turnId),"turn.ended":e=>t(e.turnId),"assistant.prompted":e=>t(e.turnId)&&o(e.ref),"assistant.message":e=>t(e.turnId)&&o(e.ref),"assistant.reasoning":e=>t(e.turnId)&&o(e.ref),"context.assembled":e=>n(e.budget)&&n(e.used)&&!!e.parts&&typeof e.parts=="object"&&u(e.resident)&&e.resident.every(o)&&n(e.reachableCount),"context.attached":e=>o(e.ref),"context.expanded":e=>o(e.ref)&&n(e.tokens),"context.retrieved":e=>t(e.tool)&&n(e.count)&&u(e.sources)&&e.sources.every(r=>r&&typeof r=="object"&&n(r.rank)),"capability.offered":e=>t(e.capability)&&t(e.reason),"capability.granted":e=>t(e.capability)&&s(e.actor),"capability.denied":e=>t(e.capability)&&s(e.actor),"capability.activated":e=>t(e.capability)&&l.includes(e.classUsed),"capability.revoked":e=>t(e.capability)&&t(e.cause),"capability.invoked":e=>t(e.capability)&&s(e.actor)&&j(e.scope)&&S.includes(e.effects)&&(e.effects==="pure"||t(e.idempotencyKey)),"capability.resulted":e=>t(e.capability)&&typeof e.ok=="boolean"&&l.includes(e.classUsed)&&!!e.cost&&n(e.cost.ms),"privacy.redacted":e=>!!e.counts&&typeof e.counts=="object"&&Object.values(e.counts).every(n),"privacy.egress":e=>t(e.host)&&typeof e.redacted=="boolean"&&typeof e.controlled=="boolean","policy.changed":e=>t(e.dial)&&s(e.actor)&&"from"in e&&"to"in e,"policy.guard_denied":e=>t(e.capability)&&t(e.reason),"data.created":e=>o(e.ref),"data.updated":e=>o(e.ref),"data.deleted":e=>o(e.ref)&&typeof e.shredded=="boolean","automation.fired":e=>t(e.ruleId)&&l.includes(e.classUsed),"automation.suppressed":e=>t(e.ruleId)&&t(e.reason),"shim.fired":e=>t(e.shimId)&&(e.engine==null||t(e.engine)),"judge.decided":e=>t(e.stage)&&t(e.choice)&&s(e.actor)&&(e.planned==null||t(e.planned))&&["read","of","chars"].every(r=>e[r]==null||n(e[r]))};function y(e){if(!e||typeof e!="object")throw new a("SHAPE","event must be an object");if(e.v!==c)throw new a("VERSION",`expected v=${c}, got ${e.v} — upcast first`,e.v);if(!t(e.id))throw new a("SHAPE","id required");if(!t(e.host))throw new a("SHAPE","host required");if(!Number.isInteger(e.seq)||e.seq<0)throw new a("SHAPE","seq must be a non-negative integer");if(!u(e.causes)||!e.causes.every(t))throw new a("SHAPE","causes must be string[]");if(!n(e.at))throw new a("SHAPE","at required (advisory wall clock)");if(!E.includes(e.type))throw new a("TYPE",`unknown type ${e.type}`,e.type);if(!e.payload||typeof e.payload!="object")throw new a("SHAPE","payload required");const r=A[e.type];if(r&&!r(e.payload))throw new a("PAYLOAD",`payload invalid for ${e.type}`,e.type);return e}function P(e){try{return y(e),!0}catch{return!1}}function k({host:e,seq:r=0,now:d=()=>Date.now(),newId:i}){if(!t(e))throw new a("SHAPE","host required");const b=i||(()=>globalThis.crypto.randomUUID());let f=r;return{get host(){return e},get seq(){return f},append(p,h,g=[]){const m=Object.freeze({v:c,id:b(),host:e,seq:f++,causes:Object.freeze([...g]),at:d(),type:p,payload:h});return y(m)}}}export{w as ACTOR_KINDS,E as ALL_TYPES,l as CLASSES,c as CURRENT_VERSION,S as EFFECTS,I as EGRESS,v as EVENT_TYPES,a as EventError,x as SCOPE_KINDS,k as createAppender,P as isValidEvent,y as validateEvent};
|
package/src/one-reply.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const c=["inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","harnessChars"];function o(t,n){if(!t)return n;if(!n)return t;const s={...t,...n};for(const u of c)(t[u]!=null||n[u]!=null)&&(s[u]=(Number(t[u])||0)+(Number(n[u])||0));return s.costUsd=t.costUsd!=null&&n.costUsd!=null?Number(t.costUsd)+Number(n.costUsd):null,s}function f(t){let n=!1,s=null,u=null,l=null;const r=e=>{e&&(n=!0,t({type:"delta",text:e}))};return{emit(e){if(e?.type==="done"){s=e;return}if(e?.type==="usage"){u=e;return}e?.type==="delta"&&e.text&&(n=!0),t(e)},seam(){r(s?.text),n&&r(`
|
|
2
|
+
|
|
3
|
+
`),s=null,l=o(l,u),u=null},finish(){const e=o(l,u);e&&t(e),s&&(n&&s.text?(r(s.text),t({...s,text:""})):t(s))}}}export{o as addUsage,f as oneReply};
|
package/src/server.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as
|
|
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
|
|
2
|
+
import{createServer as Ge}from"node:http";import O from"node:os";import{randomBytes as Ue,randomInt as Le,timingSafeEqual as We}from"node:crypto";import{mkdirSync as je,writeFileSync as Fe,readFileSync as re,existsSync as Je}from"node:fs";import{join as M}from"node:path";import*as Xe from"./engines/claude.js";import*as Ke from"./engines/codex.js";import*as ze from"./engines/antigravity.js";import{pi as Ye,opencode as Ve,kiro as Qe,copilot as Ze,deepseek as qe,hermes as et}from"./engines/cli-agents.js";import{connectorsFor as tt}from"./connectors.js";import*as nt from"./engines/custom.js";import{installService as ot,uninstallService as rt,serviceStatus as at,restartService as ae}from"./service.js";import{skillIndex as J,listRecords as it,readRecord as st,readPackageFile as ct,skillsHealth as lt,quarantinedSkills as dt,clearSkillCache as X}from"./skills.js";import{writeSkillPackage as ut,writeSkillFile as ht,deleteSkillPackage as pt,SkillWriteError as ft}from"./skill-write.js";import{agentDefRoots as mt,scanAgentDefs as gt,listAgentDefs as wt,readAgentDef as yt,planAgentExport as bt,exportAgentDef as St,agentDefsHealth as kt,AgentDefError as Tt}from"./agent-defs.js";import{capabilityToolSpecs as xt,runCapabilityTool as Et}from"./mcp-capabilities.js";import{createSession as vt,deleteSession as ie,getSession as se,activeSession as At,relayToolCall as Ot}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ct,isDefaultWorkdir as Pt,resolveWorkdir as $t,writeScopeNote as Rt}from"./workdir.js";import{sandbox as K,runSandboxCli as It,withGrant as ce,withAgentGrant as Nt,withoutOutsideWhenCapped as Dt,grantedWriteRoots as le,acceptRefusalReport as _t,liveProcesses as Ht,sandboxConfigFromEnv as Mt}from"./sandbox.js";import{createAccessGate as Bt,chatKeyOf as Gt,chatFolders as Ut}from"./access-gate.js";import{signInDenial as Lt}from"./events/sandbox-policy.js";import{gitState as Wt,gitDelta as jt}from"./scm.js";import{listConnections as Ft,putConnection as Jt,removeConnection as Xt,runEnvFor as Kt,testConnection as zt,secretBackend as de}from"./connections.js";import{worktreeFor as ue,listWorktrees as Yt,removeWorktree as Vt,withHook as Qt,WORKTREE_ROOT as he}from"./worktree.js";import{AGENT_CLIS as Zt,agentAvailable as qt,agentInstallDirs as en,enrichPath as tn,enrichAgentEnv as nn,findAgentBin as on,forgetMisses as rn,primeAgentLookups as an,resolveCommand as pe,isCompiledBinary as sn}from"./env.js";import"./sanitize.js";import{checkForUpdate as cn,selfUpdate as fe,isEmbedded as me}from"./update.js";import{callLocalMcp as ln,localMcpStatus as dn,signInLocalMcp as un,signInStatusLocalMcp as hn}from"./mcp-local.js";import{assertPublicHttpUrl as ge,assertPublicWebUrl as we}from"./ssrf.js";import{startRun as ye,endRun as z,cancelRun as pn,cancelAll as fn}from"./runs.js";import{closeWarmPools as mn,warmStatus as gn}from"./warm.js";import{SESSION_AGENTS as be,listSessions as wn,readSession as yn,adoptSession as bn,catchUp as Sn}from"./agent-sessions.js";import{agentContext as kn}from"./agent-context.js";import{normalizeThread as Se}from"./events/agent-thread.js";import{portClashPlan as Tn,serviceManagerOf as xn,STANDBY_POLL_MS as En}from"./events/service-standby.js";import{holdThread as ke}from"./threads.js";import{oneReply as vn}from"./one-reply.js";import{createSnapshot as An}from"./health-snapshot.js";import{CompatError as P,anthropicError as Y,anthropicStream as On,chatCompletionStream as Cn,completionStream as Pn,createAnthropicMessage as $n,createChatCompletion as Rn,createCompletion as In,createResponse as Nn,openAIError as S,parseAnthropicMessage as Dn,parseChatCompletion as _n,parseCompletion as Hn,parseResponse as Mn,responseStream as Bn}from"./api-compat.js";import{callerTrust as Gn,isPaired as I,parseExtensionIds as Un,capRunOptions as Ln,engineHonoursReach as Wn,createPairingStore as jn,formatPairingCode as Fn}from"./pii/trust.js";const y="0.47.1",x=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Xe,label:"Claude Code"},codex:{engine:Ke,label:"Codex"},antigravity:{engine:ze,label:"Antigravity",tools:!1},pi:{engine:Ye,label:"Pi"},opencode:{engine:Ve,label:"OpenCode"},hermes:{engine:et,label:"Hermes"},kiro:{engine:Qe,label:"Kiro"},copilot:{engine:Ze,label:"GitHub Copilot"},deepseek:{engine:qe,label:"DeepSeek Harness"},custom:{engine:nt,label:"Custom",hidden:!0}};function Te(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Jn=Un(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gn({origin:n.headers.origin||"",hasToken:Ae(n),extensionIds:Jn})),n.chatpanelTrust}function Xn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Kn(n,e){const t=n.headers.origin||"",o=Te(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const V=new Set(["127.0.0.1","localhost","::1"]);function zn(n){if(!V.has(x))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return V.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let v="";function Yn(){try{Je(D)&&(v=re(D,"utf8").trim()),v||(v=Ue(32).toString("hex"),je(M(O.homedir(),".chatpanel"),{recursive:!0}),Fe(D,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=jn({random:()=>Le(0,1e6)/1e6});function Vn(n){if(!v)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=xe.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Qn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=xe.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:v})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Zn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ee(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function ve(n,e,t){try{const o=await Ee(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function Ae(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&We(o,r)}const qn=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),eo=new Set(["/debug"]),to=n=>eo.has(n),no=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function oo(n,e){if(!zn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!Te(t))return"forbidden origin";const o=n.method==="POST"&&qn.has(e)||n.method==="GET"&&to(e)||no(n.method,e);return o&&!(Xn(t)||Ae(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!ao.has(e)?ro:null}const Oe=()=>me()?"chatpanel-gateway pair":"chatpanel-bridge pair",ro=`forbidden: this client is not paired with the bridge — run \`${Oe()}\` and enter the code in ChatPanel Settings`,ao=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Q(n,e,t){const o=N(n),r=Nt(e,Dt(Ln(t,o)));if(!Wn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":`pair this client (${Oe()})`} to use ${e}`};const a=r.reach,s=I(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:r,note:s}}async function Ce(n,e,t){const o=e?.message||String(e);try{const r=await K().status(),a=!!(r.enabled&&r.runtime)&&t?.outside!==!0,s=Lt(`${o}
|
|
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
|
-
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,d=
|
|
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||""}
|
|
6
6
|
|
|
7
|
-
[ChatPanel] The person has just allowed writing in ${
|
|
7
|
+
[ChatPanel] The person has just allowed writing in ${oe}, and you were restarted with that access. Carry on with their request: do the step that was blocked. Do not ask again.`.trim())}h.finish()})}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),h?.detail&&u("error",`${t.agent} said: ${h.detail}`),a({type:"error",error:await Ce(t.agent,h,b.sandbox)})}finally{if(!s){const h=await jt(_,C).catch(()=>null);h&&w({type:"scm",phase:"after",...h})}z(c),R&&ie(R.id),e.writableEnded||e.end()}}async function xo(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:Ft(),secretBackend:de()});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:Jt(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:Xt(r[1])}):i(e,200,zt(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function Eo(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:he,worktrees:await Yt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/worktrees"){const r=await ue({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 Vt({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 A(n,e,t){const o=E[n.agent];if(!o||o.hidden)throw new P(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!r.ok)throw new P(r.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=ye(a),c=()=>s.cancel("disconnected");t.on("close",c);let d="";try{return await ce(n.options?.sandbox,()=>ke(n.agent,n.options,s.signal,()=>o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(d+=l.text,e(l.text)):l?.type==="done"&&l.text&&!d&&(d=l.text,e(l.text))},{signal:s.signal}))),d}catch(l){throw l instanceof Error&&!(l instanceof P)&&(l.message=await Ce(n.agent,l,n.options?.sandbox)),l}finally{t.off("close",c),z(a)}}function G(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function $(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
8
8
|
|
|
9
|
-
`)}function
|
|
9
|
+
`)}function U(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
10
10
|
data: ${JSON.stringify(t)}
|
|
11
11
|
|
|
12
|
-
`)}async function U(n,e,t,o){try{const r=t(await m(n)),a=V(n,r.agent,r.options||{});if(a.error)throw new P(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${r.message}`):r)),null}}async function xo(n,e){const t=await U(n,e,Nn,k);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Pn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,k(r))}B(e);const o=An(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,k(r))}$(e,"[DONE]"),e.end()}async function Eo(n,e){const t=await U(n,e,Dn,k);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,$n(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,k(r))}B(e);const o=On(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,k(r))}$(e,"[DONE]"),e.end()}async function vo(n,e){const t=await U(n,e,_n,k);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Rn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,k(r))}B(e);const o=Hn(t.requestedModel,r=>G(e,r.type,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...k(r)};G(e,"error",a)}e.end()}async function Ao(n,e){const t=await U(n,e,In,z);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Cn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,z(r))}B(e);const o=vn(t.requestedModel,(r,a)=>G(e,r,a));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){G(e,"error",z(r))}e.end()}async function Oo(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?hn(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Ie(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?ie(t):vt(),a=d=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:d})},s=(d,l)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:d,message:l}});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:b}});const c=Tt();if(o.method==="tools/list"){const d=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...d]})}if(o.method==="tools/call"){const d=await xt(o.params?.name,o.params?.arguments||{});if(d)return a(d);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 At(r,o.params?.name,o.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function Co(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 cn({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 Po(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?un(r):await dn(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function $o(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.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=me(o)}catch(p){return i(e,400,{error:String(p?.message||p)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[p,y]of Object.entries(r)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[p]=String(y))}const d=new AbortController,l=setTimeout(()=>d.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:d.signal});try{p.url&&me(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const y=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:y})}catch(p){const y=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const Ne=256*1024,Ro=5,Io=8e3;async function No(n){let e=ge(n);const t=new AbortController,o=setTimeout(()=>t.abort(),Io);try{for(let r=0;r<=Ro;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/${b} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ge(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:Ho(await Do(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function Do(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ne);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>=Ne))break}}finally{try{await e.cancel()}catch{}}return o}function _o(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 Ho(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?_o(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Mo(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 No(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=ie(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 Go(n,e){let t;try{t=await m(n)}catch(d){return i(e,400,{error:"Bad JSON: "+d.message})}const o=E[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=V(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 d="";return typeof o.engine.complete=="function"?d=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},l=>{l.type==="delta"?d+=l.text||"":l.type==="done"&&l.text&&(d+=l.text)}),i(e,200,{text:(d||"").trim()})}catch(d){return i(e,502,{error:d?.message||String(d)})}}async function Uo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=E[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 Lo(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=he(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function Wo(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(!ye.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${ye.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await gn(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await wn(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=be({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 yn(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=be({id:o.thread?.id??o.thread});return a?i(e,200,await bn(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 Z=Be(async(n,e)=>{if(Jn(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=to(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return ao(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 io(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:{},d={...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 Sn({agent:typeof s?.agent=="string"?s.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return so(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return fo(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return go(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return wo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return mo(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return uo(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"?po(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"}):ho(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?co(e,decodeURIComponent(s),r,a):lo(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return ko(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return To(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return Re(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return Re(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:b,agents:Object.fromEntries(Qt.map(c=>[c,s?nn(c)||he(c)?.kind||null:Zt(c)])),...s?{home:O.homedir(),path:process.env.PATH,installDirs:qt(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Wo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return So(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Yn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return zn(e);if(n.method==="POST"&&t.pathname==="/whoami")return Vn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return xo(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Eo(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return vo(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Ao(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Ie(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 Ie(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return ae(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return Ee(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return Ee(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Oo(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=Dt(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return Co(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Po(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return $o(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Mo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Go(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Uo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Lo(n,e);if(n.method==="POST"&&t.pathname==="/update")return bo(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 jo(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 d;try{d=JSON.parse(c)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(d.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
|
|
12
|
+
`)}async function L(n,e,t,o){try{const r=t(await m(n)),a=Q(n,r.agent,r.options||{});if(a.error)throw new P(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${r.message}`):r)),null}}async function vo(n,e){const t=await L(n,e,_n,S);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Rn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}G(e);const o=Cn(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,S(r))}$(e,"[DONE]"),e.end()}async function Ao(n,e){const t=await L(n,e,Hn,S);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,In(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}G(e);const o=Pn(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,S(r))}$(e,"[DONE]"),e.end()}async function Oo(n,e){const t=await L(n,e,Mn,S);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Nn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}G(e);const o=Bn(t.requestedModel,r=>U(e,r.type,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...S(r)};U(e,"error",a)}e.end()}async function Co(n,e){const t=await L(n,e,Dn,Y);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,$n(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,Y(r))}G(e);const o=On(t.requestedModel,(r,a)=>U(e,r,a));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){U(e,"error",Y(r))}e.end()}async function Po(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?pn(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Ne(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?se(t):At(),a=d=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:d})},s=(d,l)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:d,message:l}});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:y}});const c=xt();if(o.method==="tools/list"){const d=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...d]})}if(o.method==="tools/call"){const d=await Et(o.params?.name,o.params?.arguments||{});if(d)return a(d);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 Ot(r,o.params?.name,o.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function $o(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 ln({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 Ro(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?hn(r):await un(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function Io(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.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=ge(o)}catch(p){return i(e,400,{error:String(p?.message||p)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[p,w]of Object.entries(r)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[p]=String(w))}const d=new AbortController,l=setTimeout(()=>d.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:d.signal});try{p.url&&ge(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const w=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:w})}catch(p){const w=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${w}`})}finally{clearTimeout(l)}}const De=256*1024,No=5,Do=8e3;async function _o(n){let e=we(n);const t=new AbortController,o=setTimeout(()=>t.abort(),Do);try{for(let r=0;r<=No;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/${y} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=we(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:Bo(await Ho(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function Ho(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,De);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>=De))break}}finally{try{await e.cancel()}catch{}}return o}function Mo(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 Bo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Mo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Go(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 _o(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 Uo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=se(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 Lo(n,e){let t;try{t=await m(n)}catch(d){return i(e,400,{error:"Bad JSON: "+d.message})}const o=E[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=Q(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 d="";return typeof o.engine.complete=="function"?d=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},l=>{l.type==="delta"?d+=l.text||"":l.type==="done"&&l.text&&(d+=l.text)}),i(e,200,{text:(d||"").trim()})}catch(d){return i(e,502,{error:d?.message||String(d)})}}async function Wo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=E[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 jo(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=pe(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function Fo(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(!be.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${be.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await wn(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await yn(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=Se({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 bn(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=Se({id:o.thread?.id??o.thread});return a?i(e,200,await Sn(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 q=Ge(async(n,e)=>{if(Kn(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=oo(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return so(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 co(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:{},d={...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 kn({agent:typeof s?.agent=="string"?s.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return lo(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return go(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return yo(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return bo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return wo(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return po(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"?mo(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"}):fo(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?uo(e,decodeURIComponent(s),r,a):ho(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return xo(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Eo(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return Ie(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return Ie(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:y,agents:Object.fromEntries(Zt.map(c=>[c,s?on(c)||pe(c)?.kind||null:qt(c)])),...s?{home:O.homedir(),path:process.env.PATH,installDirs:en(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Fo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return To(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Qn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Vn(e);if(n.method==="POST"&&t.pathname==="/whoami")return Zn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return vo(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Ao(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Co(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Ne(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 Ne(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return ie(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ve(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ve(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Po(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Uo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=_t(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return $o(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Ro(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Io(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Go(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Lo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Wo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return jo(n,e);if(n.method==="POST"&&t.pathname==="/update")return ko(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 Jo(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 d;try{d=JSON.parse(c)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(d.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
|
|
13
13
|
`)}catch(l){d.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:d.id,error:{code:-32e3,message:String(l?.message||l)}})+`
|
|
14
14
|
`)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",c=>{e+=c;let d;for(;(d=e.indexOf(`
|
|
15
|
-
`))>=0;){const l=e.slice(0,d).trim();e=e.slice(d+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function
|
|
15
|
+
`))>=0;){const l=e.slice(0,d).trim();e=e.slice(d+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function Xo(){tn(),nn(),Yn();let n=!1;q.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${k}/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=Tn({name:"bridge",self:y,holder:o?{ours:o,version:t.version}:null,managedBy:xn(process.env),port:k});if(r.action==="standby"||n&&!t){if(!n)for(const a of r.lines)u("info",a);n=!0,setTimeout(()=>q.listen(k,x),En);return}if(o)for(const a of r.lines)u("error",a);else u("error",`Port ${k} 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=fn("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const o=mn("shutdown");o&&u("info",`shutdown: closed ${o} warm agent process${o===1?"":"es"}`),K().close(),setTimeout(()=>process.exit(0),t||o?300:0).unref?.(),!t&&!o&&process.exit(0)});q.listen(k,x,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${x}:${k}`),Pe.warm(),V.has(x)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${x}. 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(E)){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."),Ee().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 Ko(){console.log(`ChatPanel Bridge v${y}
|
|
16
16
|
|
|
17
17
|
Usage:
|
|
18
|
-
chatpanel-bridge start the bridge (foreground) on ${x}:${
|
|
18
|
+
chatpanel-bridge start the bridge (foreground) on ${x}:${k}
|
|
19
19
|
chatpanel-bridge --install run automatically at login, in the background
|
|
20
20
|
chatpanel-bridge --uninstall remove the login auto-start
|
|
21
21
|
chatpanel-bridge --status show whether auto-start is set up
|
|
@@ -24,4 +24,4 @@ Usage:
|
|
|
24
24
|
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
25
25
|
chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
|
|
26
26
|
|
|
27
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function
|
|
27
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function zo(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return Ko(),!0;if(e("--version","-v"))return console.log(y),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=re(D,"utf8").trim()}catch{}const o=`http://${x}:${k}`;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: ${Fn(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 It(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{ot(),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{rt(),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=at()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const _e=process.argv.indexOf("--mcp-stdio"),He=process.argv.indexOf("--sandbox-host");if(He>=0){const{runSandboxHost:n}=await import("./sandbox-host.js");await n(process.argv[He+1],{compiled:sn()})}else if(_e>=0){const n=process.argv[_e+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Jo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await fe(y);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),ae()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():zo()||Xo();
|
package/src/threads.js
CHANGED
|
@@ -1 +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
|
|
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 still working on its last message (here or on another device). 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 L,totalMemoryBytes as B}from"./proc.js";import{historyShape as
|
|
1
|
+
import{treeRssBytes as L,totalMemoryBytes as B}from"./proc.js";import{historyShape as k,userTextMatches as D}from"./events/agent-thread.js";const b=1024**3,T=B(),z=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(T>=16*b?10*6e4:5*6e4),N=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(T*.2),3*b),I=400*1024**2;function F(o,i,u=I){const f=Math.floor(i/u),c=o>=48*b?4:o>=24*b?3:o>=12*b?2:1;return Math.max(1,Math.min(f,c))}const G=Number(process.env.CHATPANEL_WARM_MAX)||F(T,N),P=new Set;function W(o,i){if(o.answers!==i.answers||o.users.length!==i.users.length)return!1;const u=o.users.length;for(let f=0;f<u-1;f++)if(o.users[f]!==i.users[f])return!1;return u===0||D(o.users[u-1],i.users[u-1])}const g=2*6e4;function q({max:o=G,idleMs:i=z,budgetBytes:u=N,group:f=P,now:c=Date.now,measure:x=n=>L(n?.pid),log:p=()=>{}}={}){const n=new Set;let h=null;const v=()=>{let e=0;for(const r of f)e+=r.bytes;return e};let M=0;const d=e=>`${Math.round(e/1024**2)} MB`,$=new Set;function S(e){for(const r of[...$])r.key===e&&($.delete(r),r.resolve())}function m(e,r="dropped"){if(n.has(e)){n.delete(e),e.alive=!1;try{e.session?.close?.(r)}catch{}p(`warm ${e.label}: ${r} (${n.size} live)`),!n.size&&h&&(clearInterval(h),h=null),e.worker&&S(e.key)}}const _=e=>Number(e.session?.expiresAt)>0&&c()>=e.session.expiresAt-g;function U(){const e=c();for(const r of[...n])!r.busy&&e-r.lastUsed>i&&m(r,"idle")}function R(){h||!Number.isFinite(i)||i<=0||(h=setInterval(U,Math.min(i,6e4)),h.unref?.())}const A={get size(){return n.size},get bytes(){let e=0;for(const r of n)e+=r.bytes||0;return e},peek({key:e,messages:r}){const t=k(r);for(const s of n)if(!s.busy&&s.alive&&!s.worker&&s.key===e&&!_(s)&&W(s.shape,t))return!0;return!1},acquire({key:e,messages:r}){const t=k(r);for(const s of n)if(!(s.busy||!s.alive||s.worker||s.key!==e)){if(_(s)){m(s,"its sign-in is about to expire");continue}if(!W(s.shape,t)){p(`warm ${s.label}: shape differs (have ${s.shape.users.length}u/${s.shape.answers}a, asked ${t.users.length}u/${t.answers}a)`);continue}return s.busy=!0,s.lastUsed=c(),p(`warm ${s.label}: reused`),s}return null},reserve({key:e,label:r=e,evict:t=!0}){const s=()=>{let l=null;for(const E of n)!E.busy&&(!l||E.lastUsed<l.lastUsed)&&(l=E);return l};if(n.size>=o){const l=t?s():null;if(!l)return null;m(l,"evicted")}const a=M||I;for(;v()+a>u;){const l=t?s():null;if(!l)return p(`warm ${r}: not kept — ${d(v())} warm + ~${d(a)} would pass the ${d(u)} budget`),null;m(l,`evicted for memory (${d(v())} warm)`)}const w={key:e,label:r,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:c(),bytes:a};return n.add(w),p(`warm ${r}: starting (${n.size} live, ~${d(v())} of ${d(u)})`),R(),w},holds(e,r){return e.shape=k(r),e},attach(e,r){return e.session=r,r.onExit?.(()=>{e.alive&&m(e,"process exited")}),e},release(e,{user:r,answered:t}){e.alive&&(typeof r=="string"&&(e.shape={users:[...e.shape.users,r.trim()],answers:e.shape.answers+(t?1:0)}),e.busy=!1,e.lastUsed=c(),setImmediate(()=>{if(!e.alive)return;const s=x(e.session);s>0&&(e.bytes=s,M=s,p(`warm ${e.label}: ${d(s)} resident`))}))},acquireWorker({key:e,thread:r=null}){let t=null;for(const s of n){if(s.busy||!s.alive||!s.worker||s.key!==e)continue;if(_(s)){m(s,"its sign-in is about to expire");continue}const a=(r&&s.thread===r?-1e6:0)+(s.uses||0);(!t||a<t.rank)&&(t={e:s,rank:a})}return t?(t.e.busy=!0,t.e.lastUsed=c(),p(`warm ${t.e.label}: worker reused (${t.e.uses||0} turns so far)`),t.e):null},reserveWorker({key:e,label:r=e,cap:t=2}){let s=0;for(const w of n)w.worker&&w.key===e&&s++;if(s>=t)return null;const a=A.reserve({key:e,label:`${r} (worker)`,evict:!1});return a&&(a.worker=!0),a},workerFree(e,r){return new Promise(t=>{const s={key:e,resolve:()=>{clearTimeout(s.timer),t(!0)}};s.timer=setTimeout(()=>{$.delete(s),t(!1)},r),s.timer.unref?.(),$.add(s)})},releaseWorker(e,{thread:r=null,maxUses:t=12}={}){if(e.alive){if(e.uses=(e.uses||0)+1,e.thread=r,e.busy=!1,e.lastUsed=c(),e.uses>=t){m(e,`worker retired after ${e.uses} turns`);return}setImmediate(()=>{if(!e.alive)return;const s=x(e.session);s>0&&(e.bytes=s,M=s,p(`warm ${e.label}: ${d(s)} resident`))}),S(e.key)}},drop:m,closeAll(e="shutdown"){for(const r of[...n])m(r,e)},keys(){return[...n].map(e=>e.key)},reap:U};return f.add(A),A}export{N as WARM_BUDGET_BYTES,q as createWarmPool,k as historyShape,F as warmMaxFor};
|