@chatpanel/bridge 0.19.0 → 0.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.19.0",
3
+ "version": "0.20.2",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as r,writeFileSync as h,existsSync as i,mkdirSync as d}from"node:fs";import{fileURLToPath as f}from"node:url";import{dirname as m,join as n}from"node:path";const c=n(m(f(import.meta.url)),".."),v=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","sandbox-grant.js","mcp-errors.js","mcp-signin.js","mcp-config-import.js","mcp-launcher.js"];function u(){return[n(c,"node_modules","@chatpanel","events"),n(c,"..","chatpanel-events")].find(e=>i(n(e,"skill-manifest.js")))}const s=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";s&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=n(c,"src","events");s||d(l,{recursive:!0});const j=e=>`// GENERATED — do not edit.
2
+ import{readFileSync as r,writeFileSync as h,existsSync as i,mkdirSync as m}from"node:fs";import{fileURLToPath as d}from"node:url";import{dirname as f,join as n}from"node:path";const c=n(f(d(import.meta.url)),".."),v=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","sandbox-grant.js","mcp-errors.js","mcp-signin.js","mcp-config-import.js","mcp-launcher.js","agent-permission.js"];function u(){return[n(c,"node_modules","@chatpanel","events"),n(c,"..","chatpanel-events")].find(e=>i(n(e,"skill-manifest.js")))}const s=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";s&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=n(c,"src","events");s||m(l,{recursive:!0});const j=e=>`// GENERATED — do not edit.
3
3
  // Source of truth: chatpanel-events/${e} (npm @chatpanel/events).
4
4
  // Edit there, then run: npm run sync:events
5
5
  //
@@ -1,3 +1,3 @@
1
- import{unlink as F}from"node:fs/promises";import{spawnRpcChild as j}from"../rpc-child.js";import{spawn as G}from"node:child_process";import{track as J,sandbox as z}from"../sandbox.js";import{createWarmPool as K}from"../warm-pool.js";import{registerWarmPool as Q}from"../warm.js";import{createSession as R,deleteSession as L,rebindSession as V,releaseSession as X}from"../mcp-sessions.js";import{resolveClaude as Y,buildSpawnSpec as Z}from"../env.js";import{loginRequired as I,signInMessage as O}from"../sign-in.js";import{pushExtraArgs as P,FORBIDDEN as k}from"./args.js";import{buildClaudeLaunch as W,claudePrompt as ee,handleMessage as re,harnessChars as te,writeImages as se}from"./claude.js";const q=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,ae=5e3,c=Q("claude",K({log:n=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${n}`)}}));function ne(n={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||n.warm===!1)}async function U({spec:n,args:w,cwd:t,env:C,spawnImpl:h,log:S=()=>{}}){const x=[...w,"--input-format","stream-json"],[m,d,p]=Z(n,x,t,C),o=await z().wrap(m,d,p,{engine:"claude",cwd:t});o.record.layer==="none"&&S(`sandbox: claude session runs outside a sandbox — ${o.record.reason}`);const[E,l,f]=[o.bin,o.argv,o.opts];let e=null;const A=new Set;let g="",$=0,b=0;const s=j(E,l,{spawnOpts:f,spawnImpl:(r,a,i)=>J((h||G)(r,a,i),o,{kind:"warm"}),jsonrpc:!1,onStderr:r=>{g=(g+r).slice(-2e3),e&&e.touch()},onExit:r=>{if(S(`claude exited: ${r.signal||r.code}${g?` — ${g.trim().split(`
2
- `).pop()}`:""}`),e){const a=e.apiError&&I(e.apiError)?O("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${r.signal||r.code})${g?`: ${g.trim().split(`
3
- `).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:a})}for(const a of A)try{a(r)}catch{}},onMessage:r=>{if(!e||(e.touch(),r.type==="control_response"))return;const a=re(r,e.emit,e.streamedAny,t,e.flow);a.streamed&&(e.streamedAny=!0),a.result!=null&&(e.resultText=a.result),a.apiError&&(e.apiError=a.apiError),r.type==="result"&&(e.apiError&&I(e.apiError)?e.finish({status:"failed",error:O("Claude Code","claude")}):e.apiError?e.finish({status:"failed",error:`Claude Code reported an error: ${e.apiError}`}):e.finish({status:"completed",error:null}))}});return{get pid(){return s.pid},get alive(){return!s.exited},onExit(r){A.add(r)},close(){s.close()},async turn({prompt:r,emit:a,signal:i,harness:T=null}){if(s.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let y=null,_;const H=new Promise(v=>{_=v}),u={emit:a,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:b,harnessChars:T},streamedAny:!1,resultText:"",apiError:null,touch(){clearTimeout(y),y=setTimeout(()=>u.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(q/1e3)}s.`}),q)},finish(v){e===u&&(clearTimeout(y),e=null,_(v))}};e=u,u.touch();const N=()=>{if(e===u){u.interrupted=!0;try{s.send({type:"control_request",request_id:`stop_${++$}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===u&&(u.finish({status:"killed",error:null}),s.kill())},ae).unref?.()}};if(i?.aborted)return u.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};i?.addEventListener("abort",N,{once:!0});try{s.send({type:"user",message:{role:"user",content:r}})}catch(v){u.finish({status:"failed",error:v.message})}const M=await H;u.flow.costUsdTotal!=null&&(b=u.flow.costUsdTotal),i?.removeEventListener("abort",N),M.status==="timeout"&&s.kill();const B=M.status==="killed"?"killed":u.interrupted?"interrupted":M.status;return{streamedAny:u.streamedAny,resultText:u.resultText,status:B,error:M.error}}}}const D=new Set;async function oe({key:n,spec:w,options:t,label:C,launch:h=U,log:S=()=>{},force:x=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!x||!n||!w||D.has(n)||c.peek({key:n,messages:[{role:"user",content:""}]}))return!1;D.add(n);const m=c.reserve({key:n,label:`${C} (spare)`,evict:!1});if(!m)return D.delete(n),!1;let d=null,p=null;try{let o=t.mcp;const E=t.mcp?.specs||[];o?.url&&E.length&&(d=R(()=>{},E),o={...o,url:`${o.url.replace(/\/[^/]*$/,"")}/${d.id}`}),p=await W({system:"",options:{...t,mcp:o},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const l=[...p.args];P(l,t.extraArgs,k.claude,()=>{});const f=await h({spec:w,args:l,cwd:p.cwd,env:p.runEnv});f.mcpSession=d,f.systemSent="",c.attach(m,f);const e=p.cleanup;return f.onExit(()=>{d&&L(d.id),e()}),c.release(m,{user:null,answered:!1}),S(`warm ${C}: spare ready`),!0}catch(o){return d&&L(d.id),p?.cleanup?.(),c.drop(m,`spare launch failed: ${o.message}`),!1}finally{D.delete(n)}}async function Ee({messages:n,system:w,options:t,images:C},h,{signal:S,launch:x=U}={}){if(!ne(t))return{handled:!1,reason:"not eligible"};const m=Y();if(!m)return{handled:!1,reason:"claude not resolvable"};const d=`${Date.now()}-${Math.random().toString(36).slice(2)}`,p=(t.mcp?.specs||[]).map(r=>r?.name).filter(Boolean),o=[];P(o,t.extraArgs,k.claude,()=>{});const E=JSON.stringify({agent:"claude",cwd:t.workingDir||"",mode:t.permissionMode||"default",model:t.model||"",local:t.useLocalConfig!==!1,reach:t.reach||"",tools:[...p].sort(),extra:o,env:t.runEnv?Object.keys(t.runEnv).sort().map(r=>`${r}=${t.runEnv[r]}`):[],hosts:t.sandbox?.hosts?(Array.isArray(t.sandbox.hosts)?t.sandbox.hosts:String(t.sandbox.hosts).split(/[\s,;]+/)).map(r=>String(r).trim().toLowerCase()).filter(Boolean).sort():[]});let l=c.acquire({key:E,messages:n}),f=!1;if(!l){if(l=c.reserve({key:E,label:`claude ${t.workingDir||"home"}`}),!l)return{handled:!1,reason:"all warm slots busy"};f=!0;let r=null,a=null;try{let i=t.mcp;i?.url&&p.length&&(r=R(h,i.specs),i={...i,url:`${i.url.replace(/\/[^/]*$/,"")}/${r.id}`}),a=await W({system:w,options:{...t,mcp:i},tag:d});const T=[...a.args];P(T,t.extraArgs,k.claude,h);const y=await x({spec:m,args:T,cwd:a.cwd,env:a.runEnv});y.mcpSession=r,y.systemSent=String(w||""),c.attach(l,y);const _=a.cleanup;y.onExit(()=>{r&&L(r.id),_()})}catch(i){return r&&L(r.id),a?.cleanup(),c.drop(l,`launch failed: ${i.message}`),{handled:!1,reason:i.message}}}const e=l.session;e.mcpSession&&V(e.mcpSession,h,t.mcp?.specs);const A=n[n.length-1],g=await se(C,d),$=String(w||""),b=ee(f?n:[A],g,!f&&$!==e.systemSent?$:"");e.systemSent=$;let s;try{s=await e.turn({prompt:b,emit:h,signal:S,harness:te({prompt:b,system:f?$:"",specs:f?t.mcp?.specs:null})})}finally{g.forEach(r=>F(r).catch(()=>{})),e.mcpSession&&X(e.mcpSession)}if(S?.aborted||s.status==="interrupted")return s.status==="interrupted"&&e.alive?c.release(l,{user:String(A?.content||""),answered:s.streamedAny}):c.drop(l,"stopped"),{handled:!0};if(s.status!=="completed"){if(c.drop(l,s.error||s.status),!s.streamedAny)return{handled:!1,reason:s.error||s.status};throw new Error(s.error||`Claude Code ${s.status}`)}return h({type:"done",text:s.streamedAny?"":s.resultText}),c.release(l,{user:String(A?.content||""),answered:!0}),setTimeout(()=>{oe({key:E,spec:m,options:t,label:`claude ${t.workingDir||"home"}`,launch:x}).catch(()=>{})},250).unref?.(),{handled:!0}}export{Ee as chatWarm,U as launchClaudeSession,c as pool,oe as prewarmClaude,ne as warmEligible};
1
+ import{unlink as G}from"node:fs/promises";import{spawnRpcChild as J}from"../rpc-child.js";import{spawn as z}from"node:child_process";import{track as K,sandbox as Q}from"../sandbox.js";import{createWarmPool as V}from"../warm-pool.js";import{registerWarmPool as X}from"../warm.js";import{createSession as I,deleteSession as L,rebindSession as Y,releaseSession as Z,relayPermission as O}from"../mcp-sessions.js";import{resolveClaude as ee,buildSpawnSpec as re}from"../env.js";import{loginRequired as W,signInMessage as U}from"../sign-in.js";import{pushExtraArgs as N,FORBIDDEN as R}from"./args.js";import{buildClaudeLaunch as H,claudePrompt as te,handleMessage as se,harnessChars as ae,writeImages as ne,answerControlRequest as le}from"./claude.js";const B=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,oe=5e3,h=X("claude",V({log:n=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${n}`)}}));function ie(n={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||n.warm===!1)}async function F({spec:n,args:S,cwd:r,env:A,spawnImpl:E,log:v=()=>{},ask:$=null}){const w=[...S,"--input-format","stream-json"],[f,p,m]=re(n,w,r,A),c=await Q().wrap(f,p,m,{engine:"claude",cwd:r});c.record.layer==="none"&&v(`sandbox: claude session runs outside a sandbox — ${c.record.reason}`);const[i,y,u]=[c.bin,c.argv,c.opts];let e=null;const x=new Set;let g="",_=0,l=0;const t=J(i,y,{spawnOpts:u,spawnImpl:(s,a,d)=>K((E||z)(s,a,d),c,{kind:"warm"}),jsonrpc:!1,onStderr:s=>{g=(g+s).slice(-2e3),e&&e.touch()},onExit:s=>{if(v(`claude exited: ${s.signal||s.code}${g?` — ${g.trim().split(`
2
+ `).pop()}`:""}`),e){const a=e.apiError&&W(e.apiError)?U("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${s.signal||s.code})${g?`: ${g.trim().split(`
3
+ `).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:a})}for(const a of x)try{a(s)}catch{}},onMessage:s=>{if(!e||(e.touch(),s.type==="control_response"))return;if(s.type==="control_request"){const d=e;d.asking++,d.touch(),le(s,$,b=>{try{t.send(b)}catch{}}).catch(()=>{}).finally(()=>{d.asking--,e===d&&d.touch()});return}const a=se(s,e.emit,e.streamedAny,r,e.flow);a.streamed&&(e.streamedAny=!0),a.result!=null&&(e.resultText=a.result),a.apiError&&(e.apiError=a.apiError),s.type==="result"&&(e.apiError&&W(e.apiError)?e.finish({status:"failed",error:U("Claude Code","claude")}):e.apiError?e.finish({status:"failed",error:`Claude Code reported an error: ${e.apiError}`}):e.finish({status:"completed",error:null}))}});return{get pid(){return t.pid},get alive(){return!t.exited},onExit(s){x.add(s)},close(){t.close()},async turn({prompt:s,emit:a,signal:d,harness:b=null}){if(t.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let C=null,k;const D=new Promise(T=>{k=T}),o={emit:a,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:l,harnessChars:b},streamedAny:!1,resultText:"",apiError:null,asking:0,touch(){clearTimeout(C),!o.asking&&(C=setTimeout(()=>o.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(B/1e3)}s.`}),B))},finish(T){e===o&&(clearTimeout(C),e=null,k(T))}};e=o,o.touch();const q=()=>{if(e===o){o.interrupted=!0;try{t.send({type:"control_request",request_id:`stop_${++_}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===o&&(o.finish({status:"killed",error:null}),t.kill())},oe).unref?.()}};if(d?.aborted)return o.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};d?.addEventListener("abort",q,{once:!0});try{t.send({type:"user",message:{role:"user",content:s}})}catch(T){o.finish({status:"failed",error:T.message})}const M=await D;o.flow.costUsdTotal!=null&&(l=o.flow.costUsdTotal),d?.removeEventListener("abort",q),M.status==="timeout"&&t.kill();const j=M.status==="killed"?"killed":o.interrupted?"interrupted":M.status;return{streamedAny:o.streamedAny,resultText:o.resultText,status:j,error:M.error}}}}const P=new Set;async function ue({key:n,spec:S,options:r,label:A,launch:E=F,log:v=()=>{},force:$=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!$||!n||!S||P.has(n)||h.peek({key:n,messages:[{role:"user",content:""}]}))return!1;P.add(n);const w=h.reserve({key:n,label:`${A} (spare)`,evict:!1});if(!w)return P.delete(n),!1;let f=null,p=null;try{let m=r.mcp;const c=r.mcp?.specs||[];(m?.url&&c.length||r.approvals===!0)&&(f=I(()=>{},c),m?.url&&c.length&&(m={...m,url:`${m.url.replace(/\/[^/]*$/,"")}/${f.id}`})),p=await H({system:"",options:{...r,mcp:m},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const i=[...p.args];N(i,r.extraArgs,R.claude,()=>{});const y=f,u=await E({spec:S,args:i,cwd:p.cwd,env:p.runEnv,ask:p.approvals&&y?x=>O(y,x):null});u.mcpSession=f,u.systemSent="",h.attach(w,u);const e=p.cleanup;return u.onExit(()=>{f&&L(f.id),e()}),h.release(w,{user:null,answered:!1}),v(`warm ${A}: spare ready`),!0}catch(m){return f&&L(f.id),p?.cleanup?.(),h.drop(w,`spare launch failed: ${m.message}`),!1}finally{P.delete(n)}}async function Ce({messages:n,system:S,options:r,images:A},E,{signal:v,launch:$=F}={}){if(!ie(r))return{handled:!1,reason:"not eligible"};const w=ee();if(!w)return{handled:!1,reason:"claude not resolvable"};const f=`${Date.now()}-${Math.random().toString(36).slice(2)}`,p=(r.mcp?.specs||[]).map(t=>t?.name).filter(Boolean),m=[];N(m,r.extraArgs,R.claude,()=>{});const c=JSON.stringify({agent:"claude",cwd:r.workingDir||"",mode:r.permissionMode||"default",model:r.model||"",local:r.useLocalConfig!==!1,reach:r.reach||"",tools:[...p].sort(),extra:m,approvals:r.approvals===!0,env:r.runEnv?Object.keys(r.runEnv).sort().map(t=>`${t}=${r.runEnv[t]}`):[],hosts:r.sandbox?.hosts?(Array.isArray(r.sandbox.hosts)?r.sandbox.hosts:String(r.sandbox.hosts).split(/[\s,;]+/)).map(t=>String(t).trim().toLowerCase()).filter(Boolean).sort():[]});let i=h.acquire({key:c,messages:n}),y=!1;if(!i){if(i=h.reserve({key:c,label:`claude ${r.workingDir||"home"}`}),!i)return{handled:!1,reason:"all warm slots busy"};y=!0;let t=null,s=null;try{let a=r.mcp;(a?.url&&p.length||r.approvals===!0)&&(t=I(E,a?.specs||[]),a?.url&&p.length&&(a={...a,url:`${a.url.replace(/\/[^/]*$/,"")}/${t.id}`})),s=await H({system:S,options:{...r,mcp:a},tag:f});const d=[...s.args];N(d,r.extraArgs,R.claude,E);const b=t,C=await $({spec:w,args:d,cwd:s.cwd,env:s.runEnv,ask:s.approvals&&b?D=>O(b,D):null});C.mcpSession=t,C.systemSent=String(S||""),h.attach(i,C);const k=s.cleanup;C.onExit(()=>{t&&L(t.id),k()})}catch(a){return t&&L(t.id),s?.cleanup(),h.drop(i,`launch failed: ${a.message}`),{handled:!1,reason:a.message}}}const u=i.session;u.mcpSession&&Y(u.mcpSession,E,r.mcp?.specs);const e=n[n.length-1],x=await ne(A,f),g=String(S||""),_=te(y?n:[e],x,!y&&g!==u.systemSent?g:"");u.systemSent=g;let l;try{l=await u.turn({prompt:_,emit:E,signal:v,harness:ae({prompt:_,system:y?g:"",specs:y?r.mcp?.specs:null})})}finally{x.forEach(t=>G(t).catch(()=>{})),u.mcpSession&&Z(u.mcpSession)}if(v?.aborted||l.status==="interrupted")return l.status==="interrupted"&&u.alive?h.release(i,{user:String(e?.content||""),answered:l.streamedAny}):h.drop(i,"stopped"),{handled:!0};if(l.status!=="completed"){if(h.drop(i,l.error||l.status),!l.streamedAny)return{handled:!1,reason:l.error||l.status};throw new Error(l.error||`Claude Code ${l.status}`)}return E({type:"done",text:l.streamedAny?"":l.resultText}),h.release(i,{user:String(e?.content||""),answered:!0}),setTimeout(()=>{ue({key:c,spec:w,options:r,label:`claude ${r.workingDir||"home"}`,launch:$}).catch(()=>{})},250).unref?.(),{handled:!0}}export{Ce as chatWarm,F as launchClaudeSession,h as pool,ue as prewarmClaude,ie as warmEligible};
@@ -1,8 +1,10 @@
1
- import{spawn as R}from"node:child_process";import{writeFile as O,unlink as F}from"node:fs/promises";import S from"node:os";import P from"node:path";import{resolveClaude as x,buildSpawnSpec as j,isCompiledBinary as re,selfMcpStdio as oe}from"../env.js";import{signInStatus as ne,signInMessage as D,loginRequired as se}from"../sign-in.js";import{buildCliPrompt as H}from"./prompt.js";import{summarizeCliError as ae}from"../cli-errors.js";import{killOnAbort as ie}from"../proc.js";import{sandbox as le,noteSandbox as ce,track as ue}from"../sandbox.js";import{pushExtraArgs as de,FORBIDDEN as pe}from"./args.js";import{relayTimeoutMax as fe}from"../relay-timeout.js";import{displayPath as he,resolveWorkdir as U}from"../workdir.js";import{connectorsFor as me}from"../connectors.js";import{chatWarm as ye}from"./claude-warm.js";async function be(e,t){const o=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const n=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",r=P.join(S.tmpdir(),`chatpanel-claude-img-${t}-${i}.${n}`);await O(r,Buffer.from(s[2],"base64")),o.push(r)}return o}const z=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,B=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],G=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),_e=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch"])}),ge=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),we=Object.freeze(["remember","forget"]),q=Object.freeze({device:Object.freeze([]),trusted:ge});function Te(e,t=[]){const o=q[e]||q.device,i=(t||[]).filter(r=>typeof r=="string"&&/^chatpanel/i.test(r)),s=[],n=[];for(const r of i){for(const a of o)s.push(`mcp__${r}__${a}`);for(const a of we)n.push(`mcp__${r}__${a}`)}return{allow:s,deny:n}}function xe(e){if(!e||e==="any")return null;const t=G[e]?e:"device";return{allow:[...G[t]],deny:[..._e[t]]}}let A="Claude Code not found.",J=0,w=!1;async function Ye(){if(Date.now()-J>(w?3e4:4e3)){J=Date.now();try{x()||!re()&&await $()?w=!0:(w=!1,A=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{w=!1}}return w?await ne("claude",x()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:D("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:A}}async function Xe(){return["opus","sonnet","haiku"]}function Ee(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:o,args:i}=oe(e.url),s=[...new Set(e.specs.map(n=>n?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:o,args:i}}},allowedTools:s.map(n=>`mcp__${t}__${n}`)}}function Y({prompt:e,args:t,cwd:o,env:i=null,emit:s,signal:n,harness:r=null}){const a=x();if(!a)return null;const[c,h,_]=j(a,t,o,i);return new Promise((b,d)=>{le().wrap(c,h,_,{engine:"claude",cwd:o}).then(l=>{ce(s,l.record);let u;try{u=ue(R(l.bin,l.argv,l.opts),l,{kind:"agent"})}catch(f){return d(new Error(`Failed to start claude: ${f.message}`))}const g=ie(u,n);let m="",C="",p=!1,y=null;const te={sawText:!1,tail:"",boundary:!1,harnessChars:r};let v="",k;const N=()=>{clearTimeout(k),k=setTimeout(()=>{u.kill("SIGKILL"),d(new Error(`Claude Code timed out — no output for ${Math.round(z/1e3)}s.`))},z)};N(),u.stdout.on("data",f=>{N(),m+=f.toString();let M;for(;(M=m.indexOf(`
2
- `))>=0;){const W=m.slice(0,M).trim();if(m=m.slice(M+1),!W.startsWith("{"))continue;let I;try{I=JSON.parse(W)}catch{continue}const T=Q(I,s,p,o,te);T.streamed&&(p=!0),T.result!=null&&(v=T.result),T.apiError&&(y=T.apiError)}}),u.stderr.on("data",f=>{N(),C+=f.toString()}),u.on("error",f=>{clearTimeout(k),g(),d(new Error(`Failed to start claude (${c}): ${f.message}`))}),u.on("close",f=>{if(clearTimeout(k),g(),n?.aborted){b({streamedAny:p,resultText:v});return}if(y&&se(y))return d(new Error(D("Claude Code","claude")));if(f===0&&y)return d(new Error(`Claude Code reported an error: ${y}`));f===0?b({streamedAny:p,resultText:v}):d(new Error(ae("Claude Code",f,C,y||"",{agentId:"claude"})))}),u.stdin.write(e),u.stdin.end()}).catch(d)})}function Ce(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(o=>typeof o=="string"?o:o?.text||"").filter(Boolean).join(`
3
- `)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function X(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
1
+ import{spawn as q}from"node:child_process";import{writeFile as W,unlink as D}from"node:fs/promises";import O from"node:os";import R from"node:path";import{resolveClaude as S,buildSpawnSpec as H,isCompiledBinary as ae,selfMcpStdio as ie}from"../env.js";import{signInStatus as le,signInMessage as U,loginRequired as ce}from"../sign-in.js";import{buildCliPrompt as z}from"./prompt.js";import{summarizeCliError as ue}from"../cli-errors.js";import{killOnAbort as pe}from"../proc.js";import{sandbox as de,noteSandbox as fe,track as he}from"../sandbox.js";import{pushExtraArgs as me,FORBIDDEN as ye}from"./args.js";import{relayTimeoutMax as be}from"../relay-timeout.js";import{displayPath as _e,resolveWorkdir as B}from"../workdir.js";import{connectorsFor as we}from"../connectors.js";import{chatWarm as ge}from"./claude-warm.js";import{claudePermissionResponse as Te,permissionAnswer as xe}from"../events/agent-permission.js";import{relayPermission as Ee}from"../mcp-sessions.js";async function Ce(e,t){const r=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const o=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",n=R.join(O.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await W(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const G=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,J=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task"],Y=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),ke=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch"])}),Se=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),ve=Object.freeze(["remember","forget"]),X=Object.freeze({device:Object.freeze([]),trusted:Se});function Ae(e,t=[]){const r=X[e]||X.device,i=(t||[]).filter(n=>typeof n=="string"&&/^chatpanel/i.test(n)),s=[],o=[];for(const n of i){for(const a of r)s.push(`mcp__${n}__${a}`);for(const a of ve)o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function Ne(e){if(!e||e==="any")return null;const t=Y[e]?e:"device";return{allow:[...Y[t]],deny:[...ke[t]]}}let P="Claude Code not found.",K=0,E=!1;async function ot(){if(Date.now()-K>(E?3e4:4e3)){K=Date.now();try{S()||!ae()&&await F()?E=!0:(E=!1,P=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{E=!1}}return E?await le("claude",S()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:U("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:P}}async function st(){return["opus","sonnet","haiku"]}function Oe(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=ie(e.url),s=[...new Set(e.specs.map(o=>o?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:r,args:i}}},allowedTools:s.map(o=>`mcp__${t}__${o}`)}}async function Pe(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):xe("deny","This run has no approval surface.");return r(Te(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function Q({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:u=null}){const f=S();if(!f)return null;const[y,b,_]=H(f,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((m,l)=>{de().wrap(y,b,_,{engine:"claude",cwd:r}).then(p=>{fe(s,p.record);let c;try{c=he(q(p.bin,p.argv,p.opts),p,{kind:"agent"})}catch(d){return l(new Error(`Failed to start claude: ${d.message}`))}const w=pe(c,o);let h="",g="",A=!1,T=null;const oe={sawText:!1,tail:"",boundary:!1,harnessChars:n};let M="",C,$=0;const N=()=>{clearTimeout(C),!$&&(C=setTimeout(()=>{c.kill("SIGKILL"),l(new Error(`Claude Code timed out — no output for ${Math.round(G/1e3)}s.`))},G))};N();const se=d=>{try{c.stdin.write(`${JSON.stringify(d)}
2
+ `)}catch{}};c.stdout.on("data",d=>{N(),h+=d.toString();let L;for(;(L=h.indexOf(`
3
+ `))>=0;){const j=h.slice(0,L).trim();if(h=h.slice(L+1),!j.startsWith("{"))continue;let x;try{x=JSON.parse(j)}catch{continue}if(x.type==="control_request"){$++,clearTimeout(C),Pe(x,u,se).catch(()=>{}).finally(()=>{$--,N()});continue}if(x.type==="control_response")continue;const k=ee(x,s,A,r,oe);k.streamed&&(A=!0),k.result!=null&&(M=k.result),k.apiError&&(T=k.apiError),a&&x.type==="result"&&c.stdin.end()}}),c.stderr.on("data",d=>{N(),g+=d.toString()}),c.on("error",d=>{clearTimeout(C),w(),l(new Error(`Failed to start claude (${y}): ${d.message}`))}),c.on("close",d=>{if(clearTimeout(C),w(),o?.aborted){m({streamedAny:A,resultText:M});return}if(T&&ce(T))return l(new Error(U("Claude Code","claude")));if(d===0&&T)return l(new Error(`Claude Code reported an error: ${T}`));d===0?m({streamedAny:A,resultText:M}):l(new Error(ue("Claude Code",d,g,T||"",{agentId:"claude"})))}),a?c.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
4
+ `):(c.stdin.write(e),c.stdin.end())}).catch(l)})}function Me(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
+ `)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function V(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
4
6
 
5
- `}),e.boundary=!1)}function K(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function Q(e,t,o,i="",s=null){const n={streamed:!1,result:null};if(e.type==="stream_event"){const r=e.event;r?.type==="content_block_delta"&&(r.delta?.type==="text_delta"?(n.streamed=!0,X(s,t),t({type:"delta",text:r.delta.text}),K(s,r.delta.text)):r.delta?.type==="thinking_delta"&&t({type:"reasoning",text:r.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return n.apiError=(e.message?.content||[]).filter(r=>r.type==="text").map(r=>r.text).join(`
6
- `)||String(e.error||"api error"),n;for(const r of e.message?.content||[])r.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:r.name,phase:"start",callId:r.id,input:r.input,summary:Me(r,i)})):r.type==="text"&&!o&&(n.streamed=!0,X(s,t),t({type:"delta",text:r.text}),K(s,r.text))}else if(e.type==="user")for(const r of e.message?.content||[])r.type==="tool_result"&&t({type:"tool",phase:"done",callId:r.tool_use_id,status:r.is_error?"error":"ok",result:Ce(r.content)});else if(e.type==="result"){e.is_error?n.apiError=n.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?n.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const r=e.usage||e.message?.usage;if(r){const a=Number.isFinite(Number(e.total_cost_usd))?Number(e.total_cost_usd):null,c=Number(s?.costUsdBefore)||0;s&&a!=null&&(s.costUsdTotal=a),t({type:"usage",provider:"bridge",inputTokens:r.input_tokens||0,outputTokens:r.output_tokens||0,cacheReadTokens:r.cache_read_input_tokens||0,cacheWriteTokens:r.cache_creation_input_tokens||0,costUsd:a!=null?Math.max(0,a-c):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return n}const V=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let E=null;function Z({probe:e=null}={}){return E||(E=(async()=>{try{return String(await(e?e():new Promise(t=>{const[o,i,s]=j(x(),["--help"],null),n=R(o,i,{...s,stdio:["ignore","pipe","pipe"]});let r="";n.stdout.on("data",a=>{r+=a}),n.on("error",()=>t("")),n.on("close",()=>t(r)),setTimeout(()=>{try{n.kill()}catch{}t(r)},8e3).unref?.()}))||"")}catch{return""}})(),E)}async function ke(e={}){return/--effort\b/.test(await Z(e))}async function Se(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await Z(e))}function Ke(){E=null}async function Ae({system:e,options:t,tag:o}){const i=t.permissionMode||"default",s=U(t.workingDir),n=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];V&&await ke()&&n.push("--effort",V);const r=[],a=[],c=Ee(t.mcp);if(c){const l=P.join(S.tmpdir(),`chatpanel-mcp-${o}.json`);await O(l,JSON.stringify(c.config)),r.push(l),n.push("--mcp-config",l),a.push(...c.allowedTools)}const h=xe(t.reach);if(h){const l=Te(t.reach,await me("claude").catch(()=>[]));n.push("--allowedTools",...h.allow,...a,...l.allow),n.push("--disallowedTools",...h.deny,...l.deny)}else i==="bypassPermissions"?n.push("--permission-mode","bypassPermissions"):i==="acceptEdits"?(n.push("--permission-mode","acceptEdits"),a.length&&n.push("--allowedTools",...a)):n.push("--allowedTools",...B,...a);if(e)if(x()?.kind!=="wsl"&&await Se()){const u=P.join(S.tmpdir(),`chatpanel-system-${o}.md`);await O(u,e,{mode:384}),r.push(u),n.push("--append-system-prompt-file",u)}else n.push("--append-system-prompt",e);t.model&&n.push("--model",t.model),t.useLocalConfig===!1&&n.push("--setting-sources","");const _=c&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(fe(t.mcp?.specs))}:null,b=_||t.runEnv?{...t.runEnv||{},..._||{}}:null;return{args:n,cwd:s,runEnv:b,cleanup:()=>r.forEach(l=>F(l).catch(()=>{})),hasMcp:!!c}}function ee({prompt:e="",system:t="",specs:o=null}={}){const i=Array.isArray(o)&&o.length?JSON.stringify(o).length:0;return String(e).length+String(t).length+i}function ve(e,t=[],o=""){let i=H(e,o);return t.length&&(i+=`
7
+ `}),e.boundary=!1)}function Z(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function ee(e,t,r,i="",s=null){const o={streamed:!1,result:null};if(e.type==="stream_event"){const n=e.event;n?.type==="content_block_delta"&&(n.delta?.type==="text_delta"?(o.streamed=!0,V(s,t),t({type:"delta",text:n.delta.text}),Z(s,n.delta.text)):n.delta?.type==="thinking_delta"&&t({type:"reasoning",text:n.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return o.apiError=(e.message?.content||[]).filter(n=>n.type==="text").map(n=>n.text).join(`
8
+ `)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:Fe(n,i)})):n.type==="text"&&!r&&(o.streamed=!0,V(s,t),t({type:"delta",text:n.text}),Z(s,n.text))}else if(e.type==="user")for(const n of e.message?.content||[])n.type==="tool_result"&&t({type:"tool",phase:"done",callId:n.tool_use_id,status:n.is_error?"error":"ok",result:Me(n.content)});else if(e.type==="result"){e.is_error?o.apiError=o.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?o.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const n=e.usage||e.message?.usage;if(n){const a=Number.isFinite(Number(e.total_cost_usd))?Number(e.total_cost_usd):null,u=Number(s?.costUsdBefore)||0;s&&a!=null&&(s.costUsdTotal=a),t({type:"usage",provider:"bridge",inputTokens:n.input_tokens||0,outputTokens:n.output_tokens||0,cacheReadTokens:n.cache_read_input_tokens||0,cacheWriteTokens:n.cache_creation_input_tokens||0,costUsd:a!=null?Math.max(0,a-u):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return o}const te=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let v=null;function re({probe:e=null}={}){return v||(v=(async()=>{try{return String(await(e?e():new Promise(t=>{const[r,i,s]=H(S(),["--help"],null),o=q(r,i,{...s,stdio:["ignore","pipe","pipe"]});let n="";o.stdout.on("data",a=>{n+=a}),o.on("error",()=>t("")),o.on("close",()=>t(n)),setTimeout(()=>{try{o.kill()}catch{}t(n)},8e3).unref?.()}))||"")}catch{return""}})(),v)}async function $e(e={}){return/--effort\b/.test(await re(e))}async function Le(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await re(e))}function at(){v=null}async function We({system:e,options:t,tag:r}){const i=t.permissionMode||"default",s=B(t.workingDir),o=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];te&&await $e()&&o.push("--effort",te);const n=[],a=[],u=Oe(t.mcp);if(u){const l=R.join(O.tmpdir(),`chatpanel-mcp-${r}.json`);await W(l,JSON.stringify(u.config)),n.push(l),o.push("--mcp-config",l),a.push(...u.allowedTools)}const f=Ne(t.reach);if(f){const l=Ae(t.reach,await we("claude").catch(()=>[]));o.push("--allowedTools",...f.allow,...a,...l.allow),o.push("--disallowedTools",...f.deny,...l.deny)}else i==="bypassPermissions"?o.push("--permission-mode","bypassPermissions"):i==="acceptEdits"?(o.push("--permission-mode","acceptEdits"),a.length&&o.push("--allowedTools",...a)):o.push("--allowedTools",...J,...a);const y=!f&&t.approvals===!0;if(y&&o.push("--permission-prompt-tool","stdio"),e)if(S()?.kind!=="wsl"&&await Le()){const p=R.join(O.tmpdir(),`chatpanel-system-${r}.md`);await W(p,e,{mode:384}),n.push(p),o.push("--append-system-prompt-file",p)}else o.push("--append-system-prompt",e);t.model&&o.push("--model",t.model),t.useLocalConfig===!1&&o.push("--setting-sources","");const b=u&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(be(t.mcp?.specs))}:null,_=b||t.runEnv?{...t.runEnv||{},...b||{}}:null;return{args:o,cwd:s,runEnv:_,cleanup:()=>n.forEach(l=>D(l).catch(()=>{})),hasMcp:!!u,approvals:y}}function ne({prompt:e="",system:t="",specs:r=null}={}){const i=Array.isArray(r)&&r.length?JSON.stringify(r).length:0;return String(e).length+String(t).length+i}function Re(e,t=[],r=""){let i=z(e,r);return t.length&&(i+=`
7
9
 
8
- The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function Qe({messages:e,system:t,options:o,images:i},s,{signal:n}={}){const r=await ye({messages:e,system:t,options:o,images:i},s,{signal:n}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!r.handled&&!n?.aborted){if(r.thrown)throw new Error(r.reason);return Ne({messages:e,system:t,options:o,images:i},s,{signal:n})}}async function Ne({messages:e,system:t,options:o,images:i},s,{signal:n}={}){const r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await Ae({system:t,options:o,tag:r}),{args:c,cwd:h,runEnv:_}=a,b=await be(i,r),d=()=>{b.forEach(g=>F(g).catch(()=>{})),a.cleanup()},l=ve(e,b);de(c,o.extraArgs,pe.claude,s);const u=Y({prompt:l,args:c,cwd:h,env:_,emit:s,signal:n,harness:ee({prompt:l,system:t,specs:o.mcp?.specs})});if(u===null)return d(),Oe({messages:e,system:t,options:o},s,{signal:n});try{const{streamedAny:g,resultText:m}=await u;s({type:"done",text:g?"":m})}finally{d()}}async function Ve({prompt:e,system:t,model:o}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",o||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const n=Y({prompt:e,args:i,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(n===null)return Pe({prompt:e,system:t,model:o});const{resultText:r}=await n;return(s||r||"").trim()}function Me(e,t=""){const o=e.input||{};return o.command?String(o.command).slice(0,60):o.file_path?he(o.file_path,t):o.pattern?o.pattern:o.url?o.url:o.description?String(o.description).slice(0,80):o.query?String(o.query).slice(0,80):o.prompt?String(o.prompt).slice(0,80):""}let L=null;function $(){return L||(L=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),L}async function Oe({messages:e,system:t,options:o},i,{signal:s}={}){const n=await $();if(!n)throw new Error(A);const{query:r}=n,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const c=o.permissionMode||"default",h=U(o.workingDir),_=c==="acceptEdits"||c==="bypassPermissions",b=new Set(B),d=async p=>b.has(p)||_?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${p} blocked — set this agent's permission mode in ChatPanel to enable it.`};let l=!1;const u=H(e),g={sawText:!1,tail:"",boundary:!1,harnessChars:ee({prompt:u,system:t})};let m="";const C=r({prompt:u,options:{cwd:h,permissionMode:c,includePartialMessages:!0,canUseTool:d,abortController:a,settingSources:o.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...o.model?{model:o.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const p of C){const y=Q(p,i,l,h,g);y.streamed&&(l=!0),y.result!=null&&(m=y.result)}}catch(p){if(s?.aborted||a.signal.aborted)return;throw p}i({type:"done",text:l?"":m})}async function Pe({prompt:e,system:t,model:o}){const i=await $();if(!i)throw new Error(A);const{query:s}=i;let n="";const r=s({prompt:e,options:{cwd:S.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:o||"haiku"}});for await(const a of r)if(a.type==="assistant")for(const c of a.message.content)c.type==="text"&&(n+=c.text);else a.type==="result"&&a.subtype==="success"&&!n&&(n=a.result||"");return n.trim()}export{Ke as _resetEffortProbe,Ye as available,Ae as buildClaudeLaunch,Te as channelMcpTools,xe as channelToolPolicy,Qe as chat,Ne as chatCold,Ee as claudeMcpConfig,ve as claudePrompt,ke as claudeSupportsEffort,Se as claudeSupportsSystemPromptFile,Ve as complete,Q as handleMessage,ee as harnessChars,Xe as listModels,be as writeImages};
10
+ The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}async function it({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=await ge({messages:e,system:t,options:r,images:i},s,{signal:o}).catch(a=>({handled:!1,reason:a?.message||String(a),thrown:!0}));if(!n.handled&&!o?.aborted){if(n.thrown)throw new Error(n.reason);return Ie({messages:e,system:t,options:r,images:i},s,{signal:o})}}async function Ie({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await We({system:t,options:r,tag:n}),{args:u,cwd:f,runEnv:y}=a,b=await Ce(i,n),_=()=>{b.forEach(c=>D(c).catch(()=>{})),a.cleanup()},m=Re(e,b);me(u,r.extraArgs,ye.claude,s);const l=a.approvals&&r.permissionSession?c=>Ee(r.permissionSession,c):null,p=Q({prompt:m,args:u,cwd:f,env:y,emit:s,signal:o,harness:ne({prompt:m,system:t,specs:r.mcp?.specs}),host:a.approvals,ask:l});if(p===null)return _(),je({messages:e,system:t,options:r},s,{signal:o});try{const{streamedAny:c,resultText:w}=await p;s({type:"done",text:c?"":w})}finally{_()}}async function lt({prompt:e,system:t,model:r}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",r||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation."];let s="";const o=Q({prompt:e,args:i,cwd:null,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(o===null)return qe({prompt:e,system:t,model:r});const{resultText:n}=await o;return(s||n||"").trim()}function Fe(e,t=""){const r=e.input||{};return r.command?String(r.command).slice(0,60):r.file_path?_e(r.file_path,t):r.pattern?r.pattern:r.url?r.url:r.description?String(r.description).slice(0,80):r.query?String(r.query).slice(0,80):r.prompt?String(r.prompt).slice(0,80):""}let I=null;function F(){return I||(I=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),I}async function je({messages:e,system:t,options:r},i,{signal:s}={}){const o=await F();if(!o)throw new Error(P);const{query:n}=o,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const u=r.permissionMode||"default",f=B(r.workingDir),y=u==="acceptEdits"||u==="bypassPermissions",b=new Set(J),_=async h=>b.has(h)||y?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${h} blocked — set this agent's permission mode in ChatPanel to enable it.`};let m=!1;const l=z(e),p={sawText:!1,tail:"",boundary:!1,harnessChars:ne({prompt:l,system:t})};let c="";const w=n({prompt:l,options:{cwd:f,permissionMode:u,includePartialMessages:!0,canUseTool:_,abortController:a,settingSources:r.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...r.model?{model:r.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const h of w){const g=ee(h,i,m,f,p);g.streamed&&(m=!0),g.result!=null&&(c=g.result)}}catch(h){if(s?.aborted||a.signal.aborted)return;throw h}i({type:"done",text:m?"":c})}async function qe({prompt:e,system:t,model:r}){const i=await F();if(!i)throw new Error(P);const{query:s}=i;let o="";const n=s({prompt:e,options:{cwd:O.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:r||"haiku"}});for await(const a of n)if(a.type==="assistant")for(const u of a.message.content)u.type==="text"&&(o+=u.text);else a.type==="result"&&a.subtype==="success"&&!o&&(o=a.result||"");return o.trim()}export{at as _resetEffortProbe,Pe as answerControlRequest,ot as available,We as buildClaudeLaunch,Ae as channelMcpTools,Ne as channelToolPolicy,it as chat,Ie as chatCold,Oe as claudeMcpConfig,Re as claudePrompt,$e as claudeSupportsEffort,Le as claudeSupportsSystemPromptFile,lt as complete,ee as handleMessage,ne as harnessChars,st as listModels,Ce as writeImages};
@@ -0,0 +1,2 @@
1
+ const x="permission_request",f=Object.freeze({ALLOW:"allow",ALLOW_CHAT:"allow_chat",DENY:"deny"}),O=600*1e3,A="permission_prompt";function w(){return{name:A,description:"ChatPanel-internal: the person answers the agent's permission prompt. Not for the model.",parameters:{type:"object",properties:{tool:{type:"string"},input:{type:"object"},description:{type:"string"},path:{type:"string"},rules:{type:"array"}}}}}const $=e=>e===A,u=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),a=e=>typeof e=="string"?e:e==null?"":String(e);function P(e={}){const t=u(e)?e:{},o=a(t.tool_name||t.toolName||t.tool),n=[];for(const s of Array.isArray(t.permission_suggestions)?t.permission_suggestions:[])if(!(!u(s)||s.type!=="addRules"||s.behavior==="deny"))for(const i of Array.isArray(s.rules)?s.rules:[]){if(!u(i))continue;const c=a(i.toolName||o),l=a(i.ruleContent);c&&!n.some(d=>d.tool===c&&d.content===l)&&n.push({tool:c,content:l})}return{tool:o,displayName:a(t.display_name||t.displayName)||o,input:u(t.input)?t.input:{},description:a(t.description),path:a(t.blocked_path||t.path)||null,rules:n,toolUseId:a(t.tool_use_id||t.toolUseId)||null}}function y(e={}){const t=Array.isArray(e.rules)?e.rules.filter(o=>o&&o.tool):[];return t.length?t.map(o=>o.content?`${o.tool}(${o.content})`:o.tool):e.tool?[String(e.tool)]:[]}function _(e={}){const t=a(e.tool),o=u(e.input)?e.input:{},n=(r,p=240)=>r.length>p?`${r.slice(0,p-1)}…`:r;let s,i;if(t==="Bash")s="Run a command",i=n(a(o.command).trim()||a(e.description)||"a shell command");else if(t==="Edit"||t==="MultiEdit"||t==="NotebookEdit")s="Edit a file",i=a(o.file_path||o.notebook_path||e.path)||"a file";else if(t==="Write"){s="Write a file";const r=a(o.file_path||e.path)||"a file",p=a(o.content).length;i=p?`${r} (${p.toLocaleString()} chars)`:r}else if(/^mcp__/.test(t))s="Use a connected server",i=t.replace(/^mcp__/,"").replace(/__/," › ");else{s=`Use ${e.displayName||t||"a tool"}`;let r="";try{r=JSON.stringify(o)}catch{r=""}i=a(e.description)||(r&&r!=="{}"?n(r,200):t)}const c=y(e),l=Array.isArray(e.rules)?e.rules.filter(r=>r?.content):[],d=l.length&&l.some(r=>r.content!==i)?l.map(r=>r.content).join(", "):c.length&&!l.length?`every ${t} call`:null;return{title:s,detail:i,scope:d,description:a(e.description)||null}}function m(e,t=""){return e===f.ALLOW?{behavior:"allow",scope:"once"}:e===f.ALLOW_CHAT?{behavior:"allow",scope:"chat"}:{behavior:"deny",scope:"once",...t?{message:String(t)}:{}}}function b(e){return u(e)&&e.behavior==="allow"}function N(e,t){const o=new Set(Array.isArray(e)?e:[]);for(const n of y(t))o.add(n);return[...o].sort()}function E(e,t){const o=y(t);if(!o.length)return null;const n=new Set(Array.isArray(e)?e:[]);return o.every(s=>n.has(s))?m(f.ALLOW):null}function k(e,t,o={}){const n=u(o)?o:{},s=b(t);let i;if(s){if(i={behavior:"allow",updatedInput:u(n.input)?n.input:{}},t.scope==="chat"){const c=(Array.isArray(n.permission_suggestions)?n.permission_suggestions:[]).filter(l=>u(l)&&l.type==="addRules"&&l.behavior!=="deny"&&Array.isArray(l.rules)&&l.rules.length).map(l=>({type:"addRules",rules:l.rules,behavior:"allow",destination:"session"}));c.length&&(i.updatedPermissions=c)}}else i={behavior:"deny",message:a(t?.message)||"The user declined this action in ChatPanel. Continue without it, or explain what it was for and ask."};return{type:"control_response",response:{subtype:"success",request_id:String(e),response:i}}}function R(e,t){const{detail:o}=_(e),n=b(t),s=n&&t.scope==="chat"?" for this chat":"";return`${n?"Allowed":"Declined"}${s}: ${o}`}function L(e){return e==="Bash"?"code":/^(Edit|MultiEdit|NotebookEdit)$/.test(String(e))?"pencil":e==="Write"?"file":/^mcp__/.test(String(e))?"plug":"bot"}function T(){const e=new Map;async function t(o,{convId:n=null,confirm:s,agentName:i="The agent"}={}){const c=E(e.get(n)||[],o);if(c)return c;const{title:l,detail:d,scope:r,description:p}=_(o),S=[d,p&&p!==d?p:"",r?`“Allow for this chat” also covers: ${r}`:""].filter(Boolean).join(`
2
+ `);let h;try{if(typeof s!="function")throw new Error("no card");h=await s(S,{title:`${i} asks — ${l.toLowerCase()}?`,iconName:L(o.tool),scopeLabel:"Allow for this chat"})}catch(g){return m(f.DENY,`ChatPanel could not show the permission card (${g?.message||g}).`)}return h==="site"||h==="always"?(e.set(n,N(e.get(n)||[],o)),m(f.ALLOW_CHAT)):m(h==="allow"?f.ALLOW:f.DENY)}return{ask:t,forget(o){e.delete(o)},standing(o){return e.get(o)||[]},provider({convId:o=null,confirm:n,agentName:s="The agent"}={}){return{id:"permission",specs:[w()],execute:async(i,c)=>JSON.stringify(await t(c&&typeof c=="object"?c:{},{convId:o,confirm:n,agentName:s}))}}}}export{f as PERMISSION_ANSWERS,x as PERMISSION_EVENT,O as PERMISSION_TIMEOUT_MS,A as PERMISSION_TOOL_NAME,k as claudePermissionResponse,T as createPermissionDesk,_ as describePermission,$ as isPermissionTool,b as permissionAllowed,m as permissionAnswer,L as permissionIcon,y as permissionKeys,R as permissionLine,P as permissionRequestFromClaude,w as permissionToolSpec,E as recallPermission,N as rememberPermission};
@@ -1 +1 @@
1
- const c=[{tool:"uv",match:/^(uvx?|uv-?run)$/,ships:"is part of uv, the Python package runner from Astral",install:{mac:"brew install uv",linux:"curl -LsSf https://astral.sh/uv/install.sh | sh",windows:"winget install astral-sh.uv"}},{tool:"Node.js",match:/^(node|npx|npm|corepack|pnpm|yarn)$/,ships:"ships with Node.js",install:{mac:"brew install node",linux:"nvm install --lts (or the package from https://nodejs.org)",windows:"winget install OpenJS.NodeJS.LTS"}},{tool:"Python",match:/^(python[0-9.]*|py|pip[0-9.]*)$/,ships:"ships with Python 3",install:{mac:"brew install python",linux:"sudo apt install python3 python3-pip (or your distribution's package)",windows:"winget install Python.Python.3.12"}},{tool:"pipx",match:/^pipx$/,ships:"is pipx, the isolated installer for Python apps",install:{mac:"brew install pipx",linux:"python3 -m pip install --user pipx && python3 -m pipx ensurepath",windows:"python -m pip install --user pipx && python -m pipx ensurepath"}},{tool:"Docker",match:/^docker$/,ships:"is the Docker CLI",install:{mac:"brew install --cask docker (Docker Desktop), then start it once",linux:"https://docs.docker.com/engine/install/",windows:"winget install Docker.DockerDesktop, then start it once"}},{tool:"Bun",match:/^bunx?$/,ships:"ships with Bun",install:{mac:"curl -fsSL https://bun.sh/install | bash",linux:"curl -fsSL https://bun.sh/install | bash",windows:'powershell -c "irm bun.sh/install.ps1 | iex"'}},{tool:"Deno",match:/^deno$/,ships:"is Deno",install:{mac:"brew install deno",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"irm https://deno.land/install.ps1 | iex"}}];function p(t){const s=String(t||"");return/mac|darwin|iphone|ipad/i.test(s)?"mac":/win/i.test(s)?"windows":/linux|x11|android|freebsd/i.test(s)?"linux":""}const d=t=>String(t||"").trim().split(/[\\/]/).pop().replace(/\.(exe|cmd|bat|ps1)$/i,"").toLowerCase();function o(t,{platform:s=""}={}){const n=d(t);if(!n)return null;const i=p(s),e=c.find(h=>h.match.test(n))||null,a=e?i?e.install[i]:`macOS: ${e.install.mac} · Linux: ${e.install.linux} · Windows: ${e.install.windows}`:"",l=i==="windows"?`"where ${n}" prints it`:i?`"which ${n}" prints it`:`"which ${n}" (macOS/Linux) or "where ${n}" (Windows) prints it`;return{command:n,tool:e?e.tool:null,ships:e?e.ships:"",install:a,verify:`${n} --version`,fullPath:l}}function w(t,{platform:s=""}={}){const n=o(t,{platform:s}),i=String(t||"").trim();if(!n)return"No command to run.";const e=n.tool?`"${i}" ${n.ships}, and it is not installed here (or not on the PATH the bridge sees).`:`Couldn't find "${i}" — it is not installed, or not on the PATH the bridge sees.`,a=n.tool?` Install it: ${n.install} — then open a new terminal, check that "${n.verify}" works, and try again.`:` Install it, then open a new terminal, check that "${n.verify}" works, and try again.`;return`${e}${a} Already installed? Enter its full path instead: ${n.fullPath}.`}const u=[/Couldn'?t find "([^"]+)"/i,/\bspawn (\S+) ENOENT\b/,/'([^']+)' is not recognized as an internal or external command/i,/The term '([^']+)' is not recognized/i,/command not found:\s*(\S+)/i,/(?:^|[\n:]\s*)([\w./\\-]+): (?:command )?not found/i];function r(t){const s=String(t||"");for(const n of u){const i=n.exec(s);if(i&&i[1])return i[1]}return""}const m=[{id:"missing-shebang",test:t=>/(import|const|export):\s*(command not found|not found)/i.test(t)||/syntax error near unexpected token/i.test(t)&&/command not found/i.test(t),explain:t=>({summary:`${t||"This MCP server"} cannot start: its executable is missing a shebang.`,detail:"The package's entry file is JavaScript but has no `#!/usr/bin/env node` first line, so the shell tries to run it as a shell script. That is a bug in the published package, not in your setup — nothing you configure here can fix it.",fix:"Report it to the package author, pin an earlier version that worked, or use a different server.",blame:"package"})},{id:"runtime-missing",test:t=>!!r(t),explain:(t,{text:s,platform:n}={})=>{const i=r(s),e=o(i,{platform:n}),a=e?.tool?`"${i}" ${e.ships}.`:`"${i}" is the command this server is launched with.`;return{summary:`"${i}" is not installed, or not on the PATH the bridge sees${t?` — ${t} cannot start`:""}.`,detail:`${a} Nothing about the server itself has been checked yet: the launcher has to exist before it can be tried.`,fix:e?.tool?`Install it: ${e.install} — then open a new terminal, check that "${e.verify}" works, and test again. Already installed? Enter its full path instead: ${e.fullPath}.`:`Install it, then open a new terminal, check that "${e?.verify||`${i} --version`}" works, and test again. Already installed? Enter its full path instead: ${e?.fullPath||"which/where prints it"}.`,blame:"setup",command:i}}},{id:"not-found",test:t=>/npm ERR!.*(404|E404)|could not determine executable/i.test(t),explain:t=>({summary:`${t||"The package"} could not be found or has no runnable command.`,detail:"npm resolved nothing to run for this package name and version.",fix:"Check the package name and version, and that the registry in use publishes it.",blame:"config"})},{id:"no-bridge",test:t=>/can'?t reach the chatpanel bridge|ECONNREFUSED.*4319/i.test(t),explain:()=>({summary:"The ChatPanel Bridge is not running.",detail:"Local MCP servers are launched by the bridge, so nothing can start without it.",fix:"Install ChatPanel — the gateway, which brings the bridge (`npm i -g @chatpanel/gateway`, then `chatpanel-gateway --install`; or https://dl.chatpanel.net/install.sh) — or start a bridge with `npx @chatpanel/bridge`, then try again.",blame:"setup"})},{id:"node-version",test:t=>/requires node|unsupported engine|SyntaxError: Unexpected token '\?\?'/i.test(t),explain:t=>({summary:`${t||"This server"} needs a newer Node than the one launching it.`,detail:"The process started but failed on syntax its Node version does not support.",fix:"Upgrade Node, or run the server with a version manager that selects a newer one.",blame:"setup"})}];function g(t,{packageName:s="",platform:n=""}={}){const i=String(t||"");if(!i.trim())return null;for(const e of m)if(e.test(i))return{id:e.id,...e.explain(s,{text:i,platform:n}),raw:i};return null}function x(t=[]){for(const s of t){const n=String(s);if(!n.startsWith("-")&&!(n==="npx"||n==="node"))return n}return""}const f=/\b(session (not found|expired|invalid|unknown)|invalid session|no (valid )?session|not initialized|before initialization|initialization was (not )?complete|-32002)\b/i;function b(t,{status:s}={}){if(s===404)return!0;const n=String(t||"");return n?/\bHTTP 404\b/.test(n)?!0:f.test(n):!1}export{g as explainMcpError,o as installHintFor,b as isStaleMcpSession,r as missingCommandIn,w as missingCommandMessage,p as normalizePlatform,x as packageFromArgs};
1
+ const c=[{tool:"uv",match:/^(uvx?|uv-?run)$/,ships:"is part of uv, the Python package runner from Astral",install:{mac:"brew install uv",linux:"curl -LsSf https://astral.sh/uv/install.sh | sh",windows:"winget install astral-sh.uv"}},{tool:"Node.js",match:/^(node|npx|npm|corepack|pnpm|yarn)$/,ships:"ships with Node.js",install:{mac:"brew install node",linux:"nvm install --lts (or the package from https://nodejs.org)",windows:"winget install OpenJS.NodeJS.LTS"}},{tool:"Python",match:/^(python[0-9.]*|py|pip[0-9.]*)$/,ships:"ships with Python 3",install:{mac:"brew install python",linux:"sudo apt install python3 python3-pip (or your distribution's package)",windows:"winget install Python.Python.3.12"}},{tool:"pipx",match:/^pipx$/,ships:"is pipx, the isolated installer for Python apps",install:{mac:"brew install pipx",linux:"python3 -m pip install --user pipx && python3 -m pipx ensurepath",windows:"python -m pip install --user pipx && python -m pipx ensurepath"}},{tool:"Docker",match:/^docker$/,ships:"is the Docker CLI",install:{mac:"brew install --cask docker (Docker Desktop), then start it once",linux:"https://docs.docker.com/engine/install/",windows:"winget install Docker.DockerDesktop, then start it once"}},{tool:"Bun",match:/^bunx?$/,ships:"ships with Bun",install:{mac:"curl -fsSL https://bun.sh/install | bash",linux:"curl -fsSL https://bun.sh/install | bash",windows:'powershell -c "irm bun.sh/install.ps1 | iex"'}},{tool:"Deno",match:/^deno$/,ships:"is Deno",install:{mac:"brew install deno",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"irm https://deno.land/install.ps1 | iex"}}];function p(t){const s=String(t||"");return/mac|darwin|iphone|ipad/i.test(s)?"mac":/win/i.test(s)?"windows":/linux|x11|android|freebsd/i.test(s)?"linux":""}const d=t=>String(t||"").trim().split(/[\\/]/).pop().replace(/\.(exe|cmd|bat|ps1)$/i,"").toLowerCase();function o(t,{platform:s=""}={}){const n=d(t);if(!n)return null;const i=p(s),e=c.find(h=>h.match.test(n))||null,a=e?i?e.install[i]:`macOS: ${e.install.mac} · Linux: ${e.install.linux} · Windows: ${e.install.windows}`:"",l=i==="windows"?`"where ${n}" prints it`:i?`"which ${n}" prints it`:`"which ${n}" (macOS/Linux) or "where ${n}" (Windows) prints it`;return{command:n,tool:e?e.tool:null,ships:e?e.ships:"",install:a,verify:`${n} --version`,fullPath:l}}function w(t,{platform:s=""}={}){const n=o(t,{platform:s}),i=String(t||"").trim();if(!n)return"No command to run.";const e=n.tool?`"${i}" ${n.ships}, and it is not installed here (or not on the PATH the bridge sees).`:`Couldn't find "${i}" — it is not installed, or not on the PATH the bridge sees.`,a=n.tool?` Install it: ${n.install} — then open a new terminal, check that "${n.verify}" works, and try again.`:` Install it, then open a new terminal, check that "${n.verify}" works, and try again.`;return`${e}${a} Already installed? Enter its full path instead: ${n.fullPath}.`}const u=[/Couldn'?t find "([^"]+)"/i,/\bspawn (\S+) ENOENT\b/,/'([^']+)' is not recognized as an internal or external command/i,/The term '([^']+)' is not recognized/i,/command not found:\s*(\S+)/i,/(?:^|[\n:]\s*)([\w./\\-]+): (?:command )?not found/i];function r(t){const s=String(t||"");for(const n of u){const i=n.exec(s);if(i&&i[1])return i[1]}return""}const m=[{id:"missing-shebang",test:t=>/(import|const|export):\s*(command not found|not found)/i.test(t)||/syntax error near unexpected token/i.test(t)&&/command not found/i.test(t),explain:t=>({summary:`${t||"This MCP server"} cannot start: its executable is missing a shebang.`,detail:"The package's entry file is JavaScript but has no `#!/usr/bin/env node` first line, so the shell tries to run it as a shell script. That is a bug in the published package, not in your setup — nothing you configure here can fix it.",fix:"Report it to the package author, pin an earlier version that worked, or use a different server.",blame:"package"})},{id:"runtime-missing",test:t=>!!r(t),explain:(t,{text:s,platform:n}={})=>{const i=r(s),e=o(i,{platform:n}),a=e?.tool?`"${i}" ${e.ships}.`:`"${i}" is the command this server is launched with.`;return{summary:`"${i}" is not installed, or not on the PATH the bridge sees${t?` — ${t} cannot start`:""}.`,detail:`${a} Nothing about the server itself has been checked yet: the launcher has to exist before it can be tried.`,fix:e?.tool?`Install it: ${e.install} — then open a new terminal, check that "${e.verify}" works, and test again. Already installed? Enter its full path instead: ${e.fullPath}.`:`Install it, then open a new terminal, check that "${e?.verify||`${i} --version`}" works, and test again. Already installed? Enter its full path instead: ${e?.fullPath||"which/where prints it"}.`,blame:"setup",command:i}}},{id:"not-found",test:t=>/npm ERR!.*(404|E404)|could not determine executable/i.test(t),explain:t=>({summary:`${t||"The package"} could not be found or has no runnable command.`,detail:"npm resolved nothing to run for this package name and version.",fix:"Check the package name and version, and that the registry in use publishes it.",blame:"config"})},{id:"no-bridge",test:t=>/can'?t reach the chatpanel bridge|ECONNREFUSED.*4319/i.test(t),explain:()=>({summary:"The ChatPanel Bridge is not running.",detail:"Local MCP servers are launched by the bridge, so nothing can start without it.",fix:"Install ChatPanel — the gateway, which brings the bridge (`npm i -g @chatpanel/gateway --ignore-scripts`, then `chatpanel-gateway --install`; or https://dl.chatpanel.net/install.sh) — or start a bridge with `npx @chatpanel/bridge`, then try again.",blame:"setup"})},{id:"node-version",test:t=>/requires node|unsupported engine|SyntaxError: Unexpected token '\?\?'/i.test(t),explain:t=>({summary:`${t||"This server"} needs a newer Node than the one launching it.`,detail:"The process started but failed on syntax its Node version does not support.",fix:"Upgrade Node, or run the server with a version manager that selects a newer one.",blame:"setup"})}];function g(t,{packageName:s="",platform:n=""}={}){const i=String(t||"");if(!i.trim())return null;for(const e of m)if(e.test(i))return{id:e.id,...e.explain(s,{text:i,platform:n}),raw:i};return null}function x(t=[]){for(const s of t){const n=String(s);if(!n.startsWith("-")&&!(n==="npx"||n==="node"))return n}return""}const f=/\b(session (not found|expired|invalid|unknown)|invalid session|no (valid )?session|not initialized|before initialization|initialization was (not )?complete|-32002)\b/i;function b(t,{status:s}={}){if(s===404)return!0;const n=String(t||"");return n?/\bHTTP 404\b/.test(n)?!0:f.test(n):!1}export{g as explainMcpError,o as installHintFor,b as isStaleMcpSession,r as missingCommandIn,w as missingCommandMessage,p as normalizePlatform,x as packageFromArgs};
@@ -1 +1 @@
1
- import{EventError as A}from"./event.js";import{normalizeGrant as b}from"./sandbox-grant.js";const y=Object.freeze(["none","process","container","kubernetes"]),E=Object.freeze(["open","allowlist","none","gateway"]),_=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),x=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),h=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]})}),R=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),u=e=>!!e&&typeof e=="object"&&!Array.isArray(e),g=e=>Array.isArray(e)&&e.every(o=>typeof o=="string"&&o.length>0),c=(e,o)=>{if(!e)throw new A("SHAPE",o)},f=e=>[...new Set(e)];function O(e){c(u(e),"kit: must be an object"),c(typeof e.id=="string"&&e.id.length>0,"kit: id required"),c(u(e.network)&&E.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${E.join(", ")}`),c(g(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),c(g(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),c(u(e.filesystem),`kit ${e.id}: filesystem required`);for(const o of["allowWrite","denyWrite","allowRead","denyRead"])c(g(e.filesystem[o]||[]),`kit ${e.id}: filesystem.${o} must be string[]`);return c(g(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&c(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&c(Array.isArray(e.credentials)&&e.credentials.every(o=>u(o)&&typeof o.name=="string"&&typeof o.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:f(e.network.allowedDomains||[]),deniedDomains:f(e.network.deniedDomains||[])},filesystem:{allowWrite:f(e.filesystem.allowWrite),denyWrite:f(e.filesystem.denyWrite||[]),allowRead:f(e.filesystem.allowRead||[]),denyRead:f(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:u(e.limits)?{...e.limits}:{}}}import{normalizeGrant as M,mergeGrants as k,parseHostList as q}from"./sandbox-grant.js";function N({engine:e="custom",cwd:o,mode:t="open",extraHosts:r=[],extraWrite:n=[],extraDenyRead:s=[],grant:l=null}={}){const d=h[e]||h.custom;c(typeof o=="string"&&o.length>0,"kit: cwd required");const a=b(l);return O({id:`${e}:${t}`,kind:"process",network:{mode:t,allowedDomains:t==="open"?["*"]:t==="none"?[]:f([...d.hosts,...R,...r,...a.hosts]),deniedDomains:[]},filesystem:{allowWrite:f([o,...x,...d.write,...n,...a.write.filter(i=>!_.some(p=>i===p||i.startsWith(`${p}/`)))]),denyWrite:[],allowRead:[o],denyRead:f([..._,...s])}})}function z(e,{loopback:o=[],home:t="",platform:r="darwin"}={}){const n=O(e),s=d=>t&&d.startsWith("~")?t+d.slice(1):d,l=n.network.mode==="none"?[]:o.map(d=>`127.0.0.1:${d}`);return{network:{allowedDomains:f([...n.network.allowedDomains,...l]),deniedDomains:n.network.deniedDomains,allowLocalBinding:r==="darwin"&&l.length>0},filesystem:{denyRead:n.filesystem.denyRead.map(s),allowRead:n.filesystem.allowRead.map(s),allowWrite:n.filesystem.allowWrite.map(s),denyWrite:n.filesystem.denyWrite.map(s)}}}function C({layer:e="none",runtime:o=null,kitId:t=null,mode:r=null,reason:n=null,hosts:s=null}={}){return c(y.includes(e),`sandbox record: layer must be one of ${y.join(", ")}`),{layer:e,runtime:o,kit:t,mode:r,...e==="none"&&n?{reason:n}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function S(e,{platform:o="darwin"}={}){const t=String(e);if(o==="win32"){c(!/[\r\n]/.test(t),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=t;if(t===""||/[ \t\v"]/.test(t)){r='"';for(let n=0;n<t.length;n++){let s=0;for(;n<t.length&&t[n]==="\\";)s++,n++;if(n===t.length){r+="\\".repeat(s*2);break}t[n]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+t[n]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return t===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}const I=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function H(e={},{platform:o="darwin",caBundle:t=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(t)for(const n of I)e[n]||(r[n]=t);if(o==="linux")for(const n of["no_proxy","NO_PROXY"])typeof e[n]=="string"&&(r[n]=e[n].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function L(e,o=[],{platform:t="darwin"}={}){return[e,...o].map(r=>S(r,{platform:t})).join(" ")}const T=/[\\/]+/,m=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),D=e=>/^[a-z]:$/i.test(m(e))||m(e)==="";function w(e,o){const t=m(e),r=m(o);return!!r&&t!==r&&t.startsWith(r+"\\")}function W(e){const o=String(e||"").replace(/\//g,"\\").split("\\");if(o.length<2)return"";const t=o.findIndex(r=>r.toLowerCase()==="node_modules");return(t>0?o.slice(0,t):o.slice(0,-1)).join("\\")}function K({kit:e,files:o=[],home:t}){c(typeof t=="string"&&t.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?t+a.slice(1):a).replace(/\//g,"\\"),n=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(c(!D(i)&&m(i)!==m(t),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),w(i,t)&&n.push(i))}const s=(a,i)=>i.some(p=>m(a)===m(p)||w(a,p)),l=[];for(const a of o){const i=W(a);i&&w(i,t)&&l.push(i)}for(const a of e?.filesystem?.allowRead||[]){const i=r(a);w(i,t)&&l.push(i)}const d=f(l).filter(a=>!s(a,n));return{read:d.filter(a=>!d.some(i=>i!==a&&w(a,i))),write:f(n)}}const j=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function Y({engine:e="custom",home:o,env:t={},base:r={},carry:n=j}={}){c(typeof o=="string"&&o.length>0,"windows env: home required");const s=o.replace(/\//g,"\\"),l=/^[a-z]:/i.test(s)?s.slice(0,2):"",d={USERPROFILE:s,...l?{HOMEDRIVE:l,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(t))typeof i=="string"&&(r[a]!==i||n.includes(a))&&(d[a]=i);return e==="codex"&&!d.CODEX_HOME&&(d.CODEX_HOME=s+"\\.codex"),d}function v(e,o){c(Array.isArray(e),"srt-win argv: must be an array");const t=e.indexOf("exec"),r=t>=0?e.indexOf("--",t+1):-1;c(t>=0&&r>t,"srt-win argv: expected `exec … -- <shell> <command>`");const n=new Set;for(let l=t+1;l<r;l++)e[l]==="--env"&&typeof e[l+1]=="string"&&n.add(e[l+1].split("=")[0].toUpperCase());const s=[];for(const[l,d]of Object.entries(o||{}))c(/^[A-Za-z_][A-Za-z0-9_]*$/.test(l),`srt-win env: bad key ${l}`),c(!/[\r\n]/.test(d),`srt-win env: ${l} holds a newline`),n.has(l.toUpperCase())||s.push("--env",`${l}=${d}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{x as COMMON_WRITE,R as DEVELOPER_HOSTS,h as ENGINE_KITS,E as NETWORK_MODES,y as SANDBOX_LAYERS,_ as SECRET_PATHS,j as WINDOWS_CARRY_KEYS,N as kitFor,k as mergeGrants,M as normalizeGrant,q as parseHostList,H as sandboxEnvOverlay,C as sandboxRecord,L as shellJoin,S as shellQuote,z as toSrtSettings,w as underWindowsHome,O as validateKit,K as windowsGrantsFor,W as windowsInstallRoot,Y as windowsSandboxEnv,v as withSrtWinEnv};
1
+ import{EventError as b}from"./event.js";import{normalizeGrant as A}from"./sandbox-grant.js";const y=Object.freeze(["none","process","container","kubernetes"]),E=Object.freeze(["open","allowlist","none","gateway"]),h=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),x=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),_=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]}),"model-server":Object.freeze({hosts:["huggingface.co","*.huggingface.co","*.hf.co","cdn-lfs.huggingface.co","cas-bridge.xethub.hf.co","dl.chatpanel.net"],write:[]})}),R=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),p=e=>!!e&&typeof e=="object"&&!Array.isArray(e),g=e=>Array.isArray(e)&&e.every(o=>typeof o=="string"&&o.length>0),l=(e,o)=>{if(!e)throw new b("SHAPE",o)},f=e=>[...new Set(e)];function O(e){l(p(e),"kit: must be an object"),l(typeof e.id=="string"&&e.id.length>0,"kit: id required"),l(p(e.network)&&E.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${E.join(", ")}`),l(g(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),l(g(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),l(p(e.filesystem),`kit ${e.id}: filesystem required`);for(const o of["allowWrite","denyWrite","allowRead","denyRead"])l(g(e.filesystem[o]||[]),`kit ${e.id}: filesystem.${o} must be string[]`);return l(g(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&l(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&l(Array.isArray(e.credentials)&&e.credentials.every(o=>p(o)&&typeof o.name=="string"&&typeof o.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:f(e.network.allowedDomains||[]),deniedDomains:f(e.network.deniedDomains||[])},filesystem:{allowWrite:f(e.filesystem.allowWrite),denyWrite:f(e.filesystem.denyWrite||[]),allowRead:f(e.filesystem.allowRead||[]),denyRead:f(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:p(e.limits)?{...e.limits}:{}}}import{normalizeGrant as M,mergeGrants as k,parseHostList as q}from"./sandbox-grant.js";function z({engine:e="custom",cwd:o,mode:t="open",extraHosts:r=[],extraWrite:n=[],extraDenyRead:s=[],grant:c=null}={}){const d=_[e]||_.custom;l(typeof o=="string"&&o.length>0,"kit: cwd required");const a=A(c);return O({id:`${e}:${t}`,kind:"process",network:{mode:t,allowedDomains:t==="open"?["*"]:t==="none"?[]:f([...d.hosts,...R,...r,...a.hosts]),deniedDomains:[]},filesystem:{allowWrite:f([o,...x,...d.write,...n,...a.write.filter(i=>!h.some(u=>i===u||i.startsWith(`${u}/`)))]),denyWrite:[],allowRead:[o],denyRead:f([...h,...s])}})}function N(e,{loopback:o=[],home:t="",platform:r="darwin"}={}){const n=O(e),s=d=>t&&d.startsWith("~")?t+d.slice(1):d,c=n.network.mode==="none"?[]:o.map(d=>`127.0.0.1:${d}`);return{network:{allowedDomains:f([...n.network.allowedDomains,...c]),deniedDomains:n.network.deniedDomains,allowLocalBinding:r==="darwin"&&c.length>0},filesystem:{denyRead:n.filesystem.denyRead.map(s),allowRead:n.filesystem.allowRead.map(s),allowWrite:n.filesystem.allowWrite.map(s),denyWrite:n.filesystem.denyWrite.map(s)}}}function C({layer:e="none",runtime:o=null,kitId:t=null,mode:r=null,reason:n=null,hosts:s=null}={}){return l(y.includes(e),`sandbox record: layer must be one of ${y.join(", ")}`),{layer:e,runtime:o,kit:t,mode:r,...e==="none"&&n?{reason:n}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function S(e,{platform:o="darwin"}={}){const t=String(e);if(o==="win32"){l(!/[\r\n]/.test(t),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=t;if(t===""||/[ \t\v"]/.test(t)){r='"';for(let n=0;n<t.length;n++){let s=0;for(;n<t.length&&t[n]==="\\";)s++,n++;if(n===t.length){r+="\\".repeat(s*2);break}t[n]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+t[n]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return t===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}const I=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function H(e={},{platform:o="darwin",caBundle:t=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(t)for(const n of I)e[n]||(r[n]=t);if(o==="linux")for(const n of["no_proxy","NO_PROXY"])typeof e[n]=="string"&&(r[n]=e[n].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function L(e,o=[],{platform:t="darwin"}={}){return[e,...o].map(r=>S(r,{platform:t})).join(" ")}const T=/[\\/]+/,m=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),D=e=>/^[a-z]:$/i.test(m(e))||m(e)==="";function w(e,o){const t=m(e),r=m(o);return!!r&&t!==r&&t.startsWith(r+"\\")}function j(e){const o=String(e||"").replace(/\//g,"\\").split("\\");if(o.length<2)return"";const t=o.findIndex(r=>r.toLowerCase()==="node_modules");return(t>0?o.slice(0,t):o.slice(0,-1)).join("\\")}function K({kit:e,files:o=[],home:t}){l(typeof t=="string"&&t.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?t+a.slice(1):a).replace(/\//g,"\\"),n=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(l(!D(i)&&m(i)!==m(t),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),w(i,t)&&n.push(i))}const s=(a,i)=>i.some(u=>m(a)===m(u)||w(a,u)),c=[];for(const a of o){const i=j(a);i&&w(i,t)&&c.push(i)}for(const a of e?.filesystem?.allowRead||[]){const i=r(a);w(i,t)&&c.push(i)}const d=f(c).filter(a=>!s(a,n));return{read:d.filter(a=>!d.some(i=>i!==a&&w(a,i))),write:f(n)}}const W=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function v({engine:e="custom",home:o,env:t={},base:r={},carry:n=W}={}){l(typeof o=="string"&&o.length>0,"windows env: home required");const s=o.replace(/\//g,"\\"),c=/^[a-z]:/i.test(s)?s.slice(0,2):"",d={USERPROFILE:s,...c?{HOMEDRIVE:c,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(t))typeof i=="string"&&(r[a]!==i||n.includes(a))&&(d[a]=i);return e==="codex"&&!d.CODEX_HOME&&(d.CODEX_HOME=s+"\\.codex"),d}function Y(e,o){l(Array.isArray(e),"srt-win argv: must be an array");const t=e.indexOf("exec"),r=t>=0?e.indexOf("--",t+1):-1;l(t>=0&&r>t,"srt-win argv: expected `exec … -- <shell> <command>`");const n=new Set;for(let c=t+1;c<r;c++)e[c]==="--env"&&typeof e[c+1]=="string"&&n.add(e[c+1].split("=")[0].toUpperCase());const s=[];for(const[c,d]of Object.entries(o||{}))l(/^[A-Za-z_][A-Za-z0-9_]*$/.test(c),`srt-win env: bad key ${c}`),l(!/[\r\n]/.test(d),`srt-win env: ${c} holds a newline`),n.has(c.toUpperCase())||s.push("--env",`${c}=${d}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{x as COMMON_WRITE,R as DEVELOPER_HOSTS,_ as ENGINE_KITS,E as NETWORK_MODES,y as SANDBOX_LAYERS,h as SECRET_PATHS,W as WINDOWS_CARRY_KEYS,z as kitFor,k as mergeGrants,M as normalizeGrant,q as parseHostList,H as sandboxEnvOverlay,C as sandboxRecord,L as shellJoin,S as shellQuote,N as toSrtSettings,w as underWindowsHome,O as validateKit,K as windowsGrantsFor,j as windowsInstallRoot,v as windowsSandboxEnv,Y as withSrtWinEnv};
@@ -1 +1 @@
1
- import{randomUUID as u}from"node:crypto";import{relayTimeoutFor as f}from"./relay-timeout.js";import{stripHidden as d}from"./sanitize.js";const o=new Map;let r=null;const s=()=>{throw new Error("no chat is attached to this tool session")};function y(t,n){const e=u(),c={id:e,emit:t,specs:n,pending:new Map,nextId:0};return o.set(e,c),r=e,c}function w(t){return o.get(t)||null}function S(t,n,e){t.emit=n,e&&(t.specs=e),r=t.id}function T(t){for(const n of t.pending.values())n.reject(new Error("chat ended"));t.pending.clear(),t.emit=s}function k(t){const n=o.get(t);if(n){for(const e of n.pending.values())e.reject(new Error("chat ended"));if(o.delete(t),r===t){const e=[...o.keys()];r=e.length?e[e.length-1]:null}}}function v(){return r&&o.get(r)||null}function E(t,n,e){return new Promise((c,a)=>{const p=`t${++t.nextId}`,l=setTimeout(()=>{t.pending.delete(p),a(new Error("tool call timed out"))},f(t.specs,n));t.pending.set(p,{resolve:i=>{clearTimeout(l),c(m(i))},reject:i=>{clearTimeout(l),a(i)}});try{t.emit({type:"tool_request",session:t.id,id:p,name:n,input:e})}catch(i){t.pending.delete(p),clearTimeout(l),a(i)}})}function m(t){if(t==null)return{content:[{type:"text",text:"ok"}]};if(typeof t=="string")return{content:[{type:"text",text:d(t)}]};const n=[];if(t.text&&n.push({type:"text",text:d(String(t.text))}),typeof t.image=="string"){const e=/^data:([^;]+);base64,(.+)$/s.exec(t.image);e&&n.push({type:"image",data:e[2],mimeType:e[1]})}return n.length||n.push({type:"text",text:"ok"}),{content:n}}export{v as activeSession,y as createSession,k as deleteSession,w as getSession,S as rebindSession,E as relayToolCall,T as releaseSession,m as toMcpContent};
1
+ import{randomUUID as f}from"node:crypto";import{relayTimeoutFor as y}from"./relay-timeout.js";import{stripHidden as m}from"./sanitize.js";import{PERMISSION_EVENT as h,PERMISSION_TIMEOUT_MS as x,permissionRequestFromClaude as g,permissionAnswer as d,permissionAllowed as w,permissionLine as S}from"./events/agent-permission.js";const c=new Map;let a=null;const T=()=>{throw new Error("no chat is attached to this tool session")};function C(e,n){const t=f(),o={id:t,emit:e,specs:n,pending:new Map,nextId:0};return c.set(t,o),a=t,o}function _(e){return c.get(e)||null}function b(e,n,t){e.emit=n,t&&(e.specs=t),a=e.id}function v(e){for(const n of e.pending.values())n.reject(new Error("chat ended"));e.pending.clear(),e.emit=T}function N(e){const n=c.get(e);if(n){for(const t of n.pending.values())t.reject(new Error("chat ended"));if(c.delete(e),a===e){const t=[...c.keys()];a=t.length?t[t.length-1]:null}}}function q(){return a&&c.get(a)||null}function u(e,n,t,o){return new Promise((r,i)=>{const p=`t${++e.nextId}`,l=setTimeout(()=>{e.pending.delete(p),o(r,i)},t);e.pending.set(p,{resolve:s=>{clearTimeout(l),r(s)},reject:s=>{clearTimeout(l),i(s)}});try{e.emit({...n,session:e.id,id:p})}catch(s){e.pending.delete(p),clearTimeout(l),i(s)}})}async function A(e,n,t){const o=await u(e,{type:"tool_request",name:n,input:t},y(e.specs,n),(r,i)=>i(new Error("tool call timed out")));return E(o)}async function O(e,n){const t=g(n);let o;try{const r=await u(e,{type:h,...t},x,i=>i(d("deny","Nobody answered the permission prompt in ChatPanel in time.")));o=w(r)?{behavior:"allow",scope:r.scope==="chat"?"chat":"once"}:d("deny",r?.message||"")}catch(r){o=d("deny",`The permission prompt could not reach ChatPanel (${r?.message||r}).`)}try{e.emit({type:"status",text:S(t,o)})}catch{}return o}function E(e){if(e==null)return{content:[{type:"text",text:"ok"}]};if(typeof e=="string")return{content:[{type:"text",text:m(e)}]};const n=[];if(e.text&&n.push({type:"text",text:m(String(e.text))}),typeof e.image=="string"){const t=/^data:([^;]+);base64,(.+)$/s.exec(e.image);t&&n.push({type:"image",data:t[2],mimeType:t[1]})}return n.length||n.push({type:"text",text:"ok"}),{content:n}}export{q as activeSession,C as createSession,N as deleteSession,_ as getSession,b as rebindSession,O as relayPermission,A as relayToolCall,v as releaseSession,E as toMcpContent};
package/src/server.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as we}from"node:http";import A from"node:os";import{randomBytes as ye,randomInt as be,timingSafeEqual as Se}from"node:crypto";import{mkdirSync as ke,writeFileSync as Te,readFileSync as z,existsSync as ve}from"node:fs";import{join as _}from"node:path";import*as Ce from"./engines/claude.js";import*as Ee from"./engines/codex.js";import*as Oe from"./engines/antigravity.js";import{pi as xe,opencode as Ae,kiro as Pe,copilot as $e,deepseek as Ie,hermes as Ne}from"./engines/cli-agents.js";import{connectorsFor as Re}from"./connectors.js";import*as _e from"./engines/custom.js";import{installService as He,uninstallService as Me,serviceStatus as Be,restartService as K}from"./service.js";import{skillIndex as W,listRecords as Ge,readRecord as De,readPackageFile as Ue,skillsHealth as We,quarantinedSkills as Le}from"./skills.js";import{capabilityToolSpecs as je,runCapabilityTool as Je}from"./mcp-capabilities.js";import{createSession as Fe,deleteSession as V,getSession as Y,activeSession as Xe,relayToolCall as ze}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ke,isDefaultWorkdir as Ve,resolveWorkdir as Ye,writeScopeNote as Qe}from"./workdir.js";import{sandbox as Q,runSandboxCli as Ze,withGrant as Z,acceptRefusalReport as qe,liveProcesses as et}from"./sandbox.js";import{gitState as tt,gitDelta as nt}from"./scm.js";import{listConnections as ot,putConnection as rt,removeConnection as at,runEnvFor as it,testConnection as st,secretBackend as q}from"./connections.js";import{worktreeFor as ee,listWorktrees as ct,removeWorktree as lt,withHook as dt,WORKTREE_ROOT as te}from"./worktree.js";import{AGENT_CLIS as ut,enrichPath as ht,enrichAgentEnv as pt,findAgentBin as ne,resolveCommand as mt}from"./env.js";import"./sanitize.js";import{checkForUpdate as ft,selfUpdate as oe,isEmbedded as gt}from"./update.js";import{callLocalMcp as wt,localMcpStatus as yt,signInLocalMcp as bt,signInStatusLocalMcp as St}from"./mcp-local.js";import{assertPublicHttpUrl as re,assertPublicWebUrl as ae}from"./ssrf.js";import{startRun as ie,endRun as L,cancelRun as kt,cancelAll as Tt}from"./runs.js";import{closeWarmPools as vt,warmStatus as Ct}from"./warm.js";import{CompatError as P,anthropicError as j,anthropicStream as Et,chatCompletionStream as Ot,completionStream as xt,createAnthropicMessage as At,createChatCompletion as Pt,createCompletion as $t,createResponse as It,openAIError as b,parseAnthropicMessage as Nt,parseChatCompletion as Rt,parseCompletion as _t,parseResponse as Ht,responseStream as Mt}from"./api-compat.js";import{callerTrust as Bt,isPaired as $,parseExtensionIds as Gt,capRunOptions as Dt,engineHonoursReach as Ut,createPairingStore as Wt,formatPairingCode as Lt}from"./pii/trust.js";const w="0.19.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ce,label:"Claude Code"},codex:{engine:Ee,label:"Codex"},antigravity:{engine:Oe,label:"Antigravity",tools:!1},pi:{engine:xe,label:"Pi"},opencode:{engine:Ae,label:"OpenCode"},hermes:{engine:Ne,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:$e,label:"GitHub Copilot"},deepseek:{engine:Ie,label:"DeepSeek Harness"},custom:{engine:_e,label:"Custom",hidden:!0}};function se(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const jt=Gt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(t){return t.chatpanelTrust||(t.chatpanelTrust=Bt({origin:t.headers.origin||"",hasToken:ue(t),extensionIds:jt})),t.chatpanelTrust}function Jt(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function Ft(t,e){const n=t.headers.origin||"",r=se(n);e.setHeader("Access-Control-Allow-Origin",r?n||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function Xt(t){if(!J.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(n)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function zt(){try{ve(N)&&(S=z(N,"utf8").trim()),S||(S=ye(32).toString("hex"),ke(_(A.homedir(),".chatpanel"),{recursive:!0}),Te(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ce=Wt({random:()=>be(0,1e6)/1e6});function Kt(t){if(!S)return i(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ce.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Vt(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=ce.claim(n?.code);return r.ok?(u("info",`paired a ${I(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${I(t)} caller`),i(e,403,{error:r.reason}))}function Yt(t,e){const n=I(t);return i(e,200,{ok:!0,trust:n,paired:$(n),version:w})}let H=null;async function le(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function de(t,e,n){try{const r=await le(),o=t.method==="POST"?await f(t):{};if(n==="status")return i(e,200,await r.status());if(n==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return n==="pair"?i(e,200,await r.pair()):n==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?i(e,200,await r.update(o)):n==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function ue(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const r=Buffer.from(n),o=Buffer.from(S);return r.length===o.length&&Se(r,o)}const Qt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Zt=new Set(["/debug"]),qt=t=>Zt.has(t);function en(t,e){if(!Xt(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!se(n))return"forbidden origin";const r=t.method==="POST"&&Qt.has(e)||t.method==="GET"&&qt(e);return r&&!(Jt(n)||ue(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!$(I(t))&&!nn.has(e)?tn:null}const tn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",nn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(t,e,n){const r=I(t),o=Dt(n,r);if(!Ut(e,o.reach))return{error:`${$(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=$(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function f(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function on(t){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),h=await Re(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:h,...c===!1?{tools:!1}:{}}})),n=gt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await ft(w).catch(()=>({current:w,updateAvailable:!1})),r=await We().catch(()=>null),o=await Q().status().catch(a=>({enabled:!1,reason:a.message}));i(t,200,{ok:!0,version:w,agents:e,update:n,workspace:Ke,sandbox:o,localMcp:yt(),processes:et(),worktrees:te,secretBackend:q(),warm:Ct(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function rn(t,e,n){const{index:r,problems:o}=await W({extraDirs:e,workdir:n});i(t,200,{ok:!0,skills:Ge(r),problems:o})}async function an(t,e,n){i(t,200,{ok:!0,quarantined:await Le(e,n)})}async function sn(t,e,n,r){const{index:o}=await W({extraDirs:n,workdir:r}),a=De(o,e);if(!a)return i(t,404,{ok:!1,error:"unknown skill"});i(t,200,{ok:!0,skill:a})}async function cn(t,e,n,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await Ue(a,e,n);if(s.error)return i(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(t,200,{ok:!0,...s})}async function ln(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function he(t,e=""){const n=await ln();if(e){const r=n.find(o=>o.id===e);return r?i(t,200,r):i(t,404,b(new P(`Model "${e}" not found`,404,"model")))}return i(t,200,{object:"list",data:n})}async function dn(t){try{const e=await oe(w);i(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>K(),400))}catch(e){i(t,400,{ok:!1,error:String(e?.message||e)})}}async function un(t,e){let n;try{n=await f(t)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const r=C[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});const o=F(t,n.agent,n.options||{});if(o.error)return i(e,403,{error:o.error});n.options=o.options,Array.isArray(n.images)&&n.images.length&&u("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
2
+ import{createServer as ye}from"node:http";import P from"node:os";import{randomBytes as be,randomInt as Se,timingSafeEqual as ke}from"node:crypto";import{mkdirSync as Te,writeFileSync as ve,readFileSync as K,existsSync as Ce}from"node:fs";import{join as H}from"node:path";import*as Ee from"./engines/claude.js";import*as Oe from"./engines/codex.js";import*as xe from"./engines/antigravity.js";import{pi as Ae,opencode as Pe,kiro as $e,copilot as Ie,deepseek as Ne,hermes as Re}from"./engines/cli-agents.js";import{connectorsFor as _e}from"./connectors.js";import*as He from"./engines/custom.js";import{installService as Me,uninstallService as Be,serviceStatus as Ge,restartService as V}from"./service.js";import{skillIndex as W,listRecords as De,readRecord as Ue,readPackageFile as We,skillsHealth as Le,quarantinedSkills as je}from"./skills.js";import{capabilityToolSpecs as Je,runCapabilityTool as Fe}from"./mcp-capabilities.js";import{createSession as Xe,deleteSession as Y,getSession as Q,activeSession as ze,relayToolCall as Ke}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ve,isDefaultWorkdir as Ye,resolveWorkdir as Qe,writeScopeNote as Ze}from"./workdir.js";import{sandbox as Z,runSandboxCli as qe,withGrant as q,acceptRefusalReport as et,liveProcesses as tt}from"./sandbox.js";import{gitState as nt,gitDelta as ot}from"./scm.js";import{listConnections as rt,putConnection as at,removeConnection as it,runEnvFor as st,testConnection as ct,secretBackend as ee}from"./connections.js";import{worktreeFor as te,listWorktrees as lt,removeWorktree as dt,withHook as ut,WORKTREE_ROOT as ne}from"./worktree.js";import{AGENT_CLIS as pt,enrichPath as ht,enrichAgentEnv as mt,findAgentBin as oe,resolveCommand as ft}from"./env.js";import"./sanitize.js";import{checkForUpdate as gt,selfUpdate as re,isEmbedded as wt}from"./update.js";import{callLocalMcp as yt,localMcpStatus as bt,signInLocalMcp as St,signInStatusLocalMcp as kt}from"./mcp-local.js";import{assertPublicHttpUrl as ae,assertPublicWebUrl as ie}from"./ssrf.js";import{startRun as se,endRun as L,cancelRun as Tt,cancelAll as vt}from"./runs.js";import{closeWarmPools as Ct,warmStatus as Et}from"./warm.js";import{CompatError as $,anthropicError as j,anthropicStream as Ot,chatCompletionStream as xt,completionStream as At,createAnthropicMessage as Pt,createChatCompletion as $t,createCompletion as It,createResponse as Nt,openAIError as b,parseAnthropicMessage as Rt,parseChatCompletion as _t,parseCompletion as Ht,parseResponse as Mt,responseStream as Bt}from"./api-compat.js";import{callerTrust as Gt,isPaired as I,parseExtensionIds as Dt,capRunOptions as Ut,engineHonoursReach as Wt,createPairingStore as Lt,formatPairingCode as jt}from"./pii/trust.js";const w="0.20.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ee,label:"Claude Code"},codex:{engine:Oe,label:"Codex"},antigravity:{engine:xe,label:"Antigravity",tools:!1},pi:{engine:Ae,label:"Pi"},opencode:{engine:Pe,label:"OpenCode"},hermes:{engine:Re,label:"Hermes"},kiro:{engine:$e,label:"Kiro"},copilot:{engine:Ie,label:"GitHub Copilot"},deepseek:{engine:Ne,label:"DeepSeek Harness"},custom:{engine:He,label:"Custom",hidden:!0}};function ce(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Jt=Dt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gt({origin:n.headers.origin||"",hasToken:pe(n),extensionIds:Jt})),n.chatpanelTrust}function Ft(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Xt(n,e){const t=n.headers.origin||"",r=ce(t);e.setHeader("Access-Control-Allow-Origin",r?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function zt(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const R=H(P.homedir(),".chatpanel","bridge-token");let S="";function Kt(){try{Ce(R)&&(S=K(R,"utf8").trim()),S||(S=be(32).toString("hex"),Te(H(P.homedir(),".chatpanel"),{recursive:!0}),ve(R,S,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const le=Lt({random:()=>Se(0,1e6)/1e6});function Vt(n){if(!S)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=le.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Yt(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=le.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function Qt(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:w})}let M=null;async function de(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(P.homedir(),".chatpanel"),dataDir:H(P.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),M}async function ue(n,e,t){try{const r=await de(),o=n.method==="POST"?await f(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function pe(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(S);return r.length===o.length&&ke(r,o)}const Zt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),qt=new Set(["/debug"]),en=n=>qt.has(n);function tn(n,e){if(!zt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ce(t))return"forbidden origin";const r=n.method==="POST"&&Zt.has(e)||n.method==="GET"&&en(e);return r&&!(Ft(t)||pe(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!on.has(e)?nn:null}const nn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",on=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const r=N(n),o=Ut(t,r);if(!Wt(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}async function rn(n){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),p=await _e(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:p,...c===!1?{tools:!1}:{}}})),t=wt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await gt(w).catch(()=>({current:w,updateAvailable:!1})),r=await Le().catch(()=>null),o=await Z().status().catch(a=>({enabled:!1,reason:a.message}));i(n,200,{ok:!0,version:w,agents:e,update:t,workspace:Ve,sandbox:o,localMcp:bt(),processes:tt(),worktrees:ne,secretBackend:ee(),warm:Et(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function an(n,e,t){const{index:r,problems:o}=await W({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:De(r),problems:o})}async function sn(n,e,t){i(n,200,{ok:!0,quarantined:await je(e,t)})}async function cn(n,e,t,r){const{index:o}=await W({extraDirs:t,workdir:r}),a=Ue(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ln(n,e,t,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await We(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function dn(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function he(n,e=""){const t=await dn();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,b(new $(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function un(n){try{const e=await re(w);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function pn(n,e){let t;try{t=await f(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=F(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
3
3
 
4
- `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=ie(d),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};t.on("close",h),e.on("close",h),e.on("error",h);const g=p=>{s||a(p)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const p=n.options.workspace;if(m=await ee({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(d),e.writableEnded||e.end();return}}const X=m?m.path:Ye(n.options?.workingDir);let E=null;{const p=X,O=!!m||!Ve(n.options?.workingDir),y=Qe(n.agent,n.options?.permissionMode,p);a({type:"workdir",path:p,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${p}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await tt(p),E&&a({type:"scm",phase:"before",...E})}let D=null;if(E||m){const p=Array.isArray(n.options?.grants)?n.options.grants:[],{env:O,connection:y}=it({remote:E?.remote||null,grants:p,branch:m?.branch||null,connectionId:n.options?.connectionId||null});D=dt(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const U={...n.options||{},...m?{workingDir:m.path}:{},...D?{runEnv:D}:{}};let R=null;n.pageTools?.specs?.length&&(R=Fe(g,n.pageTools.specs),U.mcp={url:`http://${k}:${v}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs});try{await Z(U.sandbox,()=>r.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:U,images:Array.isArray(n.images)?n.images:[]},g,{signal:l.signal}))}catch(p){u("error",`${n.agent} chat failed: ${p?.message||p}`),a({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await nt(X,E).catch(()=>null);p&&g({type:"scm",phase:"after",...p})}L(d),R&&V(R.id),e.writableEnded||e.end()}}async function hn(t,e,n){if(t.method==="GET"&&n==="/connections")return i(e,200,{ok:!0,connections:ot(),secretBackend:q()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(t);if(n==="/connections")try{return i(e,200,{ok:!0,connection:rt(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return o?o[2]==="delete"?i(e,200,{ok:at(o[1])}):i(e,200,st(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function pn(t,e,n){if(t.method==="GET"&&n==="/worktrees")return i(e,200,{ok:!0,root:te,worktrees:await ct()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(t);if(n==="/worktrees"){const o=await ee({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(n==="/worktrees/remove"){const o=await lt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function T(t,e,n){const r=C[t.agent];if(!r||r.hidden)throw new P(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new P(o.reason||`${t.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=ie(a),d=()=>s.cancel("disconnected");n.on("close",d);let c="";try{return await Z(t.options?.sandbox,()=>r.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{n.off("close",d),L(a)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
4
+ `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=se(d),l={signal:c.signal,abort:()=>c.cancel("client")},p=()=>{s=!0,c.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const g=h=>{s||a(h)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(m=await te({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(d),e.writableEnded||e.end();return}}const X=m?m.path:Qe(t.options?.workingDir);let E=null;{const h=X,O=!!m||!Ye(t.options?.workingDir),y=Ze(t.agent,t.options?.permissionMode,h);a({type:"workdir",path:h,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${h}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await nt(h),E&&a({type:"scm",phase:"before",...E})}let U=null;if(E||m){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:y}=st({remote:E?.remote||null,grants:h,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=ut(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z=t.approvals===!0,_={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{},approvals:z};let A=null;(t.pageTools?.specs?.length||z)&&(A=Xe(g,t.pageTools?.specs||[]),_.permissionSession=A,t.pageTools?.specs?.length&&(_.mcp={url:`http://${k}:${v}/mcp/${A.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await q(_.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:_,images:Array.isArray(t.images)?t.images:[]},g,{signal:l.signal}))}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),a({type:"error",error:h?.message||String(h)})}finally{if(!s){const h=await ot(X,E).catch(()=>null);h&&g({type:"scm",phase:"after",...h})}L(d),A&&Y(A.id),e.writableEnded||e.end()}}async function hn(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:rt(),secretBackend:ee()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:at(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return o?o[2]==="delete"?i(e,200,{ok:it(o[1])}):i(e,200,ct(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function mn(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ne,worktrees:await lt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/worktrees"){const o=await te({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(t==="/worktrees/remove"){const o=await dt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function T(n,e,t){const r=C[n.agent];if(!r||r.hidden)throw new $(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new $(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=se(a),d=()=>s.cancel("disconnected");t.on("close",d);let c="";try{return await q(n.options?.sandbox,()=>r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{t.off("close",d),L(a)}}function B(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5
 
6
- `)}function B(t,e,n){t.writableEnded||t.write(`event: ${e}
7
- data: ${JSON.stringify(n)}
6
+ `)}function G(n,e,t){n.writableEnded||n.write(`event: ${e}
7
+ data: ${JSON.stringify(t)}
8
8
 
9
- `)}async function G(t,e,n,r){try{const o=n(await f(t)),a=F(t,o.agent,o.options||{});if(a.error)throw new P(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${o.message}`):o)),null}}async function mn(t,e){const n=await G(t,e,Rt,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,Pt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=Ot(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function fn(t,e){const n=await G(t,e,_t,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,$t(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=xt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function gn(t,e){const n=await G(t,e,Ht,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,It(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=Mt(n.requestedModel,o=>B(e,o.type,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...b(o)};B(e,"error",a)}e.end()}async function wn(t,e){const n=await G(t,e,Nt,j);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,At(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,j(o))}M(e);const r=Et(n.requestedModel,(o,a)=>B(e,o,a));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){B(e,"error",j(o))}e.end()}async function yn(t,e){let n={};try{n=await f(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?kt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function pe(t,e,n){let r;try{r=await f(t)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?Y(n):Xe(),a=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:w}});const d=je();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await Je(r.params?.name,r.params?.arguments||{});if(c)return a(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await ze(o,r.params?.name,r.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function bn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=n.server||{},o=n.message;if(!r.command||!o)return i(e,400,{error:"need server.command and message"});try{const a=await wt({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Sn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=n.server||{};if(!r.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 o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return i(e,200,n.status?St(o):await bt(o))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function kn(t,e){let n;try{n=await f(t)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:r,headers:o,message:a}=n||{};if(!r||!a)return i(e,400,{error:"need url and message"});let s;try{s=re(r)}catch(h){return i(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[h,g]of Object.entries(o)){const m=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(d[h]=String(g))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{h.url&&re(h.url)}catch(m){return i(e,400,{error:String(m?.message||m)})}const g=await h.text().catch(()=>"");return i(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:g})}catch(h){const g=h?.name==="AbortError"?"timed out":String(h?.message||h);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${g}`})}finally{clearTimeout(l)}}const me=256*1024,Tn=5,vn=8e3;async function Cn(t){let e=ae(t);const n=new AbortController,r=setTimeout(()=>n.abort(),vn);try{for(let o=0;o<=Tn;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:n.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${w} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ae(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:xn(await En(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function En(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,me);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(o+=s.byteLength,r+=n.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=me))break}}finally{try{await e.cancel()}catch{}}return r}function On(t){return String(t).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,n)=>{try{return String.fromCodePoint(+n)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,n)=>{try{return String.fromCodePoint(parseInt(n,16))}catch{return""}})}function xn(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?On(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function An(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=n&&n.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await Cn(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Pn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=Y(n.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(n.id);return o?(r.pending.delete(n.id),o.resolve(n.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function $n(t,e){let n;try{n=await f(t)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const r=C[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});const o=String(n.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=n.model||"",s=F(t,n.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=String(n.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function In(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=C[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(n.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Nn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(n.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=mt(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}const fe=we(async(t,e)=>{if(Ft(t,e),t.method==="OPTIONS")return e.writeHead(204),e.end();let n;try{n=new URL(t.url,`http://${t.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=en(t,n.pathname);if(r)return i(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return on(e);const o=n.searchParams.getAll("dir"),a=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return rn(e,o,a);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return an(e,o,a);if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?sn(e,decodeURIComponent(s),o,a):cn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,a)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return hn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return pn(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return he(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return he(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:w,agents:Object.fromEntries(ut.map(d=>[d,s?ne(d)||null:!!ne(d)])),...s?{home:A.homedir(),path:process.env.PATH}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return un(t,e);if(t.method==="POST"&&n.pathname==="/pair")return Vt(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return Kt(e);if(t.method==="POST"&&n.pathname==="/whoami")return Yt(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return mn(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return fn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return gn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return wn(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return pe(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const s=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return pe(t,e,s);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return V(s),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return de(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return de(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return yn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return Pn(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await f(t)}catch{s=null}const d=qe(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return bn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local/signin")return Sn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return kn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return An(t,e);if(t.method==="POST"&&n.pathname==="/complete")return $n(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return In(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return Nn(t,e);if(t.method==="POST"&&n.pathname==="/update")return dn(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Rn(t){let e="";const n=[];let r=!1,o=!1;const a=()=>{o&&!r&&!n.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;n.length;){const d=n.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
9
+ `)}async function D(n,e,t,r){try{const o=t(await f(n)),a=F(n,o.agent,o.options||{});if(a.error)throw new $(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new $(`Bad JSON: ${o.message}`):o)),null}}async function fn(n,e){const t=await D(n,e,_t,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,$t(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=xt(t.requestedModel,o=>x(e,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function gn(n,e){const t=await D(n,e,Ht,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,It(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=At(t.requestedModel,o=>x(e,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function wn(n,e){const t=await D(n,e,Mt,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,Nt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=Bt(t.requestedModel,o=>G(e,o.type,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...b(o)};G(e,"error",a)}e.end()}async function yn(n,e){const t=await D(n,e,Rt,j);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,Pt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,j(o))}B(e);const r=Ot(t.requestedModel,(o,a)=>G(e,o,a));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){G(e,"error",j(o))}e.end()}async function bn(n,e){let t={};try{t=await f(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?Tt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function me(n,e,t){let r;try{r=await f(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?Q(t):ze(),a=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:w}});const d=Je();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await Fe(r.params?.name,r.params?.arguments||{});if(c)return a(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await Ke(o,r.params?.name,r.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Sn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{},o=t.message;if(!r.command||!o)return i(e,400,{error:"need server.command and message"});try{const a=await yt({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function kn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{};if(!r.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 o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return i(e,200,t.status?kt(o):await St(o))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function Tn(n,e){let t;try{t=await f(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:a}=t||{};if(!r||!a)return i(e,400,{error:"need url and message"});let s;try{s=ae(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,g]of Object.entries(o)){const m=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(d[p]=String(g))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{p.url&&ae(p.url)}catch(m){return i(e,400,{error:String(m?.message||m)})}const g=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:g})}catch(p){const g=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${g}`})}finally{clearTimeout(l)}}const fe=256*1024,vn=5,Cn=8e3;async function En(n){let e=ie(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Cn);try{for(let o=0;o<=vn;o++){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/${w} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ie(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:An(await On(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function On(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,fe);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(o+=s.byteLength,r+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=fe))break}}finally{try{await e.cancel()}catch{}}return r}function xn(n){return String(n).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/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 An(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?xn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Pn(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await En(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function $n(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=Q(t.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function In(n,e){let t;try{t=await f(n)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=F(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=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 c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function Nn(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Rn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(t.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=ft(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}const ge=ye(async(n,e)=>{if(Xt(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 r=tn(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return rn(e);const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return an(e,o,a);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return sn(e,o,a);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),d=s.indexOf("/file/");return d===-1?cn(e,decodeURIComponent(s),o,a):ln(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return hn(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return mn(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return he(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return he(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:w,agents:Object.fromEntries(pt.map(d=>[d,s?oe(d)||null:!!oe(d)])),...s?{home:P.homedir(),path:process.env.PATH}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return pn(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Yt(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Vt(e);if(n.method==="POST"&&t.pathname==="/whoami")return Qt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return fn(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return gn(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return wn(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return yn(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return me(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 me(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return Y(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ue(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ue(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return bn(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return $n(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await f(n)}catch{s=null}const d=et(s||{});return e.writeHead(d?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return Sn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return kn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Tn(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Pn(n,e);if(n.method==="POST"&&t.pathname==="/complete")return In(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Nn(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Rn(n,e);if(n.method==="POST"&&t.pathname==="/update")return un(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function _n(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;t.length;){const d=t.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
10
10
  `)}catch(l){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(l?.message||l)}})+`
11
11
  `)}}r=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
12
- `))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&n.push(l)}s()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function _n(){ht(),pt(),zt(),fe.on("error",t=>{t&&t.code==="EADDRINUSE"&&(u("error",`Port ${v} 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)),u("error",`bridge server error: ${t?.message||t}`),process.exit(1)});for(const t of["SIGINT","SIGTERM"])process.on(t,()=>{const e=Tt("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=vt("shutdown");n&&u("info",`shutdown: closed ${n} warm agent process${n===1?"":"es"}`),Q().close(),setTimeout(()=>process.exit(0),e||n?300:0).unref?.(),!e&&!n&&process.exit(0)});fe.listen(v,k,async()=>{u("info",`listening on http://${k}:${v}`),J.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:t,label:e,hidden:n}]of Object.entries(C)){if(n)continue;const r=await t.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),le().then(t=>t.startIfConfigured()).then(t=>{t?.skipped||(t?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${t?.error||"unknown error"}`))}).catch(t=>u("error",`channels: ${t?.message||t}`))})}function Hn(){console.log(`ChatPanel Bridge v${w}
12
+ `))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Hn(){ht(),mt(),Kt(),ge.on("error",n=>{n&&n.code==="EADDRINUSE"&&(u("error",`Port ${v} 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)),u("error",`bridge server error: ${n?.message||n}`),process.exit(1)});for(const n of["SIGINT","SIGTERM"])process.on(n,()=>{const e=vt("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const t=Ct("shutdown");t&&u("info",`shutdown: closed ${t} warm agent process${t===1?"":"es"}`),Z().close(),setTimeout(()=>process.exit(0),e||t?300:0).unref?.(),!e&&!t&&process.exit(0)});ge.listen(v,k,async()=>{u("info",`listening on http://${k}:${v}`),J.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:n,label:e,hidden:t}]of Object.entries(C)){if(t)continue;const r=await n.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),de().then(n=>n.startIfConfigured()).then(n=>{n?.skipped||(n?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${n?.error||"unknown error"}`))}).catch(n=>u("error",`channels: ${n?.message||n}`))})}function Mn(){console.log(`ChatPanel Bridge v${w}
13
13
 
14
14
  Usage:
15
15
  chatpanel-bridge start the bridge (foreground) on ${k}:${v}
@@ -21,4 +21,4 @@ Usage:
21
21
  chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
22
22
  chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
23
23
 
24
- Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function Mn(){const t=process.argv,e=(...n)=>n.some(r=>t.includes(r));if(e("--help","-h"))return Hn(),!0;if(e("--version","-v"))return console.log(w),!0;if(e("pair","--pair"))return(async()=>{let n="";try{n=z(N,"utf8").trim()}catch{}const r=`http://${k}:${v}`;try{if(!n)throw new Error(`no token at ${N} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${Lt(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(t.includes("sandbox"))return Ze(t.slice(t.indexOf("sandbox")+1)).then(n=>{process.exitCode=n}),!0;if(e("--install")){try{He(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(n){u("error","Install failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--uninstall")){try{Me(),u("info","Removed the login auto-start.")}catch(n){u("error","Uninstall failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--status")){let n=!1;try{n=Be()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const ge=process.argv.indexOf("--mcp-stdio");if(ge>=0){const t=process.argv[ge+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Rn(t)}else process.argv.includes("--update")?(async()=>{try{const t=await oe(w);u("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),K()}catch(t){u("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():Mn()||_n();
24
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function Bn(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return Mn(),!0;if(e("--version","-v"))return console.log(w),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=K(R,"utf8").trim()}catch{}const r=`http://${k}:${v}`;try{if(!t)throw new Error(`no token at ${R} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${jt(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return qe(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{Me(),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{Be(),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=Ge()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const we=process.argv.indexOf("--mcp-stdio");if(we>=0){const n=process.argv[we+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),_n(n)}else process.argv.includes("--update")?(async()=>{try{const n=await re(w);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),V()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():Bn()||Hn();