@chatpanel/bridge 0.53.2 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.53.2",
3
+ "version": "0.54.0",
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": [
@@ -0,0 +1,2 @@
1
+ import u from"node:os";import r from"node:path";import{readFileSync as m,writeFileSync as l,renameSync as d,mkdirSync as f,chmodSync as h,existsSync as A,rmSync as _}from"node:fs";const E=10*6e4,y=()=>typeof process.getuid=="function"?process.getuid():"u",c=()=>process.env.CHATPANEL_AGENT_RUN_FILE||r.join(u.tmpdir(),`chatpanel-agent-run-${y()}`,"token"),g=()=>process.env.CHATPANEL_AGENT_TOKEN_SOURCE||r.join(u.homedir(),".chatpanel","agent-token"),T=()=>`http://127.0.0.1:${Number(process.env.CHATPANEL_GATEWAY_PORT)||4320}`;async function p({fetchImpl:e=fetch,file:t=c()}={}){let n="";try{n=m(g(),"utf8").trim()}catch{return!1}if(!n)return!1;let o;try{const s=await e(`${T()}/v1/agents/run-credential`,{method:"POST",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(5e3)});if(!s.ok)return!1;o=await s.json()}catch{return!1}if(!/^chp_a_[A-Za-z0-9_-]{40,60}$/.test(String(o?.token||"")))return!1;f(r.dirname(t),{recursive:!0,mode:448});try{h(r.dirname(t),448)}catch{}const i=`${t}.${process.pid}.tmp`;return l(i,`${o.token}
2
+ `,{mode:384}),d(i,t),!0}let a=null;function v(){if(a)return;p().catch(()=>{}),a=setInterval(()=>{p().catch(()=>{})},E),a.unref?.();const e=()=>{try{_(c(),{force:!0})}catch{}};process.once("exit",e)}function $(e=c()){return A(e)?{CHATPANEL_AGENT_TOKEN_PATH:e}:{}}export{E as RENEW_MS,$ as agentCredentialEnv,p as renewRunCredential,c as runCredentialFile,v as startRunCredentials};
package/src/env.js CHANGED
@@ -1,2 +1,2 @@
1
- import{isCompiledBinary as jn,hostFacts as hn}from"./events/runtime-host.js";import m from"node:os";import{spawnGroupOpts as U}from"./proc.js";import c from"node:path";import{spawn as X,spawnSync as w}from"node:child_process";import{readdirSync as T,readFileSync as M,existsSync as f}from"node:fs";let z=!1,Q=!1;const R=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function wn(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(f(c.join(o,n))||f(c.join(o,n+".exe"))))}function An(n){const t=v(n);if(t)return t;if(k()){const o=v(n);if(o)return o}return En(n)||null}function et(n){return!!B(n,{probe:"async"})}function v(n){for(const t of dn(n))if(f(t))return t;return null}function $(){return jn(hn())}function ot(n){const t=["--mcp-stdio",n];if($())return{command:process.execPath,args:t};const o=process.argv[1]||c.join(process.cwd(),"src","server.js"),e=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...e,...t]}}const A="CHATPANEL_ENV",W=6e3;function I(n){for(const t of String(n||"").split(/\r?\n/)){const o=t.indexOf(" ");if(o>0&&t.slice(0,o).trim().endsWith(A))return t.slice(o+1).trim()}return""}function Z(n){return/^[\w.+-]+$/.test(String(n||""))}function y(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=m.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function q(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const o=t?["-l","-i","-c"]:["-l","-c"];return w(y(),[...o,n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function _n(n){let t="";for(const o of String(n||"").split(/\r?\n/))o.startsWith("PATH=")&&(t=o.slice(5).trim());return t}function Pn({interactive:n=!0,ask:t=q}={}){const o=I(t(`command -p printf '%s\\t%s\\n' ${A} "$PATH"`,{interactive:n}));return d(o||_n(t("/usr/bin/env",{interactive:n})),process.platform)}const L=1e4,gn=3e5;let N=0,E=L;function k({force:n=!1,now:t=Date.now(),read:o=Pn,env:e=process.env}={}){if(process.platform==="win32"||!n&&(t-N<E||t<g))return!1;N=t;const i=d(e.PATH||"",process.platform),r=Y(j([...o({interactive:!0}),...i])),s=r.length>i.length;return E=s?L:Math.min(E*2,gn),s?(e.PATH=r.join(c.delimiter),!0):!1}function it(){N=0,E=L,h.clear(),g=0,b=H,O=!1}const h=new Map,bn=15e3;function En(n){if(process.platform==="win32"||!Z(n))return"";const t=h.get(n);if(t&&(t.bin||Date.now()-t.at<bn||Date.now()<g))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${A} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let e="";for(const i of[!1,!0]){for(const r of o){const s=q(r,{interactive:i}),l=I(s)||String(s||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&f(l)){e=l;break}}if(e)break}return h.set(n,{bin:e,at:Date.now()}),e}const H=15e3,xn=3e5;let g=0,b=H,O=!1,x=null;function Sn(n,{interactive:t}={}){return new Promise(o=>{let e="",i;try{i=X(y(),[...t?["-l","-i","-c"]:["-l","-c"],n],{stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}})}catch{o("");return}const r=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},W);i.stdout.on("data",s=>{e+=s}),i.on("error",()=>{clearTimeout(r),o("")}),i.on("close",()=>{clearTimeout(r),o(e)})})}const Cn=new RegExp(`${A}=([\\w.+-]+)$`);function J(n){const t=new Map;for(const o of String(n||"").split(/\r?\n/)){const e=o.indexOf(" ");if(e<=0)continue;const i=Cn.exec(o.slice(0,e).trim());i&&t.set(i[1],o.slice(e+1).trim())}return t}function rt({names:n=R,ask:t=Sn,now:o=()=>Date.now()}={}){if(process.platform==="win32"||O)return Promise.resolve(!1);if(x)return x;if(o()<g)return Promise.resolve(!1);const e=j([...n,...h.keys()]).filter(r=>Z(r)&&!v(r)&&!h.get(r)?.bin);if(!e.length)return Promise.resolve(!1);const i=[`command -p printf '%s\\t%s\\n' ${A} "$PATH"`,...e.map(r=>`command -p printf '%s\\t%s\\n' ${A}=${r} "$(command -v ${r} 2>/dev/null)"`)].join("; ");return x=(async()=>{let r=await t(i,{interactive:!0}),s=J(r);if(s.size||(r=await t(i,{interactive:!1}),s=J(r)),!s.size)return O=!0,!0;const l=o();let a=!1;const u=d(I(r),process.platform);u.length&&k({force:!0,now:l,read:()=>u})&&(a=!0);for(const p of e){if(!s.has(p))continue;const _=s.get(p),P=_.startsWith("/")&&f(_)?_:"";(P||v(p))&&(a=!0),h.set(p,{bin:P,at:l})}return a&&(b=H),g=l+b,a||(b=Math.min(b*2,xn)),!0})().catch(()=>!0).finally(()=>{x=null}),x}function st(){g=0,b=H,O=!1,N=0,E=L,K=0;for(const[n,t]of h)t.bin||h.delete(n);for(const[n,t]of S)t.ok||S.delete(n)}function ct({probe:n="sync"}={}){return process.env.CHATPANEL_CLAUDE_PATH?B(process.env.CHATPANEL_CLAUDE_PATH,{probe:n}):B("claude",{probe:n})}function B(n,{probe:t="sync"}={}){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!f(n))return null;const i=c.extname(n).toLowerCase();return!$()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&i===""&&!fn(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const i=Dn(n);return i||(/^[\w.-]+$/.test(n)&&Kn(n,{probe:t})?{kind:"wsl",command:n}:null)}const e=An(n);return e?{kind:"native",bin:e}:null}const Tn="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",Mn="HKCU\\Environment",vn=4e3,In=3e5;let K=0,nn=0;function yn(n,t="Path"){const o=String(t).toLowerCase();for(const e of String(n||"").split(/\r?\n/)){const i=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(e);if(i&&i[1].toLowerCase()===o)return i[2]}return""}function tn(n,t=process.env){const o=new Map(Object.keys(t||{}).map(e=>[e.toLowerCase(),t[e]]));return String(n||"").replace(/%([^%]+)%/g,(e,i)=>{const r=o.get(String(i).toLowerCase());return r==null?e:String(r)})}function Ln(n,t){try{const o=c.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),e=w(f(o)?o:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return e.status===0?yn(e.stdout,t):""}catch{return""}}function Nn({query:n=Ln,env:t=process.env}={}){const o=tn(n(Tn,"Path"),t),e=tn(n(Mn,"Path"),t);return j([...d(o,"win32"),...d(e,"win32")])}function Hn({run:n=On}={}){const t=n(`[Console]::Out.Write("${A}\`t" + $env:PATH + "\`n")`);return d(I(t),"win32")}function On(n){for(const t of["pwsh.exe","powershell.exe"])try{const o=w(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],windowsHide:!0}),e=F(o.stdout||"");if(e)return e}catch{}return""}function en({force:n=!1,now:t=Date.now(),registry:o=Nn,profile:e=Hn,env:i=process.env,home:r=m.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-nn<vn)return!1;nn=t;const s=d(i.PATH||"","win32"),l=j([...s,...o({env:i}),...G(r,"win32",i)]);t-K>=In&&R.some(u=>!l.some(p=>f(c.win32.join(p,`${u}.cmd`))||f(c.win32.join(p,`${u}.exe`))))&&(K=t,l.push(...e()));const a=Y(j(l),"win32");return a.length===s.length?!1:(i.PATH=a.join(V("win32")),!0)}function Dn(n){return on(n)||(en()?on(n):null)}function on(n){const t=C("win32");for(const o of dn(n,m.homedir(),"win32",process.env)){if(!f(o))continue;const e=t.dirname(o),i=t.extname(o).toLowerCase(),r=n==="claude"&&$n(e)||Wn(e,n)||(/^\.(c?js|mjs)$/.test(i)?o:null);if(r){if(!$())return{kind:"script",script:r};const s=Rn(e);if(s)return{kind:"script",script:r,runtime:s}}if(i===".exe")return{kind:"native",bin:o};if(i===".cmd"||i===".bat")return{kind:"cmd",bin:o};if(i===""&&fn(o))return{kind:"native",bin:o}}return null}function Rn(n,{env:t=process.env,exists:o=f}={}){const e=c.win32,i=j([n,...d(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],e.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of i){const s=e.join(r,"node.exe");if(o(s))return s}return null}function $n(n){const t=[["node_modules","@anthropic-ai","claude-code","cli.js"],["..","node_modules","@anthropic-ai","claude-code","cli.js"],["..","lib","node_modules","@anthropic-ai","claude-code","cli.js"]];for(const o of t){const e=c.join(n,...o);if(f(e))return e}return null}function Wn(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let e;try{e=M(c.join(n,o),"utf8")}catch{continue}const i=e.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(i){const r=c.join(n,i[1].replace(/[\\/]+/g,c.sep));if(f(r))return r}}return null}const S=new Map,D=new Map,kn=15e3,Bn=3e5,rn=8e3,sn=n=>["-e","bash","-lic",`command -v ${n}`];function cn(n,t){return n!==0?!1:(F(String(t||"")).replace(/\0/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).pop()||"").startsWith("/")}function ln(n,t,o){const e=S.get(n),i=t?0:Math.min(e&&!e.ok&&e.ttl?e.ttl*2:kn,Bn);S.set(n,{ok:t,at:o,ttl:i})}function Kn(n,{probe:t="sync",now:o=Date.now(),spawnSyncImpl:e=w,spawnImpl:i=X}={}){const r=S.get(n);if(r&&(r.ok||o-r.at<r.ttl))return r.ok;if(t==="async"){if(!D.has(n)){const l=new Promise(a=>{let u="",p;try{p=i("wsl.exe",sn(n),{windowsHide:!0,stdio:["ignore","pipe","ignore"]})}catch{a(!1);return}const _=setTimeout(()=>{try{p.kill()}catch{}},rn);p.stdout?.on("data",P=>{u+=P}),p.on("error",()=>{clearTimeout(_),a(!1)}),p.on("close",P=>{clearTimeout(_),a(cn(P,u))})}).then(a=>(ln(n,a,Date.now()),a)).finally(()=>D.delete(n));D.set(n,l)}return!1}let s=!1;try{const l=e("wsl.exe",sn(n),{encoding:"utf8",timeout:rn,windowsHide:!0});s=cn(l.status,l.stdout)}catch{s=!1}return ln(n,s,o),s}function lt(n){return D.get(n)||null}function Fn(n=process.env.CHATPANEL_AGENT_TOKEN_PATH||c.join(m.homedir(),".chatpanel","agent-token")){if(process.env.CHATPANEL_AGENT_TOKEN)return{};try{const t=M(n,"utf8").trim();return t&&/^[A-Za-z0-9_.~-]{16,200}$/.test(t)?{CHATPANEL_AGENT_TOKEN:t}:{}}catch{return{}}}function at(n,t,o,e=null){const i={...process.env,...Fn(),...e&&typeof e=="object"?e:{}};if(n.kind==="wsl"){const s=[];if(o){const a=Vn(o);a&&s.push("--cd",a)}return["wsl.exe",[...s,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U}]}const r={cwd:o||m.homedir(),stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U};return n.kind==="script"?[n.runtime||process.execPath,[n.script,...t],r]:n.kind==="cmd"?["cmd.exe",["/d","/s","/c",n.bin,...t],r]:[n.bin,t,r]}function Vn(n){try{const t=w("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=F(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function F(n){return n.replace(/^/,"").trim()}function Yn(n=m.homedir(),t=process.env){const o=c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node");let e;try{e=T(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!e.length)return null;const i=(r,s)=>{const l=r.slice(1).split(".").map(Number),a=s.slice(1).split(".").map(Number);for(let u=0;u<3;u+=1)if((l[u]||0)!==(a[u]||0))return(a[u]||0)-(l[u]||0);return 0};try{const r=M(c.join(t.NVM_DIR||c.join(n,".nvm"),"alias","default"),"utf8").trim(),s=r.startsWith("v")?r:`v${r}`;if(e.includes(s))return c.join(o,s,"bin")}catch{}return c.join(o,e.sort(i)[0],"bin")}function Gn(n,t=process.env){return[c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"shims"),c.join(n,".local","share","rtx","shims"),c.join(t.ASDF_DATA_DIR||c.join(n,".asdf"),"shims"),c.join(t.PYENV_ROOT||c.join(n,".pyenv"),"shims"),c.join(t.RBENV_ROOT||c.join(n,".rbenv"),"shims"),c.join(t.NODENV_ROOT||c.join(n,".nodenv"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"bin"),c.join(t.VOLTA_HOME||c.join(n,".volta"),"bin")]}function Un(n,t=process.env){const o=[],e=(i,r)=>{try{for(const s of T(i))o.push(c.join(i,s,r))}catch{}};return e(c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node"),"bin"),e(c.join(n,".local","share","fnm","node-versions"),c.join("installation","bin")),e(c.join(n,"Library","Application Support","fnm","node-versions"),c.join("installation","bin")),e(c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"installs","node"),"bin"),o}function C(n){return n==="win32"?c.win32:c}function V(n){return n==="win32"?";":c.delimiter}function d(n,t){return(n||"").split(V(t)).filter(Boolean)}function j(n){return[...new Set(n.filter(Boolean))]}const an={win32:3e4,other:65536};function Y(n,t=process.platform){const o=t==="win32"?an.win32:an.other,e=V(t),i=[];let r=0;for(const s of n){const l=s.length+(i.length?e.length:0);if(r+l>o)break;i.push(s),r+=l}return i}function G(n,t=process.platform,o=process.env){const e=C(t);if(t==="win32"){const i=o.APPDATA||e.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||e.join(n,"AppData","Local"),s=o.ProgramFiles||"C:\\Program Files",l=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=o.ProgramData||"C:\\ProgramData";return[e.join(n,".local","bin"),e.join(n,".codex","bin"),e.join(n,".claude","bin"),e.join(n,".claude","local"),e.join(n,".claude","local","bin"),e.join(i,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],e.join(s,"nodejs"),...Xn(i,r),e.join(r,"pnpm"),e.join(r,"Yarn","bin"),e.join(r,"Volta","bin"),e.join(n,".yarn","bin"),e.join(n,".bun","bin"),e.join(n,".deno","bin"),e.join(o.SCOOP||e.join(n,"scoop"),"shims"),e.join(a,"chocolatey","bin"),e.join(r,"Microsoft","WindowsApps"),e.join(r,"Microsoft","WinGet","Links"),e.join(o.MISE_DATA_DIR||e.join(r,"mise"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"bin"),e.join(r,"Programs","Claude Code"),e.join(r,"Anthropic","Claude Code"),e.join(s,"Claude Code"),e.join(s,"Anthropic","Claude Code"),e.join(l,"Claude Code"),e.join(l,"Anthropic","Claude Code")]}return[c.join(n,".local","bin"),c.join(n,".opencode","bin"),c.join(n,".codex","bin"),c.join(n,".claude","bin"),c.join(n,".claude","local"),c.join(n,".claude","local","bin"),o.PNPM_HOME||c.join(n,"Library","pnpm"),c.join(n,".local","share","pnpm"),c.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",c.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...Gn(n,o)]}function Xn(n,t){const o=c.win32,e=[];for(const i of[o.join(t,"fnm"),o.join(n,"fnm")]){let r=[];try{r=T(o.join(i,"node-versions")).filter(s=>/^v?\d+\.\d+\.\d+/.test(s)).sort((s,l)=>l.localeCompare(s,void 0,{numeric:!0}))}catch{}for(const s of r)e.push(o.join(i,"node-versions",s,"installation"))}return e}function un(n,t=process.platform){const o=C(t),e=o.join(n,".local","share","claude","versions");let i=[];try{i=T(e).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,s)=>s.localeCompare(r,void 0,{numeric:!0}))}catch{}return i.map(r=>o.join(e,r))}function pn(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function fn(n,t=M){try{const o=t(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function zn(n,t=m.homedir(),o=process.platform,e=process.env){const i=C(o),r=i.join(t,".local","bin",n),s=o==="win32"?e.LOCALAPPDATA||i.join(t,"AppData","Local"):null,l=o==="win32"?e.ProgramFiles||"C:\\Program Files":null,a=o==="win32"?e["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,u={claude:[r,i.join(t,".claude","bin","claude"),i.join(t,".claude","local","claude"),i.join(t,".claude","local","bin","claude"),...o==="win32"?[i.join(s,"Microsoft","WindowsApps","claude.exe"),i.join(s,"Programs","Claude Code","claude.exe"),i.join(s,"Anthropic","Claude Code","claude.exe"),i.join(l,"Claude Code","claude.exe"),i.join(l,"Anthropic","Claude Code","claude.exe"),i.join(a,"Claude Code","claude.exe"),i.join(a,"Anthropic","Claude Code","claude.exe"),...un(t,o)]:un(t,o)],codex:[r,i.join(t,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[i.join(t,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return j((u[n]||[r]).flatMap(p=>pn(p,o)))}function dn(n,t=m.homedir(),o=process.platform,e=process.env){const i=C(o),r=j([...d(e.PATH||"",o),...G(t,o,e)]).flatMap(s=>pn(i.join(s,n),o));return j([...r,...zn(n,t,o,e)])}const mn=["DEEPSEEK_API_KEY","DSH_HOME","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","GEMINI_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"];function ut(){if(Q||(Q=!0,process.platform==="win32"))return;const n=mn.filter(t=>!process.env[t]);if(n.length)try{const t=y(),o=`${n.map(i=>`[ -n "\${${i}:-}" ] && printf '%s\\t%s\\n' ${i} "$${i}"`).join("; ")}; true`,e=w(t,["-l","-i","-c",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const i of String(e.stdout||"").split(`
2
- `)){const r=i.indexOf(" ");if(r<=0)continue;const s=i.slice(0,r).trim(),l=i.slice(r+1);mn.includes(s)&&!process.env[s]&&l&&(process.env[s]=l)}}catch{}}function pt(){if(z)return;z=!0;const n=m.homedir();if(process.platform==="win32"){en({force:!0,home:n});return}const t=Yn(n),o=[...t?[t]:[],"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",c.join(n,".local","bin"),c.join(n,"bin"),c.join(n,".npm-global","bin"),c.join(n,".cargo","bin"),c.join(n,".deno","bin"),c.join(n,".bun","bin"),...G(n),...Un(n)];let e="";try{const s=y(),l=w(s,["-l","-c",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});l.status===0&&(e=(l.stdout||"").trim())}catch{}const i=new Set,r=[...t?[t]:[],...e?e.split(":"):[],...process.env.PATH?process.env.PATH.split(c.delimiter):[],...o].filter(s=>s&&!i.has(s)&&(i.add(s),!0));process.env.PATH=Y(r).join(c.delimiter),R.some(s=>!wn(s))&&k({force:!0})}export{R as AGENT_CLIS,et as agentAvailable,zn as agentCandidateBins,Fn as agentCredentialEnv,G as agentInstallDirs,at as buildSpawnSpec,Y as capPathList,dn as commandCandidateFiles,Kn as commandInWsl,ut as enrichAgentEnv,pt as enrichPath,tn as expandWindowsEnv,An as findAgentBin,st as forgetMisses,$ as isCompiledBinary,fn as isWindowsExecutable,Rn as nodeRuntimeWindows,Yn as nvmCurrentBin,_n as parseEnvPath,yn as parseRegValue,I as parseSentinel,J as parseWhich,rt as primeAgentLookups,Hn as profilePathWindows,k as refreshShellPath,en as refreshWindowsPath,Nn as registryPathWindows,it as resetShellProbes,ct as resolveClaude,B as resolveCommand,ot as selfMcpStdio,Pn as shellPath,Vn as toWslPath,cn as wslAnswer,lt as wslProbeInFlight};
1
+ import{isCompiledBinary as jn,hostFacts as wn}from"./events/runtime-host.js";import j from"node:os";import{spawnGroupOpts as U}from"./proc.js";import{agentCredentialEnv as hn}from"./agent-credential.js";import c from"node:path";import{spawn as X,spawnSync as h}from"node:child_process";import{readdirSync as M,readFileSync as D,existsSync as f}from"node:fs";let z=!1,Q=!1;const R=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function gn(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(f(c.join(o,n))||f(c.join(o,n+".exe"))))}function Pn(n){const t=I(n);if(t)return t;if(k()){const o=I(n);if(o)return o}return En(n)||null}function ot(n){return!!B(n,{probe:"async"})}function I(n){for(const t of dn(n))if(f(t))return t;return null}function $(){return jn(wn())}function it(n){const t=["--mcp-stdio",n];if($())return{command:process.execPath,args:t};const o=process.argv[1]||c.join(process.cwd(),"src","server.js"),e=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...e,...t]}}const g="CHATPANEL_ENV",W=6e3;function T(n){for(const t of String(n||"").split(/\r?\n/)){const o=t.indexOf(" ");if(o>0&&t.slice(0,o).trim().endsWith(g))return t.slice(o+1).trim()}return""}function q(n){return/^[\w.+-]+$/.test(String(n||""))}function v(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=j.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function J(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const o=t?["-l","-i","-c"]:["-l","-c"];return h(v(),[...o,n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function _n(n){let t="";for(const o of String(n||"").split(/\r?\n/))o.startsWith("PATH=")&&(t=o.slice(5).trim());return t}function bn({interactive:n=!0,ask:t=J}={}){const o=T(t(`command -p printf '%s\\t%s\\n' ${g} "$PATH"`,{interactive:n}));return d(o||_n(t("/usr/bin/env",{interactive:n})),process.platform)}const y=1e4,An=3e5;let L=0,x=y;function k({force:n=!1,now:t=Date.now(),read:o=bn,env:e=process.env}={}){if(process.platform==="win32"||!n&&(t-L<x||t<b))return!1;L=t;const i=d(e.PATH||"",process.platform),r=Y(m([...o({interactive:!0}),...i])),s=r.length>i.length;return x=s?y:Math.min(x*2,An),s?(e.PATH=r.join(c.delimiter),!0):!1}function rt(){L=0,x=y,w.clear(),b=0,A=H,N=!1}const w=new Map,xn=15e3;function En(n){if(process.platform==="win32"||!q(n))return"";const t=w.get(n);if(t&&(t.bin||Date.now()-t.at<xn||Date.now()<b))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${g} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let e="";for(const i of[!1,!0]){for(const r of o){const s=J(r,{interactive:i}),l=T(s)||String(s||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&f(l)){e=l;break}}if(e)break}return w.set(n,{bin:e,at:Date.now()}),e}const H=15e3,Sn=3e5;let b=0,A=H,N=!1,E=null;function Cn(n,{interactive:t}={}){return new Promise(o=>{let e="",i;try{i=X(v(),[...t?["-l","-i","-c"]:["-l","-c"],n],{stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}})}catch{o("");return}const r=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},W);i.stdout.on("data",s=>{e+=s}),i.on("error",()=>{clearTimeout(r),o("")}),i.on("close",()=>{clearTimeout(r),o(e)})})}const Mn=new RegExp(`${g}=([\\w.+-]+)$`);function Z(n){const t=new Map;for(const o of String(n||"").split(/\r?\n/)){const e=o.indexOf(" ");if(e<=0)continue;const i=Mn.exec(o.slice(0,e).trim());i&&t.set(i[1],o.slice(e+1).trim())}return t}function st({names:n=R,ask:t=Cn,now:o=()=>Date.now()}={}){if(process.platform==="win32"||N)return Promise.resolve(!1);if(E)return E;if(o()<b)return Promise.resolve(!1);const e=m([...n,...w.keys()]).filter(r=>q(r)&&!I(r)&&!w.get(r)?.bin);if(!e.length)return Promise.resolve(!1);const i=[`command -p printf '%s\\t%s\\n' ${g} "$PATH"`,...e.map(r=>`command -p printf '%s\\t%s\\n' ${g}=${r} "$(command -v ${r} 2>/dev/null)"`)].join("; ");return E=(async()=>{let r=await t(i,{interactive:!0}),s=Z(r);if(s.size||(r=await t(i,{interactive:!1}),s=Z(r)),!s.size)return N=!0,!0;const l=o();let a=!1;const u=d(T(r),process.platform);u.length&&k({force:!0,now:l,read:()=>u})&&(a=!0);for(const p of e){if(!s.has(p))continue;const P=s.get(p),_=P.startsWith("/")&&f(P)?P:"";(_||I(p))&&(a=!0),w.set(p,{bin:_,at:l})}return a&&(A=H),b=l+A,a||(A=Math.min(A*2,Sn)),!0})().catch(()=>!0).finally(()=>{E=null}),E}function ct(){b=0,A=H,N=!1,L=0,x=y,F=0;for(const[n,t]of w)t.bin||w.delete(n);for(const[n,t]of S)t.ok||S.delete(n)}function lt({probe:n="sync"}={}){return process.env.CHATPANEL_CLAUDE_PATH?B(process.env.CHATPANEL_CLAUDE_PATH,{probe:n}):B("claude",{probe:n})}function B(n,{probe:t="sync"}={}){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!f(n))return null;const i=c.extname(n).toLowerCase();return!$()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&i===""&&!fn(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const i=Rn(n);return i||(/^[\w.-]+$/.test(n)&&Kn(n,{probe:t})?{kind:"wsl",command:n}:null)}const e=Pn(n);return e?{kind:"native",bin:e}:null}const In="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",Tn="HKCU\\Environment",vn=4e3,yn=3e5;let F=0,nn=0;function Ln(n,t="Path"){const o=String(t).toLowerCase();for(const e of String(n||"").split(/\r?\n/)){const i=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(e);if(i&&i[1].toLowerCase()===o)return i[2]}return""}function tn(n,t=process.env){const o=new Map(Object.keys(t||{}).map(e=>[e.toLowerCase(),t[e]]));return String(n||"").replace(/%([^%]+)%/g,(e,i)=>{const r=o.get(String(i).toLowerCase());return r==null?e:String(r)})}function Hn(n,t){try{const o=c.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),e=h(f(o)?o:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return e.status===0?Ln(e.stdout,t):""}catch{return""}}function Nn({query:n=Hn,env:t=process.env}={}){const o=tn(n(In,"Path"),t),e=tn(n(Tn,"Path"),t);return m([...d(o,"win32"),...d(e,"win32")])}function On({run:n=Dn}={}){const t=n(`[Console]::Out.Write("${g}\`t" + $env:PATH + "\`n")`);return d(T(t),"win32")}function Dn(n){for(const t of["pwsh.exe","powershell.exe"])try{const o=h(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],windowsHide:!0}),e=K(o.stdout||"");if(e)return e}catch{}return""}function en({force:n=!1,now:t=Date.now(),registry:o=Nn,profile:e=On,env:i=process.env,home:r=j.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-nn<vn)return!1;nn=t;const s=d(i.PATH||"","win32"),l=m([...s,...o({env:i}),...G(r,"win32",i)]);t-F>=yn&&R.some(u=>!l.some(p=>f(c.win32.join(p,`${u}.cmd`))||f(c.win32.join(p,`${u}.exe`))))&&(F=t,l.push(...e()));const a=Y(m(l),"win32");return a.length===s.length?!1:(i.PATH=a.join(V("win32")),!0)}function Rn(n){return on(n)||(en()?on(n):null)}function on(n){const t=C("win32");for(const o of dn(n,j.homedir(),"win32",process.env)){if(!f(o))continue;const e=t.dirname(o),i=t.extname(o).toLowerCase(),r=n==="claude"&&Wn(e)||kn(e,n)||(/^\.(c?js|mjs)$/.test(i)?o:null);if(r){if(!$())return{kind:"script",script:r};const s=$n(e);if(s)return{kind:"script",script:r,runtime:s}}if(i===".exe")return{kind:"native",bin:o};if(i===".cmd"||i===".bat")return{kind:"cmd",bin:o};if(i===""&&fn(o))return{kind:"native",bin:o}}return null}function $n(n,{env:t=process.env,exists:o=f}={}){const e=c.win32,i=m([n,...d(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],e.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of i){const s=e.join(r,"node.exe");if(o(s))return s}return null}function Wn(n){const t=[["node_modules","@anthropic-ai","claude-code","cli.js"],["..","node_modules","@anthropic-ai","claude-code","cli.js"],["..","lib","node_modules","@anthropic-ai","claude-code","cli.js"]];for(const o of t){const e=c.join(n,...o);if(f(e))return e}return null}function kn(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let e;try{e=D(c.join(n,o),"utf8")}catch{continue}const i=e.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(i){const r=c.join(n,i[1].replace(/[\\/]+/g,c.sep));if(f(r))return r}}return null}const S=new Map,O=new Map,Bn=15e3,Fn=3e5,rn=8e3,sn=n=>["-e","bash","-lic",`command -v ${n}`];function cn(n,t){return n!==0?!1:(K(String(t||"")).replace(/\0/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).pop()||"").startsWith("/")}function ln(n,t,o){const e=S.get(n),i=t?0:Math.min(e&&!e.ok&&e.ttl?e.ttl*2:Bn,Fn);S.set(n,{ok:t,at:o,ttl:i})}function Kn(n,{probe:t="sync",now:o=Date.now(),spawnSyncImpl:e=h,spawnImpl:i=X}={}){const r=S.get(n);if(r&&(r.ok||o-r.at<r.ttl))return r.ok;if(t==="async"){if(!O.has(n)){const l=new Promise(a=>{let u="",p;try{p=i("wsl.exe",sn(n),{windowsHide:!0,stdio:["ignore","pipe","ignore"]})}catch{a(!1);return}const P=setTimeout(()=>{try{p.kill()}catch{}},rn);p.stdout?.on("data",_=>{u+=_}),p.on("error",()=>{clearTimeout(P),a(!1)}),p.on("close",_=>{clearTimeout(P),a(cn(_,u))})}).then(a=>(ln(n,a,Date.now()),a)).finally(()=>O.delete(n));O.set(n,l)}return!1}let s=!1;try{const l=e("wsl.exe",sn(n),{encoding:"utf8",timeout:rn,windowsHide:!0});s=cn(l.status,l.stdout)}catch{s=!1}return ln(n,s,o),s}function at(n){return O.get(n)||null}function ut(n,t,o,e=null){const i={...process.env,...hn(),...e&&typeof e=="object"?e:{}};if(n.kind==="wsl"){const s=[];if(o){const a=Vn(o);a&&s.push("--cd",a)}return["wsl.exe",[...s,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U}]}const r={cwd:o||j.homedir(),stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U};return n.kind==="script"?[n.runtime||process.execPath,[n.script,...t],r]:n.kind==="cmd"?["cmd.exe",["/d","/s","/c",n.bin,...t],r]:[n.bin,t,r]}function Vn(n){try{const t=h("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=K(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function K(n){return n.replace(/^/,"").trim()}function Yn(n=j.homedir(),t=process.env){const o=c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node");let e;try{e=M(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!e.length)return null;const i=(r,s)=>{const l=r.slice(1).split(".").map(Number),a=s.slice(1).split(".").map(Number);for(let u=0;u<3;u+=1)if((l[u]||0)!==(a[u]||0))return(a[u]||0)-(l[u]||0);return 0};try{const r=D(c.join(t.NVM_DIR||c.join(n,".nvm"),"alias","default"),"utf8").trim(),s=r.startsWith("v")?r:`v${r}`;if(e.includes(s))return c.join(o,s,"bin")}catch{}return c.join(o,e.sort(i)[0],"bin")}function Gn(n,t=process.env){return[c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"shims"),c.join(n,".local","share","rtx","shims"),c.join(t.ASDF_DATA_DIR||c.join(n,".asdf"),"shims"),c.join(t.PYENV_ROOT||c.join(n,".pyenv"),"shims"),c.join(t.RBENV_ROOT||c.join(n,".rbenv"),"shims"),c.join(t.NODENV_ROOT||c.join(n,".nodenv"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"bin"),c.join(t.VOLTA_HOME||c.join(n,".volta"),"bin")]}function Un(n,t=process.env){const o=[],e=(i,r)=>{try{for(const s of M(i))o.push(c.join(i,s,r))}catch{}};return e(c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node"),"bin"),e(c.join(n,".local","share","fnm","node-versions"),c.join("installation","bin")),e(c.join(n,"Library","Application Support","fnm","node-versions"),c.join("installation","bin")),e(c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"installs","node"),"bin"),o}function C(n){return n==="win32"?c.win32:c}function V(n){return n==="win32"?";":c.delimiter}function d(n,t){return(n||"").split(V(t)).filter(Boolean)}function m(n){return[...new Set(n.filter(Boolean))]}const an={win32:3e4,other:65536};function Y(n,t=process.platform){const o=t==="win32"?an.win32:an.other,e=V(t),i=[];let r=0;for(const s of n){const l=s.length+(i.length?e.length:0);if(r+l>o)break;i.push(s),r+=l}return i}function G(n,t=process.platform,o=process.env){const e=C(t);if(t==="win32"){const i=o.APPDATA||e.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||e.join(n,"AppData","Local"),s=o.ProgramFiles||"C:\\Program Files",l=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=o.ProgramData||"C:\\ProgramData";return[e.join(n,".local","bin"),e.join(n,".codex","bin"),e.join(n,".claude","bin"),e.join(n,".claude","local"),e.join(n,".claude","local","bin"),e.join(i,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],e.join(s,"nodejs"),...Xn(i,r),e.join(r,"pnpm"),e.join(r,"Yarn","bin"),e.join(r,"Volta","bin"),e.join(n,".yarn","bin"),e.join(n,".bun","bin"),e.join(n,".deno","bin"),e.join(o.SCOOP||e.join(n,"scoop"),"shims"),e.join(a,"chocolatey","bin"),e.join(r,"Microsoft","WindowsApps"),e.join(r,"Microsoft","WinGet","Links"),e.join(o.MISE_DATA_DIR||e.join(r,"mise"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"bin"),e.join(r,"Programs","Claude Code"),e.join(r,"Anthropic","Claude Code"),e.join(s,"Claude Code"),e.join(s,"Anthropic","Claude Code"),e.join(l,"Claude Code"),e.join(l,"Anthropic","Claude Code")]}return[c.join(n,".local","bin"),c.join(n,".opencode","bin"),c.join(n,".codex","bin"),c.join(n,".claude","bin"),c.join(n,".claude","local"),c.join(n,".claude","local","bin"),o.PNPM_HOME||c.join(n,"Library","pnpm"),c.join(n,".local","share","pnpm"),c.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",c.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...Gn(n,o)]}function Xn(n,t){const o=c.win32,e=[];for(const i of[o.join(t,"fnm"),o.join(n,"fnm")]){let r=[];try{r=M(o.join(i,"node-versions")).filter(s=>/^v?\d+\.\d+\.\d+/.test(s)).sort((s,l)=>l.localeCompare(s,void 0,{numeric:!0}))}catch{}for(const s of r)e.push(o.join(i,"node-versions",s,"installation"))}return e}function un(n,t=process.platform){const o=C(t),e=o.join(n,".local","share","claude","versions");let i=[];try{i=M(e).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,s)=>s.localeCompare(r,void 0,{numeric:!0}))}catch{}return i.map(r=>o.join(e,r))}function pn(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function fn(n,t=D){try{const o=t(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function zn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=i.join(t,".local","bin",n),s=o==="win32"?e.LOCALAPPDATA||i.join(t,"AppData","Local"):null,l=o==="win32"?e.ProgramFiles||"C:\\Program Files":null,a=o==="win32"?e["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,u={claude:[r,i.join(t,".claude","bin","claude"),i.join(t,".claude","local","claude"),i.join(t,".claude","local","bin","claude"),...o==="win32"?[i.join(s,"Microsoft","WindowsApps","claude.exe"),i.join(s,"Programs","Claude Code","claude.exe"),i.join(s,"Anthropic","Claude Code","claude.exe"),i.join(l,"Claude Code","claude.exe"),i.join(l,"Anthropic","Claude Code","claude.exe"),i.join(a,"Claude Code","claude.exe"),i.join(a,"Anthropic","Claude Code","claude.exe"),...un(t,o)]:un(t,o)],codex:[r,i.join(t,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[i.join(t,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return m((u[n]||[r]).flatMap(p=>pn(p,o)))}function dn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=m([...d(e.PATH||"",o),...G(t,o,e)]).flatMap(s=>pn(i.join(s,n),o));return m([...r,...zn(n,t,o,e)])}const mn=["DEEPSEEK_API_KEY","DSH_HOME","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","GEMINI_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"];function pt(){if(Q||(Q=!0,process.platform==="win32"))return;const n=mn.filter(t=>!process.env[t]);if(n.length)try{const t=v(),o=`${n.map(i=>`[ -n "\${${i}:-}" ] && printf '%s\\t%s\\n' ${i} "$${i}"`).join("; ")}; true`,e=h(t,["-l","-i","-c",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const i of String(e.stdout||"").split(`
2
+ `)){const r=i.indexOf(" ");if(r<=0)continue;const s=i.slice(0,r).trim(),l=i.slice(r+1);mn.includes(s)&&!process.env[s]&&l&&(process.env[s]=l)}}catch{}}function ft(){if(z)return;z=!0;const n=j.homedir();if(process.platform==="win32"){en({force:!0,home:n});return}const t=Yn(n),o=[...t?[t]:[],"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",c.join(n,".local","bin"),c.join(n,"bin"),c.join(n,".npm-global","bin"),c.join(n,".cargo","bin"),c.join(n,".deno","bin"),c.join(n,".bun","bin"),...G(n),...Un(n)];let e="";try{const s=v(),l=h(s,["-l","-c",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});l.status===0&&(e=(l.stdout||"").trim())}catch{}const i=new Set,r=[...t?[t]:[],...e?e.split(":"):[],...process.env.PATH?process.env.PATH.split(c.delimiter):[],...o].filter(s=>s&&!i.has(s)&&(i.add(s),!0));process.env.PATH=Y(r).join(c.delimiter),R.some(s=>!gn(s))&&k({force:!0})}export{R as AGENT_CLIS,ot as agentAvailable,zn as agentCandidateBins,G as agentInstallDirs,ut as buildSpawnSpec,Y as capPathList,dn as commandCandidateFiles,Kn as commandInWsl,pt as enrichAgentEnv,ft as enrichPath,tn as expandWindowsEnv,Pn as findAgentBin,ct as forgetMisses,$ as isCompiledBinary,fn as isWindowsExecutable,$n as nodeRuntimeWindows,Yn as nvmCurrentBin,_n as parseEnvPath,Ln as parseRegValue,T as parseSentinel,Z as parseWhich,st as primeAgentLookups,On as profilePathWindows,k as refreshShellPath,en as refreshWindowsPath,Nn as registryPathWindows,rt as resetShellProbes,lt as resolveClaude,B as resolveCommand,it as selfMcpStdio,bn as shellPath,Vn as toWslPath,cn as wslAnswer,at as wslProbeInFlight};
package/src/server.js CHANGED
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import{originAllowed as ae,isExtensionOrigin as Le}from"./origins.js";import{createServer as We}from"node:http";import O from"node:os";import{randomBytes as je,randomInt as Fe,timingSafeEqual as Je}from"node:crypto";import{mkdirSync as Xe,writeFileSync as Ke,readFileSync as ie,existsSync as Ye}from"node:fs";import{join as M}from"node:path";import*as ze from"./engines/claude.js";import*as Ve from"./engines/codex.js";import*as Qe from"./engines/antigravity.js";import{pi as Ze,opencode as qe,kiro as et,copilot as tt,deepseek as nt,hermes as ot}from"./engines/cli-agents.js";import{connectorsFor as rt}from"./connectors.js";import{agentServersFor as at,resolveAgentServer as se,builtinRefusal as it,narrowBuiltinList as st}from"./agent-mcp.js";import*as ct from"./engines/custom.js";import{installService as lt,uninstallService as dt,serviceStatus as ut,restartService as ce}from"./service.js";import{skillIndex as J,listRecords as ht,readRecord as pt,readPackageFile as ft,skillsHealth as mt,quarantinedSkills as gt,clearSkillCache as X,preferredIndex as K}from"./skills.js";import{writeSkillPackage as wt,writeSkillFile as yt,deleteSkillPackage as bt,SkillWriteError as St}from"./skill-write.js";import{agentDefRoots as kt,scanAgentDefs as Tt,listAgentDefs as vt,readAgentDef as Et,planAgentExport as xt,exportAgentDef as At,agentDefsHealth as Ot,AgentDefError as Ct}from"./agent-defs.js";import{capabilityToolSpecs as Pt,runCapabilityTool as $t}from"./mcp-capabilities.js";import{createSession as Rt,deleteSession as le,getSession as de,activeSession as It,relayToolCall as Nt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Dt,isDefaultWorkdir as _t,resolveWorkdir as Ht,writeScopeNote as Mt}from"./workdir.js";import{sandbox as Y,runSandboxCli as Bt,withGrant as ue,withAgentGrant as Gt,withoutOutsideWhenCapped as Ut,grantedWriteRoots as he,acceptRefusalReport as Lt,liveProcesses as Wt,sandboxConfigFromEnv as jt}from"./sandbox.js";import{createAccessGate as Ft,chatKeyOf as Jt,chatFolders as Xt}from"./access-gate.js";import{signInDenial as Kt}from"./events/sandbox-policy.js";import{gitState as Yt,gitDelta as zt}from"./scm.js";import{listConnections as Vt,putConnection as Qt,removeConnection as Zt,runEnvFor as qt,testConnection as en,secretBackend as pe}from"./connections.js";import{worktreeFor as fe,listWorktrees as tn,removeWorktree as nn,withHook as on,WORKTREE_ROOT as me}from"./worktree.js";import{AGENT_CLIS as rn,agentAvailable as an,agentInstallDirs as sn,enrichPath as cn,enrichAgentEnv as ln,findAgentBin as dn,forgetMisses as un,primeAgentLookups as hn,resolveCommand as ge,isCompiledBinary as pn}from"./env.js";import"./sanitize.js";import{checkForUpdate as fn,selfUpdate as we,isEmbedded as ye}from"./update.js";import{callLocalMcp as mn,localMcpStatus as gn,signInLocalMcp as wn,signInStatusLocalMcp as yn}from"./mcp-local.js";import{assertPublicHttpUrl as be,assertPublicWebUrl as Se}from"./ssrf.js";import{startRun as ke,endRun as z,cancelRun as bn,cancelAll as Sn}from"./runs.js";import{closeWarmPools as kn,warmStatus as Tn}from"./warm.js";import{SESSION_AGENTS as Te,listSessions as vn,readSession as En,adoptSession as xn,catchUp as An}from"./agent-sessions.js";import{agentContext as On}from"./agent-context.js";import{normalizeThread as ve}from"./events/agent-thread.js";import{portClashPlan as Cn,serviceManagerOf as Pn,STANDBY_POLL_MS as $n}from"./events/service-standby.js";import{holdThread as Ee}from"./threads.js";import{oneReply as Rn}from"./one-reply.js";import{createSnapshot as In}from"./health-snapshot.js";import{CompatError as P,anthropicError as V,anthropicStream as Nn,chatCompletionStream as Dn,completionStream as _n,createAnthropicMessage as Hn,createChatCompletion as Mn,createCompletion as Bn,createResponse as Gn,openAIError as S,parseAnthropicMessage as Un,parseChatCompletion as Ln,parseCompletion as Wn,parseResponse as jn,responseStream as Fn}from"./api-compat.js";import{callerTrust as Jn,isPaired as I,parseExtensionIds as Xn,capRunOptions as Kn,engineHonoursReach as Yn,createPairingStore as zn,formatPairingCode as Vn}from"./pii/trust.js";const y="0.53.2",v=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:ze,label:"Claude Code"},codex:{engine:Ve,label:"Codex"},antigravity:{engine:Qe,label:"Antigravity",tools:!1},pi:{engine:Ze,label:"Pi"},opencode:{engine:qe,label:"OpenCode"},hermes:{engine:ot,label:"Hermes"},kiro:{engine:et,label:"Kiro"},copilot:{engine:tt,label:"GitHub Copilot"},deepseek:{engine:nt,label:"DeepSeek Harness"},custom:{engine:ct,label:"Custom",hidden:!0}},Qn=Xn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Jn({origin:n.headers.origin||"",hasToken:Ce(n),extensionIds:Qn})),n.chatpanelTrust}function Zn(n,e){const t=n.headers.origin||"",r=ae(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 Q=new Set(["127.0.0.1","localhost","::1"]);function qn(n){if(!Q.has(v))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return Q.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let x="";function eo(){try{Ye(D)&&(x=ie(D,"utf8").trim()),x||(x=je(32).toString("hex"),Xe(M(O.homedir(),".chatpanel"),{recursive:!0}),Ke(D,x,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=zn({random:()=>Fe(0,1e6)/1e6});function to(n){if(!x)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=xe.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function no(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=xe.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:x})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function oo(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ae(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:x},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function Oe(n,e,t){try{const r=await Ae(),o=n.method==="POST"?await m(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 Ce(n){if(!x)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(x);return r.length===o.length&&Je(r,o)}const ro=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),ao=new Set(["/debug"]),io=n=>ao.has(n),so=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function co(n,e){if(!qn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ae(t))return"forbidden origin";const r=n.method==="POST"&&ro.has(e)||n.method==="GET"&&io(e)||so(n.method,e);return r&&!(Le(t)||Ce(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!uo.has(e)?lo:null}const Pe=()=>ye()?"chatpanel-gateway pair":"chatpanel-bridge pair",lo=`forbidden: this client is not paired with the bridge — run \`${Pe()}\` and enter the code in ChatPanel Settings`,uo=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Z(n,e,t){const r=N(n),o=Gt(e,Ut(Kn(t,r)));if(!Yn(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 (${Pe()})`} to use ${e}`};const a=o.reach,c=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 → Coding Agents to unlock them.";return{options:o,note:c}}async function $e(n,e,t){const r=e?.message||String(e);try{const o=await Y().status(),a=!!(o.enabled&&o.runtime)&&t?.outside!==!0,c=Kt(`${r}
3
- ${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:E[n]?.label||n||"This agent"});if(c)return c.line}catch{}return r}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let 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)})}const Re=In({compute:ho});async function ho(){await hn();const n=await Promise.all(Object.entries(E).filter(([,a])=>!a.hidden).map(async([a,{engine:c,label:l,tools:s}])=>{const d=await c.available().catch(f=>({ok:!1,reason:String(f?.message||f)})),p=await rt(a).catch(()=>[]),w=await at(a,{available:d.ok}).catch(()=>[]);return{id:a,label:l,available:d.ok,reason:d.reason,connectors:p,...w.length?{mcpServers:w}:{},...s===!1?{tools:!1}:{}}})),e=ye()?{current:y,updateAvailable:!1,embedded:"gateway"}:await fn(y).catch(()=>({current:y,updateAvailable:!1})),t=await mt().catch(()=>null),r=await Ot().catch(()=>null),o=await Y().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:r,sandboxStatus:o}}async function po(n,{fresh:e=!1}={}){e&&un();const{at:t,value:{agents:r,update:o,skills:a,agentDefs:c,sandboxStatus:l}}=await Re.get({fresh:e});i(n,200,{ok:!0,version:y,agents:r,update:o,checkedAt:t,workspace:Dt,sandbox:l,localMcp:gn(),processes:Wt(),worktrees:me,secretBackend:pe(),warm:Tn(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...c?{agentDefs:c}:{}})}async function fo(n,e,t,r={}){const o=await J({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:ht(K(o,r)),problems:o.problems})}async function mo(n,e,t){i(n,200,{ok:!0,quarantined:await gt(e,t)})}async function go(n,e,t,r,o={}){const a=pt(K(await J({extraDirs:t,workdir:r}),o),e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function wo(n,e,t,r,o,a={}){const c=await ft(K(await J({extraDirs:r,workdir:o}),a),e,t);if(c.error)return i(n,c.error==="unknown skill"?404:400,{ok:!1,error:c.error});i(n,200,{ok:!0,...c})}async function yo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{const r=await wt({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return X(),i(e,200,r)}catch(r){return i(e,q(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function bo(n,e,t,r){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await yt({name:t,path:r,text:o?.text??""});return X(),i(e,200,a)}catch(a){return i(e,q(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function So(n,e){try{const t=await bt({name:e});return X(),i(n,200,t)}catch(t){return i(n,q(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function q(n){return n instanceof St?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Ie(n,e){return Tt({roots:kt(process.env,O.homedir(),n,e)})}async function ko(n,e,t){const{index:r,quarantined:o,problems:a}=await Ie(e,t);i(n,200,{ok:!0,agents:vt(r),...o.length?{quarantined:o.map(c=>({id:c.agent.id,path:c.relPath,source:c.source,verdict:c.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function To(n,e,t,r){const{index:o}=await Ie(t,r),a=Et(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function vo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{return i(e,200,{ok:!0,...await xt({agent:t?.agent,to:t?.to})})}catch(r){return i(e,Ne(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function Eo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{return i(e,200,await At({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(r){return i(e,Ne(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function Ne(n){if(n instanceof Ct){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function xo(){return(await Promise.all(Object.entries(E).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function De(n,e=""){const t=await xo();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,S(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function Ao(n){try{const e=await we(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>ce(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function Oo(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=E[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=Z(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
2
+ import{originAllowed as ae,isExtensionOrigin as Le}from"./origins.js";import{startRunCredentials as We}from"./agent-credential.js";import{createServer as je}from"node:http";import O from"node:os";import{randomBytes as Fe,randomInt as Je,timingSafeEqual as Xe}from"node:crypto";import{mkdirSync as Ke,writeFileSync as Ye,readFileSync as ie,existsSync as ze}from"node:fs";import{join as M}from"node:path";import*as Ve from"./engines/claude.js";import*as Qe from"./engines/codex.js";import*as Ze from"./engines/antigravity.js";import{pi as qe,opencode as et,kiro as tt,copilot as nt,deepseek as ot,hermes as rt}from"./engines/cli-agents.js";import{connectorsFor as at}from"./connectors.js";import{agentServersFor as it,resolveAgentServer as se,builtinRefusal as st,narrowBuiltinList as ct}from"./agent-mcp.js";import*as lt from"./engines/custom.js";import{installService as dt,uninstallService as ut,serviceStatus as ht,restartService as ce}from"./service.js";import{skillIndex as J,listRecords as pt,readRecord as ft,readPackageFile as mt,skillsHealth as gt,quarantinedSkills as wt,clearSkillCache as X,preferredIndex as K}from"./skills.js";import{writeSkillPackage as yt,writeSkillFile as bt,deleteSkillPackage as St,SkillWriteError as kt}from"./skill-write.js";import{agentDefRoots as Tt,scanAgentDefs as vt,listAgentDefs as Et,readAgentDef as xt,planAgentExport as At,exportAgentDef as Ot,agentDefsHealth as Ct,AgentDefError as Pt}from"./agent-defs.js";import{capabilityToolSpecs as $t,runCapabilityTool as Rt}from"./mcp-capabilities.js";import{createSession as It,deleteSession as le,getSession as de,activeSession as Nt,relayToolCall as Dt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as _t,isDefaultWorkdir as Ht,resolveWorkdir as Mt,writeScopeNote as Bt}from"./workdir.js";import{sandbox as Y,runSandboxCli as Gt,withGrant as ue,withAgentGrant as Ut,withoutOutsideWhenCapped as Lt,grantedWriteRoots as he,acceptRefusalReport as Wt,liveProcesses as jt,sandboxConfigFromEnv as Ft}from"./sandbox.js";import{createAccessGate as Jt,chatKeyOf as Xt,chatFolders as Kt}from"./access-gate.js";import{signInDenial as Yt}from"./events/sandbox-policy.js";import{gitState as zt,gitDelta as Vt}from"./scm.js";import{listConnections as Qt,putConnection as Zt,removeConnection as qt,runEnvFor as en,testConnection as tn,secretBackend as pe}from"./connections.js";import{worktreeFor as fe,listWorktrees as nn,removeWorktree as on,withHook as rn,WORKTREE_ROOT as me}from"./worktree.js";import{AGENT_CLIS as an,agentAvailable as sn,agentInstallDirs as cn,enrichPath as ln,enrichAgentEnv as dn,findAgentBin as un,forgetMisses as hn,primeAgentLookups as pn,resolveCommand as ge,isCompiledBinary as fn}from"./env.js";import"./sanitize.js";import{checkForUpdate as mn,selfUpdate as we,isEmbedded as ye}from"./update.js";import{callLocalMcp as gn,localMcpStatus as wn,signInLocalMcp as yn,signInStatusLocalMcp as bn}from"./mcp-local.js";import{assertPublicHttpUrl as be,assertPublicWebUrl as Se}from"./ssrf.js";import{startRun as ke,endRun as z,cancelRun as Sn,cancelAll as kn}from"./runs.js";import{closeWarmPools as Tn,warmStatus as vn}from"./warm.js";import{SESSION_AGENTS as Te,listSessions as En,readSession as xn,adoptSession as An,catchUp as On}from"./agent-sessions.js";import{agentContext as Cn}from"./agent-context.js";import{normalizeThread as ve}from"./events/agent-thread.js";import{portClashPlan as Pn,serviceManagerOf as $n,STANDBY_POLL_MS as Rn}from"./events/service-standby.js";import{holdThread as Ee}from"./threads.js";import{oneReply as In}from"./one-reply.js";import{createSnapshot as Nn}from"./health-snapshot.js";import{CompatError as P,anthropicError as V,anthropicStream as Dn,chatCompletionStream as _n,completionStream as Hn,createAnthropicMessage as Mn,createChatCompletion as Bn,createCompletion as Gn,createResponse as Un,openAIError as S,parseAnthropicMessage as Ln,parseChatCompletion as Wn,parseCompletion as jn,parseResponse as Fn,responseStream as Jn}from"./api-compat.js";import{callerTrust as Xn,isPaired as I,parseExtensionIds as Kn,capRunOptions as Yn,engineHonoursReach as zn,createPairingStore as Vn,formatPairingCode as Qn}from"./pii/trust.js";const y="0.54.0",v=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Ve,label:"Claude Code"},codex:{engine:Qe,label:"Codex"},antigravity:{engine:Ze,label:"Antigravity",tools:!1},pi:{engine:qe,label:"Pi"},opencode:{engine:et,label:"OpenCode"},hermes:{engine:rt,label:"Hermes"},kiro:{engine:tt,label:"Kiro"},copilot:{engine:nt,label:"GitHub Copilot"},deepseek:{engine:ot,label:"DeepSeek Harness"},custom:{engine:lt,label:"Custom",hidden:!0}},Zn=Kn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Xn({origin:n.headers.origin||"",hasToken:Ce(n),extensionIds:Zn})),n.chatpanelTrust}function qn(n,e){const t=n.headers.origin||"",r=ae(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 Q=new Set(["127.0.0.1","localhost","::1"]);function eo(n){if(!Q.has(v))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return Q.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let x="";function to(){try{ze(D)&&(x=ie(D,"utf8").trim()),x||(x=Fe(32).toString("hex"),Ke(M(O.homedir(),".chatpanel"),{recursive:!0}),Ye(D,x,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=Vn({random:()=>Je(0,1e6)/1e6});function no(n){if(!x)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=xe.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function oo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=xe.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:x})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function ro(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ae(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:x},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function Oe(n,e,t){try{const r=await Ae(),o=n.method==="POST"?await m(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 Ce(n){if(!x)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(x);return r.length===o.length&&Xe(r,o)}const ao=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),io=new Set(["/debug"]),so=n=>io.has(n),co=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function lo(n,e){if(!eo(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ae(t))return"forbidden origin";const r=n.method==="POST"&&ao.has(e)||n.method==="GET"&&so(e)||co(n.method,e);return r&&!(Le(t)||Ce(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!ho.has(e)?uo:null}const Pe=()=>ye()?"chatpanel-gateway pair":"chatpanel-bridge pair",uo=`forbidden: this client is not paired with the bridge — run \`${Pe()}\` and enter the code in ChatPanel Settings`,ho=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Z(n,e,t){const r=N(n),o=Ut(e,Lt(Yn(t,r)));if(!zn(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 (${Pe()})`} to use ${e}`};const a=o.reach,c=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 → Coding Agents to unlock them.";return{options:o,note:c}}async function $e(n,e,t){const r=e?.message||String(e);try{const o=await Y().status(),a=!!(o.enabled&&o.runtime)&&t?.outside!==!0,c=Yt(`${r}
3
+ ${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:E[n]?.label||n||"This agent"});if(c)return c.line}catch{}return r}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let 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)})}const Re=Nn({compute:po});async function po(){await pn();const n=await Promise.all(Object.entries(E).filter(([,a])=>!a.hidden).map(async([a,{engine:c,label:l,tools:s}])=>{const d=await c.available().catch(f=>({ok:!1,reason:String(f?.message||f)})),p=await at(a).catch(()=>[]),w=await it(a,{available:d.ok}).catch(()=>[]);return{id:a,label:l,available:d.ok,reason:d.reason,connectors:p,...w.length?{mcpServers:w}:{},...s===!1?{tools:!1}:{}}})),e=ye()?{current:y,updateAvailable:!1,embedded:"gateway"}:await mn(y).catch(()=>({current:y,updateAvailable:!1})),t=await gt().catch(()=>null),r=await Ct().catch(()=>null),o=await Y().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:r,sandboxStatus:o}}async function fo(n,{fresh:e=!1}={}){e&&hn();const{at:t,value:{agents:r,update:o,skills:a,agentDefs:c,sandboxStatus:l}}=await Re.get({fresh:e});i(n,200,{ok:!0,version:y,agents:r,update:o,checkedAt:t,workspace:_t,sandbox:l,localMcp:wn(),processes:jt(),worktrees:me,secretBackend:pe(),warm:vn(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...c?{agentDefs:c}:{}})}async function mo(n,e,t,r={}){const o=await J({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:pt(K(o,r)),problems:o.problems})}async function go(n,e,t){i(n,200,{ok:!0,quarantined:await wt(e,t)})}async function wo(n,e,t,r,o={}){const a=ft(K(await J({extraDirs:t,workdir:r}),o),e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function yo(n,e,t,r,o,a={}){const c=await mt(K(await J({extraDirs:r,workdir:o}),a),e,t);if(c.error)return i(n,c.error==="unknown skill"?404:400,{ok:!1,error:c.error});i(n,200,{ok:!0,...c})}async function bo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{const r=await yt({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return X(),i(e,200,r)}catch(r){return i(e,q(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function So(n,e,t,r){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await bt({name:t,path:r,text:o?.text??""});return X(),i(e,200,a)}catch(a){return i(e,q(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function ko(n,e){try{const t=await St({name:e});return X(),i(n,200,t)}catch(t){return i(n,q(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function q(n){return n instanceof kt?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Ie(n,e){return vt({roots:Tt(process.env,O.homedir(),n,e)})}async function To(n,e,t){const{index:r,quarantined:o,problems:a}=await Ie(e,t);i(n,200,{ok:!0,agents:Et(r),...o.length?{quarantined:o.map(c=>({id:c.agent.id,path:c.relPath,source:c.source,verdict:c.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function vo(n,e,t,r){const{index:o}=await Ie(t,r),a=xt(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function Eo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{return i(e,200,{ok:!0,...await At({agent:t?.agent,to:t?.to})})}catch(r){return i(e,Ne(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function xo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{return i(e,200,await Ot({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(r){return i(e,Ne(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function Ne(n){if(n instanceof Pt){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function Ao(){return(await Promise.all(Object.entries(E).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function De(n,e=""){const t=await Ao();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,S(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function Oo(n){try{const e=await we(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>ce(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function Co(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=E[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=Z(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)}
4
4
 
5
- `)};let c=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,s=ke(l),d={signal:s.signal,abort:()=>s.cancel("client")},p=()=>{c=!0,s.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const w=h=>{c||a(h)};a({type:"run",id:l}),o.note&&a({type:"status",text:o.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(f=await fe({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),z(l),e.writableEnded||e.end();return}}const _=f?f.path:Ht(t.options?.workingDir),W=Jt(t.agent,t.options),te=W?Xt(W):[];te.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...te])]}});let C=null;{const h=_,T=!!f||!_t(t.options?.workingDir),g=Mt(t.agent,t.options?.permissionMode,h,he(h,{grant:t.options?.sandbox}));a({type:"workdir",path:h,isDefault:!T,writeScope:g||void 0}),a({type:"status",text:`Working in ${h}${T?"":" (default)"}`}),g&&a({type:"status",text:g}),C=await Yt(h),C&&a({type:"scm",phase:"before",...C})}let j=null;if(C||f){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:T,connection:g}=qt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=on(T),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...g?{connection:g}:{}}),g&&a({type:"status",text:`Git credential: ${g.kind} · ${g.host}${g.hasSecret?"":" (no token stored)"} · push: ${T.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:T.CHATPANEL_SCM_PUSH}`})}const F=t.approvals===!0,b={...t.options||{},...f?{workingDir:f.path}:{},...j?{runEnv:j}:{},approvals:F};let R=null;(t.pageTools?.specs?.length||F)&&(R=Rt(w,t.pageTools?.specs||[]),b.permissionSession=R,t.pageTools?.specs?.length&&(b.mcp={url:`http://${v}:${k}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const Ge=jt();let ne=b.sandbox||null;F&&Ge.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&b.sandbox?.outside!==!0&&(b.accessGate=Ft({agent:t.agent,label:E[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>he(_,{grant:ne})}));try{const h=Rn(w),T=(g,H)=>ue(g.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:H,options:g,images:Array.isArray(t.images)?t.images:[]},h.emit,{signal:d.signal}));await Ee(t.agent,b,d.signal,async()=>{await T(b,t.system||"");let g=b;for(let H=0;H<2&&b.accessGate?.restart().length&&!d.signal.aborted;H++){const oe=b.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...oe])]}},ne=g.sandbox;const re=oe.map(Ue=>b.accessGate.short(Ue)).join(", ");h.seam(),w({type:"status",text:`Restarted with write access to ${re} — carrying on`}),await T(g,`${t.system||""}
5
+ `)};let c=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,s=ke(l),d={signal:s.signal,abort:()=>s.cancel("client")},p=()=>{c=!0,s.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const w=h=>{c||a(h)};a({type:"run",id:l}),o.note&&a({type:"status",text:o.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(f=await fe({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),z(l),e.writableEnded||e.end();return}}const _=f?f.path:Mt(t.options?.workingDir),W=Xt(t.agent,t.options),te=W?Kt(W):[];te.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...te])]}});let C=null;{const h=_,T=!!f||!Ht(t.options?.workingDir),g=Bt(t.agent,t.options?.permissionMode,h,he(h,{grant:t.options?.sandbox}));a({type:"workdir",path:h,isDefault:!T,writeScope:g||void 0}),a({type:"status",text:`Working in ${h}${T?"":" (default)"}`}),g&&a({type:"status",text:g}),C=await zt(h),C&&a({type:"scm",phase:"before",...C})}let j=null;if(C||f){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:T,connection:g}=en({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=rn(T),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...g?{connection:g}:{}}),g&&a({type:"status",text:`Git credential: ${g.kind} · ${g.host}${g.hasSecret?"":" (no token stored)"} · push: ${T.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:T.CHATPANEL_SCM_PUSH}`})}const F=t.approvals===!0,b={...t.options||{},...f?{workingDir:f.path}:{},...j?{runEnv:j}:{},approvals:F};let R=null;(t.pageTools?.specs?.length||F)&&(R=It(w,t.pageTools?.specs||[]),b.permissionSession=R,t.pageTools?.specs?.length&&(b.mcp={url:`http://${v}:${k}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const Ge=Ft();let ne=b.sandbox||null;F&&Ge.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&b.sandbox?.outside!==!0&&(b.accessGate=Jt({agent:t.agent,label:E[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>he(_,{grant:ne})}));try{const h=In(w),T=(g,H)=>ue(g.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:H,options:g,images:Array.isArray(t.images)?t.images:[]},h.emit,{signal:d.signal}));await Ee(t.agent,b,d.signal,async()=>{await T(b,t.system||"");let g=b;for(let H=0;H<2&&b.accessGate?.restart().length&&!d.signal.aborted;H++){const oe=b.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...oe])]}},ne=g.sandbox;const re=oe.map(Ue=>b.accessGate.short(Ue)).join(", ");h.seam(),w({type:"status",text:`Restarted with write access to ${re} — carrying on`}),await T(g,`${t.system||""}
6
6
 
7
- [ChatPanel] The person has just allowed writing in ${re}, and you were restarted with that access. Carry on with their request: do the step that was blocked. Do not ask again.`.trim())}h.finish()})}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),h?.detail&&u("error",`${t.agent} said: ${h.detail}`),a({type:"error",error:await $e(t.agent,h,b.sandbox)})}finally{if(!c){const h=await zt(_,C).catch(()=>null);h&&w({type:"scm",phase:"after",...h})}z(l),R&&le(R.id),e.writableEnded||e.end()}}async function Co(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:Vt(),secretBackend:pe()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:Qt(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:Zt(o[1])}):i(e,200,en(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function Po(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:me,worktrees:await tn()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/worktrees"){const o=await fe({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 nn({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 A(n,e,t){const r=E[n.agent];if(!r||r.hidden)throw new P(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(d=>({ok:!1,reason:d?.message||String(d)}));if(!o.ok)throw new P(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,c=ke(a),l=()=>c.cancel("disconnected");t.on("close",l);let s="";try{return await ue(n.options?.sandbox,()=>Ee(n.agent,n.options,c.signal,()=>r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},d=>{d?.type==="delta"&&d.text?(s+=d.text,e(d.text)):d?.type==="done"&&d.text&&!s&&(s=d.text,e(d.text))},{signal:c.signal}))),s}catch(d){throw d instanceof Error&&!(d instanceof P)&&(d.message=await $e(n.agent,d,n.options?.sandbox)),d}finally{t.off("close",l),z(a)}}function G(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function $(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
7
+ [ChatPanel] The person has just allowed writing in ${re}, and you were restarted with that access. Carry on with their request: do the step that was blocked. Do not ask again.`.trim())}h.finish()})}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),h?.detail&&u("error",`${t.agent} said: ${h.detail}`),a({type:"error",error:await $e(t.agent,h,b.sandbox)})}finally{if(!c){const h=await Vt(_,C).catch(()=>null);h&&w({type:"scm",phase:"after",...h})}z(l),R&&le(R.id),e.writableEnded||e.end()}}async function Po(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:Qt(),secretBackend:pe()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:Zt(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:qt(o[1])}):i(e,200,tn(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function $o(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:me,worktrees:await nn()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/worktrees"){const o=await fe({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 on({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 A(n,e,t){const r=E[n.agent];if(!r||r.hidden)throw new P(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(d=>({ok:!1,reason:d?.message||String(d)}));if(!o.ok)throw new P(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,c=ke(a),l=()=>c.cancel("disconnected");t.on("close",l);let s="";try{return await ue(n.options?.sandbox,()=>Ee(n.agent,n.options,c.signal,()=>r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},d=>{d?.type==="delta"&&d.text?(s+=d.text,e(d.text)):d?.type==="done"&&d.text&&!s&&(s=d.text,e(d.text))},{signal:c.signal}))),s}catch(d){throw d instanceof Error&&!(d instanceof P)&&(d.message=await $e(n.agent,d,n.options?.sandbox)),d}finally{t.off("close",l),z(a)}}function G(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function $(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
8
8
 
9
9
  `)}function U(n,e,t){n.writableEnded||n.write(`event: ${e}
10
10
  data: ${JSON.stringify(t)}
11
11
 
12
- `)}async function L(n,e,t,r){try{const o=t(await m(n)),a=Z(n,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 $o(n,e){const t=await L(n,e,Ln,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Mn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Dn(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Ro(n,e){const t=await L(n,e,Wn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Bn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=_n(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Io(n,e){const t=await L(n,e,jn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Gn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Fn(t.requestedModel,o=>U(e,o.type,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...S(o)};U(e,"error",a)}e.end()}async function No(n,e){const t=await L(n,e,Un,V);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Hn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,V(o))}G(e);const r=Nn(t.requestedModel,(o,a)=>U(e,o,a));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",V(o))}e.end()}async function Do(n,e){let t={};try{t=await m(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?bn(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function _e(n,e,t){let r;try{r=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?de(t):It(),a=s=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:s})},c=(s,d)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:s,message:d}});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:y}});const l=Pt();if(r.method==="tools/list"){const s=o?o.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...l,...s]})}if(r.method==="tools/call"){const s=await $t(r.params?.name,r.params?.arguments||{});if(s)return a(s);if(!o)return c(-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 Nt(o,r.params?.name,r.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return c(-32601,`Method not found: ${r.method}`)}async function _o(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{},o=t.message;if(!r.command&&!r.from||!o)return i(e,400,{error:"need server.command (or server.from) and message"});try{let a;if(r.from){if(a=await se(r),a.builtin&&o.method==="tools/call"){const l=await it(a.builtin,o);if(l)return i(e,200,{jsonrpc:"2.0",id:o.id??null,result:{content:[{type:"text",text:`Refused: ${l}`}],isError:!0}})}}else a={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};let c=await mn(a,o);return a.builtin&&o.method==="tools/list"&&(c=st(a.builtin,c)),o.id==null?(e.writeHead(202),e.end()):i(e,200,c)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Ho(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t.server||{};if(!r.command&&!r.from)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});try{const o=r.from?await se(r):{key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};return i(e,200,t.status?yn(o):await wn(o))}catch(o){return i(e,200,{state:"failed",error:String(o?.message||o)})}}async function Mo(n,e){let t;try{t=await m(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 c;try{c=be(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const l={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,w]of Object.entries(o)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(l[p]=String(w))}const s=new AbortController,d=setTimeout(()=>s.abort(),3e4);try{const p=await fetch(c.href,{method:"POST",headers:l,body:JSON.stringify(a),redirect:"follow",signal:s.signal});try{p.url&&be(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const w=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:w})}catch(p){const w=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${c.host}: ${w}`})}finally{clearTimeout(d)}}const He=256*1024,Bo=5,Go=8e3;async function Uo(n){let e=Se(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Go);try{for(let o=0;o<=Bo;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/${y} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=Se(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 c=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(c)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:jo(await Lo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Lo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,He);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:c}=await e.read();if(a||(o+=c.byteLength,r+=t.decode(c,{stream:!0}),/<\/title\s*>/i.test(r)||o>=He))break}}finally{try{await e.cancel()}catch{}}return r}function Wo(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 jo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Wo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Fo(n,e){let t;try{t=await m(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 Uo(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 Jo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=de(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 Xo(n,e){let t;try{t=await m(n)}catch(s){return i(e,400,{error:"Bad JSON: "+s.message})}const r=E[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||"",c=Z(n,t.agent,{model:a});if(c.error)return i(e,403,{error:c.error});const l=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 s="";return typeof r.engine.complete=="function"?s=await r.engine.complete({prompt:o,system:l,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:l,options:c.options},d=>{d.type==="delta"?s+=d.text||"":d.type==="done"&&d.text&&(s+=d.text)}),i(e,200,{text:(s||"").trim()})}catch(s){return i(e,502,{error:s?.message||String(s)})}}async function Ko(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=E[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 Yo(n,e){let t;try{t=await m(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=ge(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}async function zo(n,e,t){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(r?.agent||"");if(!Te.includes(o))return i(e,404,{error:`${o||"that agent"} keeps no sessions Chap can read (it can: ${Te.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await vn(o,{limit:r.limit})});if(t==="/agent-sessions/read"){const a=await En(o,String(r.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=ve({id:r.thread?.id??r.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const c=await xn(o,String(r.id||""),a.id);return c?i(e,200,{session:c}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=ve({id:r.thread?.id??r.thread});return a?i(e,200,await An(o,a.id,Array.isArray(r.messages)?r.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const ee=We(async(n,e)=>{if(Zn(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=co(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return po(e,{fresh:t.searchParams.get("fresh")==="1"});const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"",c={agent:t.searchParams.get("agent")||"",source:t.searchParams.get("source")||""};if(n.method==="GET"&&t.pathname==="/skills")return fo(e,o,a,c);if(n.method==="POST"&&t.pathname==="/agent-context"){const l=await m(n).catch(()=>({})),s=l?.options&&typeof l.options=="object"?l.options:{},d={...s.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof s.permissionMode=="string"?{permissionMode:s.permissionMode}:{},...typeof s.workingDir=="string"&&s.workingDir?{workingDir:s.workingDir}:{},...typeof s.model=="string"&&s.model?{model:s.model}:{}};return i(e,200,await On({agent:typeof l?.agent=="string"?l.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return mo(e,o,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return ko(e,o,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return vo(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return Eo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return To(e,decodeURIComponent(t.pathname.slice(12)),o,a);if(n.method==="POST"&&t.pathname==="/skills")return yo(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?n.method==="DELETE"?So(e,decodeURIComponent(l)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):bo(n,e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?go(e,decodeURIComponent(l),o,a,c):wo(e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)),o,a,c)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Co(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Po(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return De(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return De(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const l=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:y,agents:Object.fromEntries(rn.map(s=>[s,l?dn(s)||ge(s)?.kind||null:an(s)])),...l?{home:O.homedir(),path:process.env.PATH,installDirs:sn(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return zo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/pair")return no(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return to(e);if(n.method==="POST"&&t.pathname==="/whoami")return oo(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return $o(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Ro(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return Io(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return No(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return _e(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const l=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return _e(n,e,l);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return le(l),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return Oe(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return Oe(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Do(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Jo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let l=null;try{l=await m(n)}catch{l=null}const s=Lt(l||{});return e.writeHead(s?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return _o(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Mo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Fo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Xo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Ko(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Yo(n,e);if(n.method==="POST"&&t.pathname==="/update")return Ao(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 Vo(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},c=async()=>{if(!r){for(r=!0;t.length;){const l=t.shift();let s;try{s=JSON.parse(l)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:l});if(s.id==null)continue;const p=(await d.text()).trim();p&&process.stdout.write(p+`
12
+ `)}async function L(n,e,t,r){try{const o=t(await m(n)),a=Z(n,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 Ro(n,e){const t=await L(n,e,Wn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Bn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=_n(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Io(n,e){const t=await L(n,e,jn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Gn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Hn(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function No(n,e){const t=await L(n,e,Fn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Un(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Jn(t.requestedModel,o=>U(e,o.type,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...S(o)};U(e,"error",a)}e.end()}async function Do(n,e){const t=await L(n,e,Ln,V);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Mn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,V(o))}G(e);const r=Dn(t.requestedModel,(o,a)=>U(e,o,a));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",V(o))}e.end()}async function _o(n,e){let t={};try{t=await m(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?Sn(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function _e(n,e,t){let r;try{r=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?de(t):Nt(),a=s=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:s})},c=(s,d)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:s,message:d}});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:y}});const l=$t();if(r.method==="tools/list"){const s=o?o.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...l,...s]})}if(r.method==="tools/call"){const s=await Rt(r.params?.name,r.params?.arguments||{});if(s)return a(s);if(!o)return c(-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 Dt(o,r.params?.name,r.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return c(-32601,`Method not found: ${r.method}`)}async function Ho(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{},o=t.message;if(!r.command&&!r.from||!o)return i(e,400,{error:"need server.command (or server.from) and message"});try{let a;if(r.from){if(a=await se(r),a.builtin&&o.method==="tools/call"){const l=await st(a.builtin,o);if(l)return i(e,200,{jsonrpc:"2.0",id:o.id??null,result:{content:[{type:"text",text:`Refused: ${l}`}],isError:!0}})}}else a={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};let c=await gn(a,o);return a.builtin&&o.method==="tools/list"&&(c=ct(a.builtin,c)),o.id==null?(e.writeHead(202),e.end()):i(e,200,c)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Mo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t.server||{};if(!r.command&&!r.from)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});try{const o=r.from?await se(r):{key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};return i(e,200,t.status?bn(o):await yn(o))}catch(o){return i(e,200,{state:"failed",error:String(o?.message||o)})}}async function Bo(n,e){let t;try{t=await m(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 c;try{c=be(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const l={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,w]of Object.entries(o)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(l[p]=String(w))}const s=new AbortController,d=setTimeout(()=>s.abort(),3e4);try{const p=await fetch(c.href,{method:"POST",headers:l,body:JSON.stringify(a),redirect:"follow",signal:s.signal});try{p.url&&be(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const w=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:w})}catch(p){const w=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${c.host}: ${w}`})}finally{clearTimeout(d)}}const He=256*1024,Go=5,Uo=8e3;async function Lo(n){let e=Se(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Uo);try{for(let o=0;o<=Go;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/${y} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=Se(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 c=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(c)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:Fo(await Wo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Wo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,He);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:c}=await e.read();if(a||(o+=c.byteLength,r+=t.decode(c,{stream:!0}),/<\/title\s*>/i.test(r)||o>=He))break}}finally{try{await e.cancel()}catch{}}return r}function jo(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 Fo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?jo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Jo(n,e){let t;try{t=await m(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 Lo(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 Xo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=de(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 Ko(n,e){let t;try{t=await m(n)}catch(s){return i(e,400,{error:"Bad JSON: "+s.message})}const r=E[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||"",c=Z(n,t.agent,{model:a});if(c.error)return i(e,403,{error:c.error});const l=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 s="";return typeof r.engine.complete=="function"?s=await r.engine.complete({prompt:o,system:l,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:l,options:c.options},d=>{d.type==="delta"?s+=d.text||"":d.type==="done"&&d.text&&(s+=d.text)}),i(e,200,{text:(s||"").trim()})}catch(s){return i(e,502,{error:s?.message||String(s)})}}async function Yo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=E[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 zo(n,e){let t;try{t=await m(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=ge(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}async function Vo(n,e,t){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(r?.agent||"");if(!Te.includes(o))return i(e,404,{error:`${o||"that agent"} keeps no sessions Chap can read (it can: ${Te.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await En(o,{limit:r.limit})});if(t==="/agent-sessions/read"){const a=await xn(o,String(r.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=ve({id:r.thread?.id??r.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const c=await An(o,String(r.id||""),a.id);return c?i(e,200,{session:c}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=ve({id:r.thread?.id??r.thread});return a?i(e,200,await On(o,a.id,Array.isArray(r.messages)?r.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const ee=je(async(n,e)=>{if(qn(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=lo(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return fo(e,{fresh:t.searchParams.get("fresh")==="1"});const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"",c={agent:t.searchParams.get("agent")||"",source:t.searchParams.get("source")||""};if(n.method==="GET"&&t.pathname==="/skills")return mo(e,o,a,c);if(n.method==="POST"&&t.pathname==="/agent-context"){const l=await m(n).catch(()=>({})),s=l?.options&&typeof l.options=="object"?l.options:{},d={...s.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof s.permissionMode=="string"?{permissionMode:s.permissionMode}:{},...typeof s.workingDir=="string"&&s.workingDir?{workingDir:s.workingDir}:{},...typeof s.model=="string"&&s.model?{model:s.model}:{}};return i(e,200,await Cn({agent:typeof l?.agent=="string"?l.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return go(e,o,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return To(e,o,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return Eo(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return xo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return vo(e,decodeURIComponent(t.pathname.slice(12)),o,a);if(n.method==="POST"&&t.pathname==="/skills")return bo(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?n.method==="DELETE"?ko(e,decodeURIComponent(l)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):So(n,e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?wo(e,decodeURIComponent(l),o,a,c):yo(e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)),o,a,c)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Po(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return $o(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return De(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return De(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const l=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:y,agents:Object.fromEntries(an.map(s=>[s,l?un(s)||ge(s)?.kind||null:sn(s)])),...l?{home:O.homedir(),path:process.env.PATH,installDirs:cn(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Vo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return Co(n,e);if(n.method==="POST"&&t.pathname==="/pair")return oo(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return no(e);if(n.method==="POST"&&t.pathname==="/whoami")return ro(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return Ro(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Io(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return No(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Do(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return _e(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const l=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return _e(n,e,l);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return le(l),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return Oe(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return Oe(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return _o(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Xo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let l=null;try{l=await m(n)}catch{l=null}const s=Wt(l||{});return e.writeHead(s?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return Ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Mo(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Bo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Jo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Ko(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Yo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return zo(n,e);if(n.method==="POST"&&t.pathname==="/update")return Oo(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 Qo(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},c=async()=>{if(!r){for(r=!0;t.length;){const l=t.shift();let s;try{s=JSON.parse(l)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:l});if(s.id==null)continue;const p=(await d.text()).trim();p&&process.stdout.write(p+`
13
13
  `)}catch(d){s.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:s.id,error:{code:-32e3,message:String(d?.message||d)}})+`
14
14
  `)}}r=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",l=>{e+=l;let s;for(;(s=e.indexOf(`
15
- `))>=0;){const d=e.slice(0,s).trim();e=e.slice(s+1),d&&t.push(d)}c()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Qo(){cn(),ln(),eo();let n=!1;ee.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${k}/health`,{signal:AbortSignal.timeout(1500)}).then(t=>t.ok?t.json():null).catch(()=>null).then(t=>{const r=!!(t?.version&&Array.isArray(t.agents)),o=Cn({name:"bridge",self:y,holder:r?{ours:r,version:t.version}:null,managedBy:Pn(process.env),port:k});if(o.action==="standby"||n&&!t){if(!n)for(const a of o.lines)u("info",a);n=!0,setTimeout(()=>ee.listen(k,v),$n);return}if(r)for(const a of o.lines)u("error",a);else u("error",`Port ${k} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings.");process.exit(1)});return}u("error",`bridge server error: ${e?.message||e}`),process.exit(1)});for(const e of["SIGINT","SIGTERM"])process.on(e,()=>{const t=Sn("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const r=kn("shutdown");r&&u("info",`shutdown: closed ${r} warm agent process${r===1?"":"es"}`),Y().close(),setTimeout(()=>process.exit(0),t||r?300:0).unref?.(),!t&&!r&&process.exit(0)});ee.listen(k,v,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${v}:${k}`),Re.warm(),Q.has(v)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${v}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:e,label:t,hidden:r}]of Object.entries(E)){if(r)continue;const o=await e.available().catch(()=>({ok:!1}));u("info",` ${o.ok?"✓":"✕"} ${t}${o.ok?"":" — "+(o.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),Ae().then(e=>e.startIfConfigured()).then(e=>{e?.skipped||(e?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${e?.error||"unknown error"}`))}).catch(e=>u("error",`channels: ${e?.message||e}`))})}function Zo(){console.log(`ChatPanel Bridge v${y}
15
+ `))>=0;){const d=e.slice(0,s).trim();e=e.slice(s+1),d&&t.push(d)}c()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Zo(){We(),ln(),dn(),to();let n=!1;ee.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${k}/health`,{signal:AbortSignal.timeout(1500)}).then(t=>t.ok?t.json():null).catch(()=>null).then(t=>{const r=!!(t?.version&&Array.isArray(t.agents)),o=Pn({name:"bridge",self:y,holder:r?{ours:r,version:t.version}:null,managedBy:$n(process.env),port:k});if(o.action==="standby"||n&&!t){if(!n)for(const a of o.lines)u("info",a);n=!0,setTimeout(()=>ee.listen(k,v),Rn);return}if(r)for(const a of o.lines)u("error",a);else u("error",`Port ${k} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings.");process.exit(1)});return}u("error",`bridge server error: ${e?.message||e}`),process.exit(1)});for(const e of["SIGINT","SIGTERM"])process.on(e,()=>{const t=kn("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const r=Tn("shutdown");r&&u("info",`shutdown: closed ${r} warm agent process${r===1?"":"es"}`),Y().close(),setTimeout(()=>process.exit(0),t||r?300:0).unref?.(),!t&&!r&&process.exit(0)});ee.listen(k,v,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${v}:${k}`),Re.warm(),Q.has(v)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${v}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:e,label:t,hidden:r}]of Object.entries(E)){if(r)continue;const o=await e.available().catch(()=>({ok:!1}));u("info",` ${o.ok?"✓":"✕"} ${t}${o.ok?"":" — "+(o.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),Ae().then(e=>e.startIfConfigured()).then(e=>{e?.skipped||(e?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${e?.error||"unknown error"}`))}).catch(e=>u("error",`channels: ${e?.message||e}`))})}function qo(){console.log(`ChatPanel Bridge v${y}
16
16
 
17
17
  Usage:
18
18
  chatpanel-bridge start the bridge (foreground) on ${v}:${k}
@@ -24,4 +24,4 @@ Usage:
24
24
  chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
25
25
  chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
26
26
 
27
- Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function qo(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return Zo(),!0;if(e("--version","-v"))return console.log(y),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=ie(D,"utf8").trim()}catch{}const r=`http://${v}:${k}`;try{if(!t)throw new Error(`no token at ${D} — 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: ${Vn(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "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 Bt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{lt(),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{dt(),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=ut()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const Me=process.argv.indexOf("--mcp-stdio"),Be=process.argv.indexOf("--sandbox-host");if(Be>=0){const{runSandboxHost:n}=await import("./sandbox-host.js");await n(process.argv[Be+1],{compiled:pn()})}else if(Me>=0){const n=process.argv[Me+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Vo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await we(y);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),ce()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():qo()||Qo();
27
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function er(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return qo(),!0;if(e("--version","-v"))return console.log(y),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=ie(D,"utf8").trim()}catch{}const r=`http://${v}:${k}`;try{if(!t)throw new Error(`no token at ${D} — 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: ${Qn(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "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 Gt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{dt(),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{ut(),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=ht()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const Me=process.argv.indexOf("--mcp-stdio"),Be=process.argv.indexOf("--sandbox-host");if(Be>=0){const{runSandboxHost:n}=await import("./sandbox-host.js");await n(process.argv[Be+1],{compiled:fn()})}else if(Me>=0){const n=process.argv[Me+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Qo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await we(y);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),ce()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():er()||Zo();