@chatpanel/bridge 0.17.3 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/bridge",
3
- "version": "0.17.3",
3
+ "version": "0.19.0",
4
4
  "type": "module",
5
5
  "description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
6
6
  "keywords": [
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as r,writeFileSync as h,existsSync as i,mkdirSync as p}from"node:fs";import{fileURLToPath as f}from"node:url";import{dirname as v,join as n}from"node:path";const c=n(v(f(import.meta.url)),".."),m=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","sandbox-grant.js","mcp-errors.js","mcp-signin.js"];function u(){return[n(c,"node_modules","@chatpanel","events"),n(c,"..","chatpanel-events")].find(e=>i(n(e,"skill-manifest.js")))}const s=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";s&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=n(c,"src","events");s||p(l,{recursive:!0});const j=e=>`// GENERATED — do not edit.
2
+ import{readFileSync as r,writeFileSync as h,existsSync as i,mkdirSync as d}from"node:fs";import{fileURLToPath as f}from"node:url";import{dirname as m,join as n}from"node:path";const c=n(m(f(import.meta.url)),".."),v=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","sandbox-grant.js","mcp-errors.js","mcp-signin.js","mcp-config-import.js","mcp-launcher.js"];function u(){return[n(c,"node_modules","@chatpanel","events"),n(c,"..","chatpanel-events")].find(e=>i(n(e,"skill-manifest.js")))}const s=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";s&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=n(c,"src","events");s||d(l,{recursive:!0});const j=e=>`// GENERATED — do not edit.
3
3
  // Source of truth: chatpanel-events/${e} (npm @chatpanel/events).
4
4
  // Edit there, then run: npm run sync:events
5
5
  //
@@ -7,4 +7,4 @@ import{readFileSync as r,writeFileSync as h,existsSync as i,mkdirSync as p}from"
7
7
  // curl one-liner install cannot fail on someone's registry, and so the compiled
8
8
  // single-file binary has nothing to resolve.
9
9
 
10
- `;let d=0;for(const e of m){const o=j(e)+r(n(a,e),"utf8"),t=n(l,e);if((i(t)?r(t,"utf8"):null)!==o){if(s){console.error(`sync-events --check: src/events/${e} differs from chatpanel-events`),d+=1;continue}h(t,o),console.log(`sync-events: updated src/events/${e}`)}}s&&(d&&(console.error("Run `npm run sync:events` and commit the result."),process.exit(1)),console.log("sync-events --check: src/events matches chatpanel-events ✓"));
10
+ `;let p=0;for(const e of v){const o=j(e)+r(n(a,e),"utf8"),t=n(l,e);if((i(t)?r(t,"utf8"):null)!==o){if(s){console.error(`sync-events --check: src/events/${e} differs from chatpanel-events`),p+=1;continue}h(t,o),console.log(`sync-events: updated src/events/${e}`)}}s&&(p&&(console.error("Run `npm run sync:events` and commit the result."),process.exit(1)),console.log("sync-events --check: src/events matches chatpanel-events ✓"));
@@ -0,0 +1,2 @@
1
+ import{execFile as y}from"node:child_process";import{mkdir as h,readFile as C,stat as d,writeFile as E}from"node:fs/promises";import{existsSync as I}from"node:fs";import w from"node:os";import p from"node:path";import{promisify as T}from"node:util";const x=T(y),S=720*6e4,b=2e4,o="-----BEGIN CERTIFICATE-----",A=()=>process.env.CHATPANEL_CA_BUNDLE||p.join(w.homedir(),".cache","chatpanel","ca-bundle.pem");function R(e){try{const t=Buffer.from(String(e).replace(/\s+/g,""),"base64");return t.length>64&&t[0]===48&&(t[1]&128)!==0}catch{return!1}}function s(...e){const t=new Set,r=[];for(const i of e)for(const n of String(i||"").split(o).slice(1)){const u=n.indexOf("-----END CERTIFICATE-----");if(u<0)continue;const f=n.slice(0,u);if(!R(f))continue;const l=`${o}${f}-----END CERTIFICATE-----
2
+ `,m=l.replace(/\s+/g,"");t.has(m)||(t.add(m),r.push(l))}return r.join("")}function g(e){return String(e||"").split(o).length-1}async function a(e,t){try{const{stdout:r}=await x(e,t,{timeout:b,maxBuffer:33554432});return r||""}catch{return""}}async function N(e=process.platform){if(e==="darwin"){const[t,r]=await Promise.all([a("/usr/bin/security",["find-certificate","-a","-p","/System/Library/Keychains/SystemRootCertificates.keychain"]),a("/usr/bin/security",["find-certificate","-a","-p","/Library/Keychains/System.keychain"])]);return s(t,r)}if(e==="win32")return s(await a("powershell.exe",["-NoProfile","-NonInteractive","-Command","$ErrorActionPreference='SilentlyContinue';foreach ($s in @('Cert:\\LocalMachine\\Root','Cert:\\CurrentUser\\Root')) { foreach ($c in Get-ChildItem $s) { '-----BEGIN CERTIFICATE-----'; [Convert]::ToBase64String($c.RawData,'InsertLineBreaks'); '-----END CERTIFICATE-----' } }"]));for(const t of["/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/ssl/ca-bundle.pem","/etc/ssl/cert.pem"])if(I(t))return s(await C(t,"utf8").catch(()=>""));return""}let c=null;async function $({now:e=Date.now(),platform:t=process.platform,source:r=N}={}){const i=A();try{const n=await d(i);if(n.size>0&&e-n.mtimeMs<S)return i}catch{}return c||(c=(async()=>{try{const n=await r(t);return g(n)<10?"":(await h(p.dirname(i),{recursive:!0}),await E(i,n,{mode:420}),i)}catch{return""}finally{c=null}})(),c)}export{g as countPem,$ as ensureCaBundle,s as mergePem,N as systemCaPem};
@@ -0,0 +1,6 @@
1
+ function W(n){const t=String(n||"").trim();if(!t)return[];const e=A(t);return e?v(e):b(t)}function S(n){if(Array.isArray(n))return n.map(String).filter(Boolean);const t=String(n||"").trim();return t?t.startsWith("[")?h(t):w(t).map(e=>e.replace(/,+$/,"")).filter(Boolean):[]}function T(n){return Array.isArray(n)?n.join(`
2
+ `):String(n||"")}function _(n){if(n&&typeof n=="object"&&!Array.isArray(n))return Object.fromEntries(Object.entries(n).filter(([e,i])=>e&&String(i??"")!=="").map(([e,i])=>[e,String(i)]));const t={};for(const e of String(n||"").split(/\n|,(?=\s*[A-Za-z_][A-Za-z0-9_]*\s*=)/)){const i=e.indexOf("=");if(i<=0)continue;const r=e.slice(0,i).trim(),s=e.slice(i+1).trim();r&&s&&(t[r]=s)}return t}function z(n){return(Array.isArray(n)?n:[]).map(String).filter(t=>/^[A-Z][A-Z0-9_]*=/.test(t.trim()))}function I(n){return Object.entries(n||{}).map(([t,e])=>`${t}=${e}`).join(`
3
+ `)}function A(n){try{return JSON.parse(n)}catch{return null}}function v(n){const t=n?.mcpServers||n?.mcp_servers||n?.servers||n;return!t||typeof t!="object"?[]:t.command||t.url?[f("Imported MCP server",t)]:Object.entries(t).map(([e,i])=>f(e,i)).filter(Boolean)}function b(n){const t=[],e=/^\s*\[(mcp_servers|mcpServers)\.([^\]]+)\]\s*$/gm;let i;for(;i=e.exec(n);)t.push({name:i[2].trim().replace(/^["']|["']$/g,""),start:e.lastIndex});return t.map((r,s)=>{const o=t[s+1]?.start?n.lastIndexOf(`
4
+ `,t[s+1].start-t[s+1].name.length-15):n.length,l=n.slice(r.start,o<r.start?n.length:o);return f(r.name,j(l))}).filter(Boolean)}function j(n){const t={};for(const o of["type","transport","command","url"]){const l=u(n,o);l!=null&&(t[o]=p(l))}const e=u(n,"args");e!=null&&(t.args=h(e));const i=u(n,"env")??u(n,"environment")??u(n,"environmentVariables");i!=null&&(t.env=m(i));const r=u(n,"headers");r!=null&&(t.headers=m(r));const s=u(n,"authorization")??u(n,"auth_header");return s!=null&&(t.headers={...t.headers||{},Authorization:p(s)}),t}function f(n,t={}){if(!t||typeof t!="object")return null;const e=d(t.command),i=d(t.url),r=String(t.type||t.transport||(e?"stdio":"http")).toLowerCase(),s={name:$(n),enabled:t.enabled!==!1};return e||r==="stdio"?e?{...s,transport:"stdio",command:e,args:S(t.args),env:g(t.env||t.environment||t.environmentVariables)}:null:i?{...s,transport:"http",url:i,headers:g(t.headers)}:null}function u(n,t){const e=String(n||"").split(/\r?\n/);for(let i=0;i<e.length;i++){const r=new RegExp(`^\\s*${C(t)}\\s*=\\s*(.*)$`).exec(e[i]);if(!r)continue;let s=x(r[1]).trim();if(!s)return"";const o=s[0],l=o==="["?"]":o==="{"?"}":"";if(!l)return s;let a=y(s,o,l);for(;a>0&&i+1<e.length;)i+=1,s+=`
5
+ ${x(e[i])}`,a=y(s,o,l);return s.trim()}return null}function h(n){const t=String(n||"").trim(),e=t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t,i=[];let r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]);)r+=1;if(r>=e.length)break;const s=e[r];if(s==='"'||s==="'"){const a=c(e,r);i.push(a.value),r=a.next;continue}let o=r;for(;o<e.length&&e[o]!==",";)o+=1;const l=e.slice(r,o).trim();l&&i.push(l),r=o+1}return i}function m(n){const t=String(n||"").trim(),e=t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t,i={};let r=0;for(;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]);)r+=1;if(r>=e.length)break;let s="";if(e[r]==='"'||e[r]==="'"){const o=c(e,r);s=o.value,r=o.next}else{let o=r;for(;o<e.length&&e[o]!=="="&&e[o]!==":";)o+=1;s=e.slice(r,o).trim(),r=o}for(;r<e.length&&/[\s=:]/.test(e[r]);)r+=1;if(!s)break;if(e[r]==='"'||e[r]==="'"){const o=c(e,r);i[s]=o.value,r=o.next}else{let o=r;for(;o<e.length&&e[o]!==",";)o+=1;i[s]=p(e.slice(r,o).trim()),r=o+1}}return i}function w(n){const t=[];let e="",i="",r=!1;for(const s of String(n||"")){if(r){e+=s,r=!1;continue}if(s==="\\"){r=!0;continue}if(i){s===i?i="":e+=s;continue}if(s==='"'||s==="'"){i=s;continue}if(/\s/.test(s)){e&&(t.push(e),e="");continue}e+=s}return e&&t.push(e),t}function c(n,t){const e=n[t];let i="",r=!1;for(let s=t+1;s<n.length;s++){const o=n[s];if(r){i+=e==='"'?O(o):o,r=!1;continue}if(o==="\\"&&e==='"'){r=!0;continue}if(o===e)return{value:i,next:s+1};i+=o}return{value:i,next:n.length}}function p(n){const t=String(n||"").trim().replace(/,+$/,"");return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?c(t,0).value:t==="true"?!0:t==="false"?!1:t}function g(n){return!n||typeof n!="object"||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).map(([t,e])=>[t,String(e)]))}function $(n){return String(n||"MCP server").replace(/[_-]+/g," ").replace(/\b[a-z]/g,t=>t.toUpperCase())}function d(n){return typeof n=="string"?n.trim():""}function x(n){let t="";for(let e=0;e<n.length;e++){const i=n[e];if(t){i===t&&(t=""),i==="\\"&&t==='"'&&(e+=1);continue}if(i==='"'||i==="'")t=i;else if(i==="#")return n.slice(0,e)}return n}function y(n,t,e){let i=0,r="";for(let s=0;s<n.length;s++){const o=n[s];if(r){o==="\\"&&r==='"'?s+=1:o===r&&(r="");continue}o==='"'||o==="'"?r=o:o===t?i+=1:o===e&&(i-=1)}return i}function O(n){return{n:`
6
+ `,r:"\r",t:" ",'"':'"',"\\":"\\"}[n]??n}function C(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{T as argsToText,z as envLikeArgs,I as envToText,S as parseArgsInput,_ as parseEnvInput,W as parseMcpConfig};
@@ -0,0 +1 @@
1
+ function c(r){for(const t of r){const n=/^git\+[^@\s]+@(.+)$/.exec(String(t));if(n)return n[1];if(/^git\+/.test(String(t)))return""}return null}const l=/^[0-9a-f]{7,40}$/i;function d(r,t){const n=Array.isArray(t)?t.map(String):String(t||"").split(/\s+/).filter(Boolean),e=String(r||"").trim().toLowerCase(),i=c(n);if(i!=null)return l.test(i)?null:{kind:"git",what:i||"the default branch",why:i?`"${i}" is a branch or tag, and ${e||"the launcher"} resolves it once and keeps the checkout — a later fix on it never arrives.`:`No ref is given, so ${e||"the launcher"} takes the default branch, resolves it once and keeps the checkout — a later fix never arrives.`,fix:"Pin a commit (…@a1b2c3d) so what runs is what was tested, or use Refresh to fetch once."};const o=n.find(a=>!a.startsWith("-")&&!/^(--from|--python|--with|-y|--package)$/.test(a));return!o||/[@=]/.test(o.replace(/^@[^/]+\//,""))?null:{kind:"package",what:o,why:`"${o}" names no version, so ${e||"the launcher"} resolves one once and serves it from cache afterwards.`,fix:"Pin a version, or use Refresh to fetch the latest once."}}function f(r,t){const n=Array.isArray(t)?t.map(String):String(t||"").split(/\s+/).filter(Boolean),e=String(r||"").trim().toLowerCase().replace(/\.(exe|cmd|bat)$/,"").split(/[\\/]/).pop();return e==="uvx"||e==="uv"?n.includes("--refresh")?n:["--refresh",...n]:e==="npx"?n.includes("--ignore-existing")?n:["--ignore-existing",...n]:null}function g(r){return f(r,[])!==null}function m({serverInfo:r=null,since:t=0,now:n=Date.now()}={}){const e=r?.name?String(r.name):"",i=r?.version?String(r.version):"",o=t?Math.max(0,n-t):0,a=Math.floor(o/6e4),s=t?a<1?"just started":a<60?`started ${a} min ago`:`started ${Math.floor(a/60)} h ago`:"",u=[e&&i?`${e} ${i}`:e||i,s].filter(Boolean).join(" · ");return{name:e,version:i,age:s,label:u}}function p(r){const t=(Array.isArray(r)?r:[]).filter(e=>{if(!e?.name||(e.inputSchema?.required||e.parameters?.required||[]).length)return!1;const o=e.annotations||{};return o.readOnlyHint===!1||o.destructiveHint===!0?!1:o.readOnlyHint===!0});return t.length?(t.find(e=>e.annotations?.openWorldHint===!1)||t[0]).name:null}const h=15*6e4;function x({since:r=0,now:t=Date.now(),ttlMs:n=h}={}){if(!r)return{expired:!0,remainingMs:0};const e=Math.max(0,r+n-t);return{expired:e<=0,remainingMs:e}}export{h as SIGN_IN_TTL_MS,g as canRefresh,m as describeRuntime,d as mutableRef,p as pickProbeTool,f as refreshArgs,x as signInCountdown};
@@ -1 +1 @@
1
- const b=-32011,t=/https?:\/\/[^\s"'<>)\]]+/,g=/\b(?:code|passcode)\b[:\s]+([A-Z0-9][A-Z0-9-]{3,}[A-Z0-9])\b/,r=/sign[ -]?in|log[ -]?in|authenticate|authoriz|verify|devicelogin|login\/device|oauth/i,h=/opening (?:your |the |a )?browser|open(?:ed|ing)? .*browser .*sign/i;function f(e){const n=String(e||"");if(!n.trim())return null;const o=n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean),c=o.join(" "),u=g.exec(c)?.[1]||null,i=o.filter(s=>r.test(s)||t.test(s)),l=i.find(s=>t.test(s)&&r.test(s))||i.find(s=>t.test(s)),a=l?t.exec(l)[0].replace(/[.,;]+$/,""):null;if(a&&(u||r.test(c)))return{url:a,code:u,message:(i.find(s=>r.test(s))||l).slice(0,300),browser:!1};const d=o.find(s=>h.test(s));return d?{url:null,code:null,message:d.slice(0,300),browser:!0}:null}function w(e){const n=e.url?` Open ${e.url}${e.code?` and enter the code ${e.code}`:""}.`:"";return{code:-32011,message:`Sign-in required: ${e.message}${n}`,data:{signIn:{url:e.url,code:e.code,message:e.message,browser:!!e.browser}}}}function _(e){if(!e||e.code!==-32011)return null;const n=e.data?.signIn;return n?{url:n.url||null,code:n.code||null,message:n.message||"",browser:!!n.browser}:{url:null,code:null,message:String(e.message||""),browser:!1}}function I(e,n){return{error:"sign_in_required",server:e,...n.url?{url:n.url}:{},...n.code?{code:n.code}:{},...n.browser?{browser:!0}:{},next:n.browser?"The server opened a browser window for the user to sign in. Tell them to complete it there, then call this tool again. Do not invent a result.":"The user has been shown this sign-in prompt. Give them the url and the code exactly, ask them to complete it, then call this tool again. Do not invent a result."}}export{b as MCP_SIGN_IN_CODE,f as parseSignInPrompt,w as signInError,_ as signInFromError,I as signInToolResult};
1
+ const _=-32011,s=/https?:\/\/[^\s"'<>)\]]+/,h=/\b(?:code|passcode)\b[:\s]+([A-Z0-9][A-Z0-9-]{3,}[A-Z0-9])\b/,i=/sign[ -]?in|log[ -]?in|authenticate|authoriz|verify|devicelogin|login\/device|oauth/i,f=/opening (?:your |the |a )?browser|open(?:ed|ing)? .*browser .*sign/i,w=/[?&]redirect_uri=https?%3A%2F%2F(?:localhost|127\.0\.0\.1)|[?&]redirect_uri=https?:\/\/(?:localhost|127\.0\.0\.1)/i;function v(n){const e=String(n||"");return/response_type=code/i.test(e)?w.test(e):!1}function b(n){const e=String(n||"");if(!e.trim())return null;const o=e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),u=o.join(" "),l=h.exec(u)?.[1]||null,c=o.filter(t=>i.test(t)||s.test(t)),a=c.find(t=>s.test(t)&&i.test(t))||c.find(t=>s.test(t)),r=a?s.exec(a)[0].replace(/[.,;]+$/,""):null;if(r&&(l||i.test(u))){const t=(c.find(g=>i.test(g))||a).slice(0,300);return!l&&v(r)?{url:r,code:null,message:t,browser:!0,interactive:!0}:{url:r,code:l,message:t,browser:!1,interactive:!1}}const d=o.find(t=>f.test(t));return d?{url:null,code:null,message:d.slice(0,300),browser:!0,interactive:!0}:null}function I(n){const e=n.url?` Open ${n.url}${n.code?` and enter the code ${n.code}`:""}.`:"";return{code:-32011,message:`Sign-in required: ${n.message}${e}`,data:{signIn:{url:n.url,code:n.code,message:n.message,browser:!!n.browser,interactive:!!n.interactive}}}}function E(n){if(!n||n.code!==-32011)return null;const e=n.data?.signIn;return e?{url:e.url||null,code:e.code||null,message:e.message||"",browser:!!e.browser,interactive:!!e.interactive}:{url:null,code:null,message:String(n.message||""),browser:!1,interactive:!1}}function S(n,e){return{error:"sign_in_required",server:n,...e.url&&!e.interactive?{url:e.url}:{},...e.code?{code:e.code}:{},...e.browser?{browser:!0}:{},next:e.interactive?"The server opened its own browser window for the user to sign in, and any link it printed works only in that window, right now. Tell them to finish signing in there and then ask again. Do NOT paste the link, and do not invent a result.":"The user has been shown this sign-in prompt. Give them the url and the code exactly, ask them to complete it, then call this tool again. Do not invent a result."}}export{_ as MCP_SIGN_IN_CODE,b as parseSignInPrompt,I as signInError,E as signInFromError,S as signInToolResult};
@@ -1 +1 @@
1
- import{EventError as b}from"./event.js";import{normalizeGrant as x}from"./sandbox-grant.js";const y=Object.freeze(["none","process","container","kubernetes"]),E=Object.freeze(["open","allowlist","none","gateway"]),h=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),A=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),O=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]})}),R=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),u=e=>!!e&&typeof e=="object"&&!Array.isArray(e),g=e=>Array.isArray(e)&&e.every(n=>typeof n=="string"&&n.length>0),c=(e,n)=>{if(!e)throw new b("SHAPE",n)},f=e=>[...new Set(e)];function _(e){c(u(e),"kit: must be an object"),c(typeof e.id=="string"&&e.id.length>0,"kit: id required"),c(u(e.network)&&E.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${E.join(", ")}`),c(g(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),c(g(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),c(u(e.filesystem),`kit ${e.id}: filesystem required`);for(const n of["allowWrite","denyWrite","allowRead","denyRead"])c(g(e.filesystem[n]||[]),`kit ${e.id}: filesystem.${n} must be string[]`);return c(g(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&c(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&c(Array.isArray(e.credentials)&&e.credentials.every(n=>u(n)&&typeof n.name=="string"&&typeof n.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:f(e.network.allowedDomains||[]),deniedDomains:f(e.network.deniedDomains||[])},filesystem:{allowWrite:f(e.filesystem.allowWrite),denyWrite:f(e.filesystem.denyWrite||[]),allowRead:f(e.filesystem.allowRead||[]),denyRead:f(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:u(e.limits)?{...e.limits}:{}}}import{normalizeGrant as G,mergeGrants as U,parseHostList as k}from"./sandbox-grant.js";function P({engine:e="custom",cwd:n,mode:t="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:s=[],grant:l=null}={}){const d=O[e]||O.custom;c(typeof n=="string"&&n.length>0,"kit: cwd required");const a=x(l);return _({id:`${e}:${t}`,kind:"process",network:{mode:t,allowedDomains:t==="open"?["*"]:t==="none"?[]:f([...d.hosts,...R,...r,...a.hosts]),deniedDomains:[]},filesystem:{allowWrite:f([n,...A,...d.write,...o,...a.write.filter(i=>!h.some(p=>i===p||i.startsWith(`${p}/`)))]),denyWrite:[],allowRead:[n],denyRead:f([...h,...s])}})}function z(e,{loopback:n=[],home:t="",platform:r="darwin"}={}){const o=_(e),s=d=>t&&d.startsWith("~")?t+d.slice(1):d,l=o.network.mode==="none"?[]:n.map(d=>`127.0.0.1:${d}`);return{network:{allowedDomains:f([...o.network.allowedDomains,...l]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&l.length>0},filesystem:{denyRead:o.filesystem.denyRead.map(s),allowRead:o.filesystem.allowRead.map(s),allowWrite:o.filesystem.allowWrite.map(s),denyWrite:o.filesystem.denyWrite.map(s)}}}function N({layer:e="none",runtime:n=null,kitId:t=null,mode:r=null,reason:o=null,hosts:s=null}={}){return c(y.includes(e),`sandbox record: layer must be one of ${y.join(", ")}`),{layer:e,runtime:n,kit:t,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function I(e,{platform:n="darwin"}={}){const t=String(e);if(n==="win32"){c(!/[\r\n]/.test(t),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=t;if(t===""||/[ \t\v"]/.test(t)){r='"';for(let o=0;o<t.length;o++){let s=0;for(;o<t.length&&t[o]==="\\";)s++,o++;if(o===t.length){r+="\\".repeat(s*2);break}t[o]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+t[o]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return t===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function H(e={},{platform:n="darwin"}={}){const t={NODE_USE_ENV_PROXY:"1"};if(n==="linux")for(const r of["no_proxy","NO_PROXY"])typeof e[r]=="string"&&(t[r]=e[r].split(",").map(o=>o.trim()).filter(o=>o&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(o)).join(","));return t}function v(e,n=[],{platform:t="darwin"}={}){return[e,...n].map(r=>I(r,{platform:t})).join(" ")}const C=/[\\/]+/,m=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),S=e=>/^[a-z]:$/i.test(m(e))||m(e)==="";function w(e,n){const t=m(e),r=m(n);return!!r&&t!==r&&t.startsWith(r+"\\")}function D(e){const n=String(e||"").replace(/\//g,"\\").split("\\");if(n.length<2)return"";const t=n.findIndex(r=>r.toLowerCase()==="node_modules");return(t>0?n.slice(0,t):n.slice(0,-1)).join("\\")}function K({kit:e,files:n=[],home:t}){c(typeof t=="string"&&t.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?t+a.slice(1):a).replace(/\//g,"\\"),o=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(c(!S(i)&&m(i)!==m(t),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),w(i,t)&&o.push(i))}const s=(a,i)=>i.some(p=>m(a)===m(p)||w(a,p)),l=[];for(const a of n){const i=D(a);i&&w(i,t)&&l.push(i)}for(const a of e?.filesystem?.allowRead||[]){const i=r(a);w(i,t)&&l.push(i)}const d=f(l).filter(a=>!s(a,o));return{read:d.filter(a=>!d.some(i=>i!==a&&w(a,i))),write:f(o)}}const W=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function T({engine:e="custom",home:n,env:t={},base:r={},carry:o=W}={}){c(typeof n=="string"&&n.length>0,"windows env: home required");const s=n.replace(/\//g,"\\"),l=/^[a-z]:/i.test(s)?s.slice(0,2):"",d={USERPROFILE:s,...l?{HOMEDRIVE:l,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(t))typeof i=="string"&&(r[a]!==i||o.includes(a))&&(d[a]=i);return e==="codex"&&!d.CODEX_HOME&&(d.CODEX_HOME=s+"\\.codex"),d}function Y(e,n){c(Array.isArray(e),"srt-win argv: must be an array");const t=e.indexOf("exec"),r=t>=0?e.indexOf("--",t+1):-1;c(t>=0&&r>t,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let l=t+1;l<r;l++)e[l]==="--env"&&typeof e[l+1]=="string"&&o.add(e[l+1].split("=")[0].toUpperCase());const s=[];for(const[l,d]of Object.entries(n||{}))c(/^[A-Za-z_][A-Za-z0-9_]*$/.test(l),`srt-win env: bad key ${l}`),c(!/[\r\n]/.test(d),`srt-win env: ${l} holds a newline`),o.has(l.toUpperCase())||s.push("--env",`${l}=${d}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{A as COMMON_WRITE,R as DEVELOPER_HOSTS,O as ENGINE_KITS,E as NETWORK_MODES,y as SANDBOX_LAYERS,h as SECRET_PATHS,W as WINDOWS_CARRY_KEYS,P as kitFor,U as mergeGrants,G as normalizeGrant,k as parseHostList,H as sandboxEnvOverlay,N as sandboxRecord,v as shellJoin,I as shellQuote,z as toSrtSettings,w as underWindowsHome,_ as validateKit,K as windowsGrantsFor,D as windowsInstallRoot,T as windowsSandboxEnv,Y as withSrtWinEnv};
1
+ import{EventError as A}from"./event.js";import{normalizeGrant as b}from"./sandbox-grant.js";const y=Object.freeze(["none","process","container","kubernetes"]),E=Object.freeze(["open","allowlist","none","gateway"]),_=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),x=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),h=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]})}),R=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),u=e=>!!e&&typeof e=="object"&&!Array.isArray(e),g=e=>Array.isArray(e)&&e.every(o=>typeof o=="string"&&o.length>0),c=(e,o)=>{if(!e)throw new A("SHAPE",o)},f=e=>[...new Set(e)];function O(e){c(u(e),"kit: must be an object"),c(typeof e.id=="string"&&e.id.length>0,"kit: id required"),c(u(e.network)&&E.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${E.join(", ")}`),c(g(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),c(g(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),c(u(e.filesystem),`kit ${e.id}: filesystem required`);for(const o of["allowWrite","denyWrite","allowRead","denyRead"])c(g(e.filesystem[o]||[]),`kit ${e.id}: filesystem.${o} must be string[]`);return c(g(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&c(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&c(Array.isArray(e.credentials)&&e.credentials.every(o=>u(o)&&typeof o.name=="string"&&typeof o.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:f(e.network.allowedDomains||[]),deniedDomains:f(e.network.deniedDomains||[])},filesystem:{allowWrite:f(e.filesystem.allowWrite),denyWrite:f(e.filesystem.denyWrite||[]),allowRead:f(e.filesystem.allowRead||[]),denyRead:f(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:u(e.limits)?{...e.limits}:{}}}import{normalizeGrant as M,mergeGrants as k,parseHostList as q}from"./sandbox-grant.js";function N({engine:e="custom",cwd:o,mode:t="open",extraHosts:r=[],extraWrite:n=[],extraDenyRead:s=[],grant:l=null}={}){const d=h[e]||h.custom;c(typeof o=="string"&&o.length>0,"kit: cwd required");const a=b(l);return O({id:`${e}:${t}`,kind:"process",network:{mode:t,allowedDomains:t==="open"?["*"]:t==="none"?[]:f([...d.hosts,...R,...r,...a.hosts]),deniedDomains:[]},filesystem:{allowWrite:f([o,...x,...d.write,...n,...a.write.filter(i=>!_.some(p=>i===p||i.startsWith(`${p}/`)))]),denyWrite:[],allowRead:[o],denyRead:f([..._,...s])}})}function z(e,{loopback:o=[],home:t="",platform:r="darwin"}={}){const n=O(e),s=d=>t&&d.startsWith("~")?t+d.slice(1):d,l=n.network.mode==="none"?[]:o.map(d=>`127.0.0.1:${d}`);return{network:{allowedDomains:f([...n.network.allowedDomains,...l]),deniedDomains:n.network.deniedDomains,allowLocalBinding:r==="darwin"&&l.length>0},filesystem:{denyRead:n.filesystem.denyRead.map(s),allowRead:n.filesystem.allowRead.map(s),allowWrite:n.filesystem.allowWrite.map(s),denyWrite:n.filesystem.denyWrite.map(s)}}}function C({layer:e="none",runtime:o=null,kitId:t=null,mode:r=null,reason:n=null,hosts:s=null}={}){return c(y.includes(e),`sandbox record: layer must be one of ${y.join(", ")}`),{layer:e,runtime:o,kit:t,mode:r,...e==="none"&&n?{reason:n}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function S(e,{platform:o="darwin"}={}){const t=String(e);if(o==="win32"){c(!/[\r\n]/.test(t),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=t;if(t===""||/[ \t\v"]/.test(t)){r='"';for(let n=0;n<t.length;n++){let s=0;for(;n<t.length&&t[n]==="\\";)s++,n++;if(n===t.length){r+="\\".repeat(s*2);break}t[n]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+t[n]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return t===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}const I=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function H(e={},{platform:o="darwin",caBundle:t=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(t)for(const n of I)e[n]||(r[n]=t);if(o==="linux")for(const n of["no_proxy","NO_PROXY"])typeof e[n]=="string"&&(r[n]=e[n].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function L(e,o=[],{platform:t="darwin"}={}){return[e,...o].map(r=>S(r,{platform:t})).join(" ")}const T=/[\\/]+/,m=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),D=e=>/^[a-z]:$/i.test(m(e))||m(e)==="";function w(e,o){const t=m(e),r=m(o);return!!r&&t!==r&&t.startsWith(r+"\\")}function W(e){const o=String(e||"").replace(/\//g,"\\").split("\\");if(o.length<2)return"";const t=o.findIndex(r=>r.toLowerCase()==="node_modules");return(t>0?o.slice(0,t):o.slice(0,-1)).join("\\")}function K({kit:e,files:o=[],home:t}){c(typeof t=="string"&&t.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?t+a.slice(1):a).replace(/\//g,"\\"),n=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(c(!D(i)&&m(i)!==m(t),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),w(i,t)&&n.push(i))}const s=(a,i)=>i.some(p=>m(a)===m(p)||w(a,p)),l=[];for(const a of o){const i=W(a);i&&w(i,t)&&l.push(i)}for(const a of e?.filesystem?.allowRead||[]){const i=r(a);w(i,t)&&l.push(i)}const d=f(l).filter(a=>!s(a,n));return{read:d.filter(a=>!d.some(i=>i!==a&&w(a,i))),write:f(n)}}const j=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function Y({engine:e="custom",home:o,env:t={},base:r={},carry:n=j}={}){c(typeof o=="string"&&o.length>0,"windows env: home required");const s=o.replace(/\//g,"\\"),l=/^[a-z]:/i.test(s)?s.slice(0,2):"",d={USERPROFILE:s,...l?{HOMEDRIVE:l,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(t))typeof i=="string"&&(r[a]!==i||n.includes(a))&&(d[a]=i);return e==="codex"&&!d.CODEX_HOME&&(d.CODEX_HOME=s+"\\.codex"),d}function v(e,o){c(Array.isArray(e),"srt-win argv: must be an array");const t=e.indexOf("exec"),r=t>=0?e.indexOf("--",t+1):-1;c(t>=0&&r>t,"srt-win argv: expected `exec … -- <shell> <command>`");const n=new Set;for(let l=t+1;l<r;l++)e[l]==="--env"&&typeof e[l+1]=="string"&&n.add(e[l+1].split("=")[0].toUpperCase());const s=[];for(const[l,d]of Object.entries(o||{}))c(/^[A-Za-z_][A-Za-z0-9_]*$/.test(l),`srt-win env: bad key ${l}`),c(!/[\r\n]/.test(d),`srt-win env: ${l} holds a newline`),n.has(l.toUpperCase())||s.push("--env",`${l}=${d}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{x as COMMON_WRITE,R as DEVELOPER_HOSTS,h as ENGINE_KITS,E as NETWORK_MODES,y as SANDBOX_LAYERS,_ as SECRET_PATHS,j as WINDOWS_CARRY_KEYS,N as kitFor,k as mergeGrants,M as normalizeGrant,q as parseHostList,H as sandboxEnvOverlay,C as sandboxRecord,L as shellJoin,S as shellQuote,z as toSrtSettings,w as underWindowsHome,O as validateKit,K as windowsGrantsFor,W as windowsInstallRoot,Y as windowsSandboxEnv,v as withSrtWinEnv};
package/src/mcp-local.js CHANGED
@@ -1,6 +1,6 @@
1
- import{spawn as C}from"node:child_process";import _ from"node:path";import{resolveCommand as z,buildSpawnSpec as O}from"./env.js";import{sandbox as j,refusalsFor as B,track as L}from"./sandbox.js";import{missingCommandMessage as N}from"./events/mcp-errors.js";import{parseSignInPrompt as D,signInError as R}from"./events/mcp-signin.js";const m=new Map,M=new Map,J=10*6e4,U=6e4,F=5*6e4,q=Object.freeze({protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"ChatPanel",version:"1.0"}}),G=150,w=4e3,K=n=>n.key||`${n.command}\0${(Array.isArray(n.args)?n.args.join(" "):n.args)||""}`,v=n=>JSON.stringify([n.command,Array.isArray(n.args)?n.args:String(n.args||""),n.env||{},n.cwd||null,n.sandbox||null]);function P(n,r){clearTimeout(n.idleTimer);for(const{reject:e,timer:i}of n.pending.values())clearTimeout(i),e(r);n.pending.clear(),m.get(n.key)===n&&m.delete(n.key);try{n.child.kill()}catch{}}function p(n){clearTimeout(n.idleTimer),n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}m.delete(n.key)},J)}function V(n){const r=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
1
+ import{spawn as R}from"node:child_process";import F from"node:os";import _ from"node:path";import{resolveCommand as G,buildSpawnSpec as J}from"./env.js";import{sandbox as U,refusalsFor as q,track as H}from"./sandbox.js";import{missingCommandMessage as K}from"./events/mcp-errors.js";import{parseSignInPrompt as V,signInError as E,signInFromError as W}from"./events/mcp-signin.js";import{pickProbeTool as Q}from"./events/mcp-launcher.js";import{envLikeArgs as X}from"./events/mcp-config-import.js";const d=new Map,v=new Map,$=10*6e4,Y=6e4,Z=5*6e4,C=Object.freeze({protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"ChatPanel",version:"1.0"}}),nn=150,en=8*6e4,tn=16*6e4,S=4e3;function j(n){const e=F.homedir(),t={};for(const[r,s]of Object.entries(n||{})){const o=String(s);t[r]=o==="~"?e:o.startsWith("~/")?_.join(e,o.slice(2)):o}return t}const x=n=>n.key||`${n.command}\0${(Array.isArray(n.args)?n.args.join(" "):n.args)||""}`,O=n=>JSON.stringify([n.command,Array.isArray(n.args)?n.args:String(n.args||""),n.env||{},n.cwd||null,n.sandbox||null]);function y(n,e){clearTimeout(n.idleTimer);for(const{reject:t,timer:r}of n.pending.values())clearTimeout(r),t(e);n.pending.clear(),d.get(n.key)===n&&d.delete(n.key);try{n.child.kill()}catch{}}function f(n){clearTimeout(n.idleTimer);const e=n.pendingSignIn?Math.max($,tn):$;n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}d.delete(n.key)},e)}function rn(n){const e=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
2
2
  `).split(`
3
- `).map(e=>e.trimEnd()).filter(Boolean).join(`
4
- `).trim();return r?r.length>w?`…${r.slice(-w)}`:r:""}function y(n,r){const e=V(r?.stderr);return e?`${n}: ${e}`:n}const T=new Map,x=new Set;function on(){const n=[];for(const r of m.values())r.child.exitCode!=null||r.child.killed||n.push({id:r.key,command:_.basename(String(r.command||"")),pid:r.child.pid??null,sandbox:r.sandbox,commandId:r.commandId,since:r.startedAt,refused:B(r.commandId)});return n}async function H(n){const r=K(n),e=v(n);if(T.has(r)){const c=await T.get(r);if(c.sig===e)return c}const i=m.get(r);if(i&&i.child.exitCode==null&&!i.child.killed){if(i.sig===e)return p(i),i;P(i,new Error("local MCP server restarted: its configuration changed"))}const a=Q(n,r,e).finally(()=>T.delete(r));return T.set(r,a),a}async function Q(n,r,e=v(n)){const i=z(n.command);if(!i)throw new Error(N(n.command,{platform:process.platform}));const a=Array.isArray(n.args)?n.args:String(n.args||"").split(/\s+/).filter(Boolean),[c,E,g]=O(i,a,n.cwd||null);g.env={...g.env||process.env,...n.env||{}},g.stdio=["pipe","pipe","pipe"];const l=await j().wrap(c,E,g,{engine:"mcp",cwd:n.cwd||null,commandId:`mcp:${String(r).slice(0,48)}`,...n.sandbox?{grant:n.sandbox}:{}}),[k,$,A]=[l.bin,l.argv,l.opts];l.record.layer==="none"&&!x.has(l.record.reason)&&(x.add(l.record.reason),console.error(`[bridge] local MCP "${n.command}" runs outside a sandbox — ${l.record.reason}`));const d=L(C(k,$,A),l,{kind:"mcp",label:r}),t={key:r,sig:e,child:d,command:n.command,sandbox:l.record,commandId:l.commandId,startedAt:Date.now(),pending:new Map,buf:"",stderr:"",idleTimer:null,initialized:!1,handshake:null},I=o=>P(t,o);return d.stdout.setEncoding("utf8"),d.stdout.on("data",o=>{t.buf+=o;let s;for(;(s=t.buf.indexOf(`
5
- `))>=0;){const u=t.buf.slice(0,s).trim();if(t.buf=t.buf.slice(s+1),u[0]!=="{"&&u[0]!=="[")continue;let h;try{h=JSON.parse(u)}catch{continue}for(const f of Array.isArray(h)?h:[h]){const b=f&&f.id!=null?t.pending.get(f.id):null;b&&(clearTimeout(b.timer),t.pending.delete(f.id),b.resolve(f))}}}),d.stderr.setEncoding("utf8"),d.stderr.on("data",o=>{t.stderr+=o,t.stderr.length>w*2&&(t.stderr=t.stderr.slice(-w*2)),t.pending.size&&(t.promptBuf=((t.promptBuf||"")+o).slice(-2e3),clearTimeout(t.promptTimer),t.promptTimer=setTimeout(()=>{const s=D(t.promptBuf);s&&(t.promptBuf="",W(t,s))},G))}),d.on("error",o=>I(new Error(y(`local MCP "${n.command}" failed to start: ${o.message}`,t)))),d.on("close",(o,s)=>{const u=s?`exited with signal ${s}`:o==null?"exited":`exited with code ${o}`;I(new Error(y(`local MCP "${n.command}" ${u}`,t)))}),m.set(r,t),p(t),t}function W(n,r){if(p(n),r.browser){for(const i of n.pending.values())clearTimeout(i.timer),i.timer=setTimeout(()=>{i.reject(new Error(y("local MCP call timed out waiting for the sign-in",n)))},F);return}const e=R(r);for(const[i,a]of n.pending)clearTimeout(a.timer),n.pending.delete(i),a.resolve({jsonrpc:"2.0",id:i,error:e})}function S(n,r){const e=()=>n.child.stdin.write(JSON.stringify(r)+`
6
- `);return r.id==null?(e(),Promise.resolve(null)):new Promise((i,a)=>{const c=setTimeout(()=>{n.pending.delete(r.id),a(new Error(y("local MCP call timed out",n)))},U);n.pending.set(r.id,{resolve:i,reject:a,timer:c}),e()})}function X(n,r){return n.initialized?Promise.resolve():(n.handshake||(n.handshake=(async()=>{const e=await S(n,{jsonrpc:"2.0",id:`cp-init-${Date.now()}`,method:"initialize",params:r});if(e?.error)throw new Error(`local MCP re-initialize failed: ${e.error.message||e.error.code}`);await S(n,{jsonrpc:"2.0",method:"notifications/initialized"}),n.initialized=!0})().finally(()=>{n.handshake=null})),n.handshake)}function an(n){return M.has(n)}async function ln(n,r){if(!n?.command)throw new Error("no command for local MCP server");const e=await H(n);return p(e),r.method==="initialize"?(M.set(e.key,r.params||{}),e.initialized=!0):r.method==="notifications/initialized"||e.initialized||await X(e,M.get(e.key)||q),S(e,r)}export{ln as callLocalMcp,an as hasInitParams,on as localMcpStatus};
3
+ `).map(t=>t.trimEnd()).filter(Boolean).join(`
4
+ `).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function M(n,e){const t=rn(e?.stderr);return t?`${n}: ${t}`:n}const T=new Map,z=new Set;function wn(){const n=[];for(const e of d.values())e.child.exitCode!=null||e.child.killed||n.push({id:e.key,command:_.basename(String(e.command||"")),pid:e.child.pid??null,sandbox:e.sandbox,commandId:e.commandId,since:e.startedAt,refused:q(e.commandId)});return n}async function L(n){const e=x(n),t=O(n);if(T.has(e)){const o=await T.get(e);if(o.sig===t)return o}const r=d.get(e);if(r&&r.child.exitCode==null&&!r.child.killed){if(r.sig===t)return f(r),r;y(r,new Error("local MCP server restarted: its configuration changed"))}const s=on(n,e,t).finally(()=>T.delete(e));return T.set(e,s),s}async function on(n,e,t=O(n)){const r=G(n.command);if(!r)throw new Error(K(n.command,{platform:process.platform}));const s=Array.isArray(n.args)?n.args:String(n.args||"").split(/\s+/).filter(Boolean),o={};for(const a of X(s)){const l=a.indexOf("=");o[a.slice(0,l).trim()]=a.slice(l+1).trim()}const[p,I,u]=J(r,s,n.cwd||null);u.env={...u.env||process.env,...j(o),...j(n.env||{})},Object.keys(o).length&&console.error(`[bridge] local MCP "${n.command}": ${Object.keys(o).join(", ")} looked like environment variables in Arguments, so they were applied as env too`),u.stdio=["pipe","pipe","pipe"];const c=await U().wrap(p,I,u,{engine:"mcp",cwd:n.cwd||null,commandId:`mcp:${String(e).slice(0,48)}`,...n.sandbox?{grant:n.sandbox}:{}}),[D,N,B]=[c.bin,c.argv,c.opts];c.record.layer==="none"&&!z.has(c.record.reason)&&(z.add(c.record.reason),console.error(`[bridge] local MCP "${n.command}" runs outside a sandbox — ${c.record.reason}`));const g=H(R(D,N,B),c,{kind:"mcp",label:e}),i={key:e,sig:t,child:g,command:n.command,sandbox:c.record,commandId:c.commandId,startedAt:Date.now(),pending:new Map,buf:"",stderr:"",idleTimer:null,initialized:!1,handshake:null,pendingSignIn:null,pendingSignInAt:0,signInIds:null},A=a=>y(i,a);return g.stdout.setEncoding("utf8"),g.stdout.on("data",a=>{i.buf+=a;let l;for(;(l=i.buf.indexOf(`
5
+ `))>=0;){const h=i.buf.slice(0,l).trim();if(i.buf=i.buf.slice(l+1),h[0]!=="{"&&h[0]!=="[")continue;let w;try{w=JSON.parse(h)}catch{continue}for(const m of Array.isArray(w)?w:[w]){m&&m.id!=null&&i.signInIds?.has(m.id)&&(i.signInIds.delete(m.id),i.signInIds.size||(i.pendingSignIn=null,i.signedInAt=Date.now(),f(i)));const k=m&&m.id!=null?i.pending.get(m.id):null;k&&(clearTimeout(k.timer),i.pending.delete(m.id),k.resolve(m))}}}),g.stderr.setEncoding("utf8"),g.stderr.on("data",a=>{i.stderr+=a,i.stderr.length>S*2&&(i.stderr=i.stderr.slice(-S*2)),i.pending.size&&(i.promptBuf=((i.promptBuf||"")+a).slice(-2e3),clearTimeout(i.promptTimer),i.promptTimer=setTimeout(()=>{const l=V(i.promptBuf);l&&(i.promptBuf="",sn(i,l))},nn))}),g.on("error",a=>A(new Error(M(`local MCP "${n.command}" failed to start: ${a.message}`,i)))),g.on("close",(a,l)=>{const h=l?`exited with signal ${l}`:a==null?"exited":`exited with code ${a}`;A(new Error(M(`local MCP "${n.command}" ${h}`,i)))}),d.set(e,i),f(i),i}function sn(n,e){if(f(n),e.code&&(n.pendingSignIn=e,n.pendingSignInAt=Date.now(),n.signInIds=new Set(n.pending.keys()),f(n)),e.browser){for(const r of n.pending.values())clearTimeout(r.timer),r.timer=setTimeout(()=>{r.reject(new Error(M("local MCP call timed out waiting for the sign-in",n)))},Z);return}const t=E(e);for(const[r,s]of n.pending)clearTimeout(s.timer),n.pending.delete(r),s.resolve({jsonrpc:"2.0",id:r,error:t})}function P(n,e){const t=()=>n.child.stdin.write(JSON.stringify(e)+`
6
+ `);return e.id==null?(t(),Promise.resolve(null)):new Promise((r,s)=>{const o=setTimeout(()=>{n.pending.delete(e.id),s(new Error(M("local MCP call timed out",n)))},Y);n.pending.set(e.id,{resolve:r,reject:s,timer:o}),t()})}function an(n,e){return n.initialized?Promise.resolve():(n.handshake||(n.handshake=(async()=>{const t=await P(n,{jsonrpc:"2.0",id:`cp-init-${Date.now()}`,method:"initialize",params:e});if(t?.error)throw new Error(`local MCP re-initialize failed: ${t.error.message||t.error.code}`);await P(n,{jsonrpc:"2.0",method:"notifications/initialized"}),n.initialized=!0})().finally(()=>{n.handshake=null})),n.handshake)}async function Sn(n,{initializeParams:e=C}={}){const t=await L(n);if(t.pendingSignIn)return{state:"prompt",signIn:t.pendingSignIn,since:t.pendingSignInAt};await b(n,{jsonrpc:"2.0",id:`cp-si-init-${Date.now()}`,method:"initialize",params:e}).catch(()=>{});const s=(await b(n,{jsonrpc:"2.0",id:`cp-si-list-${Date.now()}`,method:"tools/list",params:{}}).catch(()=>null))?.result?.tools||[],o=Q(s);if(!o)return{state:"unsupported",error:"This server declares no read-only tool that takes no arguments, so there is nothing safe to call to make it sign in."};const p=await b(n,{jsonrpc:"2.0",id:`cp-si-${Date.now()}`,method:"tools/call",params:{name:o,arguments:{}}}).catch(u=>({error:{message:String(u?.message||u)}})),I=W(p?.error);return I?{state:"prompt",signIn:I,since:d.get(x(n))?.pendingSignInAt||Date.now(),probe:o}:p?.error?{state:"failed",error:p.error.message||"the server refused",probe:o}:{state:"signed-in",probe:o}}function yn(n){const e=d.get(x(n));return!e||e.child.exitCode!=null?{state:"gone"}:e.pendingSignIn?{state:"prompt",signIn:e.pendingSignIn,since:e.pendingSignInAt}:{state:e.signedInAt?"signed-in":"idle"}}function ln(n){const e=d.get(n);return e?(y(e,new Error("local MCP server stopped")),!0):!1}function Mn(){let n=0;for(const e of[...d.keys()])ln(e)&&(n+=1);return n}function Tn(n){return d.get(n)||null}function bn(n){return v.has(n)}async function b(n,e){if(!n?.command)throw new Error("no command for local MCP server");const t=await L(n);if(f(t),e.method==="initialize")v.set(t.key,e.params||{}),t.initialized=!0;else if(e.method!=="notifications/initialized"){if(e.id!=null&&t.pendingSignIn&&Date.now()-t.pendingSignInAt<en)return{jsonrpc:"2.0",id:e.id,error:E(t.pendingSignIn)};if(e.id!=null&&t.pendingSignIn)return y(t,new Error("local MCP sign-in expired: starting a new one")),b(n,e);t.initialized||await an(t,v.get(t.key)||C)}return P(t,e)}export{Tn as _procForTest,b as callLocalMcp,bn as hasInitParams,wn as localMcpStatus,Sn as signInLocalMcp,yn as signInStatusLocalMcp,Mn as stopAllLocalMcp,ln as stopLocalMcp};
@@ -1 +1 @@
1
- import{stripHidden as Z,confusablesSkeleton as I}from"./sanitize.js";const y=/\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g,_=Object.freeze(["PERSON","ORG","LOCATION","ADDRESS","EMAIL","PHONE","ID","SSN","IBAN","CREDITCARD","CARD","POST","FAC","GROUP","NRP","ENTITY","KEY","SECRET","TERM","PII","OTHER"]);function D(e){const t=String(e??"").trim().replace(/^\[{1,2}|\]{1,2}$/g,""),n=/^([A-Z][A-Z0-9]*)_\d+$/.exec(t);return!!n&&_.includes(n[1])}const K=/\[{0,2}([A-Z][A-Z0-9]*_\d+)\]{0,2}/g,k=/^(?:[^\n()[\]]|\[\[[A-Z][A-Z0-9]*_\d+\]\])*\]\(/;function O(e,t,n,r){const s=t.startsWith("[[["),o=t.endsWith("]]]");if(!s&&!o)return r;const i=e.slice(n+t.length),c=s&&k.test(o?`]${i}`:i),f=o&&i.startsWith("(");return`${c?"[":""}${r}${f?"]":""}`}function T(){return{byToken:new Map,byValue:new Map,counts:new Map,aliases:new Map}}function v(e){return{entries:[...e?.byToken||new Map].map(([t,n])=>({token:t,value:n})),aliases:[...e?.aliases||new Map].map(([t,n])=>({alias:t,value:n}))}}function w(e){const t=T();for(const{token:n,value:r}of e?.entries||[]){const s=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(n);t.byToken.set(n,r),t.byValue.set(r,n),s&&t.counts.set(s[1],Math.max(t.counts.get(s[1])||0,Number(s[2])))}for(const{alias:n,value:r}of e?.aliases||[])t.aliases.set(n,r);return t}function h(e,t,n){const r=e.byValue.get(n);if(r)return r;const s=String(t||"PII").toUpperCase().replace(/[^A-Z0-9]/g,"")||"PII",o=(e.counts.get(s)||0)+1;e.counts.set(s,o);const i=`[[${s}_${o}]]`;return e.byToken.set(i,n),e.byValue.set(n,i),i}function x(e){return String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function m(e){return!(typeof e!="string"||e.length===0||e.length>200||/\([^)]*[+*}][^)]*\)\s*[+*{]/.test(e)||/[+*]\s*[+*]/.test(e))}function N(e,t){if(!t||t.length===0)return e;let n="",r=0;const s=e.length;for(;r<=s;){let o=null,i=null;for(const c of t){c.re.lastIndex=r;const f=c.re.exec(e);if(f&&(o===null||f.index<o.index)&&(o=f,i=c,f.index===r))break}if(!o){n+=e.slice(r);break}n+=e.slice(r,o.index),o[0].length===0?(n+=e[o.index]??"",r=o.index+1):(n+=i.repl(o),r=o.index+o[0].length)}return n}function P(e){let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let s=e.charCodeAt(r)-48;n&&(s*=2,s>9&&(s-=9)),t+=s,n=!n}return t%10===0}function $(e){if(!/^[0-9A-Fa-f:]+$/.test(e)||(e.match(/:/g)||[]).length<2)return!1;const t=e.split(":");return t.some(n=>n.length>4)?!1:e.includes("::")?t.filter(Boolean).length>=1&&t.filter(Boolean).length<=7:t.length===8&&t.every(n=>n.length>=1)}const z=[{type:"SECRET",re:/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g},{type:"EMAIL",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{type:"SSN",re:/\b\d{3}[-\s]\d{2}[-\s]\d{4}\b/g},{type:"KEY",re:/\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[0-9A-Za-z_]{22,}|xox[baprs]-[A-Za-z0-9-]{10,}|xapp-[0-9]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35}|[rs]k_(?:live|test)_[0-9A-Za-z]{16,})\b/g},{type:"KEY",re:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{type:"IP",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{type:"IP",re:/(?<![:\w])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![:\w])/g,valid:e=>$(e)},{type:"PHONE",re:/(?<![\w.])\+?\d[\d ().-]{6,}\d(?![\w])/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length<7||t.length>15||/^(?:19|20)\d\d[-./](?:0[1-9]|1[0-2])[-./](?:0[1-9]|[12]\d|3[01])(?![\d])/.test(e.trimStart())?!1:/[ ().-]/.test(e)||e.trimStart().startsWith("+")||t.length===10}},{type:"CARD",re:/\b(?:\d[ -]?){13,19}\b/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length>=13&&t.length<=19&&P(t)}}];function E(e,t,{tier:n="basic",entities:r=[],dictionary:s=[],sanitize:o=!0,sanitizeOpts:i=void 0}={}){if(e==null||e==="")return e;let c=o?Z(String(e),i):String(e);const f=t||T(),g=n==="full"||n==="entities",A=[];for(const l of s||[]){if(!l)continue;let a;try{a=l.pattern?m(l.pattern)?new RegExp(l.pattern,l.flags&&/g/.test(l.flags)?l.flags:`${l.flags||""}g`):null:l.value?new RegExp(`(?<![\\w])${x(l.value)}(?![\\w])`,"gi"):null}catch{a=null}if(a)if(l.alias!=null&&l.alias!=="")l.value&&f.aliases.set(l.alias,l.value),A.push({re:a,repl:()=>l.alias});else{const u=l.type||(l.pattern?"PII":"TERM");A.push({re:a,repl:p=>h(f,u,p[0])})}}if(c=N(c,A),g){const l=[...r||[]].filter(a=>a&&a.value).sort((a,u)=>String(u.value).length-String(a.value).length);for(const a of l){const u=new RegExp(`(?<![\\w])${x(a.value)}(?![\\w])`,"gi");c=c.replace(u,p=>h(f,a.type||"PERSON",p))}}const R=I(c),d=[],S=(l,a)=>d.some(u=>l<u.end&&a>u.start);for(const l of z){l.re.lastIndex=0;let a;for(;(a=l.re.exec(R))!==null;){if(a[0].length===0){l.re.lastIndex++;continue}const u=a.index,p=u+a[0].length;l.valid&&!l.valid(a[0])||S(u,p)||d.push({start:u,end:p,type:l.type})}}if(d.length){d.sort((u,p)=>u.start-p.start);let l="",a=0;for(const u of d)l+=c.slice(a,u.start)+h(f,u.type,c.slice(u.start,u.end)),a=u.end;c=l+c.slice(a)}return c}function b(e,t,n){if(e==null||typeof e=="string")return e==null?e:E(e,t,n);if(Array.isArray(e))return e.map(r=>b(r,t,n));if(typeof e=="object"){let r=e;return typeof e.text=="string"&&(r={...r,text:E(e.text,t,n)}),Array.isArray(e.content)&&(r={...r,content:e.content.map(s=>b(s,t,n))}),e.resource&&typeof e.resource=="object"&&typeof e.resource.text=="string"&&(r={...r,resource:{...e.resource,text:E(e.resource.text,t,n)}}),r}return e}function C(e,t){if(e==null||!t)return e;const n=String(e);return n.replace(/\[{0,3}([A-Z][A-Z0-9]*_\d+)\]{0,3}/g,(r,s,o)=>{const i=`[[${s}]]`;return t.byToken.has(i)?O(n,r,o,t.byToken.get(i)):r})}function V(e,t){let n=C(e,t);if(t?.aliases?.size){const r=[...t.aliases.keys()].filter(Boolean).sort((s,o)=>o.length-s.length);if(r.length){const s=new RegExp(`(?<![\\w])(?:${r.map(x).join("|")})(?![\\w])`,"g");n=n.replace(s,o=>t.aliases.has(o)?t.aliases.get(o):o)}}return n}function Y(e,t){const n=String(e??"");if(!n)return{text:n,unresolved:[]};const r=[],s=n.replace(y,o=>{const i=t?.byToken?.get(o);return i??(r.push(o),o)});return y.lastIndex=0,{text:s,unresolved:r}}function F(e){return y.lastIndex=0,y.test(String(e||""))}function H(e,{includeValues:t=!1,maxPairs:n=200}={}){const r=new Map,s=[];for(const[i,c]of e?.byToken||new Map){const f=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(i),g=f?f[1]:"OTHER";r.set(g,(r.get(g)||0)+1),t&&s.length<n&&s.push({token:i,value:c,type:g})}const o=[...r.entries()].map(([i,c])=>({type:i,count:c})).sort((i,c)=>c.count-i.count||i.type.localeCompare(c.type));return{total:o.reduce((i,c)=>i+c.count,0),types:o,...t?{pairs:s}:{}}}function L(e){const t=new Map;for(const r of e||[])for(const s of r?.types||[])t.set(s.type,(t.get(s.type)||0)+s.count);const n=[...t.entries()].map(([r,s])=>({type:r,count:s})).sort((r,s)=>s.count-r.count||r.type.localeCompare(s.type));return{total:n.reduce((r,s)=>r+s.count,0),types:n}}export{_ as REDACTION_TOKEN_TYPES,T as createVault,F as hasToken,D as isRedactionToken,L as mergeRedactionSummaries,b as redactResultShape,E as redactText,H as redactionSummary,C as restoreText,V as restoreWithAliases,Y as scrubPlaceholders,w as vaultFromJSON,v as vaultToJSON};
1
+ import{stripHidden as I,confusablesSkeleton as Z}from"./sanitize.js";const A=/\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g,m=Object.freeze(["PERSON","ORG","LOCATION","ADDRESS","EMAIL","PHONE","ID","SSN","IBAN","CREDITCARD","CARD","POST","FAC","GROUP","NRP","ENTITY","KEY","SECRET","TERM","PII","OTHER"]);function K(e){const t=String(e??"").trim().replace(/^\[{1,2}|\]{1,2}$/g,""),n=/^([A-Z][A-Z0-9]*)_\d+$/.exec(t);return!!n&&m.includes(n[1])}const v=/\[{0,2}([A-Z][A-Z0-9]*_\d+)\]{0,2}/g,O=/^(?:[^\n()[\]]|\[\[[A-Z][A-Z0-9]*_\d+\]\])*\]\(/;function _(e,t,n,r){const s=t.startsWith("[[["),o=t.endsWith("]]]");if(!s&&!o)return r;const a=e.slice(n+t.length),l=s&&O.test(o?`]${a}`:a),f=o&&a.startsWith("(");return`${l?"[":""}${r}${f?"]":""}`}function x(){return{byToken:new Map,byValue:new Map,counts:new Map,aliases:new Map}}function L(e){return{entries:[...e?.byToken||new Map].map(([t,n])=>({token:t,value:n})),aliases:[...e?.aliases||new Map].map(([t,n])=>({alias:t,value:n}))}}function w(e){const t=x();for(const{token:n,value:r}of e?.entries||[]){const s=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(n);t.byToken.set(n,r),t.byValue.set(r,n),s&&t.counts.set(s[1],Math.max(t.counts.get(s[1])||0,Number(s[2])))}for(const{alias:n,value:r}of e?.aliases||[])t.aliases.set(n,r);return t}function h(e,t,n){const r=e.byValue.get(n);if(r)return r;const s=String(t||"PII").toUpperCase().replace(/[^A-Z0-9]/g,"")||"PII",o=(e.counts.get(s)||0)+1;e.counts.set(s,o);const a=`[[${s}_${o}]]`;return e.byToken.set(a,n),e.byValue.set(n,a),a}function E(e){return String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function k(e){return!(typeof e!="string"||e.length===0||e.length>200||/\([^)]*[+*}][^)]*\)\s*[+*{]/.test(e)||/[+*]\s*[+*]/.test(e))}function N(e,t){if(!t||t.length===0)return e;let n="",r=0;const s=e.length;for(;r<=s;){let o=null,a=null;for(const l of t){l.re.lastIndex=r;const f=l.re.exec(e);if(f&&(o===null||f.index<o.index)&&(o=f,a=l,f.index===r))break}if(!o){n+=e.slice(r);break}n+=e.slice(r,o.index),o[0].length===0?(n+=e[o.index]??"",r=o.index+1):(n+=a.repl(o),r=o.index+o[0].length)}return n}function P(e){let t=0,n=!1;for(let r=e.length-1;r>=0;r--){let s=e.charCodeAt(r)-48;n&&(s*=2,s>9&&(s-=9)),t+=s,n=!n}return t%10===0}function D(e){if(!/^[0-9A-Fa-f:]+$/.test(e)||(e.match(/:/g)||[]).length<2)return!1;const t=e.split(":");return t.some(n=>n.length>4)?!1:e.includes("::")?t.filter(Boolean).length>=1&&t.filter(Boolean).length<=7:t.length===8&&t.every(n=>n.length>=1)}const $=[{type:"SECRET",re:/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----/g},{type:"EMAIL",re:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g},{type:"SSN",re:/\b\d{3}[-\s]\d{2}[-\s]\d{4}\b/g},{type:"KEY",re:/\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[0-9A-Za-z_]{22,}|xox[baprs]-[A-Za-z0-9-]{10,}|xapp-[0-9]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35}|[rs]k_(?:live|test)_[0-9A-Za-z]{16,})\b/g},{type:"KEY",re:/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g},{type:"IP",re:/\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g},{type:"IP",re:/(?<![:\w])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![:\w])/g,valid:e=>D(e)},{type:"PHONE",re:/(?<![\w.])\+?\d[\d ().-]{6,}\d(?![\w])/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length<7||t.length>15||/^(?:19|20)\d\d[-./](?:0[1-9]|1[0-2])[-./](?:0[1-9]|[12]\d|3[01])(?![\d])/.test(e.trimStart())?!1:/[ ().-]/.test(e)||e.trimStart().startsWith("+")||t.length===10}},{type:"CARD",re:/\b(?:\d[ -]?){13,19}\b/g,valid:e=>{const t=e.replace(/\D/g,"");return t.length>=13&&t.length<=19&&P(t)}}];function b(e,t,{tier:n="basic",entities:r=[],dictionary:s=[],sanitize:o=!0,sanitizeOpts:a=void 0}={}){if(e==null||e==="")return e;let l=o?I(String(e),a):String(e);const f=t||x(),g=n==="full"||n==="entities",y=[];for(const i of s||[]){if(!i)continue;let c;try{c=i.pattern?k(i.pattern)?new RegExp(i.pattern,i.flags&&/g/.test(i.flags)?i.flags:`${i.flags||""}g`):null:i.value?new RegExp(`(?<![\\w])${E(i.value)}(?![\\w])`,"gi"):null}catch{c=null}if(c)if(i.alias!=null&&i.alias!=="")i.value&&f.aliases.set(i.alias,i.value),y.push({re:c,repl:()=>i.alias});else{const u=i.type||(i.pattern?"PII":"TERM");y.push({re:c,repl:p=>h(f,u,p[0])})}}if(l=N(l,y),g){const i=[...r||[]].filter(c=>c&&c.value).sort((c,u)=>String(u.value).length-String(c.value).length);for(const c of i){const u=new RegExp(`(?<![\\w])${E(c.value)}(?![\\w])`,"gi");l=l.replace(u,p=>h(f,c.type||"PERSON",p))}}const R=Z(l),d=[],S=(i,c)=>d.some(u=>i<u.end&&c>u.start);for(const i of $){i.re.lastIndex=0;let c;for(;(c=i.re.exec(R))!==null;){if(c[0].length===0){i.re.lastIndex++;continue}const u=c.index,p=u+c[0].length;i.valid&&!i.valid(c[0])||S(u,p)||d.push({start:u,end:p,type:i.type})}}if(d.length){d.sort((u,p)=>u.start-p.start);let i="",c=0;for(const u of d)i+=l.slice(c,u.start)+h(f,u.type,l.slice(u.start,u.end)),c=u.end;l=i+l.slice(c)}return l}function T(e,t,n){if(e==null||typeof e=="string")return e==null?e:b(e,t,n);if(Array.isArray(e))return e.map(r=>T(r,t,n));if(typeof e=="object"){let r=e;return typeof e.text=="string"&&(r={...r,text:b(e.text,t,n)}),Array.isArray(e.content)&&(r={...r,content:e.content.map(s=>T(s,t,n))}),e.resource&&typeof e.resource=="object"&&typeof e.resource.text=="string"&&(r={...r,resource:{...e.resource,text:b(e.resource.text,t,n)}}),r}return e}function z(e,t){if(e==null||!t)return e;const n=String(e);return n.replace(/\[{0,3}([A-Z][A-Z0-9]*_\d+)\]{0,3}/g,(r,s,o)=>{const a=`[[${s}]]`;return t.byToken.has(a)?_(n,r,o,t.byToken.get(a)):r})}function H(e,t){let n=z(e,t);if(t?.aliases?.size){const r=[...t.aliases.keys()].filter(Boolean).sort((s,o)=>o.length-s.length);if(r.length){const s=new RegExp(`(?<![\\w])(?:${r.map(E).join("|")})(?![\\w])`,"g");n=n.replace(s,o=>t.aliases.has(o)?t.aliases.get(o):o)}}return n}const C=Object.freeze({PERSON:"someone",EMAIL:"an email address",PHONE:"a phone number",ADDRESS:"an address",ORG:"an organisation",URL:"a link",IP:"an IP address",CARD:"a card number",SSN:"an ID number",DATE:"a date",ID:"an identifier"});function V(e,t){const n=String(e??"");if(!n)return{text:n,unresolved:[]};const r=[],s=n.replace(A,(o,a)=>{const l=t?.byToken?.get(o);return l??(r.push(o),C[a]||"redacted")});return A.lastIndex=0,{text:s,unresolved:r}}function Y(e){return A.lastIndex=0,A.test(String(e||""))}function B(e,{includeValues:t=!1,maxPairs:n=200}={}){const r=new Map,s=[];for(const[a,l]of e?.byToken||new Map){const f=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(a),g=f?f[1]:"OTHER";r.set(g,(r.get(g)||0)+1),t&&s.length<n&&s.push({token:a,value:l,type:g})}const o=[...r.entries()].map(([a,l])=>({type:a,count:l})).sort((a,l)=>l.count-a.count||a.type.localeCompare(l.type));return{total:o.reduce((a,l)=>a+l.count,0),types:o,...t?{pairs:s}:{}}}function F(e){const t=new Map;for(const r of e||[])for(const s of r?.types||[])t.set(s.type,(t.get(s.type)||0)+s.count);const n=[...t.entries()].map(([r,s])=>({type:r,count:s})).sort((r,s)=>s.count-r.count||r.type.localeCompare(s.type));return{total:n.reduce((r,s)=>r+s.count,0),types:n}}export{m as REDACTION_TOKEN_TYPES,x as createVault,Y as hasToken,K as isRedactionToken,F as mergeRedactionSummaries,T as redactResultShape,b as redactText,B as redactionSummary,z as restoreText,H as restoreWithAliases,V as scrubPlaceholders,w as vaultFromJSON,L as vaultToJSON};
package/src/sandbox.js CHANGED
@@ -1 +1 @@
1
- import{spawn as Ht,spawnSync as $t}from"node:child_process";import{writeFileSync as ut,mkdirSync as lt,existsSync as kt}from"node:fs";import{createHash as Mt,randomBytes as pt}from"node:crypto";import{AsyncLocalStorage as Bt}from"node:async_hooks";import{fileURLToPath as wt}from"node:url";import j from"node:os";import C from"node:path";import{kitFor as jt,toSrtSettings as ht,sandboxRecord as ft,shellJoin as xt,sandboxEnvOverlay as Q,normalizeGrant as bt,windowsGrantsFor as Ft,windowsSandboxEnv as It,withSrtWinEnv as Xt,NETWORK_MODES as Ut,ENGINE_KITS as Gt,DEVELOPER_HOSTS as Vt,SECRET_PATHS as zt,COMMON_WRITE as Jt}from"./events/sandbox-policy.js";const mt=new Bt;function me(t,e){let r;try{r=bt(t)}catch{r=null}return mt.run(r,e)}function Kt(){return mt.getStore()||null}const Yt=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function qt(t){const e=Yt.exec(String(t||""));return e?{host:e[1].toLowerCase(),port:Number(e[2])||0,reason:e[3]||""}:null}const X=new Map,F=[],U=new Map,Z=new Set,Qt=50;function St({commandId:t,host:e,port:r=0,reason:c="",at:w=Date.now()}){if(!t||!e)return;let d=X.get(t);for(d||(d=new Map,X.set(t,d)),d.set(e,{at:w,reason:c,port:r}),F.push({id:t,engine:U.get(t)||String(t).split(":")[0],host:e,at:w});F.length>Qt;)F.shift()}function Zt(t){const e=X.get(t);return e?[...e.entries()].sort((r,c)=>c[1].at-r[1].at).map(([r])=>r):[]}function te(t=20){return F.slice(-t).reverse()}function Se(){X.clear(),F.length=0,U.clear(),Z.clear()}const gt=new Map;function ge(t={}){const e=gt.get(String(t?.token||""));return!e||e!==t.commandId?!1:(St({commandId:e,host:String(t.host||"").toLowerCase().slice(0,253),port:Number(t.port)||0,reason:String(t.reason||"").slice(0,200)}),!0)}let ee=0;const ne=t=>`${t}:${(++ee).toString(36)}${Date.now().toString(36).slice(-4)}`,G=new Map;function se(t,e,{kind:r="agent",label:c=""}={}){if(!t||!e)return t;try{t.sandbox=e.record}catch{}if(typeof t.on!="function")return t;const w=e.commandId||"";G.set(t,{id:w,kind:r,engine:U.get(w)||String(w).split(":")[0]||"custom",command:e.label||"",label:c,pid:t.pid??null,since:Date.now(),sandbox:e.record});const d=()=>G.delete(t);return t.once("exit",d),t.once("error",d),t}function ye(){return[...G.values()].map(t=>({...t,refused:Zt(t.id)}))}function ve(){G.clear()}function yt(t){if(t)return"";try{return wt(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}function re(t=process.env.CHATPANEL_SRT_MODULE){if(!t)return"";try{const e=t.startsWith("file:")?wt(new URL("./cli.js",t)):C.join(C.dirname(t),"cli.js");return kt(e)?e:""}catch{return""}}const vt="open",tt="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",oe=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],et=t=>String(t||"").split(",").map(e=>e.trim()).filter(Boolean);function ae(t=process.env){const e=String(t.CHATPANEL_SANDBOX||vt).toLowerCase(),r=e!=="off"&&e!=="0"&&e!=="false",c=Ut.includes(e)?e:vt;return{enabled:r,mode:c,extraHosts:et(t.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:et(t.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:et(t.CHATPANEL_SANDBOX_DENY_READ),windows:t.CHATPANEL_SANDBOX_WINDOWS==="1"}}const At=new Set;function Wt(t,e=C.join(j.tmpdir(),"chatpanel-srt")){const r=JSON.stringify(t),c=C.join(e,`${Mt("sha256").update(r).digest("hex").slice(0,16)}.json`);return At.has(c)||(lt(e,{recursive:!0,mode:448}),ut(c,r,{mode:384}),At.add(c)),c}function ie(){try{const t=$t(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return t.status===0&&String(t.stdout||"").trim().length>0}catch{return!1}}function ce({config:t=ae(),loadSrt:e=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:r=ie,cliEntry:c=re(),onRefusal:w=p=>St(p),reportUrl:d=process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT?`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT}/sandbox/refused`:"http://127.0.0.1:4319/sandbox/refused",hostEntry:_=null,compiled:h=!1,platform:a=process.platform,home:v=j.homedir(),loopback:z=oe(),selfFiles:_t=[process.execPath,process.argv[1]||""],onExit:Ot=p=>process.on("exit",p),log:H=()=>{}}={}){let p=null,x=null,u=null,J=null,$=null,O=null,P=null;const k=new Set;let rt=!1;const Tt="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",Nt="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function Lt(){if(!t.windows){x=Tt;return}if(h){x=Nt;return}try{u=await e()}catch(s){x=`sandbox-runtime is not installed — it ships with the gateway (${s.message})`;return}if(!u?.SandboxManager?.wrapWithSandboxArgv||typeof u.grantWindowsAcl!="function"||typeof u.getWindowsSandboxUserStatusAsync!="function"){x="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{O=u.resolveSrtWin({path:u.VENDORED_SRT_WIN_EXE})}catch(s){x=`Windows: srt-win.exe is not beside sandbox-runtime (${s.message})`;return}let n;try{n=await u.getWindowsSandboxUserStatusAsync({srtWin:O})}catch(s){P=!1,x=`Windows: srt-win could not be asked whether the sandbox account exists (${s.message}) — ${tt}`;return}if(P=!!(n?.provisioned&&n.sid),!P){x=`Windows: the sandbox account is not installed — ${tt}`;return}$=n.sid,p="srt-lib"}async function ot(){if(!(p||x)){if(!t.enabled){x="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(a==="win32")return Lt();if(!h)try{if(u=await e(),u?.SandboxManager?.wrapWithSandboxArgv){p="srt-lib";return}}catch(n){H(`sandbox: library not available (${n.message})`)}if(r()){p="srt-cli";return}x=h?"srt is not on PATH — the compiled bridge cannot carry it: npm i -g @anthropic-ai/sandbox-runtime":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}}let at=!1;function K(){return c&&!h?{bin:process.execPath,argv:[c]}:p==="srt-cli"||r()?{bin:"srt",argv:[]}:null}function Rt(){const n=Array.isArray(t.exactHosts)?t.exactHosts:t.mode==="open"?["*"]:t.mode==="none"?[]:[...new Set([...Object.values(Gt).flatMap(l=>l.hosts),...Vt,...t.extraHosts])],s={id:`session:${t.mode}`,network:{mode:t.mode,allowedDomains:n},filesystem:{allowWrite:[j.tmpdir(),...Jt,...t.extraWrite],denyRead:[...zt,...t.extraDenyRead]}},o=ht(s,{loopback:z,home:a==="linux"?v:"",platform:a});return O?{...o,windows:{srtWin:{path:O.exe}}}:o}async function it(){return J||(J=u.SandboxManager.initialize(Rt()).then(()=>{try{u.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(n=>{for(const s of n||[]){const o=qt(s?.line);if(!o||!s?.encodedCommand)continue;let l="";try{l=Buffer.from(s.encodedCommand,"base64").toString("utf8")}catch{continue}const m=`${l}|${o.host}|${s.timestamp instanceof Date?s.timestamp.getTime():String(s.timestamp)}`;Z.has(m)||(Z.add(m),w({commandId:l,...o,at:s.timestamp instanceof Date?s.timestamp.getTime():Date.now()}))}})}catch(n){H(`sandbox: violations not subscribed (${n.message})`)}})),J}function Dt(n){const s=C.join(j.tmpdir(),"chatpanel-srt");lt(s,{recursive:!0,mode:448});const o=C.join(s,`host-${pt(8).toString("hex")}.json`);return ut(o,JSON.stringify(n),{mode:384}),o}function Ct(n,s){const o=(i,T)=>u.expandWindowsFsPaths(i,{mode:T}).filter(g=>!k.has(`${T}:${g.toLowerCase()}`)),l=o(n,"grant"),m=o(s,"grant");if(!(!l.length&&!m.length)){u.grantWindowsAcl({sandboxUserSid:$,read:l,write:m,srtWin:O});for(const i of l)k.add(`grant:${i.toLowerCase()}`);for(const i of m)k.add(`grant:${i.toLowerCase()}`);rt||(rt=!0,Ot(()=>{try{u.revokeWindowsAcl({sandboxUserSid:$,srtWin:O})}catch{}}))}}async function Pt(n,s,o,{engine:l,workdir:m,kit:i,settings:T,commandId:g,record:A}){await it();const M=b=>typeof b=="string"&&/^[a-z]:\\/i.test(b),{read:W,write:y}=Ft({kit:i,files:[n,...M(s[0])?[s[0]]:[],..._t].filter(Boolean),home:v});Ct(W,y);const N=xt(n,s,{platform:"win32"}),L=await u.SandboxManager.wrapWithSandboxArgv(N,void 0,{filesystem:{denyRead:T.filesystem.denyRead,denyWrite:T.filesystem.denyWrite}},void 0,m,{commandId:g,commandText:N}),R=o?.env||process.env,D={...It({engine:l,home:v,env:R,base:process.env}),...Q({},{platform:a})},E=Xt(L.argv,D),B={};for(const[b,f]of Object.entries(L.env||{}))process.env[b]!==f&&(B[b]=f);return{bin:E[0],argv:E.slice(1),opts:{...o,env:{...R,...B},shell:!1},record:A,commandId:g}}return{config:t,async status(){return await ot(),{enabled:t.enabled,mode:t.mode,runtime:p,platform:a,...x?{reason:x}:{},extras:{hosts:t.extraHosts,write:t.extraWrite,denyRead:t.extraDenyRead},ownSessions:!!(p&&(p==="srt-lib"&&(_??yt(h))||a!=="win32"&&K())),refused:te(),...a==="win32"&&P!==null?{provisioned:P,...P?{}:{install:tt}}:{}}},close(){if(!(!$||!k.size)){try{u.revokeWindowsAcl({sandboxUserSid:$,srtWin:O})}catch(n){H(`sandbox: could not release the Windows grants: ${n.message}`)}k.clear()}},async wrap(n,s,o,{engine:l="custom",cwd:m=null,commandId:i=null,grant:T=Kt()}={}){await ot(),i=i||ne(l),U.set(i,l);const g=m||o?.cwd||process.cwd(),A=C.basename(String(n||"")),M=f=>({bin:n,argv:s,opts:o,record:ft({layer:"none",reason:f}),commandId:i,label:A});if(!p)return M(x);let W,y;try{y=bt(T),W=jt({engine:l,cwd:g,mode:t.mode,extraHosts:t.extraHosts,extraWrite:[j.tmpdir(),...t.extraWrite],extraDenyRead:t.extraDenyRead,grant:y})}catch(f){return M(`kit: ${f.message}`)}const N=ht(W,{loopback:z,home:a==="linux"?v:"",platform:a}),L=xt(n,s),R=t.mode==="allowlist"&&y.hosts.length>0&&!Array.isArray(t.exactHosts),D=R&&p==="srt-lib"?_??yt(h):"",E=R&&!D&&a!=="win32"?K():null,B=!!(D||E),b=ft({layer:"process",runtime:D?"srt-host":E?"srt-cli":p,kitId:W.id,mode:W.network.mode,hosts:B||!R?y.hosts:[]});R&&!B&&(b.hostsDropped=y.hosts,at||(at=!0,H(`sandbox: hosts granted to ${l} (${y.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`)));try{if(D){const S=pt(16).toString("hex");gt.set(S,i);const Y={bin:n,argv:s,cwd:o?.cwd||null,engine:l,workdir:g,grant:y,commandId:i,config:{enabled:!0,mode:t.mode,extraHosts:[],extraWrite:t.extraWrite,extraDenyRead:t.extraDenyRead,windows:t.windows,exactHosts:W.network.allowedDomains},loopback:z,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:d?{url:d,token:S}:null},I={...o?.env||process.env};return{bin:process.execPath,argv:[D,Dt(Y)],opts:{...o,env:I,shell:!1},record:b,commandId:i,label:A}}if(E){const S={...o?.env||process.env};return Object.assign(S,Q(S,{platform:a})),{bin:E.bin,argv:[...E.argv,"-s",Wt(N),"-c",L],opts:{...o,env:S,shell:!1},record:b,commandId:i,label:A}}if(p==="srt-lib"&&a==="win32")return{...await Pt(n,s,o,{engine:l,workdir:g,kit:W,settings:N,commandId:i,record:b}),label:A};if(p==="srt-lib"){await it();const S=await u.SandboxManager.wrapWithSandboxArgv(L,void 0,{filesystem:N.filesystem},void 0,g,{commandId:i,commandText:L}),Y=o?.env||process.env,I={};for(const[ct,dt]of Object.entries(S.env||{}))process.env[ct]!==dt&&(I[ct]=dt);const q={...Y,...I};return Object.assign(q,Q(q,{platform:a})),{bin:S.argv[0],argv:S.argv.slice(1),opts:{...o,env:q,shell:!1},record:b,commandId:i,label:A}}const f=K();return{bin:f.bin,argv:[...f.argv,"-s",Wt(N),"-c",L],opts:{...o,shell:!1},record:b,commandId:i,label:A}}catch(f){return H(`sandbox: could not wrap ${n}: ${f.message}`),M(f?.code==="SHAPE"?`the sandbox policy refused this run: ${f.message}`:`sandbox-runtime failed to wrap the command: ${f.message}`)}},violations(n){try{return u?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(n)||[]}catch{return[]}}}}let V=null;function Et(){if(!V){const{isCompiledBinary:t}=de();V=ce({compiled:t(),log:e=>console.error(`[bridge] ${e}`)})}return V}function Ae(t){V=t}let nt=null;function de(){return nt||(nt={isCompiledBinary:()=>{const t=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(t.startsWith("node")||t.startsWith("bun"))}}),nt}const st=new Set;function We(t,e){if(!e||e.layer!=="none"||typeof t!="function")return;const r=e.reason||"unknown";st.has(r)||(st.add(r),t({type:"status",text:`Running outside a sandbox — ${r}`}))}function Ee(){st.clear()}async function _e(t,e,r,c={},{spawnImpl:w=Ht,box:d=Et(),kind:_="agent",label:h=""}={}){const a=await d.wrap(t,e,r,c);return se(w(a.bin,a.argv,a.opts),a,{kind:_,label:h})}async function Oe(t,{box:e=Et(),platform:r=process.platform,loadSrt:c=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:w=console.log,err:d=console.error}={}){const _=t[0]||"status";if(_==="status")return w(JSON.stringify(await e.status(),null,2)),0;if(_!=="install")return d("usage: chatpanel-bridge sandbox [status|install]"),2;if(r!=="win32")return w("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let h;try{h=await c()}catch(a){return d(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${a.message})`),1}try{const a=h.resolveSrtWin({path:h.VENDORED_SRT_WIN_EXE}),v=await h.installWindowsSandboxAsync({srtWin:a});return v?.cancelled?(d("Cancelled at the administrator prompt — nothing was installed."),1):(w(`The sandbox account is installed${v?.user?.sid?` (${v.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(a){d(`install failed: ${a.message}`);try{d(h.windowsInstallInstructions())}catch{}return 1}}export{ve as _resetLiveForTest,Ee as _resetNotedForTest,Se as _resetRefusalsForTest,Ae as _setSandboxForTest,ge as acceptRefusalReport,ce as createSandbox,Kt as currentGrant,ye as liveProcesses,We as noteSandbox,qt as parseRefusalLine,te as recentRefusals,St as recordRefusal,Zt as refusalsFor,Oe as runSandboxCli,Et as sandbox,ae as sandboxConfigFromEnv,_e as sandboxedSpawn,se as track,me as withGrant};
1
+ import{spawn as $t,spawnSync as kt}from"node:child_process";import{writeFileSync as lt,mkdirSync as pt,existsSync as Mt}from"node:fs";import{createHash as Bt,randomBytes as wt}from"node:crypto";import{AsyncLocalStorage as jt}from"node:async_hooks";import{fileURLToPath as ht}from"node:url";import F from"node:os";import C from"node:path";import{ensureCaBundle as Ft}from"./ca-bundle.js";import{kitFor as It,toSrtSettings as ft,sandboxRecord as xt,shellJoin as bt,sandboxEnvOverlay as Z,normalizeGrant as mt,windowsGrantsFor as Xt,windowsSandboxEnv as Ut,withSrtWinEnv as Gt,NETWORK_MODES as Vt,ENGINE_KITS as zt,DEVELOPER_HOSTS as Jt,SECRET_PATHS as Kt,COMMON_WRITE as Yt}from"./events/sandbox-policy.js";const St=new jt;function ye(t,e){let r;try{r=mt(t)}catch{r=null}return St.run(r,e)}function qt(){return St.getStore()||null}const Qt=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function Zt(t){const e=Qt.exec(String(t||""));return e?{host:e[1].toLowerCase(),port:Number(e[2])||0,reason:e[3]||""}:null}const U=new Map,I=[],G=new Map,tt=new Set,te=50;function gt({commandId:t,host:e,port:r=0,reason:c="",at:w=Date.now()}){if(!t||!e)return;let d=U.get(t);for(d||(d=new Map,U.set(t,d)),d.set(e,{at:w,reason:c,port:r}),I.push({id:t,engine:G.get(t)||String(t).split(":")[0],host:e,at:w});I.length>te;)I.shift()}function ee(t){const e=U.get(t);return e?[...e.entries()].sort((r,c)=>c[1].at-r[1].at).map(([r])=>r):[]}function ne(t=20){return I.slice(-t).reverse()}function ve(){U.clear(),I.length=0,G.clear(),tt.clear()}const yt=new Map;function Ae(t={}){const e=yt.get(String(t?.token||""));return!e||e!==t.commandId?!1:(gt({commandId:e,host:String(t.host||"").toLowerCase().slice(0,253),port:Number(t.port)||0,reason:String(t.reason||"").slice(0,200)}),!0)}let se=0;const re=t=>`${t}:${(++se).toString(36)}${Date.now().toString(36).slice(-4)}`,V=new Map;function oe(t,e,{kind:r="agent",label:c=""}={}){if(!t||!e)return t;try{t.sandbox=e.record}catch{}if(typeof t.on!="function")return t;const w=e.commandId||"";V.set(t,{id:w,kind:r,engine:G.get(w)||String(w).split(":")[0]||"custom",command:e.label||"",label:c,pid:t.pid??null,since:Date.now(),sandbox:e.record});const d=()=>V.delete(t);return t.once("exit",d),t.once("error",d),t}function We(){return[...V.values()].map(t=>({...t,refused:ee(t.id)}))}function Ee(){V.clear()}function vt(t){if(t)return"";try{return ht(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}function ae(t=process.env.CHATPANEL_SRT_MODULE){if(!t)return"";try{const e=t.startsWith("file:")?ht(new URL("./cli.js",t)):C.join(C.dirname(t),"cli.js");return Mt(e)?e:""}catch{return""}}const At="open",et="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",ie=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],nt=t=>String(t||"").split(",").map(e=>e.trim()).filter(Boolean);function ce(t=process.env){const e=String(t.CHATPANEL_SANDBOX||At).toLowerCase(),r=e!=="off"&&e!=="0"&&e!=="false",c=Vt.includes(e)?e:At;return{enabled:r,mode:c,extraHosts:nt(t.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:nt(t.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:nt(t.CHATPANEL_SANDBOX_DENY_READ),windows:t.CHATPANEL_SANDBOX_WINDOWS==="1"}}const Wt=new Set;function Et(t,e=C.join(F.tmpdir(),"chatpanel-srt")){const r=JSON.stringify(t),c=C.join(e,`${Bt("sha256").update(r).digest("hex").slice(0,16)}.json`);return Wt.has(c)||(pt(e,{recursive:!0,mode:448}),lt(c,r,{mode:384}),Wt.add(c)),c}function de(){try{const t=kt(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return t.status===0&&String(t.stdout||"").trim().length>0}catch{return!1}}function ue({config:t=ce(),loadSrt:e=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:r=de,cliEntry:c=ae(),onRefusal:w=p=>gt(p),reportUrl:d=process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT?`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT}/sandbox/refused`:"http://127.0.0.1:4319/sandbox/refused",hostEntry:_=null,compiled:h=!1,platform:a=process.platform,home:v=F.homedir(),loopback:J=ie(),selfFiles:Ot=[process.execPath,process.argv[1]||""],onExit:Tt=p=>process.on("exit",p),log:H=()=>{}}={}){let p=null,x=null,u=null,K=null,$=null,O=null,P=null;const k=new Set;let ot=!1;const Nt="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",Lt="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function Rt(){if(!t.windows){x=Nt;return}if(h){x=Lt;return}try{u=await e()}catch(s){x=`sandbox-runtime is not installed — it ships with the gateway (${s.message})`;return}if(!u?.SandboxManager?.wrapWithSandboxArgv||typeof u.grantWindowsAcl!="function"||typeof u.getWindowsSandboxUserStatusAsync!="function"){x="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{O=u.resolveSrtWin({path:u.VENDORED_SRT_WIN_EXE})}catch(s){x=`Windows: srt-win.exe is not beside sandbox-runtime (${s.message})`;return}let n;try{n=await u.getWindowsSandboxUserStatusAsync({srtWin:O})}catch(s){P=!1,x=`Windows: srt-win could not be asked whether the sandbox account exists (${s.message}) — ${et}`;return}if(P=!!(n?.provisioned&&n.sid),!P){x=`Windows: the sandbox account is not installed — ${et}`;return}$=n.sid,p="srt-lib"}async function at(){if(!(p||x)){if(!t.enabled){x="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(a==="win32")return Rt();if(!h)try{if(u=await e(),u?.SandboxManager?.wrapWithSandboxArgv){p="srt-lib";return}}catch(n){H(`sandbox: library not available (${n.message})`)}if(r()){p="srt-cli";return}x=h?"srt is not on PATH — the compiled bridge cannot carry it: npm i -g @anthropic-ai/sandbox-runtime":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}}let it=!1;function Y(){return c&&!h?{bin:process.execPath,argv:[c]}:p==="srt-cli"||r()?{bin:"srt",argv:[]}:null}function Dt(){const n=Array.isArray(t.exactHosts)?t.exactHosts:t.mode==="open"?["*"]:t.mode==="none"?[]:[...new Set([...Object.values(zt).flatMap(l=>l.hosts),...Jt,...t.extraHosts])],s={id:`session:${t.mode}`,network:{mode:t.mode,allowedDomains:n},filesystem:{allowWrite:[F.tmpdir(),...Yt,...t.extraWrite],denyRead:[...Kt,...t.extraDenyRead]}},o=ft(s,{loopback:J,home:a==="linux"?v:"",platform:a});return O?{...o,windows:{srtWin:{path:O.exe}}}:o}async function ct(){return K||(K=u.SandboxManager.initialize(Dt()).then(()=>{try{u.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(n=>{for(const s of n||[]){const o=Zt(s?.line);if(!o||!s?.encodedCommand)continue;let l="";try{l=Buffer.from(s.encodedCommand,"base64").toString("utf8")}catch{continue}const m=`${l}|${o.host}|${s.timestamp instanceof Date?s.timestamp.getTime():String(s.timestamp)}`;tt.has(m)||(tt.add(m),w({commandId:l,...o,at:s.timestamp instanceof Date?s.timestamp.getTime():Date.now()}))}})}catch(n){H(`sandbox: violations not subscribed (${n.message})`)}})),K}function Ct(n){const s=C.join(F.tmpdir(),"chatpanel-srt");pt(s,{recursive:!0,mode:448});const o=C.join(s,`host-${wt(8).toString("hex")}.json`);return lt(o,JSON.stringify(n),{mode:384}),o}function Pt(n,s){const o=(i,T)=>u.expandWindowsFsPaths(i,{mode:T}).filter(g=>!k.has(`${T}:${g.toLowerCase()}`)),l=o(n,"grant"),m=o(s,"grant");if(!(!l.length&&!m.length)){u.grantWindowsAcl({sandboxUserSid:$,read:l,write:m,srtWin:O});for(const i of l)k.add(`grant:${i.toLowerCase()}`);for(const i of m)k.add(`grant:${i.toLowerCase()}`);ot||(ot=!0,Tt(()=>{try{u.revokeWindowsAcl({sandboxUserSid:$,srtWin:O})}catch{}}))}}async function Ht(n,s,o,{engine:l,workdir:m,kit:i,settings:T,commandId:g,record:A,caBundle:M=""}){await ct();const B=b=>typeof b=="string"&&/^[a-z]:\\/i.test(b),{read:W,write:y}=Xt({kit:i,files:[n,...B(s[0])?[s[0]]:[],...Ot].filter(Boolean),home:v});Pt(W,y);const N=bt(n,s,{platform:"win32"}),L=await u.SandboxManager.wrapWithSandboxArgv(N,void 0,{filesystem:{denyRead:T.filesystem.denyRead,denyWrite:T.filesystem.denyWrite}},void 0,m,{commandId:g,commandText:N}),R=o?.env||process.env,D={...Ut({engine:l,home:v,env:R,base:process.env}),...Z({},{platform:a,caBundle:M})},E=Gt(L.argv,D),j={};for(const[b,f]of Object.entries(L.env||{}))process.env[b]!==f&&(j[b]=f);return{bin:E[0],argv:E.slice(1),opts:{...o,env:{...R,...j},shell:!1},record:A,commandId:g}}return{config:t,async status(){return await at(),{enabled:t.enabled,mode:t.mode,runtime:p,platform:a,...x?{reason:x}:{},extras:{hosts:t.extraHosts,write:t.extraWrite,denyRead:t.extraDenyRead},ownSessions:!!(p&&(p==="srt-lib"&&(_??vt(h))||a!=="win32"&&Y())),refused:ne(),...a==="win32"&&P!==null?{provisioned:P,...P?{}:{install:et}}:{}}},close(){if(!(!$||!k.size)){try{u.revokeWindowsAcl({sandboxUserSid:$,srtWin:O})}catch(n){H(`sandbox: could not release the Windows grants: ${n.message}`)}k.clear()}},async wrap(n,s,o,{engine:l="custom",cwd:m=null,commandId:i=null,grant:T=qt()}={}){await at(),i=i||re(l),G.set(i,l);const g=m||o?.cwd||process.cwd(),A=C.basename(String(n||"")),M=f=>({bin:n,argv:s,opts:o,record:xt({layer:"none",reason:f}),commandId:i,label:A});if(!p)return M(x);const B=await Ft().catch(()=>"");let W,y;try{y=mt(T),W=It({engine:l,cwd:g,mode:t.mode,extraHosts:t.extraHosts,extraWrite:[F.tmpdir(),...t.extraWrite],extraDenyRead:t.extraDenyRead,grant:y})}catch(f){return M(`kit: ${f.message}`)}const N=ft(W,{loopback:J,home:a==="linux"?v:"",platform:a}),L=bt(n,s),R=t.mode==="allowlist"&&y.hosts.length>0&&!Array.isArray(t.exactHosts),D=R&&p==="srt-lib"?_??vt(h):"",E=R&&!D&&a!=="win32"?Y():null,j=!!(D||E),b=xt({layer:"process",runtime:D?"srt-host":E?"srt-cli":p,kitId:W.id,mode:W.network.mode,hosts:j||!R?y.hosts:[]});R&&!j&&(b.hostsDropped=y.hosts,it||(it=!0,H(`sandbox: hosts granted to ${l} (${y.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`)));try{if(D){const S=wt(16).toString("hex");yt.set(S,i);const q={bin:n,argv:s,cwd:o?.cwd||null,engine:l,workdir:g,grant:y,commandId:i,config:{enabled:!0,mode:t.mode,extraHosts:[],extraWrite:t.extraWrite,extraDenyRead:t.extraDenyRead,windows:t.windows,exactHosts:W.network.allowedDomains},loopback:J,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:d?{url:d,token:S}:null},X={...o?.env||process.env};return{bin:process.execPath,argv:[D,Ct(q)],opts:{...o,env:X,shell:!1},record:b,commandId:i,label:A}}if(E){const S={...o?.env||process.env};return Object.assign(S,Z(S,{platform:a,caBundle:B})),{bin:E.bin,argv:[...E.argv,"-s",Et(N),"-c",L],opts:{...o,env:S,shell:!1},record:b,commandId:i,label:A}}if(p==="srt-lib"&&a==="win32")return{...await Ht(n,s,o,{engine:l,workdir:g,kit:W,settings:N,commandId:i,record:b,caBundle:B}),label:A};if(p==="srt-lib"){await ct();const S=await u.SandboxManager.wrapWithSandboxArgv(L,void 0,{filesystem:N.filesystem},void 0,g,{commandId:i,commandText:L}),q=o?.env||process.env,X={};for(const[dt,ut]of Object.entries(S.env||{}))process.env[dt]!==ut&&(X[dt]=ut);const Q={...q,...X};return Object.assign(Q,Z(Q,{platform:a,caBundle:B})),{bin:S.argv[0],argv:S.argv.slice(1),opts:{...o,env:Q,shell:!1},record:b,commandId:i,label:A}}const f=Y();return{bin:f.bin,argv:[...f.argv,"-s",Et(N),"-c",L],opts:{...o,shell:!1},record:b,commandId:i,label:A}}catch(f){return H(`sandbox: could not wrap ${n}: ${f.message}`),M(f?.code==="SHAPE"?`the sandbox policy refused this run: ${f.message}`:`sandbox-runtime failed to wrap the command: ${f.message}`)}},violations(n){try{return u?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(n)||[]}catch{return[]}}}}let z=null;function _t(){if(!z){const{isCompiledBinary:t}=le();z=ue({compiled:t(),log:e=>console.error(`[bridge] ${e}`)})}return z}function _e(t){z=t}let st=null;function le(){return st||(st={isCompiledBinary:()=>{const t=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(t.startsWith("node")||t.startsWith("bun"))}}),st}const rt=new Set;function Oe(t,e){if(!e||e.layer!=="none"||typeof t!="function")return;const r=e.reason||"unknown";rt.has(r)||(rt.add(r),t({type:"status",text:`Running outside a sandbox — ${r}`}))}function Te(){rt.clear()}async function Ne(t,e,r,c={},{spawnImpl:w=$t,box:d=_t(),kind:_="agent",label:h=""}={}){const a=await d.wrap(t,e,r,c);return oe(w(a.bin,a.argv,a.opts),a,{kind:_,label:h})}async function Le(t,{box:e=_t(),platform:r=process.platform,loadSrt:c=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:w=console.log,err:d=console.error}={}){const _=t[0]||"status";if(_==="status")return w(JSON.stringify(await e.status(),null,2)),0;if(_!=="install")return d("usage: chatpanel-bridge sandbox [status|install]"),2;if(r!=="win32")return w("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let h;try{h=await c()}catch(a){return d(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${a.message})`),1}try{const a=h.resolveSrtWin({path:h.VENDORED_SRT_WIN_EXE}),v=await h.installWindowsSandboxAsync({srtWin:a});return v?.cancelled?(d("Cancelled at the administrator prompt — nothing was installed."),1):(w(`The sandbox account is installed${v?.user?.sid?` (${v.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(a){d(`install failed: ${a.message}`);try{d(h.windowsInstallInstructions())}catch{}return 1}}export{Ee as _resetLiveForTest,Te as _resetNotedForTest,ve as _resetRefusalsForTest,_e as _setSandboxForTest,Ae as acceptRefusalReport,ue as createSandbox,qt as currentGrant,We as liveProcesses,Oe as noteSandbox,Zt as parseRefusalLine,ne as recentRefusals,gt as recordRefusal,ee as refusalsFor,Le as runSandboxCli,_t as sandbox,ce as sandboxConfigFromEnv,Ne as sandboxedSpawn,oe as track,ye as withGrant};
package/src/server.js CHANGED
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as we}from"node:http";import A from"node:os";import{randomBytes as ye,randomInt as be,timingSafeEqual as Se}from"node:crypto";import{mkdirSync as ke,writeFileSync as Te,readFileSync as z,existsSync as Ce}from"node:fs";import{join as _}from"node:path";import*as ve from"./engines/claude.js";import*as Ee from"./engines/codex.js";import*as Oe from"./engines/antigravity.js";import{pi as xe,opencode as Ae,kiro as Pe,copilot as $e,deepseek as Ie,hermes as Ne}from"./engines/cli-agents.js";import{connectorsFor as Re}from"./connectors.js";import*as _e from"./engines/custom.js";import{installService as He,uninstallService as Me,serviceStatus as Be,restartService as K}from"./service.js";import{skillIndex as L,listRecords as Ge,readRecord as De,readPackageFile as Ue,skillsHealth as Le,quarantinedSkills as We}from"./skills.js";import{capabilityToolSpecs as je,runCapabilityTool as Fe}from"./mcp-capabilities.js";import{createSession as Je,deleteSession as V,getSession as Y,activeSession as Xe,relayToolCall as ze}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ke,isDefaultWorkdir as Ve,resolveWorkdir as Ye,writeScopeNote as Qe}from"./workdir.js";import{sandbox as Q,runSandboxCli as Ze,withGrant as Z,acceptRefusalReport as qe,liveProcesses as et}from"./sandbox.js";import{gitState as tt,gitDelta as nt}from"./scm.js";import{listConnections as ot,putConnection as rt,removeConnection as at,runEnvFor as it,testConnection as st,secretBackend as q}from"./connections.js";import{worktreeFor as ee,listWorktrees as ct,removeWorktree as lt,withHook as dt,WORKTREE_ROOT as te}from"./worktree.js";import{AGENT_CLIS as ut,enrichPath as ht,enrichAgentEnv as pt,findAgentBin as ne,resolveCommand as mt}from"./env.js";import"./sanitize.js";import{checkForUpdate as ft,selfUpdate as oe,isEmbedded as gt}from"./update.js";import{callLocalMcp as wt,localMcpStatus as yt}from"./mcp-local.js";import{assertPublicHttpUrl as re,assertPublicWebUrl as ae}from"./ssrf.js";import{startRun as ie,endRun as W,cancelRun as bt,cancelAll as St}from"./runs.js";import{closeWarmPools as kt,warmStatus as Tt}from"./warm.js";import{CompatError as P,anthropicError as j,anthropicStream as Ct,chatCompletionStream as vt,completionStream as Et,createAnthropicMessage as Ot,createChatCompletion as xt,createCompletion as At,createResponse as Pt,openAIError as b,parseAnthropicMessage as $t,parseChatCompletion as It,parseCompletion as Nt,parseResponse as Rt,responseStream as _t}from"./api-compat.js";import{callerTrust as Ht,isPaired as $,parseExtensionIds as Mt,capRunOptions as Bt,engineHonoursReach as Gt,createPairingStore as Dt,formatPairingCode as Ut}from"./pii/trust.js";const w="0.17.3",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",C=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,v={claude:{engine:ve,label:"Claude Code"},codex:{engine:Ee,label:"Codex"},antigravity:{engine:Oe,label:"Antigravity",tools:!1},pi:{engine:xe,label:"Pi"},opencode:{engine:Ae,label:"OpenCode"},hermes:{engine:Ne,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:$e,label:"GitHub Copilot"},deepseek:{engine:Ie,label:"DeepSeek Harness"},custom:{engine:_e,label:"Custom",hidden:!0}};function se(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const Lt=Mt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(t){return t.chatpanelTrust||(t.chatpanelTrust=Ht({origin:t.headers.origin||"",hasToken:ue(t),extensionIds:Lt})),t.chatpanelTrust}function Wt(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function jt(t,e){const n=t.headers.origin||"",r=se(n);e.setHeader("Access-Control-Allow-Origin",r?n||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const F=new Set(["127.0.0.1","localhost","::1"]);function Ft(t){if(!F.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return F.has(n)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function Jt(){try{Ce(N)&&(S=z(N,"utf8").trim()),S||(S=ye(32).toString("hex"),ke(_(A.homedir(),".chatpanel"),{recursive:!0}),Te(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ce=Dt({random:()=>be(0,1e6)/1e6});function Xt(t){if(!S)return i(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ce.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function zt(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=ce.claim(n?.code);return r.ok?(u("info",`paired a ${I(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${I(t)} caller`),i(e,403,{error:r.reason}))}function Kt(t,e){const n=I(t);return i(e,200,{ok:!0,trust:n,paired:$(n),version:w})}let H=null;async function le(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${C}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function de(t,e,n){try{const r=await le(),o=t.method==="POST"?await f(t):{};if(n==="status")return i(e,200,await r.status());if(n==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return n==="pair"?i(e,200,await r.pair()):n==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?i(e,200,await r.update(o)):n==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function ue(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const r=Buffer.from(n),o=Buffer.from(S);return r.length===o.length&&Se(r,o)}const Vt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/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"]),Yt=new Set(["/debug"]),Qt=t=>Yt.has(t);function Zt(t,e){if(!Ft(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!se(n))return"forbidden origin";const r=t.method==="POST"&&Vt.has(e)||t.method==="GET"&&Qt(e);return r&&!(Wt(n)||ue(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!$(I(t))&&!en.has(e)?qt:null}const qt="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",en=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function J(t,e,n){const r=I(t),o=Bt(n,r);if(!Gt(e,o.reach))return{error:`${$(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=$(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function f(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function tn(t){const e=await Promise.all(Object.entries(v).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),h=await Re(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:h,...c===!1?{tools:!1}:{}}})),n=gt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await ft(w).catch(()=>({current:w,updateAvailable:!1})),r=await Le().catch(()=>null),o=await Q().status().catch(a=>({enabled:!1,reason:a.message}));i(t,200,{ok:!0,version:w,agents:e,update:n,workspace:Ke,sandbox:o,localMcp:yt(),processes:et(),worktrees:te,secretBackend:q(),warm:Tt(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function nn(t,e,n){const{index:r,problems:o}=await L({extraDirs:e,workdir:n});i(t,200,{ok:!0,skills:Ge(r),problems:o})}async function on(t,e,n){i(t,200,{ok:!0,quarantined:await We(e,n)})}async function rn(t,e,n,r){const{index:o}=await L({extraDirs:n,workdir:r}),a=De(o,e);if(!a)return i(t,404,{ok:!1,error:"unknown skill"});i(t,200,{ok:!0,skill:a})}async function an(t,e,n,r,o){const{index:a}=await L({extraDirs:r,workdir:o}),s=await Ue(a,e,n);if(s.error)return i(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(t,200,{ok:!0,...s})}async function sn(){return(await Promise.all(Object.entries(v).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function he(t,e=""){const n=await sn();if(e){const r=n.find(o=>o.id===e);return r?i(t,200,r):i(t,404,b(new P(`Model "${e}" not found`,404,"model")))}return i(t,200,{object:"list",data:n})}async function cn(t){try{const e=await oe(w);i(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>K(),400))}catch(e){i(t,400,{ok:!1,error:String(e?.message||e)})}}async function ln(t,e){let n;try{n=await f(t)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const r=v[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});const o=J(t,n.agent,n.options||{});if(o.error)return i(e,403,{error:o.error});n.options=o.options,Array.isArray(n.images)&&n.images.length&&u("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
2
+ import{createServer as we}from"node:http";import A from"node:os";import{randomBytes as ye,randomInt as be,timingSafeEqual as Se}from"node:crypto";import{mkdirSync as ke,writeFileSync as Te,readFileSync as z,existsSync as ve}from"node:fs";import{join as _}from"node:path";import*as Ce from"./engines/claude.js";import*as Ee from"./engines/codex.js";import*as Oe from"./engines/antigravity.js";import{pi as xe,opencode as Ae,kiro as Pe,copilot as $e,deepseek as Ie,hermes as Ne}from"./engines/cli-agents.js";import{connectorsFor as Re}from"./connectors.js";import*as _e from"./engines/custom.js";import{installService as He,uninstallService as Me,serviceStatus as Be,restartService as K}from"./service.js";import{skillIndex as W,listRecords as Ge,readRecord as De,readPackageFile as Ue,skillsHealth as We,quarantinedSkills as Le}from"./skills.js";import{capabilityToolSpecs as je,runCapabilityTool as Je}from"./mcp-capabilities.js";import{createSession as Fe,deleteSession as V,getSession as Y,activeSession as Xe,relayToolCall as ze}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ke,isDefaultWorkdir as Ve,resolveWorkdir as Ye,writeScopeNote as Qe}from"./workdir.js";import{sandbox as Q,runSandboxCli as Ze,withGrant as Z,acceptRefusalReport as qe,liveProcesses as et}from"./sandbox.js";import{gitState as tt,gitDelta as nt}from"./scm.js";import{listConnections as ot,putConnection as rt,removeConnection as at,runEnvFor as it,testConnection as st,secretBackend as q}from"./connections.js";import{worktreeFor as ee,listWorktrees as ct,removeWorktree as lt,withHook as dt,WORKTREE_ROOT as te}from"./worktree.js";import{AGENT_CLIS as ut,enrichPath as ht,enrichAgentEnv as pt,findAgentBin as ne,resolveCommand as mt}from"./env.js";import"./sanitize.js";import{checkForUpdate as ft,selfUpdate as oe,isEmbedded as gt}from"./update.js";import{callLocalMcp as wt,localMcpStatus as yt,signInLocalMcp as bt,signInStatusLocalMcp as St}from"./mcp-local.js";import{assertPublicHttpUrl as re,assertPublicWebUrl as ae}from"./ssrf.js";import{startRun as ie,endRun as L,cancelRun as kt,cancelAll as Tt}from"./runs.js";import{closeWarmPools as vt,warmStatus as Ct}from"./warm.js";import{CompatError as P,anthropicError as j,anthropicStream as Et,chatCompletionStream as Ot,completionStream as xt,createAnthropicMessage as At,createChatCompletion as Pt,createCompletion as $t,createResponse as It,openAIError as b,parseAnthropicMessage as Nt,parseChatCompletion as Rt,parseCompletion as _t,parseResponse as Ht,responseStream as Mt}from"./api-compat.js";import{callerTrust as Bt,isPaired as $,parseExtensionIds as Gt,capRunOptions as Dt,engineHonoursReach as Ut,createPairingStore as Wt,formatPairingCode as Lt}from"./pii/trust.js";const w="0.19.0",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ce,label:"Claude Code"},codex:{engine:Ee,label:"Codex"},antigravity:{engine:Oe,label:"Antigravity",tools:!1},pi:{engine:xe,label:"Pi"},opencode:{engine:Ae,label:"OpenCode"},hermes:{engine:Ne,label:"Hermes"},kiro:{engine:Pe,label:"Kiro"},copilot:{engine:$e,label:"GitHub Copilot"},deepseek:{engine:Ie,label:"DeepSeek Harness"},custom:{engine:_e,label:"Custom",hidden:!0}};function se(t){return!t||t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}const jt=Gt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function I(t){return t.chatpanelTrust||(t.chatpanelTrust=Bt({origin:t.headers.origin||"",hasToken:ue(t),extensionIds:jt})),t.chatpanelTrust}function Jt(t){return t.startsWith("chrome-extension://")||t.startsWith("moz-extension://")||t.startsWith("http://localhost")||t.startsWith("http://127.0.0.1")||t.startsWith("http://[::1]")}function Ft(t,e){const n=t.headers.origin||"",r=se(n);e.setHeader("Access-Control-Allow-Origin",r?n||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function Xt(t){if(!J.has(k))return!0;const e=String(t.headers.host||"");if(!e)return!1;const n=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(n)}const N=_(A.homedir(),".chatpanel","bridge-token");let S="";function zt(){try{ve(N)&&(S=z(N,"utf8").trim()),S||(S=ye(32).toString("hex"),ke(_(A.homedir(),".chatpanel"),{recursive:!0}),Te(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ce=Wt({random:()=>be(0,1e6)/1e6});function Kt(t){if(!S)return i(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ce.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Vt(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=ce.claim(n?.code);return r.ok?(u("info",`paired a ${I(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${I(t)} caller`),i(e,403,{error:r.reason}))}function Yt(t,e){const n=I(t);return i(e,200,{ok:!0,trust:n,paired:$(n),version:w})}let H=null;async function le(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(A.homedir(),".chatpanel"),dataDir:_(A.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${v}`,token:S},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function de(t,e,n){try{const r=await le(),o=t.method==="POST"?await f(t):{};if(n==="status")return i(e,200,await r.status());if(n==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return n==="pair"?i(e,200,await r.pair()):n==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?i(e,200,await r.update(o)):n==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function ue(t){if(!S)return!1;const e=String(t.headers.authorization||""),n=(e.startsWith("Bearer ")?e.slice(7):String(t.headers["x-api-key"]||t.headers["x-chatpanel-token"]||"")).trim();if(!n)return!1;const r=Buffer.from(n),o=Buffer.from(S);return r.length===o.length&&Se(r,o)}const Qt=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),Zt=new Set(["/debug"]),qt=t=>Zt.has(t);function en(t,e){if(!Xt(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!se(n))return"forbidden origin";const r=t.method==="POST"&&Qt.has(e)||t.method==="GET"&&qt(e);return r&&!(Jt(n)||ue(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!$(I(t))&&!nn.has(e)?tn:null}const tn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",nn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(t,e,n){const r=I(t),o=Dt(n,r);if(!Ut(e,o.reach))return{error:`${$(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${$(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=$(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function f(t){return new Promise((e,n)=>{let r="";t.on("data",o=>{r+=o,r.length>50*1024*1024&&n(new Error("Body too large"))}),t.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){n(o)}}),t.on("error",n)})}async function on(t){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),h=await Re(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:h,...c===!1?{tools:!1}:{}}})),n=gt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await ft(w).catch(()=>({current:w,updateAvailable:!1})),r=await We().catch(()=>null),o=await Q().status().catch(a=>({enabled:!1,reason:a.message}));i(t,200,{ok:!0,version:w,agents:e,update:n,workspace:Ke,sandbox:o,localMcp:yt(),processes:et(),worktrees:te,secretBackend:q(),warm:Ct(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function rn(t,e,n){const{index:r,problems:o}=await W({extraDirs:e,workdir:n});i(t,200,{ok:!0,skills:Ge(r),problems:o})}async function an(t,e,n){i(t,200,{ok:!0,quarantined:await Le(e,n)})}async function sn(t,e,n,r){const{index:o}=await W({extraDirs:n,workdir:r}),a=De(o,e);if(!a)return i(t,404,{ok:!1,error:"unknown skill"});i(t,200,{ok:!0,skill:a})}async function cn(t,e,n,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await Ue(a,e,n);if(s.error)return i(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(t,200,{ok:!0,...s})}async function ln(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,n])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await n.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...n})=>n)}async function he(t,e=""){const n=await ln();if(e){const r=n.find(o=>o.id===e);return r?i(t,200,r):i(t,404,b(new P(`Model "${e}" not found`,404,"model")))}return i(t,200,{object:"list",data:n})}async function dn(t){try{const e=await oe(w);i(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>K(),400))}catch(e){i(t,400,{ok:!1,error:String(e?.message||e)})}}async function un(t,e){let n;try{n=await f(t)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const r=C[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});const o=F(t,n.agent,n.options||{});if(o.error)return i(e,403,{error:o.error});n.options=o.options,Array.isArray(n.images)&&n.images.length&&u("info",`chat: ${n.agent} received ${n.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
3
3
 
4
- `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=ie(d),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};t.on("close",h),e.on("close",h),e.on("error",h);const g=p=>{s||a(p)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const p=n.options.workspace;if(m=await ee({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),W(d),e.writableEnded||e.end();return}}const X=m?m.path:Ye(n.options?.workingDir);let E=null;{const p=X,O=!!m||!Ve(n.options?.workingDir),y=Qe(n.agent,n.options?.permissionMode,p);a({type:"workdir",path:p,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${p}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await tt(p),E&&a({type:"scm",phase:"before",...E})}let D=null;if(E||m){const p=Array.isArray(n.options?.grants)?n.options.grants:[],{env:O,connection:y}=it({remote:E?.remote||null,grants:p,branch:m?.branch||null,connectionId:n.options?.connectionId||null});D=dt(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const U={...n.options||{},...m?{workingDir:m.path}:{},...D?{runEnv:D}:{}};let R=null;n.pageTools?.specs?.length&&(R=Je(g,n.pageTools.specs),U.mcp={url:`http://${k}:${C}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs});try{await Z(U.sandbox,()=>r.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:U,images:Array.isArray(n.images)?n.images:[]},g,{signal:l.signal}))}catch(p){u("error",`${n.agent} chat failed: ${p?.message||p}`),a({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await nt(X,E).catch(()=>null);p&&g({type:"scm",phase:"after",...p})}W(d),R&&V(R.id),e.writableEnded||e.end()}}async function dn(t,e,n){if(t.method==="GET"&&n==="/connections")return i(e,200,{ok:!0,connections:ot(),secretBackend:q()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(t);if(n==="/connections")try{return i(e,200,{ok:!0,connection:rt(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return o?o[2]==="delete"?i(e,200,{ok:at(o[1])}):i(e,200,st(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function un(t,e,n){if(t.method==="GET"&&n==="/worktrees")return i(e,200,{ok:!0,root:te,worktrees:await ct()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(t);if(n==="/worktrees"){const o=await ee({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(n==="/worktrees/remove"){const o=await lt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function T(t,e,n){const r=v[t.agent];if(!r||r.hidden)throw new P(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new P(o.reason||`${t.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=ie(a),d=()=>s.cancel("disconnected");n.on("close",d);let c="";try{return await Z(t.options?.sandbox,()=>r.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{n.off("close",d),W(a)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
4
+ `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=ie(d),l={signal:c.signal,abort:()=>c.cancel("client")},h=()=>{s=!0,c.cancel("disconnected")};t.on("close",h),e.on("close",h),e.on("error",h);const g=p=>{s||a(p)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const p=n.options.workspace;if(m=await ee({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(d),e.writableEnded||e.end();return}}const X=m?m.path:Ye(n.options?.workingDir);let E=null;{const p=X,O=!!m||!Ve(n.options?.workingDir),y=Qe(n.agent,n.options?.permissionMode,p);a({type:"workdir",path:p,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${p}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await tt(p),E&&a({type:"scm",phase:"before",...E})}let D=null;if(E||m){const p=Array.isArray(n.options?.grants)?n.options.grants:[],{env:O,connection:y}=it({remote:E?.remote||null,grants:p,branch:m?.branch||null,connectionId:n.options?.connectionId||null});D=dt(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const U={...n.options||{},...m?{workingDir:m.path}:{},...D?{runEnv:D}:{}};let R=null;n.pageTools?.specs?.length&&(R=Fe(g,n.pageTools.specs),U.mcp={url:`http://${k}:${v}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs});try{await Z(U.sandbox,()=>r.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:U,images:Array.isArray(n.images)?n.images:[]},g,{signal:l.signal}))}catch(p){u("error",`${n.agent} chat failed: ${p?.message||p}`),a({type:"error",error:p?.message||String(p)})}finally{if(!s){const p=await nt(X,E).catch(()=>null);p&&g({type:"scm",phase:"after",...p})}L(d),R&&V(R.id),e.writableEnded||e.end()}}async function hn(t,e,n){if(t.method==="GET"&&n==="/connections")return i(e,200,{ok:!0,connections:ot(),secretBackend:q()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(t);if(n==="/connections")try{return i(e,200,{ok:!0,connection:rt(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return o?o[2]==="delete"?i(e,200,{ok:at(o[1])}):i(e,200,st(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function pn(t,e,n){if(t.method==="GET"&&n==="/worktrees")return i(e,200,{ok:!0,root:te,worktrees:await ct()});if(t.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(t);if(n==="/worktrees"){const o=await ee({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(n==="/worktrees/remove"){const o=await lt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function T(t,e,n){const r=C[t.agent];if(!r||r.hidden)throw new P(`Unknown ChatPanel agent "${t.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new P(o.reason||`${t.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=ie(a),d=()=>s.cancel("disconnected");n.on("close",d);let c="";try{return await Z(t.options?.sandbox,()=>r.engine.chat({messages:t.messages,system:t.system,options:t.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{n.off("close",d),L(a)}}function M(t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(t,e){t.writableEnded||t.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
5
5
 
6
6
  `)}function B(t,e,n){t.writableEnded||t.write(`event: ${e}
7
7
  data: ${JSON.stringify(n)}
8
8
 
9
- `)}async function G(t,e,n,r){try{const o=n(await f(t)),a=J(t,o.agent,o.options||{});if(a.error)throw new P(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${o.message}`):o)),null}}async function hn(t,e){const n=await G(t,e,It,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,xt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=vt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function pn(t,e){const n=await G(t,e,Nt,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,At(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=Et(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function mn(t,e){const n=await G(t,e,Rt,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,Pt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=_t(n.requestedModel,o=>B(e,o.type,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...b(o)};B(e,"error",a)}e.end()}async function fn(t,e){const n=await G(t,e,$t,j);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,Ot(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,j(o))}M(e);const r=Ct(n.requestedModel,(o,a)=>B(e,o,a));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){B(e,"error",j(o))}e.end()}async function gn(t,e){let n={};try{n=await f(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?bt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function pe(t,e,n){let r;try{r=await f(t)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?Y(n):Xe(),a=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:w}});const d=je();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await Fe(r.params?.name,r.params?.arguments||{});if(c)return a(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await ze(o,r.params?.name,r.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function wn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=n.server||{},o=n.message;if(!r.command||!o)return i(e,400,{error:"need server.command and message"});try{const a=await wt({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function yn(t,e){let n;try{n=await f(t)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:r,headers:o,message:a}=n||{};if(!r||!a)return i(e,400,{error:"need url and message"});let s;try{s=re(r)}catch(h){return i(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[h,g]of Object.entries(o)){const m=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(d[h]=String(g))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{h.url&&re(h.url)}catch(m){return i(e,400,{error:String(m?.message||m)})}const g=await h.text().catch(()=>"");return i(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",body:g})}catch(h){const g=h?.name==="AbortError"?"timed out":String(h?.message||h);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${g}`})}finally{clearTimeout(l)}}const me=256*1024,bn=5,Sn=8e3;async function kn(t){let e=ae(t);const n=new AbortController,r=setTimeout(()=>n.abort(),Sn);try{for(let o=0;o<=bn;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:n.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${w} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ae(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:vn(await Tn(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Tn(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,me);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(o+=s.byteLength,r+=n.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=me))break}}finally{try{await e.cancel()}catch{}}return r}function Cn(t){return String(t).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,n)=>{try{return String.fromCodePoint(+n)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,n)=>{try{return String.fromCodePoint(parseInt(n,16))}catch{return""}})}function vn(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?Cn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function En(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=n&&n.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await kn(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function On(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=Y(n.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(n.id);return o?(r.pending.delete(n.id),o.resolve(n.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function xn(t,e){let n;try{n=await f(t)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const r=v[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});const o=String(n.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=n.model||"",s=J(t,n.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=String(n.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function An(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=v[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(n.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Pn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(n.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=mt(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}const fe=we(async(t,e)=>{if(jt(t,e),t.method==="OPTIONS")return e.writeHead(204),e.end();let n;try{n=new URL(t.url,`http://${t.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=Zt(t,n.pathname);if(r)return i(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return tn(e);const o=n.searchParams.getAll("dir"),a=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return nn(e,o,a);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return on(e,o,a);if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?rn(e,decodeURIComponent(s),o,a):an(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,a)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return dn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return un(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return he(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return he(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:w,agents:Object.fromEntries(ut.map(d=>[d,s?ne(d)||null:!!ne(d)])),...s?{home:A.homedir(),path:process.env.PATH}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return ln(t,e);if(t.method==="POST"&&n.pathname==="/pair")return zt(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return Xt(e);if(t.method==="POST"&&n.pathname==="/whoami")return Kt(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return hn(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return pn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return mn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return fn(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return pe(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const s=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return pe(t,e,s);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return V(s),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return de(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return de(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return gn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return On(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await f(t)}catch{s=null}const d=qe(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return wn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return yn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return En(t,e);if(t.method==="POST"&&n.pathname==="/complete")return xn(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return An(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return Pn(t,e);if(t.method==="POST"&&n.pathname==="/update")return cn(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function $n(t){let e="";const n=[];let r=!1,o=!1;const a=()=>{o&&!r&&!n.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;n.length;){const d=n.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
9
+ `)}async function G(t,e,n,r){try{const o=n(await f(t)),a=F(t,o.agent,o.options||{});if(a.error)throw new P(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${o.message}`):o)),null}}async function mn(t,e){const n=await G(t,e,Rt,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,Pt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=Ot(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function fn(t,e){const n=await G(t,e,_t,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,$t(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=xt(n.requestedModel,o=>x(e,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function gn(t,e){const n=await G(t,e,Ht,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,It(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}M(e);const r=Mt(n.requestedModel,o=>B(e,o.type,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...b(o)};B(e,"error",a)}e.end()}async function wn(t,e){const n=await G(t,e,Nt,j);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return i(e,200,At(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,j(o))}M(e);const r=Et(n.requestedModel,(o,a)=>B(e,o,a));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){B(e,"error",j(o))}e.end()}async function yn(t,e){let n={};try{n=await f(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?kt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function pe(t,e,n){let r;try{r=await f(t)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?Y(n):Xe(),a=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:w}});const d=je();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await Je(r.params?.name,r.params?.arguments||{});if(c)return a(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await ze(o,r.params?.name,r.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function bn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=n.server||{},o=n.message;if(!r.command||!o)return i(e,400,{error:"need server.command and message"});try{const a=await wt({key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox},o);return o.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Sn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=n.server||{};if(!r.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return i(e,200,n.status?St(o):await bt(o))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function kn(t,e){let n;try{n=await f(t)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:r,headers:o,message:a}=n||{};if(!r||!a)return i(e,400,{error:"need url and message"});let s;try{s=re(r)}catch(h){return i(e,400,{error:String(h?.message||h)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[h,g]of Object.entries(o)){const m=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(d[h]=String(g))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{h.url&&re(h.url)}catch(m){return i(e,400,{error:String(m?.message||m)})}const g=await h.text().catch(()=>"");return i(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:g})}catch(h){const g=h?.name==="AbortError"?"timed out":String(h?.message||h);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${g}`})}finally{clearTimeout(l)}}const me=256*1024,Tn=5,vn=8e3;async function Cn(t){let e=ae(t);const n=new AbortController,r=setTimeout(()=>n.abort(),vn);try{for(let o=0;o<=Tn;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:n.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${w} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ae(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:xn(await En(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function En(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,me);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(o+=s.byteLength,r+=n.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=me))break}}finally{try{await e.cancel()}catch{}}return r}function On(t){return String(t).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,n)=>{try{return String.fromCodePoint(+n)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,n)=>{try{return String.fromCodePoint(parseInt(n,16))}catch{return""}})}function xn(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?On(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function An(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=n&&n.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await Cn(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Pn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=Y(n.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(n.id);return o?(r.pending.delete(n.id),o.resolve(n.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function $n(t,e){let n;try{n=await f(t)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const r=C[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});const o=String(n.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=n.model||"",s=F(t,n.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=String(n.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function In(t,e){let n;try{n=await f(t)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=C[n.agent];if(!r)return i(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(n.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Nn(t,e){let n;try{n=await f(t)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(n.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=mt(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}const fe=we(async(t,e)=>{if(Ft(t,e),t.method==="OPTIONS")return e.writeHead(204),e.end();let n;try{n=new URL(t.url,`http://${t.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=en(t,n.pathname);if(r)return i(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return on(e);const o=n.searchParams.getAll("dir"),a=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return rn(e,o,a);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return an(e,o,a);if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?sn(e,decodeURIComponent(s),o,a):cn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,a)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return hn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return pn(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return he(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return he(e,decodeURIComponent(n.pathname.slice(11)));if(t.method==="GET"&&n.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:w,agents:Object.fromEntries(ut.map(d=>[d,s?ne(d)||null:!!ne(d)])),...s?{home:A.homedir(),path:process.env.PATH}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return un(t,e);if(t.method==="POST"&&n.pathname==="/pair")return Vt(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return Kt(e);if(t.method==="POST"&&n.pathname==="/whoami")return Yt(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return mn(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return fn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return gn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return wn(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return pe(t,e,null);if(t.method==="GET")return e.writeHead(405),e.end()}if(n.pathname.startsWith("/mcp/")){const s=decodeURIComponent(n.pathname.slice(5));if(t.method==="POST")return pe(t,e,s);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return V(s),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return de(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return de(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return yn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return Pn(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await f(t)}catch{s=null}const d=qe(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return bn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local/signin")return Sn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return kn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return An(t,e);if(t.method==="POST"&&n.pathname==="/complete")return $n(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return In(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return Nn(t,e);if(t.method==="POST"&&n.pathname==="/update")return dn(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Rn(t){let e="";const n=[];let r=!1,o=!1;const a=()=>{o&&!r&&!n.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;n.length;){const d=n.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
10
10
  `)}catch(l){c.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32e3,message:String(l?.message||l)}})+`
11
11
  `)}}r=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",d=>{e+=d;let c;for(;(c=e.indexOf(`
12
- `))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&n.push(l)}s()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function In(){ht(),pt(),Jt(),fe.on("error",t=>{t&&t.code==="EADDRINUSE"&&(u("error",`Port ${C} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings."),process.exit(1)),u("error",`bridge server error: ${t?.message||t}`),process.exit(1)});for(const t of["SIGINT","SIGTERM"])process.on(t,()=>{const e=St("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=kt("shutdown");n&&u("info",`shutdown: closed ${n} warm agent process${n===1?"":"es"}`),Q().close(),setTimeout(()=>process.exit(0),e||n?300:0).unref?.(),!e&&!n&&process.exit(0)});fe.listen(C,k,async()=>{u("info",`listening on http://${k}:${C}`),F.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:t,label:e,hidden:n}]of Object.entries(v)){if(n)continue;const r=await t.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),le().then(t=>t.startIfConfigured()).then(t=>{t?.skipped||(t?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${t?.error||"unknown error"}`))}).catch(t=>u("error",`channels: ${t?.message||t}`))})}function Nn(){console.log(`ChatPanel Bridge v${w}
12
+ `))>=0;){const l=e.slice(0,c).trim();e=e.slice(c+1),l&&n.push(l)}s()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function _n(){ht(),pt(),zt(),fe.on("error",t=>{t&&t.code==="EADDRINUSE"&&(u("error",`Port ${v} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings."),process.exit(1)),u("error",`bridge server error: ${t?.message||t}`),process.exit(1)});for(const t of["SIGINT","SIGTERM"])process.on(t,()=>{const e=Tt("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=vt("shutdown");n&&u("info",`shutdown: closed ${n} warm agent process${n===1?"":"es"}`),Q().close(),setTimeout(()=>process.exit(0),e||n?300:0).unref?.(),!e&&!n&&process.exit(0)});fe.listen(v,k,async()=>{u("info",`listening on http://${k}:${v}`),J.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:t,label:e,hidden:n}]of Object.entries(C)){if(n)continue;const r=await t.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),le().then(t=>t.startIfConfigured()).then(t=>{t?.skipped||(t?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${t?.error||"unknown error"}`))}).catch(t=>u("error",`channels: ${t?.message||t}`))})}function Hn(){console.log(`ChatPanel Bridge v${w}
13
13
 
14
14
  Usage:
15
- chatpanel-bridge start the bridge (foreground) on ${k}:${C}
15
+ chatpanel-bridge start the bridge (foreground) on ${k}:${v}
16
16
  chatpanel-bridge --install run automatically at login, in the background
17
17
  chatpanel-bridge --uninstall remove the login auto-start
18
18
  chatpanel-bridge --status show whether auto-start is set up
@@ -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 Rn(){const t=process.argv,e=(...n)=>n.some(r=>t.includes(r));if(e("--help","-h"))return Nn(),!0;if(e("--version","-v"))return console.log(w),!0;if(e("pair","--pair"))return(async()=>{let n="";try{n=z(N,"utf8").trim()}catch{}const r=`http://${k}:${C}`;try{if(!n)throw new Error(`no token at ${N} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${Ut(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(t.includes("sandbox"))return Ze(t.slice(t.indexOf("sandbox")+1)).then(n=>{process.exitCode=n}),!0;if(e("--install")){try{He(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(n){u("error","Install failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--uninstall")){try{Me(),u("info","Removed the login auto-start.")}catch(n){u("error","Uninstall failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--status")){let n=!1;try{n=Be()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const ge=process.argv.indexOf("--mcp-stdio");if(ge>=0){const t=process.argv[ge+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),$n(t)}else process.argv.includes("--update")?(async()=>{try{const t=await oe(w);u("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),K()}catch(t){u("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():Rn()||In();
24
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function Mn(){const t=process.argv,e=(...n)=>n.some(r=>t.includes(r));if(e("--help","-h"))return Hn(),!0;if(e("--version","-v"))return console.log(w),!0;if(e("pair","--pair"))return(async()=>{let n="";try{n=z(N,"utf8").trim()}catch{}const r=`http://${k}:${v}`;try{if(!n)throw new Error(`no token at ${N} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${Lt(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(t.includes("sandbox"))return Ze(t.slice(t.indexOf("sandbox")+1)).then(n=>{process.exitCode=n}),!0;if(e("--install")){try{He(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(n){u("error","Install failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--uninstall")){try{Me(),u("info","Removed the login auto-start.")}catch(n){u("error","Uninstall failed: "+(n?.message||n)),process.exitCode=1}return!0}if(e("--status")){let n=!1;try{n=Be()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const ge=process.argv.indexOf("--mcp-stdio");if(ge>=0){const t=process.argv[ge+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Rn(t)}else process.argv.includes("--update")?(async()=>{try{const t=await oe(w);u("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),K()}catch(t){u("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():Mn()||_n();