@chatpanel/bridge 0.53.0 → 0.53.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.53.0",
3
+ "version": "0.53.2",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
package/src/env.js CHANGED
@@ -1,2 +1,2 @@
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 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 hn(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(f(c.join(o,n))||f(c.join(o,n+".exe"))))}function bn(n){const t=I(n);if(t)return t;if(k()){const o=I(n);if(o)return o}return xn(n)||null}function tt(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 et(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 b="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(b))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 gn(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=J}={}){const o=T(t(`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,{interactive:n}));return d(o||gn(t("/usr/bin/env",{interactive:n})),process.platform)}const y=1e4,_n=3e5;let L=0,x=y;function k({force:n=!1,now:t=Date.now(),read:o=Pn,env:e=process.env}={}){if(process.platform==="win32"||!n&&(t-L<x||t<_))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,_n),s?(e.PATH=r.join(c.delimiter),!0):!1}function ot(){L=0,x=y,w.clear(),_=0,A=H,O=!1}const w=new Map,An=15e3;function xn(n){if(process.platform==="win32"||!q(n))return"";const t=w.get(n);if(t&&(t.bin||Date.now()-t.at<An||Date.now()<_))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${b} "$(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,En=3e5;let _=0,A=H,O=!1,E=null;function Sn(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 Cn=new RegExp(`${b}=([\\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=Cn.exec(o.slice(0,e).trim());i&&t.set(i[1],o.slice(e+1).trim())}return t}function it({names:n=R,ask:t=Sn,now:o=()=>Date.now()}={}){if(process.platform==="win32"||O)return Promise.resolve(!1);if(E)return E;if(o()<_)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' ${b} "$PATH"`,...e.map(r=>`command -p printf '%s\\t%s\\n' ${b}=${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 O=!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 g=s.get(p),P=g.startsWith("/")&&f(g)?g:"";(P||I(p))&&(a=!0),w.set(p,{bin:P,at:l})}return a&&(A=H),_=l+A,a||(A=Math.min(A*2,En)),!0})().catch(()=>!0).finally(()=>{E=null}),E}function rt(){_=0,A=H,O=!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 st({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)&&Fn(n,{probe:t})?{kind:"wsl",command:n}:null)}const e=bn(n);return e?{kind:"native",bin:e}:null}const Mn="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",In="HKCU\\Environment",Tn=4e3,vn=3e5;let F=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=h(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 Hn({query:n=Ln,env:t=process.env}={}){const o=tn(n(Mn,"Path"),t),e=tn(n(In,"Path"),t);return m([...d(o,"win32"),...d(e,"win32")])}function On({run:n=Nn}={}){const t=n(`[Console]::Out.Write("${b}\`t" + $env:PATH + "\`n")`);return d(T(t),"win32")}function Nn(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=Hn,profile:e=On,env:i=process.env,home:r=j.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-nn<Tn)return!1;nn=t;const s=d(i.PATH||"","win32"),l=m([...s,...o({env:i}),...G(r,"win32",i)]);t-F>=vn&&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 Dn(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"&&$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=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 $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=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,N=new Map,kn=15e3,Bn=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:kn,Bn);S.set(n,{ok:t,at:o,ttl:i})}function Fn(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(!N.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 g=setTimeout(()=>{try{p.kill()}catch{}},rn);p.stdout?.on("data",P=>{u+=P}),p.on("error",()=>{clearTimeout(g),a(!1)}),p.on("close",P=>{clearTimeout(g),a(cn(P,u))})}).then(a=>(ln(n,a,Date.now()),a)).finally(()=>N.delete(n));N.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 ct(n){return N.get(n)||null}function lt(n,t,o,e=null){const i=e&&typeof e=="object"&&Object.keys(e).length?{...process.env,...e}:process.env;if(n.kind==="wsl"){const s=[];if(o){const a=Kn(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 Kn(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 Vn(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 Yn(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 Gn(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"),...Un(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",...Yn(n,o)]}function Un(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 Xn(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,...Xn(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 at(){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 ut(){if(z)return;z=!0;const n=j.homedir();if(process.platform==="win32"){en({force:!0,home:n});return}const t=Vn(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),...Gn(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=>!hn(s))&&k({force:!0})}export{R as AGENT_CLIS,tt as agentAvailable,Xn as agentCandidateBins,G as agentInstallDirs,lt as buildSpawnSpec,Y as capPathList,dn as commandCandidateFiles,Fn as commandInWsl,at as enrichAgentEnv,ut as enrichPath,tn as expandWindowsEnv,bn as findAgentBin,rt as forgetMisses,$ as isCompiledBinary,fn as isWindowsExecutable,Rn as nodeRuntimeWindows,Vn as nvmCurrentBin,gn as parseEnvPath,yn as parseRegValue,T as parseSentinel,Z as parseWhich,it as primeAgentLookups,On as profilePathWindows,k as refreshShellPath,en as refreshWindowsPath,Hn as registryPathWindows,ot as resetShellProbes,st as resolveClaude,B as resolveCommand,et as selfMcpStdio,Pn as shellPath,Kn as toWslPath,cn as wslAnswer,ct as wslProbeInFlight};
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,2 +1,2 @@
1
- const T="permission_request",u=Object.freeze({ALLOW:"allow",ALLOW_CHAT:"allow_chat",DENY:"deny"}),W=600*1e3,w="permission_prompt";function E(){return{name:w,description:"Chap-internal: the person answers the agent's permission prompt. Not for the model.",parameters:{type:"object",properties:{tool:{type:"string"},input:{type:"object"},description:{type:"string"},path:{type:"string"},rules:{type:"array"}}}}}const k=t=>t===w,p=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),a=t=>typeof t=="string"?t:t==null?"":String(t);function R(t={}){const e=p(t)?t:{},o=a(e.tool_name||e.toolName||e.tool),s=[];for(const n of Array.isArray(e.permission_suggestions)?e.permission_suggestions:[])if(!(!p(n)||n.type!=="addRules"||n.behavior==="deny"))for(const l of Array.isArray(n.rules)?n.rules:[]){if(!p(l))continue;const c=a(l.toolName||o),i=a(l.ruleContent);c&&!s.some(f=>f.tool===c&&f.content===i)&&s.push({tool:c,content:i})}return{tool:o,displayName:a(e.display_name||e.displayName)||o,input:p(e.input)?e.input:{},description:a(e.description),path:a(e.blocked_path||e.path)||null,rules:s,toolUseId:a(e.tool_use_id||e.toolUseId)||null}}function A(t={}){const e=Array.isArray(t.rules)?t.rules.filter(o=>o&&o.tool):[];return e.length?e.map(o=>o.content?`${o.tool}(${o.content})`:o.tool):t.tool?[String(t.tool)]:[]}function L(t={}){const e=a(t.tool),o=p(t.input)?t.input:{},s=(r,d=240)=>r.length>d?`${r.slice(0,d-1)}…`:r;let n,l;if(e==="Bash")n="Run a command",l=s(a(o.command).trim()||a(t.description)||"a shell command");else if(e==="Edit"||e==="MultiEdit"||e==="NotebookEdit")n="Edit a file",l=a(o.file_path||o.notebook_path||t.path)||"a file";else if(e==="Write"){n="Write a file";const r=a(o.file_path||t.path)||"a file",d=a(o.content).length;l=d?`${r} (${d.toLocaleString()} chars)`:r}else if(/^mcp__/.test(e))n="Use a connected server",l=e.replace(/^mcp__/,"").replace(/__/," › ");else{n=`Use ${t.displayName||e||"a tool"}`;let r="";try{r=JSON.stringify(o)}catch{r=""}l=a(t.description)||(r&&r!=="{}"?s(r,200):e)}const c=A(t),i=Array.isArray(t.rules)?t.rules.filter(r=>r?.content):[],f=i.length&&i.some(r=>r.content!==l)?i.map(r=>r.content).join(", "):c.length&&!i.length?`every ${e} call`:null,h=p(t.access)?a(t.access.folder):"",g=h?`This works in ${h}, outside the folders it may change. Allowing it opens ${h} to it for the rest of this chat.`:null;return{title:n,detail:l,scope:f,description:a(t.description)||null,access:g}}function m(t,e=""){return t===u.ALLOW?{behavior:"allow",scope:"once"}:t===u.ALLOW_CHAT?{behavior:"allow",scope:"chat"}:{behavior:"deny",scope:"once",...e?{message:String(e)}:{}}}function b(t){return p(t)&&t.behavior==="allow"}function O(t,e){const o=new Set(Array.isArray(t)?t:[]);for(const s of A(e))o.add(s);return[...o].sort()}const S="*";function x(t,e){const o=new Set(Array.isArray(t)?t:[]);if(o.has(S))return m(u.ALLOW);const s=A(e);return s.length&&s.every(n=>o.has(n))?m(u.ALLOW):null}function C(t,e,o={}){const s=p(o)?o:{},n=b(e);let l;if(n){if(l={behavior:"allow",updatedInput:p(s.input)?s.input:{}},e.scope==="chat"){const c=(Array.isArray(s.permission_suggestions)?s.permission_suggestions:[]).filter(i=>p(i)&&i.type==="addRules"&&i.behavior!=="deny"&&Array.isArray(i.rules)&&i.rules.length).map(i=>({type:"addRules",rules:i.rules,behavior:"allow",destination:"session"}));c.length&&(l.updatedPermissions=c)}}else l={behavior:"deny",message:a(e?.message)||"The user declined this action in Chap. Continue without it, or explain what it was for and ask."};return{type:"control_response",response:{subtype:"success",request_id:String(t),response:l}}}function P(t,e){const{detail:o}=L(t),s=b(e),n=s&&e.scope==="chat"?" for this chat":"";return`${s?"Allowed":"Declined"}${n}: ${o}`}function $(t){return t==="Bash"?"code":/^(Edit|MultiEdit|NotebookEdit)$/.test(String(t))?"pencil":t==="Write"?"file":/^mcp__/.test(String(t))?"plug":"bot"}function I({memory:t=new Map}={}){const e=t;async function o(s,{convId:n=null,confirm:l,agentName:c="The agent"}={}){const i=p(s.access)?null:x(await e.get(n)||[],s);if(i)return i;const{title:f,detail:h,scope:g,description:r,access:d}=L(s),N=[d,h,r&&r!==h?r:"",g?`“Allow for this chat” also covers: ${g}`:""].filter(Boolean).join(`
2
- `);let y;try{if(typeof l!="function")throw new Error("no card");y=await l(N,{title:`${c} asks — ${f.toLowerCase()}?`,iconName:$(s.tool),scopeLabel:"Allow for this chat",allLabel:"Allow all in this chat"})}catch(_){return m(u.DENY,`Chap could not show the permission card (${_?.message||_}).`)}return y==="all"?(await e.set(n,[S]),m(u.ALLOW_CHAT)):y==="site"||y==="always"?(await e.set(n,O(await e.get(n)||[],s)),m(u.ALLOW_CHAT)):m(y==="allow"?u.ALLOW:u.DENY)}return{ask:o,forget(s){e.delete(s)},standing(s){return e.get(s)||[]},provider({convId:s=null,confirm:n,agentName:l="The agent"}={}){return{id:"permission",specs:[E()],execute:async(c,i)=>JSON.stringify(await o(i&&typeof i=="object"?i:{},{convId:s,confirm:n,agentName:l}))}}}}export{S as ALLOW_ALL,u as PERMISSION_ANSWERS,T as PERMISSION_EVENT,W as PERMISSION_TIMEOUT_MS,w as PERMISSION_TOOL_NAME,C as claudePermissionResponse,I as createPermissionDesk,L as describePermission,k as isPermissionTool,b as permissionAllowed,m as permissionAnswer,$ as permissionIcon,A as permissionKeys,P as permissionLine,R as permissionRequestFromClaude,E as permissionToolSpec,x as recallPermission,O as rememberPermission};
1
+ const T="permission_request",h=Object.freeze({ALLOW:"allow",ALLOW_CHAT:"allow_chat",DENY:"deny"}),k=600*1e3,L="permission_prompt";function N(){return{name:L,description:"Chap-internal: the person answers the agent's permission prompt. Not for the model.",parameters:{type:"object",properties:{tool:{type:"string"},input:{type:"object"},description:{type:"string"},path:{type:"string"},rules:{type:"array"}}}}}const C=t=>t===L,c=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),a=t=>typeof t=="string"?t:t==null?"":String(t);function P(t={}){const e=c(t)?t:{},o=a(e.tool_name||e.toolName||e.tool),n=[];for(const s of Array.isArray(e.permission_suggestions)?e.permission_suggestions:[])if(!(!c(s)||s.type!=="addRules"||s.behavior==="deny"))for(const r of Array.isArray(s.rules)?s.rules:[]){if(!c(r))continue;const p=a(r.toolName||o),l=a(r.ruleContent);p&&!n.some(u=>u.tool===p&&u.content===l)&&n.push({tool:p,content:l})}return{tool:o,displayName:a(e.display_name||e.displayName)||o,input:c(e.input)?e.input:{},description:a(e.description),path:a(e.blocked_path||e.path)||null,rules:n,toolUseId:a(e.tool_use_id||e.toolUseId)||null}}function A(t={}){const e=Array.isArray(t.rules)?t.rules.filter(o=>o&&o.tool):[];return e.length?e.map(o=>o.content?`${o.tool}(${o.content})`:o.tool):t.tool?[String(t.tool)]:[]}function S(t={}){const e=a(t.tool),o=c(t.input)?t.input:{},n=(i,m=240)=>i.length>m?`${i.slice(0,m-1)}…`:i;let s,r;if(e==="Bash")s="Run a command",r=n(a(o.command).trim()||a(t.description)||"a shell command");else if(e==="Edit"||e==="MultiEdit"||e==="NotebookEdit")s="Edit a file",r=a(o.file_path||o.notebook_path||t.path)||"a file";else if(e==="Write"){s="Write a file";const i=a(o.file_path||t.path)||"a file",m=a(o.content).length;r=m?`${i} (${m.toLocaleString()} chars)`:i}else if(/^mcp__/.test(e))s="Use a connected server",r=e.replace(/^mcp__/,"").replace(/__/," › ");else{s=`Use ${t.displayName||e||"a tool"}`;let i="";try{i=JSON.stringify(o)}catch{i=""}r=a(t.description)||(i&&i!=="{}"?n(i,200):e)}const p=A(t),l=Array.isArray(t.rules)?t.rules.filter(i=>i?.content):[],u=l.length&&l.some(i=>i.content!==r)?l.map(i=>i.content).join(", "):p.length&&!l.length?`every ${e} call`:null,f=c(t.access)?a(t.access.folder):"",d=f?`This works in ${f}, outside the folders it may change. Allowing it opens ${f} to it for the rest of this chat.`:null;return{title:s,detail:r,scope:u,description:a(t.description)||null,access:d}}function y(t,e=""){return t===h.ALLOW?{behavior:"allow",scope:"once"}:t===h.ALLOW_CHAT?{behavior:"allow",scope:"chat"}:{behavior:"deny",scope:"once",...e?{message:String(e)}:{}}}function _(t){return c(t)&&t.behavior==="allow"}function E(t,e){const o=new Set(Array.isArray(t)?t:[]);for(const n of A(e))o.add(n);return[...o].sort()}const b="*";function O(t,e){const o=new Set(Array.isArray(t)?t:[]);if(o.has(b))return y(h.ALLOW);const n=A(e);return n.length&&n.every(s=>o.has(s))?y(h.ALLOW):null}function R(t,e,o={}){const n=c(o)?o:{},s=_(e);let r;if(s){if(r={behavior:"allow",updatedInput:c(n.input)?n.input:{}},e.scope==="chat"){const p=(Array.isArray(n.permission_suggestions)?n.permission_suggestions:[]).filter(l=>c(l)&&l.type==="addRules"&&l.behavior!=="deny"&&Array.isArray(l.rules)&&l.rules.length).map(l=>({type:"addRules",rules:l.rules,behavior:"allow",destination:"session"}));p.length&&(r.updatedPermissions=p)}}else r={behavior:"deny",message:a(e?.message)||"The user declined this action in Chap. Continue without it, or explain what it was for and ask."};return{type:"control_response",response:{subtype:"success",request_id:String(t),response:r}}}function I(t,e){const{detail:o}=S(t),n=_(e),s=n&&e.scope==="chat"?" for this chat":"";return`${n?"Allowed":"Declined"}${s}: ${o}`}function $(t){return t==="Bash"?"code":/^(Edit|MultiEdit|NotebookEdit)$/.test(String(t))?"pencil":t==="Write"?"file":/^mcp__/.test(String(t))?"plug":"bot"}const W=4e5;function M(t={},e=null){if(!_(e)||!c(t))return null;const o=c(t.input)?t.input:{};if(!["Write","Create","write_file"].includes(String(t.tool||"")))return null;const n=String(o.file_path||o.path||""),s=typeof o.content=="string"?o.content:"";return!/\.svg$/i.test(n)||!/<svg[\s>]/i.test(s)||s.length>W?null:{kind:"svg",title:n.split(/[\\/]/).pop()||"picture.svg",text:s}}function v({memory:t=new Map}={}){const e=t;async function o(n,{convId:s=null,confirm:r,agentName:p="The agent"}={}){const l=c(n.access)?null:O(await e.get(s)||[],n);if(l)return l;const{title:u,detail:f,scope:d,description:i,access:m}=S(n),x=[m,f,i&&i!==f?i:"",d?`“Allow for this chat” also covers: ${d}`:""].filter(Boolean).join(`
2
+ `);let g;try{if(typeof r!="function")throw new Error("no card");g=await r(x,{title:`${p} asks — ${u.toLowerCase()}?`,iconName:$(n.tool),scopeLabel:"Allow for this chat",allLabel:"Allow all in this chat"})}catch(w){return y(h.DENY,`Chap could not show the permission card (${w?.message||w}).`)}return g==="all"?(await e.set(s,[b]),y(h.ALLOW_CHAT)):g==="site"||g==="always"?(await e.set(s,E(await e.get(s)||[],n)),y(h.ALLOW_CHAT)):y(g==="allow"?h.ALLOW:h.DENY)}return{ask:o,forget(n){e.delete(n)},standing(n){return e.get(n)||[]},provider({convId:n=null,confirm:s,agentName:r="The agent",onAnswered:p=null}={}){return{id:"permission",specs:[N()],execute:async(l,u)=>{const f=u&&typeof u=="object"?u:{},d=await o(f,{convId:n,confirm:s,agentName:r});try{p?.(f,d)}catch{}return JSON.stringify(d)}}}}}export{b as ALLOW_ALL,W as MAX_SHOWN_PICTURE,h as PERMISSION_ANSWERS,T as PERMISSION_EVENT,k as PERMISSION_TIMEOUT_MS,L as PERMISSION_TOOL_NAME,R as claudePermissionResponse,v as createPermissionDesk,S as describePermission,C as isPermissionTool,_ as permissionAllowed,y as permissionAnswer,$ as permissionIcon,A as permissionKeys,I as permissionLine,P as permissionRequestFromClaude,N as permissionToolSpec,M as pictureFromPermission,O as recallPermission,E as rememberPermission};
package/src/origins.js ADDED
@@ -0,0 +1 @@
1
+ const o=/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d{1,5})?$/,e=/^(chrome|moz)-extension:\/\/[A-Za-z0-9-]+$/;function r(t){const n=String(t||"");return e.test(n)||o.test(n)}function s(t){return!t||r(t)}export{r as isExtensionOrigin,s as originAllowed};
package/src/server.js CHANGED
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as Le}from"node:http";import O from"node:os";import{randomBytes as We,randomInt as je,timingSafeEqual as Fe}from"node:crypto";import{mkdirSync as Je,writeFileSync as Xe,readFileSync as ae,existsSync as Ke}from"node:fs";import{join as M}from"node:path";import*as ze from"./engines/claude.js";import*as Ye from"./engines/codex.js";import*as Ve from"./engines/antigravity.js";import{pi as Qe,opencode as Ze,kiro as qe,copilot as et,deepseek as tt,hermes as nt}from"./engines/cli-agents.js";import{connectorsFor as ot}from"./connectors.js";import{agentServersFor as rt,resolveAgentServer as ie,builtinRefusal as at,narrowBuiltinList as it}from"./agent-mcp.js";import*as st from"./engines/custom.js";import{installService as ct,uninstallService as lt,serviceStatus as dt,restartService as se}from"./service.js";import{skillIndex as J,listRecords as ut,readRecord as ht,readPackageFile as pt,skillsHealth as ft,quarantinedSkills as mt,clearSkillCache as X,preferredIndex as K}from"./skills.js";import{writeSkillPackage as gt,writeSkillFile as wt,deleteSkillPackage as yt,SkillWriteError as bt}from"./skill-write.js";import{agentDefRoots as St,scanAgentDefs as kt,listAgentDefs as Tt,readAgentDef as vt,planAgentExport as xt,exportAgentDef as Et,agentDefsHealth as At,AgentDefError as Ot}from"./agent-defs.js";import{capabilityToolSpecs as Ct,runCapabilityTool as Pt}from"./mcp-capabilities.js";import{createSession as $t,deleteSession as ce,getSession as le,activeSession as Rt,relayToolCall as It}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Nt,isDefaultWorkdir as Dt,resolveWorkdir as _t,writeScopeNote as Ht}from"./workdir.js";import{sandbox as z,runSandboxCli as Mt,withGrant as de,withAgentGrant as Bt,withoutOutsideWhenCapped as Gt,grantedWriteRoots as ue,acceptRefusalReport as Ut,liveProcesses as Lt,sandboxConfigFromEnv as Wt}from"./sandbox.js";import{createAccessGate as jt,chatKeyOf as Ft,chatFolders as Jt}from"./access-gate.js";import{signInDenial as Xt}from"./events/sandbox-policy.js";import{gitState as Kt,gitDelta as zt}from"./scm.js";import{listConnections as Yt,putConnection as Vt,removeConnection as Qt,runEnvFor as Zt,testConnection as qt,secretBackend as he}from"./connections.js";import{worktreeFor as pe,listWorktrees as en,removeWorktree as tn,withHook as nn,WORKTREE_ROOT as fe}from"./worktree.js";import{AGENT_CLIS as on,agentAvailable as rn,agentInstallDirs as an,enrichPath as sn,enrichAgentEnv as cn,findAgentBin as ln,forgetMisses as dn,primeAgentLookups as un,resolveCommand as me,isCompiledBinary as hn}from"./env.js";import"./sanitize.js";import{checkForUpdate as pn,selfUpdate as ge,isEmbedded as we}from"./update.js";import{callLocalMcp as fn,localMcpStatus as mn,signInLocalMcp as gn,signInStatusLocalMcp as wn}from"./mcp-local.js";import{assertPublicHttpUrl as ye,assertPublicWebUrl as be}from"./ssrf.js";import{startRun as Se,endRun as Y,cancelRun as yn,cancelAll as bn}from"./runs.js";import{closeWarmPools as Sn,warmStatus as kn}from"./warm.js";import{SESSION_AGENTS as ke,listSessions as Tn,readSession as vn,adoptSession as xn,catchUp as En}from"./agent-sessions.js";import{agentContext as An}from"./agent-context.js";import{normalizeThread as Te}from"./events/agent-thread.js";import{portClashPlan as On,serviceManagerOf as Cn,STANDBY_POLL_MS as Pn}from"./events/service-standby.js";import{holdThread as ve}from"./threads.js";import{oneReply as $n}from"./one-reply.js";import{createSnapshot as Rn}from"./health-snapshot.js";import{CompatError as P,anthropicError as V,anthropicStream as In,chatCompletionStream as Nn,completionStream as Dn,createAnthropicMessage as _n,createChatCompletion as Hn,createCompletion as Mn,createResponse as Bn,openAIError as S,parseAnthropicMessage as Gn,parseChatCompletion as Un,parseCompletion as Ln,parseResponse as Wn,responseStream as jn}from"./api-compat.js";import{callerTrust as Fn,isPaired as I,parseExtensionIds as Jn,capRunOptions as Xn,engineHonoursReach as Kn,createPairingStore as zn,formatPairingCode as Yn}from"./pii/trust.js";const y="0.53.0",v=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,x={claude:{engine:ze,label:"Claude Code"},codex:{engine:Ye,label:"Codex"},antigravity:{engine:Ve,label:"Antigravity",tools:!1},pi:{engine:Qe,label:"Pi"},opencode:{engine:Ze,label:"OpenCode"},hermes:{engine:nt,label:"Hermes"},kiro:{engine:qe,label:"Kiro"},copilot:{engine:et,label:"GitHub Copilot"},deepseek:{engine:tt,label:"DeepSeek Harness"},custom:{engine:st,label:"Custom",hidden:!0}};function xe(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Vn=Jn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Fn({origin:n.headers.origin||"",hasToken:Ce(n),extensionIds:Vn})),n.chatpanelTrust}function Qn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Zn(n,e){const t=n.headers.origin||"",r=xe(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 E="";function eo(){try{Ke(D)&&(E=ae(D,"utf8").trim()),E||(E=We(32).toString("hex"),Je(M(O.homedir(),".chatpanel"),{recursive:!0}),Xe(D,E,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const Ee=zn({random:()=>je(0,1e6)/1e6});function to(n){if(!E)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=Ee.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=Ee.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:E})):(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:E},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(!E)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(E);return r.length===o.length&&Fe(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&&!xe(t))return"forbidden origin";const r=n.method==="POST"&&ro.has(e)||n.method==="GET"&&io(e)||so(n.method,e);return r&&!(Qn(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=()=>we()?"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=Bt(e,Gt(Xn(t,r)));if(!Kn(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 z().status(),a=!!(o.enabled&&o.runtime)&&t?.outside!==!0,c=Xt(`${r}
3
- ${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:x[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=Rn({compute:ho});async function ho(){await un();const n=await Promise.all(Object.entries(x).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 ot(a).catch(()=>[]),w=await rt(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=we()?{current:y,updateAvailable:!1,embedded:"gateway"}:await pn(y).catch(()=>({current:y,updateAvailable:!1})),t=await ft().catch(()=>null),r=await At().catch(()=>null),o=await z().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&&dn();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:Nt,sandbox:l,localMcp:mn(),processes:Lt(),worktrees:fe,secretBackend:he(),warm:kn(),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:ut(K(o,r)),problems:o.problems})}async function mo(n,e,t){i(n,200,{ok:!0,quarantined:await mt(e,t)})}async function go(n,e,t,r,o={}){const a=ht(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 pt(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 gt({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 wt({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 yt({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 bt?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 kt({roots:St(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:Tt(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=vt(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 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 Et({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 Ot){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function Eo(){return(await Promise.all(Object.entries(x).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 Eo();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 ge(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>se(),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=x[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{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)}
4
4
 
5
- `)};let c=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,s=Se(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 pe({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),Y(l),e.writableEnded||e.end();return}}const _=f?f.path:_t(t.options?.workingDir),W=Ft(t.agent,t.options),te=W?Jt(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||!Dt(t.options?.workingDir),g=Ht(t.agent,t.options?.permissionMode,h,ue(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 Kt(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}=Zt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=nn(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=$t(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=Wt();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:x[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>ue(_,{grant:ne})}));try{const h=$n(w),T=(g,H)=>de(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 ve(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: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||""}
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})}Y(l),R&&ce(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:Yt(),secretBackend:he()});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:Vt(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,qt(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:fe,worktrees:await en()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/worktrees"){const o=await pe({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 tn({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=x[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=Se(a),l=()=>c.cancel("disconnected");t.on("close",l);let s="";try{return await de(n.options?.sandbox,()=>ve(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),Y(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 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)}
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,Un,S);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,S(o))}G(e);const r=Nn(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,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 Io(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=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 No(n,e){const t=await L(n,e,Gn,V);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,_n(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,V(o))}G(e);const r=In(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?yn(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?le(t):Rt(),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=Ct();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 Pt(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 It(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 ie(r),a.builtin&&o.method==="tools/call"){const l=await at(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 fn(a,o);return a.builtin&&o.method==="tools/list"&&(c=it(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 ie(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?wn(o):await gn(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=ye(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&&ye(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=be(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=be(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=le(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=x[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=x[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=me(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}async function Yo(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(!ke.includes(o))return i(e,404,{error:`${o||"that agent"} keeps no sessions Chap can read (it can: ${ke.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await Tn(o,{limit:r.limit})});if(t==="/agent-sessions/read"){const a=await vn(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=Te({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=Te({id:r.thread?.id??r.thread});return a?i(e,200,await En(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=Le(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 An({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 xo(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(on.map(s=>[s,l?ln(s)||me(s)?.kind||null:rn(s)])),...l?{home:O.homedir(),path:process.env.PATH,installDirs:an(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Yo(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 ce(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=Ut(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 zo(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 $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+`
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(){sn(),cn(),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=On({name:"bridge",self:y,holder:r?{ours:r,version:t.version}:null,managedBy:Cn(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),Pn);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=bn("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const r=Sn("shutdown");r&&u("info",`shutdown: closed ${r} warm agent process${r===1?"":"es"}`),z().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(x)){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 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}
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=ae(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: ${Yn(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 Mt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{ct(),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{lt(),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=dt()}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:hn()})}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 ge(y);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),se()}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 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();