@chatpanel/bridge 0.29.4 → 0.29.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/ca-bundle.js +2 -2
- package/src/events/sandbox-policy.js +1 -1
- package/src/sandbox.js +1 -1
- package/src/server.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.29.
|
|
3
|
+
"version": "0.29.5",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
package/src/ca-bundle.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`,
|
|
1
|
+
import{execFile as E}from"node:child_process";import{mkdir as h,readFile as w,rm as I,stat as T,writeFile as b}from"node:fs/promises";import{existsSync as x}from"node:fs";import u from"node:os";import f from"node:path";import{promisify as A}from"node:util";import{CA_BUNDLE_RELPATH_LEGACY as B,caBundlePath as R,readDenialFor as S}from"./events/sandbox-policy.js";const N=A(E),P=720*6e4,_=2e4,l="-----BEGIN CERTIFICATE-----",y=(e=u.homedir())=>process.env.CHATPANEL_CA_BUNDLE||f.normalize(R(e));function g(e){try{const t=Buffer.from(String(e).replace(/\s+/g,""),"base64");return t.length>64&&t[0]===48&&(t[1]&128)!==0}catch{return!1}}function m(...e){const t=new Set,n=[];for(const o of e)for(const a of String(o||"").split(l).slice(1)){const r=a.indexOf("-----END CERTIFICATE-----");if(r<0)continue;const c=a.slice(0,r);if(!g(c))continue;const i=`${l}${c}-----END CERTIFICATE-----
|
|
2
|
+
`,p=i.replace(/\s+/g,"");t.has(p)||(t.add(p),n.push(i))}return n.join("")}function F(e){return String(e||"").split(l).length-1}async function d(e,t){try{const{stdout:n}=await N(e,t,{timeout:_,maxBuffer:33554432});return n||""}catch{return""}}async function L(e=process.platform){if(e==="darwin"){const[t,n]=await Promise.all([d("/usr/bin/security",["find-certificate","-a","-p","/System/Library/Keychains/SystemRootCertificates.keychain"]),d("/usr/bin/security",["find-certificate","-a","-p","/Library/Keychains/System.keychain"])]);return m(t,n)}if(e==="win32")return m(await d("powershell.exe",["-NoProfile","-NonInteractive","-Command","$ErrorActionPreference='SilentlyContinue';foreach ($s in @('Cert:\\LocalMachine\\Root','Cert:\\CurrentUser\\Root')) { foreach ($c in Get-ChildItem $s) { '-----BEGIN CERTIFICATE-----'; [Convert]::ToBase64String($c.RawData,'InsertLineBreaks'); '-----END CERTIFICATE-----' } }"]));for(const t of["/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/ssl/ca-bundle.pem","/etc/ssl/cert.pem"])if(x(t))return m(await w(t,"utf8").catch(()=>""));return""}let s=null,C=!1;const O=(e=u.homedir())=>y(e);async function j({now:e=Date.now(),platform:t=process.platform,source:n=L,home:o=u.homedir(),log:a=()=>{}}={}){const r=y(o),c=S(r,{home:o});if(c)return C||(C=!0,a(`ca-bundle: ${r} is denied to sandboxed processes by ${c} — no CA bundle will be exported`)),"";try{const i=await T(r);if(i.size>0&&e-i.mtimeMs<P)return r}catch{}return s||(s=(async()=>{try{const i=await n(t);return F(i)<10?"":(await h(f.dirname(r),{recursive:!0}),await b(r,i,{mode:420}),await I(f.join(o,...B.split("/")),{force:!0}).catch(()=>{}),r)}catch{return""}finally{s=null}})(),s)}export{O as caBundleFile,F as countPem,j as ensureCaBundle,m as mergePem,L as systemCaPem};
|
|
@@ -1 +1 @@
|
|
|
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};
|
|
1
|
+
import{EventError as j}from"./event.js";import{normalizeGrant as A}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as C,SECRET_DIR_PAIRS as P}from"./secret-names.js";const x=Object.freeze(["none","process","container","kubernetes"]),R=Object.freeze(["open","allowlist","none","gateway"]),y=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},_=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),O=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},L=y.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function S(e,t=""){const n=m(g(_(g(e),t)));if(!n)return!1;for(const o of y)if(O(n,o)||t&&O(n,_(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return L.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 $=Object.freeze([...[...C].map(e=>`~/**/${e}`),...P.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}`)]);function F(e,{home:t="",globs:n=[...y,...$]}={}){const r=m(g(_(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),i=m(g(t));for(const c of n){const l=m(g(c));if(l){if(l.startsWith("~/**/")){if(i&&!O(r,i))continue;const a=l.slice(5).split("/").filter(Boolean).map(v);for(let s=0;s+a.length<=o.length;s+=1)if(a.every((f,p)=>f.test(o[s+p])))return c;continue}if(O(r,_(l,t)))return c}}return null}function v(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const I=".cache/chatpanel/ca-bundle.crt",X=".cache/chatpanel/ca-bundle.pem";function V(e=""){const t=m(g(e));return t?`${t}/${I}`:`~/${I}`}const N=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"]),W=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:[]})}),T=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"]),h=e=>!!e&&typeof e=="object"&&!Array.isArray(e),b=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),d=(e,t)=>{if(!e)throw new j("SHAPE",t)},u=e=>[...new Set(e)];function D(e){d(h(e),"kit: must be an object"),d(typeof e.id=="string"&&e.id.length>0,"kit: id required"),d(h(e.network)&&R.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${R.join(", ")}`),d(b(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),d(b(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),d(h(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])d(b(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return d(b(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&d(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&d(Array.isArray(e.credentials)&&e.credentials.every(t=>h(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:u(e.network.allowedDomains||[]),deniedDomains:u(e.network.deniedDomains||[])},filesystem:{allowWrite:u(e.filesystem.allowWrite),denyWrite:u(e.filesystem.denyWrite||[]),allowRead:u(e.filesystem.allowRead||[]),denyRead:u(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:h(e.limits)?{...e.limits}:{}}}import{normalizeGrant as ce,mergeGrants as le,parseHostList as fe}from"./sandbox-grant.js";function Q({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:i=[],grant:c=null,home:l="",reads:a="enumerated"}={}){const s=W[e]||W.custom;d(typeof t=="string"&&t.length>0,"kit: cwd required");const f=A(c);return D({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:u([...s.hosts,...T,...r,...f.hosts]),deniedDomains:[]},filesystem:{allowWrite:u([t,...z,...s.write,...[...o,...f.write].filter(p=>!S(p,l))]),denyWrite:[],allowRead:a==="inverted"?u([t,...N,...s.write,...H({grant:f,extraWrite:o,cwd:t,home:l})]):[t],denyRead:u([...a==="inverted"?["~",...l?[l]:[]]:[],...y,...$,...i])}})}function H({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 f=String(s||"").trim();for(;f.length>1&&(f.endsWith("/")||f.endsWith("\\"));)f=f.slice(0,-1);return f},c=(s,f)=>s===f||s.startsWith(`${f}/`)||s.startsWith(`${f}\\`),l=i(o(n)),a=[];for(const s of[...A(e).write,...Array.isArray(t)?t:[]]){const f=i(o(i(s)));if(f&&!S(f,r)&&!(l&&c(f,l))&&!a.some(p=>c(f,p))){for(let p=a.length-1;p>=0;p--)c(a[p],f)&&a.splice(p,1);a.push(f)}}return a}function Z(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=D(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:u([...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 J({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:i=null}={}){return d(x.includes(e),`sandbox record: layer must be one of ${x.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(i)&&i.length?{hosts:u(i)}:{}}}function k(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){d(!/[\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 K=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function ee(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of K)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 te(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>k(r,{platform:n})).join(" ")}const ne=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),U=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function E(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function Y(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 oe({kit:e,files:t=[],home:n}){d(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("\\\\")||(d(!U(s)&&w(s)!==w(n),`windows grants: a write on ${s} would hand the sandbox account the whole profile`),E(s,n)&&o.push(s))}const i=(a,s)=>s.some(f=>w(a)===w(f)||E(a,f)),c=[];for(const a of t){const s=Y(a);s&&E(s,n)&&c.push(s)}for(const a of e?.filesystem?.allowRead||[]){const s=r(a);E(s,n)&&c.push(s)}const l=u(c).filter(a=>!i(a,o));return{read:l.filter(a=>!l.some(s=>s!==a&&E(a,s))),write:u(o)}}const B=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 re({engine:e="custom",home:t,env:n={},base:r={},carry:o=B}={}){d(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 se(e,t){d(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;d(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||{}))d(/^[A-Za-z_][A-Za-z0-9_]*$/.test(c),`srt-win env: bad key ${c}`),d(!/[\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{I as CA_BUNDLE_RELPATH,X as CA_BUNDLE_RELPATH_LEGACY,z as COMMON_WRITE,T as DEVELOPER_HOSTS,W as ENGINE_KITS,R as NETWORK_MODES,x as SANDBOX_LAYERS,y as SECRET_PATHS,$ as SECRET_READ_GLOBS,N as TOOLCHAIN_READ,B as WINDOWS_CARRY_KEYS,V as caBundlePath,S as isSecretWritePath,Q as kitFor,le as mergeGrants,ce as normalizeGrant,fe as parseHostList,F as readDenialFor,ee as sandboxEnvOverlay,J as sandboxRecord,te as shellJoin,k as shellQuote,Z as toSrtSettings,E as underWindowsHome,D as validateKit,oe as windowsGrantsFor,Y as windowsInstallRoot,re as windowsSandboxEnv,se as withSrtWinEnv,H as writableRoots};
|
package/src/sandbox.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
|
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 A 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=A.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,b=[],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}),b.push({id:e,engine:g.get(e)||String(e).split(":")[0],host:t,at:a});b.length>Se;)b.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 b.slice(-e).reverse()}function Ue(){T.clear(),b.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=A.homedir(),loopback:v=ye(),selfFiles:H=[process.execPath,process.argv[1]||""],onExit:$=c=>process.on("exit",c),runtimeId:_=process.env.CHATPANEL_SANDBOX_RUNTIME||"srt",makeRuntime:B=null,log:f=()=>{}}={}){let c=null,R=null,l={ok:!1,runtime:null,reason:null,ownSessions:!1};function h(){if(c||R)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:f}):fe(_,{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:f})}catch(r){R=r?.message||String(r),f(`sandbox: ${R}`)}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:R,ownSessions:!1},l;try{l={...l,...await r.detect()}}catch(x){l={ok:!1,runtime:null,reason:`the ${r.id} sandbox could not be started: ${x.message}`,ownSessions:!1}}return l}return{config:e,async status(){const r=await k(),x=h();return{enabled:e.enabled,mode:e.mode,runtime:r.runtime,platform:i,layer:x?.id||_,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){f(`sandbox: close failed: ${r.message}`)}},async wrap(r,x,O,{engine:y="custom",cwd:ee=null,commandId:m=null,grant:te=K()}={}){const M=await k();m=m||_e(y),g.set(m,y);const F=ee||O?.cwd||process.cwd(),X=ie.basename(String(r||"")),N=S=>({bin:r,argv:x,opts:O,record:le({layer:"none",reason:S}),commandId:m,label:X});if(!M.ok)return N(M.reason);const ne=await ue({home:A.homedir(),log:f}).catch(()=>"");let G,D;try{D=I(te),G=ce({engine:y,cwd:F,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[A.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead,grant:D,home:A.homedir(),reads:e.reads})}catch(S){return N(`kit: ${S.message}`)}let w;try{w=await h().wrap({kit:G,grant:D,bin:r,argv:x,opts:O,engine:y,workdir:F,commandId:m,caBundle:ne})}catch(S){return f(`sandbox: could not wrap ${r}: ${S.message}`),N(`the ${_} sandbox failed to wrap the command: ${S.message}`)}return!w||w.passReason?N(w?.passReason||`the ${_} sandbox returned nothing`):{...w,commandId:w.commandId||m,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,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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)}
|
|
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.5",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
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
|
|