@chatpanel/bridge 0.24.1 → 0.29.4

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.
@@ -1 +1 @@
1
- import{EventError as b}from"./event.js";import{normalizeGrant as A}from"./sandbox-grant.js";const y=Object.freeze(["none","process","container","kubernetes"]),E=Object.freeze(["open","allowlist","none","gateway"]),h=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),x=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),_=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]}),"model-server":Object.freeze({hosts:["huggingface.co","*.huggingface.co","*.hf.co","cdn-lfs.huggingface.co","cas-bridge.xethub.hf.co","dl.chatpanel.net"],write:[]})}),R=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),p=e=>!!e&&typeof e=="object"&&!Array.isArray(e),g=e=>Array.isArray(e)&&e.every(o=>typeof o=="string"&&o.length>0),l=(e,o)=>{if(!e)throw new b("SHAPE",o)},f=e=>[...new Set(e)];function O(e){l(p(e),"kit: must be an object"),l(typeof e.id=="string"&&e.id.length>0,"kit: id required"),l(p(e.network)&&E.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${E.join(", ")}`),l(g(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),l(g(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),l(p(e.filesystem),`kit ${e.id}: filesystem required`);for(const o of["allowWrite","denyWrite","allowRead","denyRead"])l(g(e.filesystem[o]||[]),`kit ${e.id}: filesystem.${o} must be string[]`);return l(g(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&l(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&l(Array.isArray(e.credentials)&&e.credentials.every(o=>p(o)&&typeof o.name=="string"&&typeof o.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:f(e.network.allowedDomains||[]),deniedDomains:f(e.network.deniedDomains||[])},filesystem:{allowWrite:f(e.filesystem.allowWrite),denyWrite:f(e.filesystem.denyWrite||[]),allowRead:f(e.filesystem.allowRead||[]),denyRead:f(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:p(e.limits)?{...e.limits}:{}}}import{normalizeGrant as M,mergeGrants as k,parseHostList as q}from"./sandbox-grant.js";function z({engine:e="custom",cwd:o,mode:t="open",extraHosts:r=[],extraWrite:n=[],extraDenyRead:s=[],grant:c=null}={}){const d=_[e]||_.custom;l(typeof o=="string"&&o.length>0,"kit: cwd required");const a=A(c);return O({id:`${e}:${t}`,kind:"process",network:{mode:t,allowedDomains:t==="open"?["*"]:t==="none"?[]:f([...d.hosts,...R,...r,...a.hosts]),deniedDomains:[]},filesystem:{allowWrite:f([o,...x,...d.write,...n,...a.write.filter(i=>!h.some(u=>i===u||i.startsWith(`${u}/`)))]),denyWrite:[],allowRead:[o],denyRead:f([...h,...s])}})}function N(e,{loopback:o=[],home:t="",platform:r="darwin"}={}){const n=O(e),s=d=>t&&d.startsWith("~")?t+d.slice(1):d,c=n.network.mode==="none"?[]:o.map(d=>`127.0.0.1:${d}`);return{network:{allowedDomains:f([...n.network.allowedDomains,...c]),deniedDomains:n.network.deniedDomains,allowLocalBinding:r==="darwin"&&c.length>0},filesystem:{denyRead:n.filesystem.denyRead.map(s),allowRead:n.filesystem.allowRead.map(s),allowWrite:n.filesystem.allowWrite.map(s),denyWrite:n.filesystem.denyWrite.map(s)}}}function C({layer:e="none",runtime:o=null,kitId:t=null,mode:r=null,reason:n=null,hosts:s=null}={}){return l(y.includes(e),`sandbox record: layer must be one of ${y.join(", ")}`),{layer:e,runtime:o,kit:t,mode:r,...e==="none"&&n?{reason:n}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function S(e,{platform:o="darwin"}={}){const t=String(e);if(o==="win32"){l(!/[\r\n]/.test(t),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=t;if(t===""||/[ \t\v"]/.test(t)){r='"';for(let n=0;n<t.length;n++){let s=0;for(;n<t.length&&t[n]==="\\";)s++,n++;if(n===t.length){r+="\\".repeat(s*2);break}t[n]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+t[n]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return t===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}const I=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function H(e={},{platform:o="darwin",caBundle:t=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(t)for(const n of I)e[n]||(r[n]=t);if(o==="linux")for(const n of["no_proxy","NO_PROXY"])typeof e[n]=="string"&&(r[n]=e[n].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function L(e,o=[],{platform:t="darwin"}={}){return[e,...o].map(r=>S(r,{platform:t})).join(" ")}const T=/[\\/]+/,m=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),D=e=>/^[a-z]:$/i.test(m(e))||m(e)==="";function w(e,o){const t=m(e),r=m(o);return!!r&&t!==r&&t.startsWith(r+"\\")}function j(e){const o=String(e||"").replace(/\//g,"\\").split("\\");if(o.length<2)return"";const t=o.findIndex(r=>r.toLowerCase()==="node_modules");return(t>0?o.slice(0,t):o.slice(0,-1)).join("\\")}function K({kit:e,files:o=[],home:t}){l(typeof t=="string"&&t.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?t+a.slice(1):a).replace(/\//g,"\\"),n=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(l(!D(i)&&m(i)!==m(t),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),w(i,t)&&n.push(i))}const s=(a,i)=>i.some(u=>m(a)===m(u)||w(a,u)),c=[];for(const a of o){const i=j(a);i&&w(i,t)&&c.push(i)}for(const a of e?.filesystem?.allowRead||[]){const i=r(a);w(i,t)&&c.push(i)}const d=f(c).filter(a=>!s(a,n));return{read:d.filter(a=>!d.some(i=>i!==a&&w(a,i))),write:f(n)}}const W=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function v({engine:e="custom",home:o,env:t={},base:r={},carry:n=W}={}){l(typeof o=="string"&&o.length>0,"windows env: home required");const s=o.replace(/\//g,"\\"),c=/^[a-z]:/i.test(s)?s.slice(0,2):"",d={USERPROFILE:s,...c?{HOMEDRIVE:c,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(t))typeof i=="string"&&(r[a]!==i||n.includes(a))&&(d[a]=i);return e==="codex"&&!d.CODEX_HOME&&(d.CODEX_HOME=s+"\\.codex"),d}function Y(e,o){l(Array.isArray(e),"srt-win argv: must be an array");const t=e.indexOf("exec"),r=t>=0?e.indexOf("--",t+1):-1;l(t>=0&&r>t,"srt-win argv: expected `exec … -- <shell> <command>`");const n=new Set;for(let c=t+1;c<r;c++)e[c]==="--env"&&typeof e[c+1]=="string"&&n.add(e[c+1].split("=")[0].toUpperCase());const s=[];for(const[c,d]of Object.entries(o||{}))l(/^[A-Za-z_][A-Za-z0-9_]*$/.test(c),`srt-win env: bad key ${c}`),l(!/[\r\n]/.test(d),`srt-win env: ${c} holds a newline`),n.has(c.toUpperCase())||s.push("--env",`${c}=${d}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{x as COMMON_WRITE,R as DEVELOPER_HOSTS,_ as ENGINE_KITS,E as NETWORK_MODES,y as SANDBOX_LAYERS,h as SECRET_PATHS,W as WINDOWS_CARRY_KEYS,z as kitFor,k as mergeGrants,M as normalizeGrant,q as parseHostList,H as sandboxEnvOverlay,C as sandboxRecord,L as shellJoin,S as shellQuote,N as toSrtSettings,w as underWindowsHome,O as validateKit,K as windowsGrantsFor,j as windowsInstallRoot,v as windowsSandboxEnv,Y as withSrtWinEnv};
1
+ import{EventError as D}from"./event.js";import{normalizeGrant as O}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as $,SECRET_DIR_PAIRS as j}from"./secret-names.js";const b=Object.freeze(["none","process","container","kubernetes"]),A=Object.freeze(["open","allowlist","none","gateway"]),_=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),g=e=>{let t=String(e||"").trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"));)t=t.slice(0,-1);return t},R=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,y=e=>String(e||"").replace(/\\/g,"/"),x=(e,t)=>{const n=y(g(e)),r=y(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},C=_.map(e=>y(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function S(e,t=""){const n=y(g(R(g(e),t)));if(!n)return!1;for(const o of _)if(x(n,o)||t&&x(n,R(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return C.some(o=>{for(let i=0;i+o.length<=r.length;i+=1)if(o.every((c,l)=>c.toLowerCase()===r[i+l]))return!0;return!1})}const P=Object.freeze([...[...$].map(e=>`~/**/${e}`),...j.map(([e,t])=>`~/**/${e}/${t}`),...[".env",".netrc","_netrc",".git-credentials",".pgpass",".my.cnf",".npmrc",".pypirc",".htpasswd",".terraformrc",".vault-token","credentials","credentials.toml","id_rsa","id_dsa","id_ecdsa","id_ed25519","*.pem","*.p12","*.pfx","*.jks","*.keystore","*.kdbx","*.ppk"].map(e=>`~/**/${e}`)]),v=Object.freeze(["~/.npm","~/.cache","~/.local","~/Library/Caches","~/.nvm","~/.volta","~/.asdf","~/.nodenv","~/.bun","~/.deno","~/.pyenv","~/.rye","~/.pdm","~/.cargo","~/.rustup","~/go","~/.goenv","~/.m2","~/.gradle","~/.sdkman","~/.jenv","~/.gem","~/.rbenv","~/.bundle","~/.composer","~/.nuget","~/.dotnet","~/.stack","~/.ghcup","~/.opam","~/.pub-cache","~/.gitconfig","~/.config/git"]),z=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),I=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]}),"model-server":Object.freeze({hosts:["huggingface.co","*.huggingface.co","*.hf.co","cdn-lfs.huggingface.co","cas-bridge.xethub.hf.co","dl.chatpanel.net"],write:[]})}),N=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"]),w=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),f=(e,t)=>{if(!e)throw new D("SHAPE",t)},p=e=>[...new Set(e)];function W(e){f(w(e),"kit: must be an object"),f(typeof e.id=="string"&&e.id.length>0,"kit: id required"),f(w(e.network)&&A.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${A.join(", ")}`),f(E(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),f(E(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),f(w(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])f(E(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return f(E(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&f(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&f(Array.isArray(e.credentials)&&e.credentials.every(t=>w(t)&&typeof t.name=="string"&&typeof t.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:p(e.network.allowedDomains||[]),deniedDomains:p(e.network.deniedDomains||[])},filesystem:{allowWrite:p(e.filesystem.allowWrite),denyWrite:p(e.filesystem.denyWrite||[]),allowRead:p(e.filesystem.allowRead||[]),denyRead:p(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:w(e.limits)?{...e.limits}:{}}}import{normalizeGrant as oe,mergeGrants as re,parseHostList as se}from"./sandbox-grant.js";function B({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:i=[],grant:c=null,home:l="",reads:a="enumerated"}={}){const s=I[e]||I.custom;f(typeof t=="string"&&t.length>0,"kit: cwd required");const d=O(c);return W({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:p([...s.hosts,...N,...r,...d.hosts]),deniedDomains:[]},filesystem:{allowWrite:p([t,...z,...s.write,...[...o,...d.write].filter(u=>!S(u,l))]),denyWrite:[],allowRead:a==="inverted"?p([t,...v,...s.write,...L({grant:d,extraWrite:o,cwd:t,home:l})]):[t],denyRead:p([...a==="inverted"?["~",...l?[l]:[]]:[],..._,...P,...i])}})}function L({grant:e=null,extraWrite:t=[],cwd:n="",home:r=""}={}){const o=s=>r&&(s==="~"||s.startsWith("~/")||s.startsWith("~\\"))?r+s.slice(1):s,i=s=>{let d=String(s||"").trim();for(;d.length>1&&(d.endsWith("/")||d.endsWith("\\"));)d=d.slice(0,-1);return d},c=(s,d)=>s===d||s.startsWith(`${d}/`)||s.startsWith(`${d}\\`),l=i(o(n)),a=[];for(const s of[...O(e).write,...Array.isArray(t)?t:[]]){const d=i(o(i(s)));if(d&&!S(d,r)&&!(l&&c(d,l))&&!a.some(u=>c(d,u))){for(let u=a.length-1;u>=0;u--)c(a[u],d)&&a.splice(u,1);a.push(d)}}return a}function q(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=W(e),i=l=>n&&l.startsWith("~")?n+l.slice(1):l,c=o.network.mode==="none"?[]:t.map(l=>`127.0.0.1:${l}`);return{network:{allowedDomains:p([...o.network.allowedDomains,...c]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&c.length>0},filesystem:{denyRead:o.filesystem.denyRead.map(i),allowRead:o.filesystem.allowRead.map(i),allowWrite:o.filesystem.allowWrite.map(i),denyWrite:o.filesystem.denyWrite.map(i)}}}function X({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:i=null}={}){return f(b.includes(e),`sandbox record: layer must be one of ${b.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(i)&&i.length?{hosts:p(i)}:{}}}function T(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){f(!/[\r\n]/.test(n),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=n;if(n===""||/[ \t\v"]/.test(n)){r='"';for(let o=0;o<n.length;o++){let i=0;for(;o<n.length&&n[o]==="\\";)i++,o++;if(o===n.length){r+="\\".repeat(i*2);break}n[o]==='"'?r+="\\".repeat(i*2+1)+'"':r+="\\".repeat(i)+n[o]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return n===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}const H=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function F(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of H)e[o]||(r[o]=n);if(t==="linux")for(const o of["no_proxy","NO_PROXY"])typeof e[o]=="string"&&(r[o]=e[o].split(",").map(i=>i.trim()).filter(i=>i&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(i)).join(","));return r}function V(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>T(r,{platform:n})).join(" ")}const Q=/[\\/]+/,m=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),k=e=>/^[a-z]:$/i.test(m(e))||m(e)==="";function h(e,t){const n=m(e),r=m(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function K(e){const t=String(e||"").replace(/\//g,"\\").split("\\");if(t.length<2)return"";const n=t.findIndex(r=>r.toLowerCase()==="node_modules");return(n>0?t.slice(0,n):t.slice(0,-1)).join("\\")}function Z({kit:e,files:t=[],home:n}){f(typeof n=="string"&&n.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?n+a.slice(1):a).replace(/\//g,"\\"),o=[];for(const a of e?.filesystem?.allowWrite||[]){const s=r(a);!/^[a-z]:\\/i.test(s)&&!s.startsWith("\\\\")||(f(!k(s)&&m(s)!==m(n),`windows grants: a write on ${s} would hand the sandbox account the whole profile`),h(s,n)&&o.push(s))}const i=(a,s)=>s.some(d=>m(a)===m(d)||h(a,d)),c=[];for(const a of t){const s=K(a);s&&h(s,n)&&c.push(s)}for(const a of e?.filesystem?.allowRead||[]){const s=r(a);h(s,n)&&c.push(s)}const l=p(c).filter(a=>!i(a,o));return{read:l.filter(a=>!l.some(s=>s!==a&&h(a,s))),write:p(o)}}const Y=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 J({engine:e="custom",home:t,env:n={},base:r={},carry:o=Y}={}){f(typeof t=="string"&&t.length>0,"windows env: home required");const i=t.replace(/\//g,"\\"),c=/^[a-z]:/i.test(i)?i.slice(0,2):"",l={USERPROFILE:i,...c?{HOMEDRIVE:c,HOMEPATH:i.slice(2)}:{}};for(const[a,s]of Object.entries(n))typeof s=="string"&&(r[a]!==s||o.includes(a))&&(l[a]=s);return e==="codex"&&!l.CODEX_HOME&&(l.CODEX_HOME=i+"\\.codex"),l}function ee(e,t){f(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;f(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let c=n+1;c<r;c++)e[c]==="--env"&&typeof e[c+1]=="string"&&o.add(e[c+1].split("=")[0].toUpperCase());const i=[];for(const[c,l]of Object.entries(t||{}))f(/^[A-Za-z_][A-Za-z0-9_]*$/.test(c),`srt-win env: bad key ${c}`),f(!/[\r\n]/.test(l),`srt-win env: ${c} holds a newline`),o.has(c.toUpperCase())||i.push("--env",`${c}=${l}`);return[...e.slice(0,r),...i,...e.slice(r)]}export{z as COMMON_WRITE,N as DEVELOPER_HOSTS,I as ENGINE_KITS,A as NETWORK_MODES,b as SANDBOX_LAYERS,_ as SECRET_PATHS,P as SECRET_READ_GLOBS,v as TOOLCHAIN_READ,Y as WINDOWS_CARRY_KEYS,S as isSecretWritePath,B as kitFor,re as mergeGrants,oe as normalizeGrant,se as parseHostList,F as sandboxEnvOverlay,X as sandboxRecord,V as shellJoin,T as shellQuote,q as toSrtSettings,h as underWindowsHome,W as validateKit,Z as windowsGrantsFor,K as windowsInstallRoot,J as windowsSandboxEnv,ee as withSrtWinEnv,L as writableRoots};
@@ -0,0 +1 @@
1
+ const e=new Set([".ssh",".aws",".gnupg",".gpg",".kube",".azure",".gcloud",".docker",".chatpanel",".password-store",".1password",".op","Keychains",".vault-token",".oci",".bluemix",".ibmcloud",".doctl",".linode",".scaleway",".hcloud",".civo",".terraform.d",".pulumi",".wrangler",".netlify",".vercel",".supabase",".heroku",".databricks",".snowflake",".kaggle",".circleci",".okta",".aliyun",".tencentcloud"]),s=[[".config","gh"],[".config","gcloud"],[".config","hub"],["Library","Keychains"],["Library","Cookies"],[".config","doctl"],[".config","fly"],[".config","openstack"],[".config","containers"],[".m2","settings.xml"],[".gradle","gradle.properties"],[".cargo","credentials.toml"],[".cargo","credentials"],[".gem","credentials"],[".composer","auth.json"],[".cache","huggingface"],[".ansible","vault_pass"],[".aws","sso"]],a=[/^\.env(\..+)?$/i,/^id_(rsa|dsa|ecdsa|ed25519)$/,/\.(pem|key|p12|pfx|jks|keystore|kdbx|ppk|gpg|pgp|asc|keychain|keychain-db)$/i,/^(credentials(\.json)?|\.netrc|_netrc|\.npmrc|\.pypirc|\.git-credentials|\.htpasswd|\.pgpass|\.my\.cnf|token\.json|\.vault-token)$/i,/^secrets?(\.(json|ya?ml|toml|env|txt))?$/i,/\.tfstate(\.backup)?$/i,/\.tfvars$/i,/^service[-_]?account.*\.json$/i,/^\.(bash|zsh|sh|python|node_repl|mysql|psql|irb|lesshst)_?history$/],o=/^\.env\.(example|sample|template|dist)$/i;export{e as SECRET_DIR_NAMES,s as SECRET_DIR_PAIRS,o as SECRET_FILE_ALLOW,a as SECRET_FILE_RES};
@@ -0,0 +1,3 @@
1
+ import{parseFrontmatter as y,renderFrontmatter as L}from"./frontmatter.js";import{isSafeSkillPath as $,normalizeSkill as w,SKILL_FILE_KINDS as u,SkillManifestError as c}from"./skill-manifest.js";const m="SKILL.md",S=/^[a-z0-9][a-z0-9_-]*$/,I=512*1024,b=200,x=Object.freeze(["name","description","version","platforms","command","icon"]);function P(t){const{meta:e,body:n}=y(t);return{meta:e,body:n.trim()}}function A({meta:t={},body:e="",dirName:n="",relPath:a="",source:o="",files:f=[],hash:s=""}={}){const r=i(t.name)||n,l=S.test(String(r))?String(r):n,g={};for(const p of u){const d=f.filter(k=>k.startsWith(`${p}/`)).map(k=>k.slice(p.length+1));d.length&&(g[p]=d)}const h={};for(const[p,d]of Object.entries(t))x.includes(p)||(h[p]=d);return w({id:l,name:String(r),command:S.test(l)?l:"",description:i(t.description),prompt:String(e||"").trim(),...i(t.version)?{version:i(t.version)}:{},...i(t.icon)?{icon:i(t.icon)}:{},...Array.isArray(t.platforms)?{platforms:t.platforms.map(i).filter(Boolean)}:{},...Object.keys(g).length?{files:g}:{},...Object.keys(h).length?{packageMeta:h}:{},...o?{origin:{source:o,id:a||l,...s?{hash:s}:{}}}:{}})}function M(t){const e=t||{},n={name:i(e.id)||i(e.name)||"skill",description:i(e.description)||i(e.name)};i(e.version)&&(n.version=i(e.version)),i(e.icon)&&(n.icon=i(e.icon)),Array.isArray(e.platforms)&&e.platforms.length&&(n.platforms=[...e.platforms]);for(const[a,o]of Object.entries(e.packageMeta||{}))n[a]===void 0&&(n[a]=o);return L(n,`
2
+ ${String(e.prompt||"").trim()}
3
+ `)}function F(t,{files:e=[]}={}){const n=w(t||{});if(!i(n.id))throw new c("ID","a skill package needs an id — it is the directory name");if(!S.test(String(n.id)))throw new c("ID",`"${n.id}" cannot be a directory name (letters, digits, _ and - only)`);if(!i(n.prompt))throw new c("PROMPT",`${n.id}: a skill package with no instructions is an empty folder`);const a=M(n);if(a.length>I)throw new c("SIZE",`${n.id}: SKILL.md is ${a.length} bytes — a procedure document, not a corpus`);const o=[{path:m,text:a,kind:"skill"}],f=new Set([m.toLowerCase()]);for(const s of e){const r=String(s?.path||"").trim();if(!r)continue;if(!$(r))throw new c("PATH",`${n.id}: "${r}" is not a safe path inside a package`);const l=r.split("/")[0];if(!u.includes(l))throw new c("PATH",`${n.id}: "${r}" is not in one of ${u.join(", ")}`);if(f.has(r.toLowerCase()))throw new c("PATH",`${n.id}: "${r}" is written twice`);f.add(r.toLowerCase()),o.push({path:r,text:String(s.text??""),kind:l})}if(o.length>b)throw new c("SIZE",`${n.id}: ${o.length} files is not a skill, it is a repository`);return o}function K(t,{dirName:e="",source:n="local"}={}){const a=t.find(s=>s.path===m),{meta:o,body:f}=P(a?.text||"");return A({meta:o,body:f,dirName:e||i(o.name),relPath:e||i(o.name),source:n,files:t.filter(s=>s.path!==m).map(s=>s.path)})}function i(t){return t==null?"":typeof t=="string"?t.trim():typeof t=="number"||typeof t=="boolean"?String(t):""}export{m as SKILL_FILE,P as parseSkillMd,M as renderSkillMd,A as skillFromPackage,K as skillFromPlan,F as skillPackagePlan};
@@ -0,0 +1 @@
1
+ import{validateBudget as y,normalizeBudget as x}from"./budget.js";import{normalizeEngineSpec as O,validateEngineSpec as j,tierOf as $}from"./engine.js";const k=/^[a-z][a-z0-9_-]{0,63}$/i,E=/^[a-z][a-z0-9_-]{0,31}$/i,c=Object.freeze(["model","subagent","recipe"]),l=Object.freeze(["cheap","balanced","strong"]),p=Object.freeze(["judge","converge","concat","first"]),g=Object.freeze(["fixed","planner"]),N=Object.freeze(["none","data","web","mcp","history","shell","fs:write","scm:read","scm:push","scm:pr","scm:merge"]),M=Object.freeze(["shell","fs:write","scm:read","scm:push","scm:pr","scm:merge"]),f=/^(none|data|web|history|mcp|mcp:[a-zA-Z0-9_.:-]{1,64}|shell|fs:write|scm:(read|push|pr|merge))$/,h=8,R=/^[a-z][a-z0-9_-]{0,63}$/i;class T extends Error{constructor(t,i){super(i),this.name="TeamError",this.code=t}}const u=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function m(e){const t=(Array.isArray(e)?e:typeof e=="string"?[e]:[]).map(n=>String(n||"").trim()).filter(Boolean),i=[...new Set(t.filter(n=>f.test(n)))];return!i.length||i.includes("none")?["none"]:i}function b(e){const t=[];if(!u(e))return{ok:!1,errors:["team must be an object"]};if(k.test(String(e.name||""))||t.push("name: a short identifier (letters, digits, _ -)"),!Array.isArray(e.roles)||!e.roles.length)t.push("roles: a non-empty array");else{e.roles.length>h&&t.push(`roles: at most ${h}`);const n=new Set;e.roles.forEach((s,o)=>{const r=`roles[${o}]`;if(!u(s)){t.push(`${r}: must be an object`);return}E.test(String(s.id||""))?n.has(s.id)&&t.push(`${r}.id: duplicate "${s.id}"`):t.push(`${r}.id: a short identifier`),n.add(s.id),s.mode!==void 0&&!c.includes(s.mode)&&t.push(`${r}.mode: one of ${c.join(", ")}`),s.prefer!==void 0&&!l.includes(s.prefer)&&t.push(`${r}.prefer: one of ${l.join(", ")}`),(s.mode||"model")==="recipe"&&!s.recipe&&t.push(`${r}.recipe: a recipe name is required in recipe mode`),s.agent!==void 0&&s.agent!==null&&!R.test(String(s.agent))&&t.push(`${r}.agent: an agent id`),(s.mode||"model")!=="recipe"&&!s.agent&&!String(s.prompt||"").trim()&&t.push(`${r}.prompt: what this role does`),t.push(...j(s.engine,`${r}.engine`));const a=(Array.isArray(s.grants)?s.grants:[]).filter(d=>!f.test(String(d)));a.length&&t.push(`${r}.grants: not grantable: ${a.join(", ")}${a.some(d=>/^page/.test(String(d)))?" (a tab is one person's; a team may not act on it)":""}`)})}e.merge!==void 0&&!p.includes(e.merge)&&t.push(`merge: one of ${p.join(", ")}`),e.plan!==void 0&&!g.includes(e.plan)&&t.push(`plan: one of ${g.join(", ")}`),e.judge!==void 0&&e.judge!==null&&!(Array.isArray(e.roles)&&e.roles.some(n=>n?.id===e.judge))&&t.push("judge: must name one of the roles");const i=y(e.budget);return i.ok||t.push(...i.errors.map(n=>`budget: ${n}`)),{ok:t.length===0,errors:t}}function S(e,{builtin:t=!1}={}){const i=b(e);if(!i.ok)throw new T("INVALID",i.errors.join("; "));return{name:String(e.name),description:String(e.description||"").trim().slice(0,300),plan:g.includes(e.plan)?e.plan:"fixed",merge:p.includes(e.merge)?e.merge:e.judge?"judge":"concat",judge:e.judge||null,roles:e.roles.map(n=>({id:String(n.id),name:String(n.name||n.id).slice(0,60),mode:c.includes(n.mode)?n.mode:"model",prefer:l.includes(n.prefer)?n.prefer:n.engine?$(n.engine):"balanced",...n.model?{model:String(n.model)}:{},...n.agent?{agent:String(n.agent)}:{},...n.engine?{engine:O(n.engine)}:{},prompt:String(n.prompt||"").trim().slice(0,4e3),...n.agent&&!(Array.isArray(n.grants)&&n.grants.length)?{}:{grants:m(n.grants)},...n.recipe?{recipe:String(n.recipe)}:{},...Array.isArray(n.dependsOn)?{dependsOn:n.dependsOn.map(String).filter(s=>s!==n.id)}:{},...Array.isArray(n.skills)&&n.skills.length?{skills:n.skills.map(String).slice(0,32)}:{},...n.workdir?{workdir:String(n.workdir).slice(0,400)}:{},...n.egress==="redacted"||n.egress==="delegated"?{egress:n.egress}:{},...n.memoryScope?{memoryScope:String(n.memoryScope).slice(0,120)}:{}})),budget:x(e.budget),enabled:e.enabled!==!1,...e.origin&&u(e.origin)?{origin:{...e.origin}}:{},...t?{builtin:!0}:{},...e.createdAt?{createdAt:e.createdAt}:{}}}function D(e){return Object.freeze(S(e))}function G(e,t,i=""){const n=m(e);return n.includes("none")||t==="page"?!1:t==="mcp"?n.includes("mcp")||!!i&&n.includes(`mcp:${i}`):n.includes(t)}const w=["read","push","pr","merge"];function B(e,t){const i=m(e),n=w.indexOf(String(t||"").replace(/^scm:/,""));return n<0||i.includes("none")?!1:Math.max(-1,...i.filter(o=>o.startsWith("scm:")).map(o=>w.indexOf(o.slice(4))))>=n}function F(e){const t=e.model||e.prefer||"balanced",i=(e.grants||["none"]).join(", ");return`${e.name||e.id}${e.agent?` (agent: ${e.agent})`:""} — ${t}${e.mode&&e.mode!=="model"?` (${e.mode})`:""} · tools: ${i}`}const z=Object.freeze([{name:"research",description:"Research a question from the web and your own notes, then write it up.",plan:"fixed",merge:"judge",judge:"writer",roles:[{id:"researcher",prompt:"Research the request thoroughly. Search the web and the user's own history. Report each fact as a finding with where it came from; note disagreements between sources.",prefer:"balanced",grants:["web","data"]},{id:"writer",prompt:"Write the answer the user asked for from the board's findings, citing them. Say plainly what was not found.",prefer:"strong",grants:["none"]}],budget:{tokens:4e4,ms:3e5}},{name:"review",description:"Two independent reads of a draft, reconciled into one set of comments.",plan:"fixed",merge:"converge",roles:[{id:"editor",prompt:"Read the draft as an editor: structure, clarity, what is missing. One finding per issue, with the passage it refers to.",prefer:"strong",grants:["none"]},{id:"checker",prompt:"Read the draft as a fact-checker: every claim that could be wrong, with what you checked against. Use the user's history and the web.",prefer:"balanced",grants:["data","web"]}],budget:{tokens:3e4,ms:24e4}},{name:"feature",description:"Architect plans, an Implementer builds on a branch, Reviewer and Tester check, Scribe writes it up. The Architect judges.",plan:"planner",merge:"judge",judge:"architect",roles:[{id:"architect",agent:"architect"},{id:"implementer",agent:"implementer",dependsOn:["architect"]},{id:"reviewer",agent:"reviewer",dependsOn:["implementer"]},{id:"tester",agent:"tester",dependsOn:["implementer"]},{id:"scribe",agent:"scribe",dependsOn:["reviewer","tester"]}],budget:{tokens:4e5,ms:36e5}},{name:"fix",description:"One Implementer fixes it on a branch, the Tester runs the guard, the Scribe notes it.",plan:"fixed",merge:"concat",roles:[{id:"implementer",agent:"implementer"},{id:"tester",agent:"tester",dependsOn:["implementer"]},{id:"scribe",agent:"scribe",dependsOn:["tester"]}],budget:{tokens:15e4,ms:18e5}},{name:"docs",description:"The Architect decides what the docs should say; the Scribe proposes the text.",plan:"fixed",merge:"concat",roles:[{id:"architect",agent:"architect"},{id:"scribe",agent:"scribe",dependsOn:["architect"]}],budget:{tokens:8e4,ms:9e5}},{name:"release",description:"The Tester runs the guard on the merged branch, Release bumps and asks before publishing, the Scribe records the version.",plan:"fixed",merge:"concat",roles:[{id:"tester",agent:"tester"},{id:"release",agent:"release",dependsOn:["tester"]},{id:"scribe",agent:"scribe",dependsOn:["release"]}],budget:{tokens:6e4,ms:18e5}}]);function _(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^[^a-z]+/,"").replace(/-+$/,"").slice(0,64)}function I(){return z.map(e=>({...e,roles:e.roles.map(t=>({...t,...t.grants?{grants:[...t.grants]}:{},...t.dependsOn?{dependsOn:[...t.dependsOn]}:{}})),budget:{...e.budget}}))}function q(){return{name:"",description:"",plan:"fixed",merge:"concat",judge:null,roles:[{id:"role1",prompt:"",prefer:"balanced",grants:["none"]}],budget:{tokens:2e4,ms:3e5}}}const A=e=>String(Array.isArray(e)?e.join(","):e||"").split(/[,\s]+/).map(t=>t.trim()).filter(Boolean);function C(e){const t=(Array.isArray(e.roles)?e.roles:[]).map(r=>({id:String(r.id||"").trim(),name:String(r.name||"").trim()||void 0,prompt:String(r.prompt||""),prefer:r.prefer||"balanced",...r.model?{model:String(r.model)}:{},...r.agent?{agent:String(r.agent).trim()}:{},...r.engine?{engine:r.engine}:{},...Array.isArray(r.dependsOn)?{dependsOn:r.dependsOn.map(String)}:{},...A(r.grants).length?{grants:A(r.grants)}:r.agent?{}:{grants:["none"]}})),i={};for(const r of["tokens","calls","ms","usd"]){const a=Number(e.budget?.[r]);e.budget?.[r]!==""&&e.budget?.[r]!=null&&Number.isFinite(a)&&a>0&&(i[r]=a)}const n=e.merge||"concat",s={name:_(e.name),description:String(e.description||"").trim(),plan:e.plan||"fixed",merge:n,judge:n==="judge"&&(e.judge||t[t.length-1]?.id)||null,roles:t,budget:i,enabled:e.enabled!==!1,...e.createdAt?{createdAt:e.createdAt}:{}},o=b(s);return o.ok?{ok:!0,team:S(s)}:{ok:!1,errors:o.errors}}export{R as AGENT_REF_RE,N as GRANTABLE,f as GRANT_RE,h as MAX_ROLES,p as MERGE_POLICIES,g as PLAN_MODES,E as ROLE_ID_RE,c as ROLE_MODES,l as ROLE_PREFERS,z as STARTER_TEAMS,k as TEAM_NAME_RE,T as TeamError,M as WORK_GRANTS,q as blankTeam,D as defineTeam,F as describeRole,G as grantAllows,m as normalizeGrants,S as normalizeTeam,B as scmAllows,_ as slugTeamName,I as starterTeams,C as teamFromForm,b as validateTeam};
@@ -0,0 +1,12 @@
1
+ function F(r){const n={};let e=n;const i=String(r||"").split(/\r?\n/);for(let t=0;t<i.length;t++){const s=i[t].trim();if(!s||s.startsWith("#"))continue;const l=/^\[\[\s*(.+?)\s*\]\]\s*(?:#.*)?$/.exec(s);if(l){e=z(n,S(l[1]));continue}const c=/^\[\s*(.+?)\s*\]\s*(?:#.*)?$/.exec(s);if(c){e=W(n,S(c[1]));continue}const f=_(s);if(f<0)continue;const h=S(s.slice(0,f).trim());if(!h.length)continue;let u=s.slice(f+1).trim();const a=/^("""|''')/.exec(u);if(a){const p=a[1],j=u.slice(3),N=j.indexOf(p);let w;if(N>=0)w=j.slice(0,N);else{const k=[j];for(;t+1<i.length;){t+=1;const R=i[t].indexOf(p);if(R>=0){k.push(i[t].slice(0,R));break}k.push(i[t])}w=k.join(`
2
+ `)}q(e,h,P(w,p==='"""'));continue}const b=u[0]==="["?"[":u[0]==="{"?"{":"";if(b){const p=b==="["?"]":"}";for(u=d(u);$(u,b,p)>0&&t+1<i.length;)t+=1,u+=`
3
+ ${d(i[t])}`;q(e,h,b==="["?E(u):O(u));continue}q(e,h,T(d(u).trim()))}return n}function I(r,{header:n=""}={}){const e=[];if(n)for(const i of String(n).split(`
4
+ `))e.push(`# ${i}`.trimEnd());return n&&e.push(""),A(r&&typeof r=="object"?r:{},[],e),`${e.join(`
5
+ `).replace(/\n{3,}/g,`
6
+
7
+ `).trim()}
8
+ `}function A(r,n,e){const i=[],t=[],o=[];for(const[s,l]of Object.entries(r))l!=null&&(m(l)?t.push([s,l]):Array.isArray(l)&&l.length&&l.every(m)?o.push([s,l]):i.push([s,l]));n.length&&(i.length||!t.length&&!o.length)&&e.push(`[${n.map(g).join(".")}]`);for(const[s,l]of i)e.push(`${g(s)} = ${x(l)}`);i.length&&e.push("");for(const[s,l]of t)A(l,[...n,s],e),e.push("");for(const[s,l]of o)for(const c of l){e.push(`[[${[...n,s].map(g).join(".")}]]`);for(const[f,h]of Object.entries(c))h!=null&&(m(h)?A(h,[...n,s,f],e):e.push(`${g(f)} = ${x(h)}`));e.push("")}}const M=/^[A-Za-z0-9_-]+$/,g=r=>M.test(String(r))?String(r):`"${C(String(r))}"`;function x(r){if(typeof r=="boolean")return r?"true":"false";if(typeof r=="number")return Number.isFinite(r)?String(r):"0";if(Array.isArray(r))return`[${r.filter(e=>e!=null).map(x).join(", ")}]`;if(m(r))return`{ ${Object.entries(r).filter(([,e])=>e!=null).map(([e,i])=>`${g(e)} = ${x(i)}`).join(", ")} }`;const n=String(r);return n.includes(`
9
+ `)?`"""
10
+ ${n.replace(/\\/g,"\\\\").replace(/"""/g,'\\"\\"\\"')}"""`:`"${C(n)}"`}function C(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}const m=r=>!!r&&typeof r=="object"&&!Array.isArray(r);function P(r,n){const e=r.replace(/^\r?\n/,"");return n?e.replace(/\\(.)/g,(i,t)=>B(t)):e}function S(r){const n=[];let e="",i="";for(let t=0;t<r.length;t++){const o=r[t];if(i){if(o==="\\"&&i==='"'){e+=B(r[t+1]??""),t+=1;continue}if(o===i){i="";continue}e+=o;continue}if(o==='"'||o==="'"){i=o;continue}if(o==="."){n.push(e.trim()),e="";continue}e+=o}return e.trim()&&n.push(e.trim()),n.filter(Boolean)}function _(r){let n="",e=0;for(let i=0;i<r.length;i++){const t=r[i];if(n){if(t==="\\"&&n==='"'){i+=1;continue}t===n&&(n="");continue}if(t==='"'||t==="'")n=t;else if(t==="["||t==="{")e+=1;else if(t==="]"||t==="}")e-=1;else if(t==="="&&e===0)return i}return-1}function W(r,n){let e=r;for(const i of n){let t=e[i];Array.isArray(t)&&(t=t[t.length-1]),m(t)||(t={},e[i]=t),e=t}return e}function z(r,n){const e=W(r,n.slice(0,-1)),i=n[n.length-1];Array.isArray(e[i])||(e[i]=[]);const t={};return e[i].push(t),t}function q(r,n,e){const i=n.length>1?W(r,n.slice(0,-1)):r;i[n[n.length-1]]=e}function K(r,n){const e=String(r||"").split(/\r?\n/);for(let i=0;i<e.length;i++){const t=new RegExp(`^\\s*${D(n)}\\s*=\\s*(.*)$`).exec(e[i]);if(!t)continue;let o=d(t[1]).trim();if(!o)return"";const s=o[0],l=s==="["?"]":s==="{"?"}":"";if(!l)return o;let c=$(o,s,l);for(;c>0&&i+1<e.length;)i+=1,o+=`
11
+ ${d(e[i])}`,c=$(o,s,l);return o.trim()}return null}function E(r){const n=String(r||"").trim(),e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n,i=[];let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t+=1;if(t>=e.length)break;const o=e[t];if(o==='"'||o==="'"){const c=y(e,t);i.push(c.value),t=c.next;continue}if(o==="{"||o==="["){const c=o==="{"?"}":"]";let f=t,h=0;for(;f<e.length;f++){const a=$(e.slice(t,f+1),o,c);if(h=a,a===0)break}const u=e.slice(t,Math.min(f+1,e.length));i.push(o==="{"?O(u):E(u)),t=f+1;continue}let s=t;for(;s<e.length&&e[s]!==",";)s+=1;const l=e.slice(t,s).trim();l&&i.push(T(l)),t=s+1}return i}function O(r){const n=String(r||"").trim(),e=n.startsWith("{")&&n.endsWith("}")?n.slice(1,-1):n,i={};let t=0;for(;t<e.length;){for(;t<e.length&&/[\s,]/.test(e[t]);)t+=1;if(t>=e.length)break;let o="";if(e[t]==='"'||e[t]==="'"){const s=y(e,t);o=s.value,t=s.next}else{let s=t;for(;s<e.length&&e[s]!=="="&&e[s]!==":";)s+=1;o=e.slice(t,s).trim(),t=s}for(;t<e.length&&/[\s=:]/.test(e[t]);)t+=1;if(!o)break;if(e[t]==='"'||e[t]==="'"){const s=y(e,t);i[o]=s.value,t=s.next}else if(e[t]==="{"||e[t]==="["){const s=e[t],l=s==="{"?"}":"]";let c=t;for(;c<e.length&&$(e.slice(t,c+1),s,l)!==0;c++);const f=e.slice(t,Math.min(c+1,e.length));i[o]=s==="{"?O(f):E(f),t=c+1}else{let s=t;for(;s<e.length&&e[s]!==",";)s+=1;i[o]=T(e.slice(t,s).trim()),t=s+1}}return i}function T(r){const n=String(r||"").trim().replace(/,+$/,"");return n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?y(n,0).value:n==="true"?!0:n==="false"?!1:/^[+-]?\d+$/.test(n)||/^[+-]?(?:\d+\.\d+|\d+[eE][+-]?\d+|\d+\.\d+[eE][+-]?\d+)$/.test(n)?Number(n):n}function y(r,n){const e=r[n];let i="",t=!1;for(let o=n+1;o<r.length;o++){const s=r[o];if(t){i+=e==='"'?B(s):s,t=!1;continue}if(s==="\\"&&e==='"'){t=!0;continue}if(s===e)return{value:i,next:o+1};i+=s}return{value:i,next:r.length}}function d(r){let n="";for(let e=0;e<r.length;e++){const i=r[e];if(n){i===n&&(n=""),i==="\\"&&n==='"'&&(e+=1);continue}if(i==='"'||i==="'")n=i;else if(i==="#")return r.slice(0,e)}return r}function $(r,n,e){let i=0,t="";for(let o=0;o<r.length;o++){const s=r[o];if(t){s==="\\"&&t==='"'?o+=1:s===t&&(t="");continue}s==='"'||s==="'"?t=s:s===n?i+=1:s===e&&(i-=1)}return i}function B(r){return{n:`
12
+ `,r:"\r",t:" ",'"':'"',"\\":"\\"}[r]??r}function D(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{$ as bracketDepth,E as parseArray,O as parseInlineTable,T as parseScalar,F as parseToml,y as readQuoted,I as renderToml,S as splitKeyPath,d as stripComment,K as tomlValue};
package/src/mcp-local.js CHANGED
@@ -1,4 +1,4 @@
1
- import{spawn as B}from"node:child_process";import{registryEnv as G,normalizeRegistries as H}from"./events/registries.js";function F(n){try{return H({npm:n.CHATPANEL_REGISTRY_NPM,pypi:n.CHATPANEL_REGISTRY_PYPI,models:n.CHATPANEL_REGISTRY_MODELS,github:n.CHATPANEL_REGISTRY_GITHUB})}catch{return{}}}import Y from"node:os";import k from"node:path";import{resolveCommand as U,buildSpawnSpec as J}from"./env.js";import{sandbox as q,refusalsFor as K,track as V}from"./sandbox.js";import{missingCommandMessage as W}from"./events/mcp-errors.js";import{parseSignInPrompt as Q,signInError as x,signInFromError as X}from"./events/mcp-signin.js";import{pickProbeTool as Z}from"./events/mcp-launcher.js";import{envLikeArgs as nn}from"./events/mcp-config-import.js";const d=new Map,b=new Map,C=10*6e4,en=6e4,tn=5*6e4,$=Object.freeze({protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"ChatPanel",version:"1.0"}}),rn=150,on=8*6e4,sn=16*6e4,S=4e3;function L(n){const e=Y.homedir(),t={};for(const[i,s]of Object.entries(n||{})){const o=String(s);t[i]=o==="~"?e:o.startsWith("~/")?k.join(e,o.slice(2)):o}return t}const A=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 T(n,e){clearTimeout(n.idleTimer);for(const{reject:t,timer:i}of n.pending.values())clearTimeout(i),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(C,sn):C;n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}d.delete(n.key)},e)}function an(n){const e=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
1
+ import{spawn as B}from"node:child_process";import{registryEnv as G,normalizeRegistries as H}from"./events/registries.js";function F(n){try{return H({npm:n.CHATPANEL_REGISTRY_NPM,pypi:n.CHATPANEL_REGISTRY_PYPI,models:n.CHATPANEL_REGISTRY_MODELS,github:n.CHATPANEL_REGISTRY_GITHUB})}catch{return{}}}import Y from"node:os";import k from"node:path";import{resolveCommand as U,buildSpawnSpec as J}from"./env.js";import{sandbox as q,refusalsFor as K,track as V}from"./sandbox.js";import{missingCommandMessage as W}from"./events/mcp-errors.js";import{parseSignInPrompt as Q,signInError as x,signInFromError as X}from"./events/mcp-signin.js";import{pickProbeTool as Z}from"./events/mcp-launcher.js";import{envLikeArgs as nn}from"./events/mcp-args-env.js";const d=new Map,b=new Map,C=10*6e4,en=6e4,tn=5*6e4,$=Object.freeze({protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"ChatPanel",version:"1.0"}}),rn=150,on=8*6e4,sn=16*6e4,S=4e3;function L(n){const e=Y.homedir(),t={};for(const[i,s]of Object.entries(n||{})){const o=String(s);t[i]=o==="~"?e:o.startsWith("~/")?k.join(e,o.slice(2)):o}return t}const A=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 T(n,e){clearTimeout(n.idleTimer);for(const{reject:t,timer:i}of n.pending.values())clearTimeout(i),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(C,sn):C;n.idleTimer=setTimeout(()=>{try{n.child.kill()}catch{}d.delete(n.key)},e)}function an(n){const e=String(n||"").replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/\r/g,`
2
2
  `).split(`
3
3
  `).map(t=>t.trimEnd()).filter(Boolean).join(`
4
4
  `).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function y(n,e){const t=an(e?.stderr);return t?`${n}: ${t}`:n}const M=new Map,j=new Set;function Mn(){const n=[];for(const e of d.values())e.child.exitCode!=null||e.child.killed||n.push({id:e.key,command:k.basename(String(e.command||"")),pid:e.child.pid??null,sandbox:e.sandbox,commandId:e.commandId,since:e.startedAt,refused:K(e.commandId)});return n}async function z(n){const e=A(n),t=O(n);if(M.has(e)){const o=await M.get(e);if(o.sig===t)return o}const i=d.get(e);if(i&&i.child.exitCode==null&&!i.child.killed){if(i.sig===t)return f(i),i;T(i,new Error("local MCP server restarted: its configuration changed"))}const s=ln(n,e,t).finally(()=>M.delete(e));return M.set(e,s),s}async function ln(n,e,t=O(n)){const i=U(n.command);if(!i)throw new Error(W(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 nn(s)){const l=a.indexOf("=");o[a.slice(0,l).trim()]=a.slice(l+1).trim()}const[p,h,u]=J(i,s,n.cwd||null);u.env={...u.env||process.env,...G(F(u.env||process.env)),...L(o),...L(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 q().wrap(p,h,u,{engine:"mcp",cwd:n.cwd||null,commandId:`mcp:${String(e).slice(0,48)}`,...n.sandbox?{grant:n.sandbox}:{}}),[N,R,D]=[c.bin,c.argv,c.opts];c.record.layer==="none"&&!j.has(c.record.reason)&&(j.add(c.record.reason),console.error(`[bridge] local MCP "${n.command}" runs outside a sandbox — ${c.record.reason}`));const g=V(B(N,R,D),c,{kind:"mcp",label:e}),r={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},v=a=>T(r,a);return g.stdout.setEncoding("utf8"),g.stdout.on("data",a=>{r.buf+=a;let l;for(;(l=r.buf.indexOf(`
package/src/net.js CHANGED
@@ -1 +1 @@
1
- function u(e){const t=String(e).match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return null;const r=t.slice(1).map(Number);return r.some(o=>o>255)?null:r}const s=e=>String(e||"").toLowerCase().replace(/^\[|\]$/g,"");function i(e){const t=s(e);if(!t)return!1;if(t==="localhost"||t.endsWith(".localhost")||t==="::1")return!0;const r=u(t);return!!(r&&r[0]===127)}function f(e){const t=s(e);if(t==="metadata.google.internal"||t==="metadata")return!0;const r=u(t);return r?r[0]===169&&r[1]===254||r[0]===100&&r[1]===100&&r[2]===100&&r[3]===200:!1}function l(e){const t=s(e);if(!t||t.endsWith(".local")||t==="::"||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe8")||t.startsWith("fe9")||t.startsWith("fea")||t.startsWith("feb"))return!0;const r=u(t);if(r){const[o,n]=r;if(o===0||o===10||o===169&&n===254||o===172&&n>=16&&n<=31||o===192&&n===168||o===100&&n>=64&&n<=127)return!0}return!1}function c(e,{allowLoopback:t=!0,allowPrivate:r=!0}={}){const o=s(e);return!o||f(o)?!0:i(o)?!t:l(o)?!r:!1}function a(e,t={}){let r;try{r=new URL(e)}catch{throw new Error(`invalid URL: ${e}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`only http(s) URLs allowed (got "${r.protocol}")`);if(c(r.hostname,t))throw new Error(`refusing to reach a blocked address (${r.hostname})`);return r}const h=(e,t={})=>a(e,{allowLoopback:!0,allowPrivate:!0,...t}),p=e=>a(e,{allowLoopback:!1,allowPrivate:!1});export{h as assertEndpointUrl,a as assertFetchableUrl,p as assertPublicWebUrl,c as isBlockedHost,i as isLoopbackHost,f as isMetadataHost,l as isPrivateHost};
1
+ export*from"./pii/net.js";
package/src/pii/net.js CHANGED
@@ -1 +1 @@
1
- function u(e){const t=String(e).match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return null;const r=t.slice(1).map(Number);return r.some(o=>o>255)?null:r}const s=e=>String(e||"").toLowerCase().replace(/^\[|\]$/g,"");function i(e){const t=s(e);if(!t)return!1;if(t==="localhost"||t.endsWith(".localhost")||t==="::1")return!0;const r=u(t);return!!(r&&r[0]===127)}function f(e){const t=s(e);if(t==="metadata.google.internal"||t==="metadata")return!0;const r=u(t);return r?r[0]===169&&r[1]===254||r[0]===100&&r[1]===100&&r[2]===100&&r[3]===200:!1}function l(e){const t=s(e);if(!t||t.endsWith(".local")||t==="::"||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe8")||t.startsWith("fe9")||t.startsWith("fea")||t.startsWith("feb"))return!0;const r=u(t);if(r){const[o,n]=r;if(o===0||o===10||o===169&&n===254||o===172&&n>=16&&n<=31||o===192&&n===168||o===100&&n>=64&&n<=127)return!0}return!1}function c(e,{allowLoopback:t=!0,allowPrivate:r=!0}={}){const o=s(e);return!o||f(o)?!0:i(o)?!t:l(o)?!r:!1}function a(e,t={}){let r;try{r=new URL(e)}catch{throw new Error(`invalid URL: ${e}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`only http(s) URLs allowed (got "${r.protocol}")`);if(c(r.hostname,t))throw new Error(`refusing to reach a blocked address (${r.hostname})`);return r}const h=(e,t={})=>a(e,{allowLoopback:!0,allowPrivate:!0,...t}),p=e=>a(e,{allowLoopback:!1,allowPrivate:!1});export{h as assertEndpointUrl,a as assertFetchableUrl,p as assertPublicWebUrl,c as isBlockedHost,i as isLoopbackHost,f as isMetadataHost,l as isPrivateHost};
1
+ function f(n){const t=String(n).match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return null;const r=t.slice(1).map(Number);return r.some(e=>e>255)?null:r}function s(n){if(!n.includes(":"))return null;let t=n;const r=t.match(/^(.*:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);if(r){const i=f(r[2]);if(!i)return null;t=`${r[1]}${((i[0]<<8|i[1])>>>0).toString(16)}:${((i[2]<<8|i[3])>>>0).toString(16)}`}const e=t.split("::");if(e.length>2)return null;const o=i=>(i?i.split(":"):[]).map(h=>/^[0-9a-f]{1,4}$/.test(h)?parseInt(h,16):NaN),u=o(e[0]),c=e.length===2?o(e[1]):[];if(u.concat(c).some(Number.isNaN))return null;const a=8-u.length-c.length;return(e.length===2?a<0:a!==0)?null:u.concat(new Array(e.length===2?a:0).fill(0),c)}function d(n){const t=s(n);return!t||t[0]||t[1]||t[2]||t[3]||t[4]||t[5]!==65535?n:[t[6]>>8,t[6]&255,t[7]>>8,t[7]&255].join(".")}const l=n=>d(String(n||"").trim().toLowerCase().replace(/^\[|\]$/g,""));function x(n){const t=l(n);if(!t)return!1;if(t==="localhost"||t.endsWith(".localhost"))return!0;const r=s(t);if(r)return r.slice(0,7).every(o=>o===0)&&r[7]===1;const e=f(t);return!!(e&&e[0]===127)}function m(n){const t=l(n);if(t==="metadata.google.internal"||t==="metadata")return!0;const r=s(t);if(r)return r[0]===64768&&r[1]===3778&&!r[2]&&!r[3]&&!r[4]&&!r[5]&&!r[6]&&r[7]===596;const e=f(t);return e?e[0]===169&&e[1]===254||e[0]===100&&e[1]===100&&e[2]===100&&e[3]===200:!1}function g(n){const t=l(n);if(!t||t.endsWith(".local"))return!0;const r=s(t);if(r)return!!(r.every(o=>o===0)||(r[0]&65024)===64512||(r[0]&65472)===65152||(r[0]&65472)===65216||r.slice(0,6).every(o=>o===0)||r[0]===100&&r[1]===65435);const e=f(t);if(e){const[o,u]=e;if(o===0||o===10||o===169&&u===254||o===172&&u>=16&&u<=31||o===192&&u===168||o===100&&u>=64&&u<=127)return!0}return!1}function w(n,{allowLoopback:t=!0,allowPrivate:r=!0}={}){const e=l(n);return!e||m(e)?!0:x(e)?!t:g(e)?!r:!1}function p(n,t={}){let r;try{r=new URL(n)}catch{throw new Error(`invalid URL: ${n}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`only http(s) URLs allowed (got "${r.protocol}")`);if(w(r.hostname,t))throw new Error(`refusing to reach a blocked address (${r.hostname})`);return r}const b=(n,t={})=>p(n,{allowLoopback:!0,allowPrivate:!0,...t}),v=n=>p(n,{allowLoopback:!1,allowPrivate:!1});export{b as assertEndpointUrl,p as assertFetchableUrl,v as assertPublicWebUrl,w as isBlockedHost,x as isLoopbackHost,m as isMetadataHost,g as isPrivateHost};
@@ -1 +1 @@
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};
1
+ import{stripHidden as k,confusablesSkeleton as m}from"./sanitize.js";const A=/\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g,O=Object.freeze(["PERSON","ORG","LOCATION","ADDRESS","EMAIL","PHONE","ID","SSN","IBAN","CREDITCARD","CARD","POST","FAC","GROUP","NRP","ENTITY","KEY","SECRET","TERM","PII","OTHER"]);function L(e){const t=String(e??"").trim().replace(/^\[{1,2}|\]{1,2}$/g,""),n=/^([A-Z][A-Z0-9]*)_\d+$/.exec(t);return!!n&&O.includes(n[1])}const w=/\[{0,2}([A-Z][A-Z0-9]*_\d+)\]{0,2}/g,_=/^(?:[^\n()[\]]|\[\[[A-Z][A-Z0-9]*_\d+\]\])*\]\(/;function N(e,t,n,r){const s=t.startsWith("[[["),o=t.endsWith("]]]");if(!s&&!o)return r;const i=e.slice(n+t.length),a=s&&_.test(o?`]${i}`:i),f=o&&i.startsWith("(");return`${a?"[":""}${r}${f?"]":""}`}function S(){return{byToken:new Map,byValue:new Map,counts:new Map,aliases:new Map}}function H(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 V(e){const t=S();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 E(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 P(e){return!(typeof e!="string"||e.length===0||e.length>200||/\([^)]*[+*}][^)]*\)\s*[+*{]/.test(e)||/[+*]\s*[+*]/.test(e))}function D(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 a of t){a.re.lastIndex=r;const f=a.re.exec(e);if(f&&(o===null||f.index<o.index)&&(o=f,i=a,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 $(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 z(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 C=[{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=>z(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&&$(t)}}];function b(e,t,{tier:n="basic",entities:r=[],dictionary:s=[],sanitize:o=!0,sanitizeOpts:i=void 0}={}){if(e==null||e==="")return e;let a=o?k(String(e),i):String(e);const f=t||S(),d=n==="full"||n==="entities",y=[];for(const l of s||[]){if(!l)continue;let c;try{c=l.pattern?P(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{c=null}if(c)if(l.alias!=null&&l.alias!=="")l.value&&f.aliases.set(l.alias,l.value),y.push({re:c,repl:()=>l.alias});else{const u=l.type||(l.pattern?"PII":"TERM");y.push({re:c,repl:p=>E(f,u,p[0])})}}a=D(a,y);const Z=m(a),g=[],R=(l,c)=>g.some(u=>l<u.end&&c>u.start);for(const l of C){l.re.lastIndex=0;let c;for(;(c=l.re.exec(Z))!==null;){if(c[0].length===0){l.re.lastIndex++;continue}const u=c.index,p=u+c[0].length;l.valid&&!l.valid(c[0])||R(u,p)||g.push({start:u,end:p,type:l.type})}}if(d){const l=[...r||[]].filter(c=>c&&c.value).sort((c,u)=>String(u.value).length-String(c.value).length);for(const c of l){const u=new RegExp(`(?<![\\w])${x(c.value)}(?![\\w])`,"gi");u.lastIndex=0;let p;for(;(p=u.exec(a))!==null;){if(p[0].length===0){u.lastIndex++;continue}const h=p.index,T=h+p[0].length;R(h,T)||g.push({start:h,end:T,type:c.type||"PERSON",token:E(f,c.type||"PERSON",p[0])})}}}if(g.length){g.sort((u,p)=>u.start-p.start);let l="",c=0;for(const u of g)l+=a.slice(c,u.start)+(u.token||E(f,u.type,a.slice(u.start,u.end))),c=u.end;a=l+a.slice(c)}return a}function I(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=>I(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=>I(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 M(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)?N(n,r,o,t.byToken.get(i)):r})}function Y(e,t){let n=M(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}const K=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 B(e,t){const n=String(e??"");if(!n)return{text:n,unresolved:[]};const r=[],s=n.replace(A,(o,i)=>{const a=t?.byToken?.get(o);return a??(r.push(o),K[i]||"redacted")});return A.lastIndex=0,{text:s,unresolved:r}}function F(e){return A.lastIndex=0,A.test(String(e||""))}function j(e,{includeValues:t=!1,maxPairs:n=200}={}){const r=new Map,s=[];for(const[i,a]of e?.byToken||new Map){const f=/^\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]$/.exec(i),d=f?f[1]:"OTHER";r.set(d,(r.get(d)||0)+1),t&&s.length<n&&s.push({token:i,value:a,type:d})}const o=[...r.entries()].map(([i,a])=>({type:i,count:a})).sort((i,a)=>a.count-i.count||i.type.localeCompare(a.type));return{total:o.reduce((i,a)=>i+a.count,0),types:o,...t?{pairs:s}:{}}}function W(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{O as REDACTION_TOKEN_TYPES,S as createVault,F as hasToken,L as isRedactionToken,W as mergeRedactionSummaries,I as redactResultShape,b as redactText,j as redactionSummary,M as restoreText,Y as restoreWithAliases,B as scrubPlaceholders,V as vaultFromJSON,H as vaultToJSON};
@@ -0,0 +1 @@
1
+ import{EventError as f}from"./events/event.js";const e=(n,t)=>{if(!n)throw new f("SHAPE",t)};function m({id:n,label:t,detect:o,wrap:s,violations:r,close:u}){return e(typeof n=="string"&&/^[a-z][a-z0-9-]*$/.test(n),"sandbox runtime: id must be a lowercase slug"),e(typeof t=="string"&&t.length>0,`sandbox runtime ${n}: label required`),e(typeof o=="function",`sandbox runtime ${n}: detect() required`),e(typeof s=="function",`sandbox runtime ${n}: wrap() required`),e(r==null||typeof r=="function",`sandbox runtime ${n}: violations must be a function`),e(u==null||typeof u=="function",`sandbox runtime ${n}: close must be a function`),Object.freeze({id:n,label:t,detect:o,wrap:s,violations:r||(()=>[]),close:u||(()=>{})})}const i=new Map;function b(n,t){return e(typeof n=="string"&&n.length>0,"sandbox runtime: id required"),e(typeof t=="function",`sandbox runtime ${n}: factory must be a function`),i.set(n,t),n}function a(){return[...i.keys()]}function x(n,t={}){const o=i.get(n);if(!o)throw new f("SHAPE",`sandbox runtime ${JSON.stringify(n)} is not registered — known: ${a().join(", ")||"none"}`);return o(t)}export{x as createSandboxRuntime,m as defineSandboxRuntime,b as registerSandboxRuntime,a as sandboxRuntimeIds};
@@ -0,0 +1 @@
1
+ import{spawnSync as pe}from"node:child_process";import{writeFileSync as Y,mkdirSync as Z,existsSync as xe}from"node:fs";import{createHash as Se,randomBytes as ye}from"node:crypto";import{fileURLToPath as ge}from"node:url";import P from"node:os";import L from"node:path";import{toSrtSettings as ee,sandboxRecord as ve,shellJoin as te,sandboxEnvOverlay as k,windowsGrantsFor as We,windowsSandboxEnv as Ae,withSrtWinEnv as Ee,ENGINE_KITS as Oe,DEVELOPER_HOSTS as $e,SECRET_PATHS as De,COMMON_WRITE as Le}from"./events/sandbox-policy.js";import{defineSandboxRuntime as Re,registerSandboxRuntime as Te}from"./sandbox-runtime.js";function Ne(t=process.env.CHATPANEL_SRT_MODULE){if(!t)return"";try{const r=t.startsWith("file:")?ge(new URL("./cli.js",t)):L.join(L.dirname(t),"cli.js");return xe(r)?r:""}catch{return""}}const ne=new Set;function se(t,r=L.join(P.tmpdir(),"chatpanel-srt")){const S=JSON.stringify(t),p=L.join(r,`${Se("sha256").update(S).digest("hex").slice(0,16)}.json`);return ne.has(p)||(Z(r,{recursive:!0,mode:448}),Y(p,S,{mode:384}),ne.add(p)),p}function Ce(){try{const t=pe(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return t.status===0&&String(t.stdout||"").trim().length>0}catch{return!1}}const I="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)";function _e({config:t,platform:r=process.platform,home:S=P.homedir(),loopback:p=[],compiled:v=!1,selfFiles:re=[process.execPath,process.argv[1]||""],onExit:oe=H=>process.on("exit",H),hostEntry:U=null,reportUrl:V="",mintReportToken:ie=()=>"",onRefusal:ae=()=>{},parseRefusal:ce=()=>null,loadSrt:F=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:z=Ce,cliEntry:B=Ne(),hostEntryFor:J=()=>"",log:R=()=>{}}={}){const H=new Set;let c=null,u=null,o=null,j=null,T=null,y=null,W=null;const N=new Set;let X=!1;const de="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)",le="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 ue(){if(!t.windows){u=de;return}if(v){u=le;return}try{o=await F()}catch(e){u=`sandbox-runtime is not installed — it ships with the gateway (${e.message})`;return}if(!o?.SandboxManager?.wrapWithSandboxArgv||typeof o.grantWindowsAcl!="function"||typeof o.getWindowsSandboxUserStatusAsync!="function"){u="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{y=o.resolveSrtWin({path:o.VENDORED_SRT_WIN_EXE})}catch(e){u=`Windows: srt-win.exe is not beside sandbox-runtime (${e.message})`;return}let n;try{n=await o.getWindowsSandboxUserStatusAsync({srtWin:y})}catch(e){W=!1,u=`Windows: srt-win could not be asked whether the sandbox account exists (${e.message}) — ${I}`;return}if(W=!!(n?.provisioned&&n.sid),!W){u=`Windows: the sandbox account is not installed — ${I}`;return}T=n.sid,c="srt-lib"}async function he(){if(!(c||u)){if(!t.enabled){u="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(r==="win32")return ue();if(!v)try{if(o=await F(),o?.SandboxManager?.wrapWithSandboxArgv){c="srt-lib";return}}catch(n){R(`sandbox: library not available (${n.message})`)}if(z()){c="srt-cli";return}u=v?"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 G=!1;function M(){return B&&!v?{bin:process.execPath,argv:[B]}:c==="srt-cli"||z()?{bin:"srt",argv:[]}:null}function we(){const n=Array.isArray(t.exactHosts)?t.exactHosts:t.mode==="open"?["*"]:t.mode==="none"?[]:[...new Set([...Object.values(Oe).flatMap(a=>a.hosts),...$e,...t.extraHosts])],e={id:`session:${t.mode}`,network:{mode:t.mode,allowedDomains:n},filesystem:{allowWrite:[P.tmpdir(),...Le,...t.extraWrite],denyRead:[...De,...t.extraDenyRead]}},s=ee(e,{loopback:p,home:r==="linux"?S:"",platform:r});return y?{...s,windows:{srtWin:{path:y.exe}}}:s}async function K(){return j||(j=o.SandboxManager.initialize(we()).then(()=>{try{o.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(n=>{for(const e of n||[]){const s=ce(e?.line);if(!s||!e?.encodedCommand)continue;let a="";try{a=Buffer.from(e.encodedCommand,"base64").toString("utf8")}catch{continue}const i=`${a}|${s.host}|${e.timestamp instanceof Date?e.timestamp.getTime():String(e.timestamp)}`;H.has(i)||(H.add(i),ae({commandId:a,...s,at:e.timestamp instanceof Date?e.timestamp.getTime():Date.now()}))}})}catch(n){R(`sandbox: violations not subscribed (${n.message})`)}})),j}function fe(n){const e=L.join(P.tmpdir(),"chatpanel-srt");Z(e,{recursive:!0,mode:448});const s=L.join(e,`host-${ye(8).toString("hex")}.json`);return Y(s,JSON.stringify(n),{mode:384}),s}function be(n,e){const s=(h,f)=>o.expandWindowsFsPaths(h,{mode:f}).filter(d=>!N.has(`${f}:${d.toLowerCase()}`)),a=s(n,"grant"),i=s(e,"grant");if(!(!a.length&&!i.length)){o.grantWindowsAcl({sandboxUserSid:T,read:a,write:i,srtWin:y});for(const h of a)N.add(`grant:${h.toLowerCase()}`);for(const h of i)N.add(`grant:${h.toLowerCase()}`);X||(X=!0,oe(()=>{try{o.revokeWindowsAcl({sandboxUserSid:T,srtWin:y})}catch{}}))}}async function me(n,e,s,{engine:a,workdir:i,kit:h,settings:f,commandId:d,record:C,caBundle:A=""}){await K();const E=w=>typeof w=="string"&&/^[a-z]:\\/i.test(w),{read:O,write:g}=We({kit:h,files:[n,...E(e[0])?[e[0]]:[],...re].filter(Boolean),home:S});be(O,g);const x=te(n,e,{platform:"win32"}),_=await o.SandboxManager.wrapWithSandboxArgv(x,void 0,{filesystem:{denyRead:f.filesystem.denyRead,denyWrite:f.filesystem.denyWrite}},void 0,i,{commandId:d,commandText:x}),b=s?.env||process.env,m={...Ae({engine:a,home:S,env:b,base:process.env}),...k({},{platform:r,caBundle:A})},l=Ee(_.argv,m),$={};for(const[w,D]of Object.entries(_.env||{}))process.env[w]!==D&&($[w]=D);return{bin:l[0],argv:l.slice(1),opts:{...s,env:{...b,...$},shell:!1},record:C,commandId:d}}return Re({id:"srt",label:"Anthropic sandbox-runtime",async detect(){return await he(),{ok:!!c,runtime:c,reason:u,ownSessions:!!(c&&(c==="srt-lib"&&(U??J(v))||r!=="win32"&&M())),...r==="win32"&&W!==null?{provisioned:W,...W?{}:{install:I}}:{}}},async wrap({kit:n,grant:e,bin:s,argv:a,opts:i,engine:h,workdir:f,commandId:d,caBundle:C=""}){const A=ee(n,{loopback:p,home:r==="linux"?S:"",platform:r}),E=te(s,a),O=t.mode==="allowlist"&&e.hosts.length>0&&!Array.isArray(t.exactHosts),g=O&&c==="srt-lib"?U??J(v):"",x=O&&!g&&r!=="win32"?M():null,_=!!(g||x),b=ve({layer:"process",runtime:g?"srt-host":x?"srt-cli":c,kitId:n.id,mode:n.network.mode,hosts:_||!O?e.hosts:[]});O&&!_&&(b.hostsDropped=e.hosts,G||(G=!0,R(`sandbox: hosts granted to ${h} (${e.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(g){const l=ie(d),$={bin:s,argv:a,cwd:i?.cwd||null,engine:h,workdir:f,grant:e,commandId:d,config:{enabled:!0,mode:t.mode,extraHosts:[],extraWrite:t.extraWrite,extraDenyRead:t.extraDenyRead,windows:t.windows,exactHosts:n.network.allowedDomains},loopback:p,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:V?{url:V,token:l}:null},w={...i?.env||process.env};return{bin:process.execPath,argv:[g,fe($)],opts:{...i,env:w,shell:!1},record:b,commandId:d}}if(x){const l={...i?.env||process.env};return Object.assign(l,k(l,{platform:r,caBundle:C})),{bin:x.bin,argv:[...x.argv,"-s",se(A),"-c",E],opts:{...i,env:l,shell:!1},record:b,commandId:d}}if(c==="srt-lib"&&r==="win32")return{...await me(s,a,i,{engine:h,workdir:f,kit:n,settings:A,commandId:d,record:b,caBundle:C})};if(c==="srt-lib"){await K();const l=await o.SandboxManager.wrapWithSandboxArgv(E,void 0,{filesystem:A.filesystem},void 0,f,{commandId:d,commandText:E}),$=i?.env||process.env,w={};for(const[q,Q]of Object.entries(l.env||{}))process.env[q]!==Q&&(w[q]=Q);const D={...$,...w};return Object.assign(D,k(D,{platform:r,caBundle:C})),{bin:l.argv[0],argv:l.argv.slice(1),opts:{...i,env:D,shell:!1},record:b,commandId:d}}const m=M();return{bin:m.bin,argv:[...m.argv,"-s",se(A),"-c",E],opts:{...i,shell:!1},record:b,commandId:d}}catch(m){return R(`sandbox: could not wrap ${s}: ${m.message}`),{passReason:m?.code==="SHAPE"?`the sandbox policy refused this run: ${m.message}`:`sandbox-runtime failed to wrap the command: ${m.message}`}}},violations(n){try{return o?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(n)||[]}catch{return[]}},close(){if(!(!T||!N.size)){try{o.revokeWindowsAcl({sandboxUserSid:T,srtWin:y})}catch(n){R(`sandbox: could not release the Windows grants: ${n.message}`)}N.clear()}}})}Te("srt",t=>_e(t));export{_e as createSrtRuntime};
package/src/sandbox.js CHANGED
@@ -1 +1 @@
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};
1
+ import{spawn as re}from"node:child_process";import"node:fs";import{randomBytes as se}from"node:crypto";import{AsyncLocalStorage as oe}from"node:async_hooks";import{fileURLToPath as ae}from"node:url";import N from"node:os";import ie from"node:path";import{ensureCaBundle as ue}from"./ca-bundle.js";import{kitFor as ce,sandboxRecord as le,normalizeGrant as I,writableRoots as de,NETWORK_MODES as pe}from"./events/sandbox-policy.js";import{createSandboxRuntime as fe,sandboxRuntimeIds as xe}from"./sandbox-runtime.js";import"./sandbox-srt.js";const U=new oe;function Ge(e,t){let n;try{n=I(e)}catch{n=null}return U.run(n,t)}function K(){return U.getStore()||null}function Ie(e,{config:t=Q(),grant:n=K(),home:s=N.homedir()}={}){try{return de({grant:n,extraWrite:t.extraWrite,cwd:e,home:s})}catch{return[]}}const me=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function V(e){const t=me.exec(String(e||""));return t?{host:t[1].toLowerCase(),port:Number(t[2])||0,reason:t[3]||""}:null}const T=new Map,A=[],g=new Map,we=new Set,Se=50;function Y({commandId:e,host:t,port:n=0,reason:s="",at:a=Date.now()}){if(!e||!t)return;let o=T.get(e);for(o||(o=new Map,T.set(e,o)),o.set(t,{at:a,reason:s,port:n}),A.push({id:e,engine:g.get(e)||String(e).split(":")[0],host:t,at:a});A.length>Se;)A.shift()}function he(e){const t=T.get(e);return t?[...t.entries()].sort((n,s)=>s[1].at-n[1].at).map(([n])=>n):[]}function Ae(e=20){return A.slice(-e).reverse()}function Ue(){T.clear(),A.length=0,g.clear(),we.clear()}const j=new Map;function z(e){const t=se(16).toString("hex");return j.set(t,e),t}function Ke(e={}){const t=j.get(String(e?.token||""));return!t||t!==e.commandId?!1:(Y({commandId:t,host:String(e.host||"").toLowerCase().slice(0,253),port:Number(e.port)||0,reason:String(e.reason||"").slice(0,200)}),!0)}let be=0;const _e=e=>`${e}:${(++be).toString(36)}${Date.now().toString(36).slice(-4)}`,E=new Map;function Re(e,t,{kind:n="agent",label:s=""}={}){if(!e||!t)return e;try{e.sandbox=t.record}catch{}if(typeof e.on!="function")return e;const a=t.commandId||"";E.set(e,{id:a,kind:n,engine:g.get(a)||String(a).split(":")[0]||"custom",command:t.label||"",label:s,pid:e.pid??null,since:Date.now(),sandbox:t.record});const o=()=>E.delete(e);return e.once("exit",o),e.once("error",o),e}function Ve(){return[...E.values()].map(e=>({...e,refused:he(e.id)}))}function Ye(){E.clear()}function J(e){if(e)return"";try{return ae(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}const q="open",je="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",ye=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],C=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean);function Q(e=process.env){const t=String(e.CHATPANEL_SANDBOX||q).toLowerCase(),n=t!=="off"&&t!=="0"&&t!=="false",s=pe.includes(t)?t:q;return{enabled:n,mode:s,extraHosts:C(e.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:C(e.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:C(e.CHATPANEL_SANDBOX_DENY_READ),windows:e.CHATPANEL_SANDBOX_WINDOWS==="1",reads:e.CHATPANEL_SANDBOX_READS==="inverted"?"inverted":"enumerated"}}function Ne({config:e=Q(),loadSrt:t=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:n=void 0,cliEntry:s=void 0,onRefusal:a=c=>Y(c),reportUrl:o=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:d=null,compiled:u=!1,platform:i=process.platform,home:p=N.homedir(),loopback:v=ye(),selfFiles:H=[process.execPath,process.argv[1]||""],onExit:$=c=>process.on("exit",c),runtimeId:b=process.env.CHATPANEL_SANDBOX_RUNTIME||"srt",makeRuntime:B=null,log:S=()=>{}}={}){let c=null,_=null,l={ok:!1,runtime:null,reason:null,ownSessions:!1};function h(){if(c||_)return c;try{c=B?B({config:e,platform:i,home:p,loopback:v,compiled:u,selfFiles:H,onExit:$,hostEntry:d,reportUrl:o,mintReportToken:z,onRefusal:a,parseRefusal:V,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:J,log:S}):fe(b,{config:e,platform:i,home:p,loopback:v,compiled:u,selfFiles:H,onExit:$,hostEntry:d,reportUrl:o,mintReportToken:z,onRefusal:a,parseRefusal:V,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:J,log:S})}catch(r){_=r?.message||String(r),S(`sandbox: ${_}`)}return c}async function k(){if(!e.enabled)return l={ok:!1,runtime:null,reason:"sandboxing is off (CHATPANEL_SANDBOX=off)",ownSessions:!1},l;const r=h();if(!r)return l={ok:!1,runtime:null,reason:_,ownSessions:!1},l;try{l={...l,...await r.detect()}}catch(f){l={ok:!1,runtime:null,reason:`the ${r.id} sandbox could not be started: ${f.message}`,ownSessions:!1}}return l}return{config:e,async status(){const r=await k(),f=h();return{enabled:e.enabled,mode:e.mode,runtime:r.runtime,platform:i,layer:f?.id||b,layers:xe(),...r.reason?{reason:r.reason}:{},extras:{hosts:e.extraHosts,write:e.extraWrite,denyRead:e.extraDenyRead},ownSessions:!!r.ownSessions,refused:Ae(),...r.provisioned!==void 0?{provisioned:r.provisioned}:{},...r.install?{install:r.install}:{}}},close(){try{h()?.close()}catch(r){S(`sandbox: close failed: ${r.message}`)}},async wrap(r,f,O,{engine:R="custom",cwd:ee=null,commandId:x=null,grant:te=K()}={}){const M=await k();x=x||_e(R),g.set(x,R);const F=ee||O?.cwd||process.cwd(),X=ie.basename(String(r||"")),y=w=>({bin:r,argv:f,opts:O,record:le({layer:"none",reason:w}),commandId:x,label:X});if(!M.ok)return y(M.reason);const ne=await ue().catch(()=>"");let G,D;try{D=I(te),G=ce({engine:R,cwd:F,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[N.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead,grant:D,home:N.homedir(),reads:e.reads})}catch(w){return y(`kit: ${w.message}`)}let m;try{m=await h().wrap({kit:G,grant:D,bin:r,argv:f,opts:O,engine:R,workdir:F,commandId:x,caBundle:ne})}catch(w){return S(`sandbox: could not wrap ${r}: ${w.message}`),y(`the ${b} sandbox failed to wrap the command: ${w.message}`)}return!m||m.passReason?y(m?.passReason||`the ${b} sandbox returned nothing`):{...m,commandId:m.commandId||x,label:X}},violations(r){try{return h()?.violations(r)||[]}catch{return[]}}}}let L=null;function Z(){if(!L){const{isCompiledBinary:e}=Te();L=Ne({compiled:e(),log:t=>console.error(`[bridge] ${t}`)})}return L}function ze(e){L=e}let P=null;function Te(){return P||(P={isCompiledBinary:()=>{const e=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}}),P}const W=new Set;function Je(e,t){if(!t||t.layer!=="none"||typeof e!="function")return;const n=t.reason||"unknown";W.has(n)||(W.add(n),e({type:"status",text:`Running outside a sandbox — ${n}`}))}function qe(){W.clear()}async function Qe(e,t,n,s={},{spawnImpl:a=re,box:o=Z(),kind:d="agent",label:u=""}={}){const i=await o.wrap(e,t,n,s);return Re(a(i.bin,i.argv,i.opts),i,{kind:d,label:u})}async function Ze(e,{box:t=Z(),platform:n=process.platform,loadSrt:s=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:a=console.log,err:o=console.error}={}){const d=e[0]||"status";if(d==="status")return a(JSON.stringify(await t.status(),null,2)),0;if(d!=="install")return o("usage: chatpanel-bridge sandbox [status|install]"),2;if(n!=="win32")return a("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let u;try{u=await s()}catch(i){return o(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${i.message})`),1}try{const i=u.resolveSrtWin({path:u.VENDORED_SRT_WIN_EXE}),p=await u.installWindowsSandboxAsync({srtWin:i});return p?.cancelled?(o("Cancelled at the administrator prompt — nothing was installed."),1):(a(`The sandbox account is installed${p?.user?.sid?` (${p.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(i){o(`install failed: ${i.message}`);try{o(u.windowsInstallInstructions())}catch{}return 1}}export{Ye as _resetLiveForTest,qe as _resetNotedForTest,Ue as _resetRefusalsForTest,ze as _setSandboxForTest,Ke as acceptRefusalReport,Ne as createSandbox,K as currentGrant,Ie as grantedWriteRoots,Ve as liveProcesses,Je as noteSandbox,V as parseRefusalLine,Ae as recentRefusals,Y as recordRefusal,he as refusalsFor,Ze as runSandboxCli,Z as sandbox,Q as sandboxConfigFromEnv,Qe as sandboxedSpawn,Re as track,Ge as withGrant};
package/src/server.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import{createServer as ye}from"node:http";import A from"node:os";import{randomBytes as be,randomInt as Se,timingSafeEqual as ke}from"node:crypto";import{mkdirSync as Te,writeFileSync as ve,readFileSync as K,existsSync as Ce}from"node:fs";import{join as H}from"node:path";import*as Ee from"./engines/claude.js";import*as Oe from"./engines/codex.js";import*as Ae from"./engines/antigravity.js";import{pi as xe,opencode as Pe,kiro as $e,copilot as Ie,deepseek as Ne,hermes as Re}from"./engines/cli-agents.js";import{connectorsFor as _e}from"./connectors.js";import*as He from"./engines/custom.js";import{installService as Me,uninstallService as Be,serviceStatus as De,restartService as V}from"./service.js";import{skillIndex as W,listRecords as Ge,readRecord as Ue,readPackageFile as We,skillsHealth as Le,quarantinedSkills as je}from"./skills.js";import{capabilityToolSpecs as Je,runCapabilityTool as Fe}from"./mcp-capabilities.js";import{createSession as Xe,deleteSession as Y,getSession as Q,activeSession as ze,relayToolCall as Ke}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ve,isDefaultWorkdir as Ye,resolveWorkdir as Qe,writeScopeNote as Ze}from"./workdir.js";import{sandbox as Z,runSandboxCli as qe,withGrant as q,acceptRefusalReport as et,liveProcesses as tt}from"./sandbox.js";import{gitState as nt,gitDelta as ot}from"./scm.js";import{listConnections as rt,putConnection as at,removeConnection as it,runEnvFor as st,testConnection as ct,secretBackend as ee}from"./connections.js";import{worktreeFor as te,listWorktrees as lt,removeWorktree as dt,withHook as ut,WORKTREE_ROOT as ne}from"./worktree.js";import{AGENT_CLIS as pt,agentAvailable as ht,agentInstallDirs as mt,enrichPath as ft,enrichAgentEnv as gt,findAgentBin as wt,resolveCommand as oe}from"./env.js";import"./sanitize.js";import{checkForUpdate as yt,selfUpdate as re,isEmbedded as bt}from"./update.js";import{callLocalMcp as St,localMcpStatus as kt,signInLocalMcp as Tt,signInStatusLocalMcp as vt}from"./mcp-local.js";import{assertPublicHttpUrl as ae,assertPublicWebUrl as ie}from"./ssrf.js";import{startRun as se,endRun as L,cancelRun as Ct,cancelAll as Et}from"./runs.js";import{closeWarmPools as Ot,warmStatus as At}from"./warm.js";import{CompatError as $,anthropicError as j,anthropicStream as xt,chatCompletionStream as Pt,completionStream as $t,createAnthropicMessage as It,createChatCompletion as Nt,createCompletion as Rt,createResponse as _t,openAIError as b,parseAnthropicMessage as Ht,parseChatCompletion as Mt,parseCompletion as Bt,parseResponse as Dt,responseStream as Gt}from"./api-compat.js";import{callerTrust as Ut,isPaired as I,parseExtensionIds as Wt,capRunOptions as Lt,engineHonoursReach as jt,createPairingStore as Jt,formatPairingCode as Ft}from"./pii/trust.js";const w="0.24.1",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,C={claude:{engine:Ee,label:"Claude Code"},codex:{engine:Oe,label:"Codex"},antigravity:{engine:Ae,label:"Antigravity",tools:!1},pi:{engine:xe,label:"Pi"},opencode:{engine:Pe,label:"OpenCode"},hermes:{engine:Re,label:"Hermes"},kiro:{engine:$e,label:"Kiro"},copilot:{engine:Ie,label:"GitHub Copilot"},deepseek:{engine:Ne,label:"DeepSeek Harness"},custom:{engine:He,label:"Custom",hidden:!0}};function ce(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Xt=Wt(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Ut({origin:n.headers.origin||"",hasToken:pe(n),extensionIds:Xt})),n.chatpanelTrust}function zt(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Kt(n,e){const t=n.headers.origin||"",r=ce(t);e.setHeader("Access-Control-Allow-Origin",r?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const J=new Set(["127.0.0.1","localhost","::1"]);function Vt(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const R=H(A.homedir(),".chatpanel","bridge-token");let S="";function Yt(){try{Ce(R)&&(S=K(R,"utf8").trim()),S||(S=be(32).toString("hex"),Te(H(A.homedir(),".chatpanel"),{recursive:!0}),ve(R,S,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const le=Jt({random:()=>Se(0,1e6)/1e6});function Qt(n){if(!S)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=le.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Zt(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=le.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function qt(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:w})}let M=null;async function de(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(A.homedir(),".chatpanel"),dataDir:H(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)}}),M}async function ue(n,e,t){try{const r=await de(),o=n.method==="POST"?await f(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function pe(n){if(!S)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(S);return r.length===o.length&&ke(r,o)}const en=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"]),tn=new Set(["/debug"]),nn=n=>tn.has(n);function on(n,e){if(!Vt(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ce(t))return"forbidden origin";const r=n.method==="POST"&&en.has(e)||n.method==="GET"&&nn(e);return r&&!(zt(t)||pe(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!an.has(e)?rn:null}const rn="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",an=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function F(n,e,t){const r=N(n),o=Lt(t,r);if(!jt(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const a=o.reach,s=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Agent Tools to unlock them.";return{options:o,note:s}}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function f(n){return new Promise((e,t)=>{let r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}async function sn(n){const e=await Promise.all(Object.entries(C).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:d,tools:c}])=>{const l=await s.available().catch(g=>({ok:!1,reason:String(g?.message||g)})),p=await _e(a).catch(()=>[]);return{id:a,label:d,available:l.ok,reason:l.reason,connectors:p,...c===!1?{tools:!1}:{}}})),t=bt()?{current:w,updateAvailable:!1,embedded:"gateway"}:await yt(w).catch(()=>({current:w,updateAvailable:!1})),r=await Le().catch(()=>null),o=await Z().status().catch(a=>({enabled:!1,reason:a.message}));i(n,200,{ok:!0,version:w,agents:e,update:t,workspace:Ve,sandbox:o,localMcp:kt(),processes:tt(),worktrees:ne,secretBackend:ee(),warm:At(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{}})}async function cn(n,e,t){const{index:r,problems:o}=await W({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Ge(r),problems:o})}async function ln(n,e,t){i(n,200,{ok:!0,quarantined:await je(e,t)})}async function dn(n,e,t,r){const{index:o}=await W({extraDirs:t,workdir:r}),a=Ue(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function un(n,e,t,r,o){const{index:a}=await W({extraDirs:r,workdir:o}),s=await We(a,e,t);if(s.error)return i(n,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});i(n,200,{ok:!0,...s})}async function pn(){return(await Promise.all(Object.entries(C).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function he(n,e=""){const t=await pn();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,b(new $(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function hn(n){try{const e=await re(w);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>V(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function mn(n,e){let t;try{t=await f(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=F(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
2
+ import{createServer as Te}from"node:http";import E from"node:os";import{randomBytes as Ee,randomInt as ve,timingSafeEqual as Oe}from"node:crypto";import{mkdirSync as Ae,writeFileSync as Ce,readFileSync as Y,existsSync as xe}from"node:fs";import{join as _}from"node:path";import*as Pe from"./engines/claude.js";import*as Re from"./engines/codex.js";import*as Ie from"./engines/antigravity.js";import{pi as $e,opencode as Ne,kiro as De,copilot as _e,deepseek as He,hermes as Me}from"./engines/cli-agents.js";import{connectorsFor as Ue}from"./connectors.js";import*as Be from"./engines/custom.js";import{installService as We,uninstallService as Ge,serviceStatus as Le,restartService as Q}from"./service.js";import{skillIndex as G,listRecords as je,readRecord as Fe,readPackageFile as Je,skillsHealth as Xe,quarantinedSkills as ze,clearSkillCache as L}from"./skills.js";import{writeSkillPackage as Ke,writeSkillFile as Ve,deleteSkillPackage as Ye,SkillWriteError as Qe}from"./skill-write.js";import{agentDefRoots as Ze,scanAgentDefs as qe,listAgentDefs as et,readAgentDef as tt,planAgentExport as nt,exportAgentDef as ot,agentDefsHealth as rt,AgentDefError as at}from"./agent-defs.js";import{capabilityToolSpecs as it,runCapabilityTool as st}from"./mcp-capabilities.js";import{createSession as ct,deleteSession as Z,getSession as q,activeSession as lt,relayToolCall as dt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as ut,isDefaultWorkdir as ht,resolveWorkdir as pt,writeScopeNote as ft}from"./workdir.js";import{sandbox as ee,runSandboxCli as mt,withGrant as te,grantedWriteRoots as gt,acceptRefusalReport as yt,liveProcesses as wt}from"./sandbox.js";import{gitState as bt,gitDelta as St}from"./scm.js";import{listConnections as kt,putConnection as Tt,removeConnection as Et,runEnvFor as vt,testConnection as Ot,secretBackend as ne}from"./connections.js";import{worktreeFor as oe,listWorktrees as At,removeWorktree as Ct,withHook as xt,WORKTREE_ROOT as re}from"./worktree.js";import{AGENT_CLIS as Pt,agentAvailable as Rt,agentInstallDirs as It,enrichPath as $t,enrichAgentEnv as Nt,findAgentBin as Dt,resolveCommand as ae}from"./env.js";import"./sanitize.js";import{checkForUpdate as _t,selfUpdate as ie,isEmbedded as Ht}from"./update.js";import{callLocalMcp as Mt,localMcpStatus as Ut,signInLocalMcp as Bt,signInStatusLocalMcp as Wt}from"./mcp-local.js";import{assertPublicHttpUrl as se,assertPublicWebUrl as ce}from"./ssrf.js";import{startRun as le,endRun as j,cancelRun as Gt,cancelAll as Lt}from"./runs.js";import{closeWarmPools as jt,warmStatus as Ft}from"./warm.js";import{CompatError as R,anthropicError as F,anthropicStream as Jt,chatCompletionStream as Xt,completionStream as zt,createAnthropicMessage as Kt,createChatCompletion as Vt,createCompletion as Yt,createResponse as Qt,openAIError as b,parseAnthropicMessage as Zt,parseChatCompletion as qt,parseCompletion as en,parseResponse as tn,responseStream as nn}from"./api-compat.js";import{callerTrust as on,isPaired as I,parseExtensionIds as rn,capRunOptions as an,engineHonoursReach as sn,createPairingStore as cn,formatPairingCode as ln}from"./pii/trust.js";const g="0.29.4",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",v=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:Pe,label:"Claude Code"},codex:{engine:Re,label:"Codex"},antigravity:{engine:Ie,label:"Antigravity",tools:!1},pi:{engine:$e,label:"Pi"},opencode:{engine:Ne,label:"OpenCode"},hermes:{engine:Me,label:"Hermes"},kiro:{engine:De,label:"Kiro"},copilot:{engine:_e,label:"GitHub Copilot"},deepseek:{engine:He,label:"DeepSeek Harness"},custom:{engine:Be,label:"Custom",hidden:!0}};function de(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 dn=rn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function $(t){return t.chatpanelTrust||(t.chatpanelTrust=on({origin:t.headers.origin||"",hasToken:fe(t),extensionIds:dn})),t.chatpanelTrust}function un(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 hn(t,e){const n=t.headers.origin||"",r=de(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 pn(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=_(E.homedir(),".chatpanel","bridge-token");let S="";function fn(){try{xe(N)&&(S=Y(N,"utf8").trim()),S||(S=Ee(32).toString("hex"),Ae(_(E.homedir(),".chatpanel"),{recursive:!0}),Ce(N,S,{mode:384}))}catch(t){u("error",`could not initialise bridge token: ${t?.message||t}`)}}const ue=cn({random:()=>ve(0,1e6)/1e6});function mn(t){if(!S)return a(t,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ue.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),a(t,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function gn(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=ue.claim(n?.code);return r.ok?(u("info",`paired a ${$(t)} client${t.headers.origin?` (${t.headers.origin})`:""}`),a(e,200,{ok:!0,token:S})):(u("info",`pairing refused (${r.reason}) from ${$(t)} caller`),a(e,403,{error:r.reason}))}function yn(t,e){const n=$(t);return a(e,200,{ok:!0,trust:n,paired:I(n),version:g})}let H=null;async function he(){if(H)return H;const{createChannelService:t}=await import("./channels/service.js");return H=t({home:_(E.homedir(),".chatpanel"),dataDir:_(E.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 pe(t,e,n){try{const r=await he(),o=t.method==="POST"?await m(t):{};if(n==="status")return a(e,200,await r.status());if(n==="connect"){const i=await r.connect(o);return a(e,200,{ok:!0,...i})}return n==="pair"?a(e,200,await r.pair()):n==="unpair"?a(e,200,await r.unpair(String(o.actorId||""))):n==="settings"?a(e,200,await r.update(o)):n==="disconnect"?a(e,200,await r.stop({forget:!!o.forget})):a(e,404,{error:"unknown channel action"})}catch(r){return a(e,400,{error:r?.message||String(r)})}}function fe(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&&Oe(r,o)}const wn=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"]),bn=new Set(["/debug"]),Sn=t=>bn.has(t),kn=(t,e)=>t!=="GET"&&t!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Tn(t,e){if(!pn(t))return"forbidden host";const n=t.headers.origin||"";if(n&&!de(n))return"forbidden origin";const r=t.method==="POST"&&wn.has(e)||t.method==="GET"&&Sn(e)||kn(t.method,e);return r&&!(un(n)||fe(t))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I($(t))&&!vn.has(e)?En:null}const En="forbidden: this client is not paired with the bridge — run `chatpanel-bridge pair` (or `chatpanel-gateway pair`) and enter the code in ChatPanel Settings",vn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(t,e,n){const r=$(t),o=an(n,r);if(!sn(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":"pair this client (chatpanel-bridge pair)"} to use ${e}`};const i=o.reach,s=I(r)?i==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":i==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:o,note:s}}function a(t,e,n){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(n))}function m(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(O).filter(([,s])=>!s.hidden).map(async([s,{engine:d,label:c,tools:l}])=>{const h=await d.available().catch(p=>({ok:!1,reason:String(p?.message||p)})),y=await Ue(s).catch(()=>[]);return{id:s,label:c,available:h.ok,reason:h.reason,connectors:y,...l===!1?{tools:!1}:{}}})),n=Ht()?{current:g,updateAvailable:!1,embedded:"gateway"}:await _t(g).catch(()=>({current:g,updateAvailable:!1})),r=await Xe().catch(()=>null),o=await rt().catch(()=>null),i=await ee().status().catch(s=>({enabled:!1,reason:s.message}));a(t,200,{ok:!0,version:g,agents:e,update:n,workspace:ut,sandbox:i,localMcp:Ut(),processes:wt(),worktrees:re,secretBackend:ne(),warm:Ft(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...r?{skills:r}:{},...o?{agentDefs:o}:{}})}async function An(t,e,n){const{index:r,problems:o}=await G({extraDirs:e,workdir:n});a(t,200,{ok:!0,skills:je(r),problems:o})}async function Cn(t,e,n){a(t,200,{ok:!0,quarantined:await ze(e,n)})}async function xn(t,e,n,r){const{index:o}=await G({extraDirs:n,workdir:r}),i=Fe(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown skill"});a(t,200,{ok:!0,skill:i})}async function Pn(t,e,n,r,o){const{index:i}=await G({extraDirs:r,workdir:o}),s=await Je(i,e,n);if(s.error)return a(t,s.error==="unknown skill"?404:400,{ok:!1,error:s.error});a(t,200,{ok:!0,...s})}async function Rn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{const r=await Ke({skill:n?.skill,files:n?.files||[],overwrite:!!n?.overwrite});return L(),a(e,200,r)}catch(r){return a(e,z(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function In(t,e,n,r){let o;try{o=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}try{const i=await Ve({name:n,path:r,text:o?.text??""});return L(),a(e,200,i)}catch(i){return a(e,z(i),{ok:!1,error:i.message,code:i.code||"ERROR"})}}async function $n(t,e){try{const n=await Ye({name:e});return L(),a(t,200,n)}catch(n){return a(t,z(n),{ok:!1,error:n.message,code:n.code||"ERROR"})}}function z(t){return t instanceof Qe?t.code==="NOT_FOUND"?404:t.code==="EXISTS"||t.code==="FULL"?409:t.code==="REFUSED"||t.code==="OUTSIDE"?403:400:400}async function me(t,e){return qe({roots:Ze(process.env,E.homedir(),t,e)})}async function Nn(t,e,n){const{index:r,quarantined:o,problems:i}=await me(e,n);a(t,200,{ok:!0,agents:et(r),...o.length?{quarantined:o.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...i.length?{problems:i}:{}})}async function Dn(t,e,n,r){const{index:o}=await me(n,r),i=tt(o,e);if(!i)return a(t,404,{ok:!1,error:"unknown agent definition"});a(t,200,{ok:!0,...i})}async function _n(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,{ok:!0,...await nt({agent:n?.agent,to:n?.to})})}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function Hn(t,e){let n;try{n=await m(t)}catch(r){return a(e,400,{error:"Bad JSON: "+r.message})}try{return a(e,200,await ot({agent:n?.agent,to:n?.to,overwrite:!!n?.overwrite}))}catch(r){return a(e,ge(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function ge(t){if(t instanceof at){if(t.code==="NOT_OURS")return 409;if(t.code==="TARGET")return 400}return 400}async function Mn(){return(await Promise.all(Object.entries(O).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 ye(t,e=""){const n=await Mn();if(e){const r=n.find(o=>o.id===e);return r?a(t,200,r):a(t,404,b(new R(`Model "${e}" not found`,404,"model")))}return a(t,200,{object:"list",data:n})}async function Un(t){try{const e=await ie(g);a(t,200,{ok:!0,updated:!0,from:e.from,to:e.to}),t.on("finish",()=>setTimeout(()=>Q(),400))}catch(e){a(t,400,{ok:!1,error:String(e?.message||e)})}}async function Bn(t,e){let n;try{n=await m(t)}catch(f){return a(e,400,{error:"Bad JSON: "+f.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=X(t,n.agent,n.options||{});if(o.error)return a(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 i=f=>{e.writableEnded||e.write(`data: ${JSON.stringify(f)}
3
3
 
4
- `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=se(d),l={signal:c.signal,abort:()=>c.cancel("client")},p=()=>{s=!0,c.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const g=h=>{s||a(h)};a({type:"run",id:d}),o.note&&a({type:"status",text:o.note});let m=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(m=await te({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),m.error){a({type:"error",error:`workspace: ${m.error}`}),L(d),e.writableEnded||e.end();return}}const X=m?m.path:Qe(t.options?.workingDir);let E=null;{const h=X,O=!!m||!Ye(t.options?.workingDir),y=Ze(t.agent,t.options?.permissionMode,h);a({type:"workdir",path:h,isDefault:!O,writeScope:y||void 0}),a({type:"status",text:`Working in ${h}${O?"":" (default)"}`}),y&&a({type:"status",text:y}),E=await nt(h),E&&a({type:"scm",phase:"before",...E})}let U=null;if(E||m){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:O,connection:y}=st({remote:E?.remote||null,grants:h,branch:m?.branch||null,connectionId:t.options?.connectionId||null});U=ut(O),m&&a({type:"workspace",path:m.path,branch:m.branch,base:m.base,created:m.created,repo:m.repo,...y?{connection:y}:{}}),y&&a({type:"status",text:`Git credential: ${y.kind} · ${y.host}${y.hasSecret?"":" (no token stored)"} · push: ${O.CHATPANEL_SCM_PUSH==="own"?`${m?.branch} only`:O.CHATPANEL_SCM_PUSH}`})}const z=t.approvals===!0,_={...t.options||{},...m?{workingDir:m.path}:{},...U?{runEnv:U}:{},approvals:z};let P=null;(t.pageTools?.specs?.length||z)&&(P=Xe(g,t.pageTools?.specs||[]),_.permissionSession=P,t.pageTools?.specs?.length&&(_.mcp={url:`http://${k}:${v}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await q(_.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:_,images:Array.isArray(t.images)?t.images:[]},g,{signal:l.signal}))}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),a({type:"error",error:h?.message||String(h)})}finally{if(!s){const h=await ot(X,E).catch(()=>null);h&&g({type:"scm",phase:"after",...h})}L(d),P&&Y(P.id),e.writableEnded||e.end()}}async function fn(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:rt(),secretBackend:ee()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:at(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return o?o[2]==="delete"?i(e,200,{ok:it(o[1])}):i(e,200,ct(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function gn(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ne,worktrees:await lt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await f(n);if(t==="/worktrees"){const o=await te({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(t==="/worktrees/remove"){const o=await dt({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function T(n,e,t){const r=C[n.agent];if(!r||r.hidden)throw new $(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!o.ok)throw new $(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=se(a),d=()=>s.cancel("disconnected");t.on("close",d);let c="";try{return await q(n.options?.sandbox,()=>r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(c+=l.text,e(l.text)):l?.type==="done"&&l.text&&!c&&(c=l.text,e(l.text))},{signal:s.signal})),c}finally{t.off("close",d),L(a)}}function B(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function x(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
4
+ `)};let s=!1;const d=`run_${Math.random().toString(36).slice(2,10)}`,c=le(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 y=f=>{s||i(f)};i({type:"run",id:d}),o.note&&i({type:"status",text:o.note});let p=null;if(n.options?.workspace&&typeof n.options.workspace=="object"){const f=n.options.workspace;if(p=await oe({repo:f.repo,projectId:f.projectId,jobId:f.jobId,base:f.base||null}),p.error){i({type:"error",error:`workspace: ${p.error}`}),j(d),e.writableEnded||e.end();return}}const K=p?p.path:pt(n.options?.workingDir);let A=null;{const f=K,C=!!p||!ht(n.options?.workingDir),w=ft(n.agent,n.options?.permissionMode,f,gt(f,{grant:n.options?.sandbox}));i({type:"workdir",path:f,isDefault:!C,writeScope:w||void 0}),i({type:"status",text:`Working in ${f}${C?"":" (default)"}`}),w&&i({type:"status",text:w}),A=await bt(f),A&&i({type:"scm",phase:"before",...A})}let W=null;if(A||p){const f=Array.isArray(n.options?.grants)?n.options.grants:[],{env:C,connection:w}=vt({remote:A?.remote||null,grants:f,branch:p?.branch||null,connectionId:n.options?.connectionId||null});W=xt(C),p&&i({type:"workspace",path:p.path,branch:p.branch,base:p.base,created:p.created,repo:p.repo,...w?{connection:w}:{}}),w&&i({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${C.CHATPANEL_SCM_PUSH==="own"?`${p?.branch} only`:C.CHATPANEL_SCM_PUSH}`})}const V=n.approvals===!0,D={...n.options||{},...p?{workingDir:p.path}:{},...W?{runEnv:W}:{},approvals:V};let P=null;(n.pageTools?.specs?.length||V)&&(P=ct(y,n.pageTools?.specs||[]),D.permissionSession=P,n.pageTools?.specs?.length&&(D.mcp={url:`http://${k}:${v}/mcp/${P.id}`,serverName:"chatpanel_browser",specs:n.pageTools.specs}));try{await te(D.sandbox,()=>r.engine.chat({messages:Array.isArray(n.messages)?n.messages:[],system:n.system||"",options:D,images:Array.isArray(n.images)?n.images:[]},y,{signal:l.signal}))}catch(f){u("error",`${n.agent} chat failed: ${f?.message||f}`),i({type:"error",error:f?.message||String(f)})}finally{if(!s){const f=await St(K,A).catch(()=>null);f&&y({type:"scm",phase:"after",...f})}j(d),P&&Z(P.id),e.writableEnded||e.end()}}async function Wn(t,e,n){if(t.method==="GET"&&n==="/connections")return a(e,200,{ok:!0,connections:kt(),secretBackend:ne()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await m(t);if(n==="/connections")try{return a(e,200,{ok:!0,connection:Tt(r.connection||r,{token:r.token||null})})}catch(i){return a(e,400,{error:String(i?.message||i)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(n);return o?o[2]==="delete"?a(e,200,{ok:Et(o[1])}):a(e,200,Ot(o[1],r.remote||"")):a(e,404,{error:"Not found"})}async function Gn(t,e,n){if(t.method==="GET"&&n==="/worktrees")return a(e,200,{ok:!0,root:re,worktrees:await At()});if(t.method!=="POST")return a(e,405,{error:"method not allowed"});const r=await m(t);if(n==="/worktrees"){const o=await oe({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return a(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(n==="/worktrees/remove"){const o=await Ct({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return a(e,o.ok?200:400,o)}return a(e,404,{error:"Not found"})}async function T(t,e,n){const r=O[t.agent];if(!r||r.hidden)throw new R(`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 R(o.reason||`${t.agent} is unavailable`,503,"model");const i=`run_${Math.random().toString(36).slice(2,10)}`,s=le(i),d=()=>s.cancel("disconnected");n.on("close",d);let c="";try{return await te(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),j(i)}}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
- `)}function D(n,e,t){n.writableEnded||n.write(`event: ${e}
7
- data: ${JSON.stringify(t)}
6
+ `)}function U(t,e,n){t.writableEnded||t.write(`event: ${e}
7
+ data: ${JSON.stringify(n)}
8
8
 
9
- `)}async function G(n,e,t,r){try{const o=t(await f(n)),a=F(n,o.agent,o.options||{});if(a.error)throw new $(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new $(`Bad JSON: ${o.message}`):o)),null}}async function wn(n,e){const t=await G(n,e,Mt,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,Nt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=Pt(t.requestedModel,o=>x(e,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function yn(n,e){const t=await G(n,e,Bt,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,Rt(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=$t(t.requestedModel,o=>x(e,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){x(e,b(o))}x(e,"[DONE]"),e.end()}async function bn(n,e){const t=await G(n,e,Dt,b);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,_t(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,b(o))}B(e);const r=Gt(t.requestedModel,o=>D(e,o.type,o));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...b(o)};D(e,"error",a)}e.end()}async function Sn(n,e){const t=await G(n,e,Ht,j);if(!t)return;if(!t.stream)try{const o=await T(t,()=>{},e);return i(e,200,It(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,j(o))}B(e);const r=xt(t.requestedModel,(o,a)=>D(e,o,a));try{await T(t,o=>r.delta(o),e),r.done()}catch(o){D(e,"error",j(o))}e.end()}async function kn(n,e){let t={};try{t=await f(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?Ct(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function me(n,e,t){let r;try{r=await f(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?Q(t):ze(),a=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:c,message:l}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:w}});const d=Je();if(r.method==="tools/list"){const c=o?o.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await Fe(r.params?.name,r.params?.arguments||{});if(c)return a(c);if(!o)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await Ke(o,r.params?.name,r.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function Tn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{},o=t.message;if(!r.command||!o)return i(e,400,{error:"need server.command and message"});try{const a=await St({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 vn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{};if(!r.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const o={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};try{return i(e,200,t.status?vt(o):await Tt(o))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function Cn(n,e){let t;try{t=await f(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:a}=t||{};if(!r||!a)return i(e,400,{error:"need url and message"});let s;try{s=ae(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const d={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,g]of Object.entries(o)){const m=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(m)||m.startsWith("x-"))&&(d[p]=String(g))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(a),redirect:"follow",signal:c.signal});try{p.url&&ae(p.url)}catch(m){return i(e,400,{error:String(m?.message||m)})}const g=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:g})}catch(p){const g=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${g}`})}finally{clearTimeout(l)}}const fe=256*1024,En=5,On=8e3;async function An(n){let e=ie(n);const t=new AbortController,r=setTimeout(()=>t.abort(),On);try{for(let o=0;o<=En;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${w} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ie(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:$n(await xn(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function xn(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,fe);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(o+=s.byteLength,r+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=fe))break}}finally{try{await e.cancel()}catch{}}return r}function Pn(n){return String(n).replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function $n(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Pn(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function In(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await An(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 Nn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=Q(t.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Rn(n,e){let t;try{t=await f(n)}catch(c){return i(e,400,{error:"Bad JSON: "+c.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=F(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const d=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let c="";return typeof r.engine.complete=="function"?c=await r.engine.complete({prompt:o,system:d,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:d,options:s.options},l=>{l.type==="delta"?c+=l.text||"":l.type==="done"&&l.text&&(c+=l.text)}),i(e,200,{text:(c||"").trim()})}catch(c){return i(e,502,{error:c?.message||String(c)})}}async function _n(n,e){let t;try{t=await f(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=C[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function Hn(n,e){let t;try{t=await f(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(t.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=oe(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}const ge=ye(async(n,e)=>{if(Kt(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=on(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return sn(e);const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return cn(e,o,a);if(n.method==="GET"&&t.pathname==="/skills-quarantined")return ln(e,o,a);if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),d=s.indexOf("/file/");return d===-1?dn(e,decodeURIComponent(s),o,a):un(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return fn(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return gn(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return he(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return he(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:w,agents:Object.fromEntries(pt.map(d=>[d,s?wt(d)||oe(d)?.kind||null:ht(d)])),...s?{home:A.homedir(),path:process.env.PATH,installDirs:mt(A.homedir())}:{}})}if(n.method==="POST"&&t.pathname==="/chat")return mn(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Zt(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Qt(e);if(n.method==="POST"&&t.pathname==="/whoami")return qt(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return wn(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return yn(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return bn(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Sn(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return me(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return me(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return Y(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ue(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ue(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return kn(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Nn(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await f(n)}catch{s=null}const d=et(s||{});return e.writeHead(d?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return Tn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return vn(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Cn(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return In(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Rn(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return _n(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Hn(n,e);if(n.method==="POST"&&t.pathname==="/update")return hn(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Mn(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},s=async()=>{if(!r){for(r=!0;t.length;){const d=t.shift();let c;try{c=JSON.parse(d)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:d});if(c.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
9
+ `)}async function B(t,e,n,r){try{const o=n(await m(t)),i=X(t,o.agent,o.options||{});if(i.error)throw new R(i.error,403,"permission");return o.options=i.options,o}catch(o){return a(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${o.message}`):o)),null}}async function Ln(t,e){const n=await B(t,e,qt,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Vt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(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 jn(t,e){const n=await B(t,e,en,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Yt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=zt(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 B(t,e,tn,b);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Qt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,b(o))}M(e);const r=nn(n.requestedModel,o=>U(e,o.type,o));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){const i={type:"error",sequence_number:0,...b(o)};U(e,"error",i)}e.end()}async function Jn(t,e){const n=await B(t,e,Zt,F);if(!n)return;if(!n.stream)try{const o=await T(n,()=>{},e);return a(e,200,Kt(n.requestedModel,o))}catch(o){return e.writableEnded?void 0:a(e,o?.status||500,F(o))}M(e);const r=Jt(n.requestedModel,(o,i)=>U(e,o,i));try{await T(n,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",F(o))}e.end()}async function Xn(t,e){let n={};try{n=await m(t)||{}}catch{}const r=String(n.id||"").trim(),o=r?Gt(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),a(e,200,{ok:!0,cancelled:o})}async function we(t,e,n){let r;try{r=await m(t)}catch{return a(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=n?q(n):lt(),i=c=>{o&&e.setHeader("Mcp-Session-Id",o.id),a(e,200,{jsonrpc:"2.0",id:r.id??null,result:c})},s=(c,l)=>a(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 i({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const d=it();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 i({tools:[...d,...c]})}if(r.method==="tools/call"){const c=await st(r.params?.name,r.params?.arguments||{});if(c)return i(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 i(await dt(o,r.params?.name,r.params?.arguments||{}))}catch(l){return i({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${r.method}`)}async function zn(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{},o=n.message;if(!r.command||!o)return a(e,400,{error:"need server.command and message"});try{const i=await Mt({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()):a(e,200,i)}catch(i){return a(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(i?.message||i)}})}}async function Kn(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=n.server||{};if(!r.command)return a(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 a(e,200,n.status?Wt(o):await Bt(o))}catch(i){return a(e,200,{state:"failed",error:String(i?.message||i)})}}async function Vn(t,e){let n;try{n=await m(t)}catch(h){return a(e,400,{error:"Bad JSON: "+h.message})}const{url:r,headers:o,message:i}=n||{};if(!r||!i)return a(e,400,{error:"need url and message"});let s;try{s=se(r)}catch(h){return a(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,y]of Object.entries(o)){const p=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(p)||p.startsWith("x-"))&&(d[h]=String(y))}const c=new AbortController,l=setTimeout(()=>c.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:d,body:JSON.stringify(i),redirect:"follow",signal:c.signal});try{h.url&&se(h.url)}catch(p){return a(e,400,{error:String(p?.message||p)})}const y=await h.text().catch(()=>"");return a(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return a(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const be=256*1024,Yn=5,Qn=8e3;async function Zn(t){let e=ce(t);const n=new AbortController,r=setTimeout(()=>n.abort(),Qn);try{for(let o=0;o<=Yn;o++){const i=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/${g} (+link-title)`}});if(i.status>=300&&i.status<400&&i.headers.get("location")){if(e=ce(new URL(i.headers.get("location"),e).href),i.body)try{await i.body.cancel()}catch{}continue}if(!i.ok){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}const s=i.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(i.body)try{await i.body.cancel()}catch{}return{title:null}}return{title:to(await qn(i)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function qn(t){if(!t.body?.getReader)return(await t.text().catch(()=>"")).slice(0,be);const e=t.body.getReader(),n=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:i,value:s}=await e.read();if(i||(o+=s.byteLength,r+=n.decode(s,{stream:!0}),/<\/title\s*>/i.test(r)||o>=be))break}}finally{try{await e.cancel()}catch{}}return r}function eo(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 to(t){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(t);return e?eo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function no(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=n&&n.url;if(!r||typeof r!="string")return a(e,400,{error:"need url"});try{const o=await Zn(r);return a(e,200,{title:o.title||null,url:o.url||r})}catch(o){const i=o?.name==="AbortError"?"timed out":String(o?.message||o);return a(e,400,{error:`couldn't fetch title: ${i}`})}}async function oo(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=q(n.session);if(!r)return a(e,404,{error:"no such session"});const o=r.pending.get(n.id);return o?(r.pending.delete(n.id),o.resolve(n.result),a(e,200,{ok:!0})):a(e,404,{error:"no such pending call"})}async function ro(t,e){let n;try{n=await m(t)}catch(c){return a(e,400,{error:"Bad JSON: "+c.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});const o=String(n.prompt||"").slice(0,6e3);if(!o)return a(e,400,{error:"Empty prompt"});const i=n.model||"",s=X(t,n.agent,{model:i});if(s.error)return a(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:i}):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)}),a(e,200,{text:(c||"").trim()})}catch(c){return a(e,502,{error:c?.message||String(c)})}}async function ao(t,e){let n;try{n=await m(t)}catch(o){return a(e,400,{error:"Bad JSON: "+o.message})}const r=O[n.agent];if(!r)return a(e,404,{error:`Unknown agent "${n.agent}"`});if(typeof r.engine.listModels!="function")return a(e,200,{models:[]});try{const o=await r.engine.listModels(n.options||{});return a(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return a(e,502,{error:o?.message||String(o)})}}async function io(t,e){let n;try{n=await m(t)}catch(i){return a(e,400,{error:"Bad JSON: "+i.message})}const r=String(n.command||"").trim();if(!r)return a(e,400,{error:"No command"});let o=null;try{o=ae(r)}catch{o=null}return a(e,200,{ok:!!o,via:o?o.kind:null})}const Se=Te(async(t,e)=>{if(hn(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 a(e,400,{error:"bad request"})}const r=Tn(t,n.pathname);if(r)return a(e,403,{error:r});try{if(t.method==="GET"&&n.pathname==="/health")return On(e);const o=n.searchParams.getAll("dir"),i=n.searchParams.get("workdir")||"";if(t.method==="GET"&&n.pathname==="/skills")return An(e,o,i);if(t.method==="GET"&&n.pathname==="/skills-quarantined")return Cn(e,o,i);if(t.method==="GET"&&n.pathname==="/agent-defs")return Nn(e,o,i);if(t.method==="POST"&&n.pathname==="/agent-defs/export-plan")return _n(t,e);if(t.method==="POST"&&n.pathname==="/agent-defs/export")return Hn(t,e);if(t.method==="GET"&&n.pathname.startsWith("/agent-defs/"))return Dn(e,decodeURIComponent(n.pathname.slice(12)),o,i);if(t.method==="POST"&&n.pathname==="/skills")return Rn(t,e);if((t.method==="PUT"||t.method==="POST"||t.method==="DELETE")&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?t.method==="DELETE"?$n(e,decodeURIComponent(s)):a(e,405,{ok:!1,error:"use POST /skills to save a skill"}):t.method==="DELETE"?a(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):In(t,e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)))}if(t.method==="GET"&&n.pathname.startsWith("/skills/")){const s=n.pathname.slice(8),d=s.indexOf("/file/");return d===-1?xn(e,decodeURIComponent(s),o,i):Pn(e,decodeURIComponent(s.slice(0,d)),decodeURIComponent(s.slice(d+6)),o,i)}if(n.pathname==="/connections"||n.pathname.startsWith("/connections/"))return Wn(t,e,n.pathname);if(n.pathname==="/worktrees"||n.pathname.startsWith("/worktrees/"))return Gn(t,e,n.pathname);if(t.method==="GET"&&n.pathname==="/v1/models")return ye(e);if(t.method==="GET"&&n.pathname.startsWith("/v1/models/"))return ye(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 a(e,200,{version:g,agents:Object.fromEntries(Pt.map(d=>[d,s?Dt(d)||ae(d)?.kind||null:Rt(d)])),...s?{home:E.homedir(),path:process.env.PATH,installDirs:It(E.homedir())}:{}})}if(t.method==="POST"&&n.pathname==="/chat")return Bn(t,e);if(t.method==="POST"&&n.pathname==="/pair")return gn(t,e);if(t.method==="POST"&&n.pathname==="/pair/code")return mn(e);if(t.method==="POST"&&n.pathname==="/whoami")return yn(t,e);if(t.method==="POST"&&n.pathname==="/v1/chat/completions")return Ln(t,e);if(t.method==="POST"&&n.pathname==="/v1/completions")return jn(t,e);if(t.method==="POST"&&n.pathname==="/v1/responses")return Fn(t,e);if(t.method==="POST"&&n.pathname==="/v1/messages")return Jn(t,e);if(n.pathname==="/mcp"){if(t.method==="POST")return we(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 we(t,e,s);if(t.method==="GET")return e.writeHead(405),e.end();if(t.method==="DELETE")return Z(s),e.writeHead(204),e.end()}if(t.method==="GET"&&n.pathname==="/channels")return pe(t,e,"status");if(t.method==="POST"&&n.pathname.startsWith("/channels/"))return pe(t,e,n.pathname.slice(10));if(t.method==="POST"&&n.pathname==="/cancel")return Xn(t,e);if(t.method==="POST"&&n.pathname==="/tool-result")return oo(t,e);if(t.method==="POST"&&n.pathname==="/sandbox/refused"){let s=null;try{s=await m(t)}catch{s=null}const d=yt(s||{});return e.writeHead(d?204:403),e.end()}if(t.method==="POST"&&n.pathname==="/mcp-local")return zn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-local/signin")return Kn(t,e);if(t.method==="POST"&&n.pathname==="/mcp-remote")return Vn(t,e);if(t.method==="POST"&&n.pathname==="/fetch-title")return no(t,e);if(t.method==="POST"&&n.pathname==="/complete")return ro(t,e);if(t.method==="POST"&&n.pathname==="/list-models")return ao(t,e);if(t.method==="POST"&&n.pathname==="/agent-check")return io(t,e);if(t.method==="POST"&&n.pathname==="/update")return Un(e);a(e,404,{error:"Not found"})}catch(o){a(e,500,{error:o?.message||String(o)})}});function u(t,e){(t==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function so(t){let e="";const n=[];let r=!1,o=!1;const i=()=>{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
- `)}}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&&t.push(l)}s()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Bn(){ft(),gt(),Yt(),ge.on("error",n=>{n&&n.code==="EADDRINUSE"&&(u("error",`Port ${v} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings."),process.exit(1)),u("error",`bridge server error: ${n?.message||n}`),process.exit(1)});for(const n of["SIGINT","SIGTERM"])process.on(n,()=>{const e=Et("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const t=Ot("shutdown");t&&u("info",`shutdown: closed ${t} warm agent process${t===1?"":"es"}`),Z().close(),setTimeout(()=>process.exit(0),e||t?300:0).unref?.(),!e&&!t&&process.exit(0)});ge.listen(v,k,async()=>{u("info",`listening on http://${k}:${v}`),J.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:n,label:e,hidden:t}]of Object.entries(C)){if(t)continue;const r=await n.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${e}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),de().then(n=>n.startIfConfigured()).then(n=>{n?.skipped||(n?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${n?.error||"unknown error"}`))}).catch(n=>u("error",`channels: ${n?.message||n}`))})}function Dn(){console.log(`ChatPanel Bridge v${w}
11
+ `)}}r=!1,i()}};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,i()}),process.stdin.resume()}function co(){$t(),Nt(),fn(),Se.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=Lt("shutdown");e&&u("info",`shutdown: stopped ${e} running agent${e===1?"":"s"}`);const n=jt("shutdown");n&&u("info",`shutdown: closed ${n} warm agent process${n===1?"":"es"}`),ee().close(),setTimeout(()=>process.exit(0),e||n?300:0).unref?.(),!e&&!n&&process.exit(0)});Se.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(O)){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."),he().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 lo(){console.log(`ChatPanel Bridge v${g}
13
13
 
14
14
  Usage:
15
15
  chatpanel-bridge start the bridge (foreground) on ${k}:${v}
@@ -21,4 +21,4 @@ Usage:
21
21
  chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
22
22
  chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
23
23
 
24
- Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function Gn(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return Dn(),!0;if(e("--version","-v"))return console.log(w),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=K(R,"utf8").trim()}catch{}const r=`http://${k}:${v}`;try{if(!t)throw new Error(`no token at ${R} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${Ft(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return qe(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{Me(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){u("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{Be(),u("info","Removed the login auto-start.")}catch(t){u("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=De()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const we=process.argv.indexOf("--mcp-stdio");if(we>=0){const n=process.argv[we+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Mn(n)}else process.argv.includes("--update")?(async()=>{try{const n=await re(w);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),V()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():Gn()||Bn();
24
+ Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function uo(){const t=process.argv,e=(...n)=>n.some(r=>t.includes(r));if(e("--help","-h"))return lo(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let n="";try{n=Y(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)}),i=await o.json().catch(()=>({}));if(!o.ok)throw new Error(i.error||`HTTP ${o.status}`);console.log(`Pairing code: ${ln(i.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(t.includes("sandbox"))return mt(t.slice(t.indexOf("sandbox")+1)).then(n=>{process.exitCode=n}),!0;if(e("--install")){try{We(),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{Ge(),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=Le()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${n?"installed":"not installed"}`),!0}return!1}const ke=process.argv.indexOf("--mcp-stdio");if(ke>=0){const t=process.argv[ke+1];t||(console.error("--mcp-stdio requires a URL"),process.exit(1)),so(t)}else process.argv.includes("--update")?(async()=>{try{const t=await ie(g);u("info",`Updated v${t.from} → v${t.to}. Restarting the background service…`),Q()}catch(t){u("error","Update failed: "+(t?.message||t)),process.exitCode=1}})():uo()||co();
@@ -0,0 +1 @@
1
+ import{mkdir as p,writeFile as N,rm as A,readdir as P,realpath as k,stat as v}from"node:fs/promises";import{join as $,resolve as b,sep as E}from"node:path";import g from"node:os";import{skillPackagePlan as D,skillFromPlan as L,SKILL_FILE as F}from"./events/skill-package.js";import{scanSkill as U,admits as M,scanSummary as R}from"./events/skill-scan.js";import{skillRoots as B}from"./skills.js";const x=/^[a-z0-9][a-z0-9_-]*$/,I=2*1024*1024,_=500;class i extends Error{constructor(e,r){super(r),this.name="SkillWriteError",this.code=e}}function O(o=process.env,e=g.homedir()){const r=B(o,e).find(c=>c.writable);if(!r)throw new i("NO_ROOT","no writable skill directory is configured");return r.dir}async function C({skill:o,files:e=[],overwrite:r=!1,env:c=process.env,home:s=g.homedir()}={}){const n=O(c,s),t=String(o?.id||"").trim();if(!x.test(t))throw new i("NAME",`"${t}" cannot be a directory name (letters, digits, _ and - only)`);const a=D(o,{files:e}),d=a.reduce((l,u)=>l+Buffer.byteLength(u.text,"utf8"),0);if(d>I)throw new i("SIZE",`${t}: ${Math.round(d/1024)} KB is more than a skill package should be`);const w=L(a,{dirName:t,source:"local"}),f=U({name:w.name,prompt:w.prompt,files:a.map(l=>l.path)});if(!M(f.verdict))throw new i("REFUSED",`${t}: refused before writing — ${R(f)}`);await p(n,{recursive:!0});const m=await k(n);if(await X(m)>=_)throw new i("FULL",`${n} already holds ${_} skills`);const h=$(m,t),S=await v(h).catch(()=>null);if(S&&!r)throw new i("EXISTS",`${t} already exists — pass overwrite to replace it`);if(S&&!S.isDirectory())throw new i("EXISTS",`${t} exists and is not a directory`);await p(h,{recursive:!0}),await y(h,m);for(const l of a){const u=b(h,l.path),T=u.slice(0,u.lastIndexOf(E));await p(T,{recursive:!0}),await y(T,m),await N(u,l.text,"utf8")}return{ok:!0,name:t,dir:h,files:a.map(l=>l.path),skill:w,scan:{verdict:f.verdict,findings:f.findings.length}}}async function G({name:o,path:e,text:r="",env:c=process.env,home:s=g.homedir()}={}){const n=O(c,s),t=String(o||"").trim();if(!x.test(t))throw new i("NAME",`"${t}" is not a skill name`);const a=await k(n).catch(()=>{throw new i("NOT_FOUND","no skills have been written yet")}),d=$(a,t);if(!(await v(d).catch(()=>null))?.isDirectory())throw new i("NOT_FOUND",`${t} is not a skill in ${n}`);if(String(e)===F)throw new i("PATH",`write ${F} by saving the skill, so it is rendered and scanned`);if(D({id:t,name:t,description:"x",prompt:"x"},{files:[{path:e,text:""}]}),Buffer.byteLength(String(r),"utf8")>I)throw new i("SIZE",`${e} is too large for a package file`);const w=b(d,e),f=w.slice(0,w.lastIndexOf(E));return await p(f,{recursive:!0}),await y(f,a),await N(w,String(r),"utf8"),{ok:!0,name:t,path:e}}async function Y({name:o,env:e=process.env,home:r=g.homedir()}={}){const c=O(e,r),s=String(o||"").trim();if(!x.test(s))throw new i("NAME",`"${s}" is not a skill name`);const n=await k(c).catch(()=>null);if(!n)throw new i("NOT_FOUND","no skills have been written yet");const t=$(n,s);if(!(await v(t).catch(()=>null))?.isDirectory())throw new i("NOT_FOUND",`${s} is not a skill in ${c}`);return await y(t,n),await A(t,{recursive:!0,force:!0}),{ok:!0,name:s}}async function y(o,e){const r=await k(o).catch(()=>null);if(!r)throw new i("PATH","that path does not resolve");if(r!==e&&!r.startsWith(e+E))throw new i("OUTSIDE","that path resolves outside the skills directory")}async function X(o){return(await P(o,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).length}export{i as SkillWriteError,Y as deleteSkillPackage,O as writableRoot,G as writeSkillFile,C as writeSkillPackage};