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