@chatpanel/bridge 0.47.1 → 0.47.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/engines/cli-agents.js +1 -1
- package/src/engines/custom.js +5 -5
- package/src/events/sandbox-policy.js +1 -1
- package/src/mcp-local.js +4 -4
- package/src/pii/pii-detect.js +2 -2
- package/src/server.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.47.
|
|
3
|
+
"version": "0.47.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": [
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{agentAvailable as b,selfMcpStdio as u}from"../env.js";function a(e,o,i,t={}){let r=!1,s=0;const n={
|
|
1
|
+
import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{agentAvailable as b,selfMcpStdio as u}from"../env.js";function a(e,o,i,t={}){let r=!1,s=0;const n={sandboxEngine:e,...o,command:e};return{spec:n,async available(){if(Date.now()-s>(r?3e4:4e3)){s=Date.now();try{r=b(e)}catch{r=!1}}return r?{ok:!0}:{ok:!1,reason:i}},listModels(l={}){return t.listModels?t.listModels(e,l):A(e,o.listModelsArgs,l.workingDir)},chat(l,c,p){return h(n,l,c,p)}}}const H=a("pi",{args:"-p",promptVia:"stdin",modelArg:"--model {model}",imageArg:"@{path}",toolAdapter:"pi-extension",listModelsArgs:"--list-models",label:"Pi"},"pi not found on PATH. Install Pi, then run `pi` once to sign in."),D=a("opencode",{args:"run --format json --dangerously-skip-permissions",promptVia:"stdin",modelArg:"-m {model}",imageArg:"-f {path}",format:"opencode-json",requiresStableMcp:!0,stableMcpConfigCheck:"opencode",listModelsArgs:"models",label:"OpenCode"},"opencode not found on PATH. Install opencode, then sign in."),P=a("kiro-cli",{args:"chat --no-interactive --require-mcp-startup",promptVia:"stdin",modelArg:"--model {model}",trustAllToolsForMcp:!0,trustAllToolsArg:"--trust-all-tools",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"kiro",stableMcpSetupArgs:["mcp","add","--scope","global","--name","chatpanel_browser","--url","http://127.0.0.1:4319/mcp","--force"],stableMcpSetupCommand:"kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force",listModelsArgs:"--list-models",label:"Kiro"},"kiro-cli not found on PATH. Install Kiro CLI, then sign in."),S=["--output-format","json","--no-color","--log-level","none","--no-ask-user","--no-auto-update","--no-remote","--no-remote-export"],_=a("copilot",{args:S,promptVia:"stdin",modelArg:"--model {model}",imageArg:"--attachment {path}",format:"copilot-json",mcpArg:"--additional-mcp-config @{file}",permissionArgs:{default:["--allow-all-tools"],acceptEdits:["--allow-all-tools","--allow-all-paths"],bypassPermissions:["--allow-all"]},forbidden:"copilot",label:"GitHub Copilot"},"copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.",{listModels:(e,o)=>M(e,o.workingDir)});async function M(e="copilot",o){const i=await d(e,["help","config"],o),t=[],r=new Set;let s=!1;for(const n of String(i||"").split(`
|
|
2
2
|
`)){const l=/^\s*`([A-Za-z][\w.]*)`\s*:/.exec(n);if(l){s=l[1]==="model";continue}if(!s)continue;const c=/^\s*-\s*"([^"]+)"\s*$/.exec(n);if(!c)continue;const p=c[1];if(!r.has(p)&&(r.add(p),t.push(p),t.length>=200))break}return t.length?["auto",...t]:[]}const T=a("dsh",{args:["--profile","headless","{prompt}"],promptVia:"arg",format:"text",modelPatch:{arg:"--patch {file}",build:e=>`- id: ${g}
|
|
3
3
|
config:
|
|
4
4
|
provider: ${k}
|
package/src/engines/custom.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{spawn as v}from"node:child_process";import{readFile as Q,writeFile as k,unlink as Y}from"node:fs/promises";import T from"node:os";import
|
|
2
|
-
`)){const o=r.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available|usage|options|commands)$/i.test(o)&&!e.has(o)&&(e.add(o),n.push(o),n.length>=200))break}return n}async function Xt(t={}){if(!await D(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return wt(n.command,n.listModelsArgs,t.workingDir)}async function wt(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await St(t,r.split(/\s+/).filter(Boolean),e);return ht(o)}async function St(t,n,e,r=2e4){if(!t)return"";const o=L(t);if(!o)throw new Error(U(t,{platform:process.platform}));const s=e?
|
|
1
|
+
import{spawn as v}from"node:child_process";import{readFile as Q,writeFile as k,unlink as Y}from"node:fs/promises";import T from"node:os";import A from"node:path";import{resolveCommand as L,buildSpawnSpec as _,selfMcpStdio as tt}from"../env.js";import{missingCommandMessage as U}from"../events/mcp-errors.js";import{sandbox as I,noteSandbox as et,track as F,grantedWriteRoots as rt}from"../sandbox.js";import{harnessDirArgs as nt}from"../events/harness-cards.js";import{isProEntitled as D}from"../entitlement.js";import{killOnAbort as ot}from"../proc.js";import{buildCliPrompt as it,fitCliPrompt as st,argvPromptBudget as at}from"./prompt.js";import{pushExtraArgs as lt,FORBIDDEN as H}from"./args.js";import{createStreamParser as ct,STREAM_FORMATS as mt}from"./stream-formats.js";import{resolveWorkdir as ut}from"../workdir.js";import{cliError as pt}from"../cli-errors.js";async function dt(t,n){const e=[];for(let r=0;r<(t?.length||0);r++){const o=/^data:([^;]+);base64,(.+)$/s.exec(t[r]?.dataUrl||"");if(!o)continue;const s=(o[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",d=A.join(T.tmpdir(),`chatpanel-custom-img-${n}-${r}.${s}`);await k(d,Buffer.from(o[2],"base64")),e.push(d)}return e}function ft(t,n){const e=String(t||"").trim();if(!e||!n.length)return[];const r=[];for(const o of n)r.push(...e.includes("{path}")?e.replaceAll("{path}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]);return r}const J=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,gt="http://127.0.0.1:4319/mcp",j="http://127.0.0.1:4319/mcp";async function Wt(){return{ok:!0}}function ht(t){const n=[],e=new Set;for(const r of String(t||"").split(`
|
|
2
|
+
`)){const o=r.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available|usage|options|commands)$/i.test(o)&&!e.has(o)&&(e.add(o),n.push(o),n.length>=200))break}return n}async function Xt(t={}){if(!await D(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return wt(n.command,n.listModelsArgs,t.workingDir)}async function wt(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await St(t,r.split(/\s+/).filter(Boolean),e);return ht(o)}async function St(t,n,e,r=2e4){if(!t)return"";const o=L(t);if(!o)throw new Error(U(t,{platform:process.platform}));const s=e?A.resolve(e):null,[d,f,g]=_(o,n,s);g.env={...g.env||process.env,NO_COLOR:"1",CLICOLOR:"0"};const y=await I().wrap(d,f,g,{engine:"custom",cwd:s}),{bin:m,argv:$,opts:u}=y;return new Promise((i,h)=>{let S;try{S=F(v(m,$,u),y,{kind:"probe"})}catch(C){return h(new Error(`Failed to start ${t}: ${C.message}`))}let l="";const M=setTimeout(()=>{S.kill("SIGKILL"),h(new Error(`${t} timed out.`))},r);S.stdout.on("data",C=>l+=C.toString()),S.on("error",C=>{clearTimeout(M),h(new Error(`Failed to start ${t}: ${C.message}`))}),S.on("close",()=>{clearTimeout(M),i(l)});try{S.stdin.end()}catch{}})}function z(t){return(t?.specs||[]).filter(n=>n?.name)}function G(t,n){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${n}_${e}`}function yt(t,n){return["--extension",t]}function Ct(t,n){const e=String(t||"").trim(),r=z(n).map(s=>s.name).filter(Boolean);if(!e||!r.length)return[];const o=r.join(",");return e.includes("{tools}")?e.replaceAll("{tools}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]}function $t(t={},n){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?Ct(t.trustToolsArg,n):[]}function bt(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${j}`}function xt(t={}){const n=typeof t.stableMcpSetupArgs=="function"?t.stableMcpSetupArgs():t.stableMcpSetupArgs,e=Array.isArray(n)?n.filter(r=>r!=null).map(String):null;return e?.length?{command:t.stableMcpSetupCommandName||t.command,args:e}:null}function At(t){const n=z(t),e=n.map((o,s)=>{const d=G(o.name,s),f=o.parameters||{type:"object",properties:{}};return`const ${d}Tool = {
|
|
3
3
|
name: ${JSON.stringify(o.name)},
|
|
4
4
|
label: ${JSON.stringify(o.name)},
|
|
5
5
|
description: ${JSON.stringify(o.description||o.name)},
|
|
@@ -65,7 +65,7 @@ ${e}
|
|
|
65
65
|
export default function (pi: ExtensionAPI) {
|
|
66
66
|
${r}
|
|
67
67
|
}
|
|
68
|
-
`}async function Mt(t,n){const e=
|
|
68
|
+
`}async function Mt(t,n){const e=A.join(T.tmpdir(),`chatpanel-pi-tools-${n}.ts`);return await k(e,At(t)),e}async function Tt(){const t=process.env.XDG_CONFIG_HOME||A.join(T.homedir(),".config"),n=[A.join(t,"opencode","opencode.jsonc"),A.join(T.homedir(),"Library","Application Support","opencode","opencode.jsonc")];for(const e of n)try{if((await Q(e,"utf8")).includes(gt))return!0}catch{}return!1}async function K(t,n,e){const r=L(t);if(!r)return"";const[o,s,d]=_(r,n,e||null),f=await I().wrap(o,s,d,{engine:"custom",cwd:e||null}),{bin:g,argv:y,opts:m}=f;return new Promise($=>{const u=F(v(g,y,m),f,{kind:"probe"});let i="",h="";const S=setTimeout(()=>{u.kill("SIGKILL"),$(i+h)},4e3);u.stdout.on("data",l=>i+=l.toString()),u.stderr.on("data",l=>h+=l.toString()),u.on("error",()=>{clearTimeout(S),$(i+h)}),u.on("close",()=>{clearTimeout(S),$(i+h)});try{u.stdin.end()}catch{}})}async function Et(t,n){for(const e of["workspace","global","default"]){const r=await K(t,["mcp","list",e],n);if(r.includes(j)||/chatpanel_browser/i.test(r))return!0}return!1}async function Ot(t,n){const e=await K(t,["mcp","list"],n);return e.includes(j)||/chatpanel_browser/i.test(e)}async function Pt(t,n){return t.stableMcpConfigCheck==="kiro"?Et(t.command||"kiro-cli",n):t.stableMcpConfigCheck==="opencode"?Tt():t.stableMcpConfigCheck==="hermes"?Ot(t.command||"hermes",n):!1}async function vt(t,n){const e=L(t.command);if(!e)throw new Error(`Couldn't find "${t.command}" to set up browser tools.`);const[r,o,s]=_(e,t.args,n||null);s.env={...s.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const d=await I().wrap(r,o,s,{engine:"custom",cwd:n||null}),{bin:f,argv:g,opts:y}=d;await new Promise((m,$)=>{let u;try{u=F(v(f,g,y),d,{kind:"probe"})}catch(l){return $(new Error(`Failed to start ${t.command}: ${l.message}`))}let i="",h="";const S=setTimeout(()=>{u.kill("SIGKILL"),$(new Error(`${t.command} MCP setup timed out.`))},2e4);u.stderr.on("data",l=>i+=l.toString()),u.stdout?.on("data",l=>h+=l.toString()),u.on("error",l=>{clearTimeout(S),$(new Error(`Failed to start ${t.command}: ${l.message}`))}),u.on("close",l=>{if(clearTimeout(S),l===0)return m(`${h}
|
|
69
69
|
${i}`.trim());$(new Error(`${t.command} MCP setup exited ${l}: ${i.trim().split(`
|
|
70
|
-
`).pop()||"failed"}`))});try{u.stdin.end()}catch{}})}function kt(t,n){const e=String(n?.message||n||"");return/mcp['" ]* Python SDK|No module named ['"]?mcp|MCP support/i.test(e)?`${t} has no MCP support installed. Run \`hermes setup\` (or install the \`mcp\` package in its environment), then retry.`:/streamable_http|HTTP transport/i.test(e)?`${t}'s MCP client has no HTTP transport; ChatPanel registers a stdio server instead. Upgrade its \`mcp\` package if this persists.`:e.slice(0,200)||"the CLI could not register the tools"}async function Lt(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const s=o.hasConfig||Pt,d=o.runSetup||vt;if(await s(t,n))return!0;const f=bt(t);if(!t.autoSetupStableMcp){const m=`${e} needs one-time browser-tool setup: ${f}`;throw r({type:"status",text:m}),new Error(m)}const g=
|
|
71
|
-
`).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${f}`)}async function Qt({messages:t,system:n,options:e,images:r},o,{signal:s}={}){if(!await D(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return _t(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:s})}async function _t(t,{messages:n,system:e,options:r={},images:o},s,{signal:d}={}){if(!t.command)throw new Error("This agent has no command configured.");const f=L(t.command);if(!f)throw new Error(U(t.command,{platform:process.platform}));let g=it(n,e),y=ut(r.workingDir);const m=t.label||t.command,$=Object.hasOwn(mt,t.format)?t.format:"text",u=t.promptVia==="arg"?"arg":"stdin";let i=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];if(lt(i,r.extraArgs,H[t.forbidden]||H.custom,s),r.model&&t.modelArg){const a=String(t.modelArg),c=a.includes("{model}")?a.replaceAll("{model}",r.model).split(/\s+/).filter(Boolean):[...a.split(/\s+/).filter(Boolean),r.model];i=[...i,...c]}if(t.permissionArgs){const a=String(r.permissionMode||"default"),c=t.permissionArgs[a]||t.permissionArgs.default||[];i=[...i,...c.map(String)]}i=[...i,...nt({harness:t.dirsHarness||t.command,roots:rt(y),dirs:t.dirs!==void 0?t.dirs:r.dirs})];const h=`${Date.now()}-${Math.random().toString(36).slice(2)}`,S=t.imageArg?await dt(o,h):[],l=[],M=()=>[...S,...l].forEach(a=>Y(a).catch(()=>{}));if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const a=await Mt(r.mcp,h);l.push(a),i=[...yt(a,r.mcp),...i]}else if(r.mcp?.url&&t.mcpArg){const a=r.mcp.serverName||"chatpanel_browser",{command:c,args:p}=tt(r.mcp.url),w=
|
|
70
|
+
`).pop()||"failed"}`))});try{u.stdin.end()}catch{}})}function kt(t,n){const e=String(n?.message||n||"");return/mcp['" ]* Python SDK|No module named ['"]?mcp|MCP support/i.test(e)?`${t} has no MCP support installed. Run \`hermes setup\` (or install the \`mcp\` package in its environment), then retry.`:/streamable_http|HTTP transport/i.test(e)?`${t}'s MCP client has no HTTP transport; ChatPanel registers a stdio server instead. Upgrade its \`mcp\` package if this persists.`:e.slice(0,200)||"the CLI could not register the tools"}async function Lt(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const s=o.hasConfig||Pt,d=o.runSetup||vt;if(await s(t,n))return!0;const f=bt(t);if(!t.autoSetupStableMcp){const m=`${e} needs one-time browser-tool setup: ${f}`;throw r({type:"status",text:m}),new Error(m)}const g=xt(t);if(!g?.command){const m=`${e} needs one-time browser-tool setup: ${f}`;throw r({type:"status",text:m}),new Error(m)}r({type:"status",text:`${e} is setting up one-time browser tools...`});const y=String(await d(g,n)||"").trim();if(await s(t,n))return!0;throw new Error(`${e} browser-tool setup did not register the server.`+(y?` ${y.split(`
|
|
71
|
+
`).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${f}`)}async function Qt({messages:t,system:n,options:e,images:r},o,{signal:s}={}){if(!await D(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return _t(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:s})}async function _t(t,{messages:n,system:e,options:r={},images:o},s,{signal:d}={}){if(!t.command)throw new Error("This agent has no command configured.");const f=L(t.command);if(!f)throw new Error(U(t.command,{platform:process.platform}));let g=it(n,e),y=ut(r.workingDir);const m=t.label||t.command,$=Object.hasOwn(mt,t.format)?t.format:"text",u=t.promptVia==="arg"?"arg":"stdin";let i=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];if(lt(i,r.extraArgs,H[t.forbidden]||H.custom,s),r.model&&t.modelArg){const a=String(t.modelArg),c=a.includes("{model}")?a.replaceAll("{model}",r.model).split(/\s+/).filter(Boolean):[...a.split(/\s+/).filter(Boolean),r.model];i=[...i,...c]}if(t.permissionArgs){const a=String(r.permissionMode||"default"),c=t.permissionArgs[a]||t.permissionArgs.default||[];i=[...i,...c.map(String)]}i=[...i,...nt({harness:t.dirsHarness||t.command,roots:rt(y),dirs:t.dirs!==void 0?t.dirs:r.dirs})];const h=`${Date.now()}-${Math.random().toString(36).slice(2)}`,S=t.imageArg?await dt(o,h):[],l=[],M=()=>[...S,...l].forEach(a=>Y(a).catch(()=>{}));if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const a=await Mt(r.mcp,h);l.push(a),i=[...yt(a,r.mcp),...i]}else if(r.mcp?.url&&t.mcpArg){const a=r.mcp.serverName||"chatpanel_browser",{command:c,args:p}=tt(r.mcp.url),w=A.join(T.tmpdir(),`chatpanel-mcp-${h}.json`);await k(w,JSON.stringify({mcpServers:{[a]:{command:c,args:p}}})),l.push(w);const b=String(t.mcpArg);i=[...b.includes("{file}")?b.replaceAll("{file}",w).split(/\s+/).filter(Boolean):[...b.split(/\s+/).filter(Boolean),w],...i]}if(r.mcp?.url)try{await Lt(t,y,m,s)}catch(a){s({type:"status",text:`${m}: continuing without ChatPanel's browser tools — ${kt(m,a)}`}),r={...r,mcp:null}}if(r.mcp?.url&&i.push(...$t(t,r.mcp)),r.model&&typeof t.modelPatch?.build=="function"){const a=/^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(r.model))?String(r.model):"";if(a){const c=A.join(T.tmpdir(),`chatpanel-modelpatch-${h}.yml`);await k(c,t.modelPatch.build(a)),l.push(c);const p=String(t.modelPatch.arg||"--patch {file}");i=[...p.includes("{file}")?p.replaceAll("{file}",c).split(/\s+/).filter(Boolean):[...p.split(/\s+/).filter(Boolean),c],...i]}}const C=ft(t.imageArg,S);let N=!1;if(C.length&&(i=i.flatMap(a=>a==="{images}"?(N=!0,C):[a])),u==="arg"){const a=i.reduce((w,b)=>w+String(b).length+3,0)+C.reduce((w,b)=>w+String(b).length+3,0),c=st(n,e,at({viaCmdExe:f.kind==="cmd",otherArgsChars:a}));(c.dropped||c.prompt!==g)&&(g=c.prompt,s({type:"status",text:`${m} takes the prompt as a command-line argument, which this system caps — the oldest ${c.dropped||"part of the"} turn${c.dropped===1?"":"s"} of this conversation ${c.dropped?"were":"was"} left out to fit.`}));let p=!1;i=i.map(w=>w.includes("{prompt}")?(p=!0,w.replaceAll("{prompt}",g)):w),p||(C.length&&!N&&i.push(...C),i.push(g))}else C.length&&!N&&i.push(...C);const[Z,q,R]=_(f,i,y,r.runEnv||null);R.env={...R.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const E=await I().wrap(Z,q,R,{engine:t.sandboxEngine||"custom",cwd:y});et(s,E.record);const[V,W,X]=[E.bin,E.argv,E.opts];await new Promise((a,c)=>{let p;try{p=F(v(V,W,X),E,{kind:"agent"})}catch(x){return M(),c(new Error(`Failed to start ${m}: ${x.message}`))}const w=ot(p,d);let b="";const O=ct($,s);let P;const B=()=>{clearTimeout(P),P=setTimeout(()=>{p.kill("SIGKILL"),M(),c(new Error(`${m} timed out — no output for ${Math.round(J/1e3)}s.`))},J)};B(),p.stdout.on("data",x=>{B(),O.push(x.toString())}),p.stderr.on("data",x=>{B(),b+=x.toString()}),p.on("error",x=>{clearTimeout(P),w(),M(),c(new Error(`Failed to start ${m}: ${x.message}`))}),p.on("close",x=>{if(clearTimeout(P),w(),M(),d?.aborted){a();return}x===0?(s({type:"done",text:O.streamed?"":O.finish()}),a()):c(pt(m,x,b))}),u==="stdin"&&p.stdin.write(g),p.stdin.end()})}export{j as CHATPANEL_STABLE_MCP_URL,Wt as available,At as buildPiExtensionSource,Qt as chat,K as commandOutput,Lt as ensureStableMcpConfig,Xt as listModels,wt as listSpecModels,kt as mcpSetupHint,$t as mcpTrustArgs,yt as piToolArgs,St as runForStdout,_t as runSpec,bt as stableMcpSetupCommand,xt as stableMcpSetupPlan,Ct as trustToolArgs};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as L}from"./event.js";import{normalizeGrant as y,SIGN_IN_NAMES as P,SIGN_IN_LABELS as x}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as T,SECRET_DIR_PAIRS as H}from"./secret-names.js";const k=Object.freeze(["none","process","container","kubernetes","external"]),N=Object.freeze(["open","allowlist","none","gateway"]),S=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},O=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),A=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},G=S.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function W(e,t=""){const n=m(g(O(g(e),t)));if(!n)return!1;for(const o of S)if(A(n,o)||t&&A(n,O(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return G.some(o=>{for(let s=0;s+o.length<=r.length;s+=1)if(o.every((l,c)=>l.toLowerCase()===r[s+c]))return!0;return!1})}const j=Object.freeze([...[...T].map(e=>`~/**/${e}`),...H.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 ae(e,{home:t="",globs:n=[...S,...j]}={}){const r=m(g(O(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),s=m(g(t));for(const l of n){const c=m(g(l));if(c){if(c.startsWith("~/**/")){if(s&&!A(r,s))continue;const a=c.slice(5).split("/").filter(Boolean).map(K);for(let i=0;i+a.length<=o.length;i+=1)if(a.every((d,u)=>d.test(o[i+u])))return l;continue}if(A(r,O(c,t)))return l}}return null}function K(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const C=".cache/chatpanel/ca-bundle.crt",ce=".cache/chatpanel/ca-bundle.pem";function le(e=""){const t=m(g(e));return t?`${t}/${C}`:`~/${C}`}const B=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"]),v=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"],keychain:!0,sockets:["/tmp/cc-socks","/private/tmp/cc-socks"]}),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:[]})}),M="~/Library/Keychains",U=/(^|\/)Keychains\/?$/,I=Object.freeze({aws:Object.freeze({label:x.aws,where:"~/.aws",read:["~/.aws","~/.aws/credentials","~/.aws/sso"],hosts:["*.amazonaws.com","*.api.aws"],failure:/could not load (aws )?credentials|unable to locate credentials|CredentialsProviderError|NoCredentialProviders|failed to refresh cached credentials|aws credentials? (not found|could not be)/i}),oci:Object.freeze({label:x.oci,where:"~/.oci",read:["~/.oci","~/.oci/**/*.pem"],hosts:["*.oraclecloud.com"],failure:/could not find config file at .*\.oci|ConfigFileNotFound|oci config(uration)? (file )?(was )?not found|\.oci[\\/]config.*(not found|no such file|not permitted|permission denied)/i}),gcloud:Object.freeze({label:x.gcloud,where:"~/.config/gcloud",read:["~/.config/gcloud"],hosts:["*.googleapis.com","accounts.google.com"],failure:/could not load the default credentials|DefaultCredentialsError|could not (automatically )?(find|determine) (default )?credentials|application default credentials (were|are) not (found|available)/i}),azure:Object.freeze({label:x.azure,where:"~/.azure",read:["~/.azure"],hosts:["*.azure.com","login.microsoftonline.com"],failure:/DefaultAzureCredential failed|CredentialUnavailableError|please run 'az login'|AzureCliCredential authentication (unavailable|failed)/i})});function D(e){return f((y(e).signIn||[]).flatMap(t=>I[t].read))}function Y(e){return f((y(e).signIn||[]).flatMap(t=>I[t].hosts))}function de(e,{grant:t=null,sandboxed:n=!0,agentLabel:r="This agent",agent:o=""}={}){if(!n)return null;let s=[];try{s=y(t).signIn||[]}catch{}const l=String(e||"");for(const c of P){const a=I[c];if(!(s.includes(c)||!a.failure.test(l)))return{store:c,line:`${r} could not sign in to ${a.label}: the ChatPanel sandbox keeps your ${a.label} sign-in (${a.where}) from every agent until you allow it. To allow it for this agent only, turn on ${a.label} under "May sign in with" in its Coding Agents settings${o?`, or run: chatpanel-gateway sandbox allow ${o} ${c}`:""}. Nothing else it is denied changes.`}}return null}const F=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"]),E=e=>!!e&&typeof e=="object"&&!Array.isArray(e),_=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),p=(e,t)=>{if(!e)throw new L("SHAPE",t)},f=e=>[...new Set(e)];function $(e){p(E(e),"kit: must be an object"),p(typeof e.id=="string"&&e.id.length>0,"kit: id required"),p(E(e.network)&&N.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${N.join(", ")}`),p(_(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),p(_(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),p(E(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])p(_(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return p(_(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),p(_(e.network.unixSockets||[])&&(e.network.unixSockets||[]).every(t=>t.startsWith("/")&&t.replace(/\/+$/,"")!==""),`kit ${e.id}: network.unixSockets must be absolute folders, never /`),e.image!=null&&p(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&p(Array.isArray(e.credentials)&&e.credentials.every(t=>E(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:f(e.network.allowedDomains||[]),deniedDomains:f(e.network.deniedDomains||[]),...(e.network.unixSockets||[]).length?{unixSockets:f(e.network.unixSockets)}:{}},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:E(e.limits)?{...e.limits}:{}}}import{normalizeGrant as xe,mergeGrants as Se,mergePersonGrants as Oe,parseHostList as Ae,SIGN_IN_NAMES as Re,SIGN_IN_LABELS as Ie}from"./sandbox-grant.js";import{SANDBOX_READ_MODES as ke,SANDBOX_RUNTIMES as Ne,parseWrapperTemplate as We,expandWrapper as je}from"./sandbox-choice.js";const X=e=>String(e).replace(/([\\/])\*$/,"$1**");function q({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:s=[],grant:l=null,home:c="",reads:a="enumerated",readOnly:i=!1,peers:d=!0}={}){const u=v[e]||v.custom;p(typeof t=="string"&&t.length>0,"kit: cwd required");const h=y(l);return $({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:f([...u.hosts,...F,...r,...h.hosts,...Y(h)]),deniedDomains:[],unixSockets:d?[...u.sockets||[]]:[]},filesystem:{allowWrite:f(i?[...z,...u.write]:[t,...z,...u.write,...[...o,...h.write].filter(R=>!W(R,c)).map(X)]),denyWrite:[],allowRead:f(a==="inverted"?[t,...B,...u.write,...u.keychain?[M]:[],...Z({grant:h,extraWrite:o,cwd:t,home:c}),...D(h)]:[t,...D(h)]),denyRead:f([...a==="inverted"?["~",...c?[c]:[]]:[],...[...S,...j].filter(R=>!(u.keychain&&U.test(R))),...s])}})}const V=Object.freeze({noWrite:Object.freeze(["runtime/sandbox-runtime","runtime/ort","bin","node_modules","package.json","package-lock.json","git-hooks","policy.json","bridge-token","agent-threads.json","update-check.json","launch.vbs","workspace","worktrees","channels","desktop","cli","actions-runner","release.env"]),noRead:Object.freeze(["channels","desktop","cli","actions-runner","release.env","workspace","worktrees"])});function ue({stateDir:e,codeDirs:t=[],home:n="",mode:r="open",hosts:o=[],scratch:s=[],fence:l=V}={}){p(typeof e=="string"&&e.length>1,"gateway kit: stateDir required");const c=q({engine:"custom",cwd:e,mode:r,extraHosts:o,home:n,reads:"inverted",peers:!1}),a=u=>typeof u=="string"&&u.startsWith("/")&&u.replace(/\/+$/,"")!==""&&u!==n,i=t.filter(a),d=u=>`${e.replace(/\/+$/,"")}/${u}`;return $({...c,id:`gateway:${r}`,filesystem:{...c.filesystem,allowWrite:f([e,"/tmp","/private/tmp",...s.filter(a)]),denyWrite:f([...i,...l.noWrite.map(d)]),allowRead:f([...c.filesystem.allowRead,...i]),denyRead:f([...c.filesystem.denyRead,...l.noRead.map(d)])}})}function Q(e){if(!/[*?[{]/.test(e))return e;const t=e.split(/[\\/]/),n=t.findIndex(s=>/[*?[{]/.test(s)),r=e.includes("\\")&&!e.includes("/")?"\\":"/",o=t.slice(0,n).join(r);return o&&o!=="~"?o:""}function Z({grant:e=null,extraWrite:t=[],cwd:n="",home:r=""}={}){const o=i=>r&&(i==="~"||i.startsWith("~/")||i.startsWith("~\\"))?r+i.slice(1):i,s=i=>{let d=String(i||"").trim();for(;d.length>1&&(d.endsWith("/")||d.endsWith("\\"));)d=d.slice(0,-1);return d},l=(i,d)=>i===d||i.startsWith(`${d}/`)||i.startsWith(`${d}\\`),c=s(o(n)),a=[];for(const i of[...y(e).write,...Array.isArray(t)?t:[]]){const d=Q(s(o(s(i))));if(d&&!W(d,r)&&!(c&&l(d,c))&&!a.some(u=>l(d,u))){for(let u=a.length-1;u>=0;u--)l(a[u],d)&&a.splice(u,1);a.push(d)}}return a}function fe(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=$(e),s=c=>n&&c.startsWith("~")?n+c.slice(1):c,l=o.network.mode==="none"?[]:t.map(c=>`127.0.0.1:${c}`);return{network:{allowedDomains:f([...o.network.allowedDomains,...l]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&l.length>0,...r==="darwin"&&o.network.unixSockets?.length?{allowUnixSockets:o.network.unixSockets}:{}},filesystem:{denyRead:o.filesystem.denyRead.map(s),allowRead:o.filesystem.allowRead.map(s),allowWrite:o.filesystem.allowWrite.map(s),denyWrite:o.filesystem.denyWrite.map(s)}}}function pe({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:s=null}={}){return p(k.includes(e),`sandbox record: layer must be one of ${k.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function J(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){p(!/[\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 s=0;for(;o<n.length&&n[o]==="\\";)s++,o++;if(o===n.length){r+="\\".repeat(s*2);break}n[o]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+n[o]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return n===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}const ee=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function ge(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of ee)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(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function me(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>J(r,{platform:n})).join(" ")}const we=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),te=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function b(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function ne(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 he({kit:e,files:t=[],home:n}){p(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 i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(p(!te(i)&&w(i)!==w(n),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),b(i,n)&&o.push(i))}const s=(a,i)=>i.some(d=>w(a)===w(d)||b(a,d)),l=[];for(const a of t){const i=ne(a);i&&b(i,n)&&l.push(i)}for(const a of e?.filesystem?.allowRead||[]){if(/[*?[]/.test(a))continue;const i=r(a);b(i,n)&&l.push(i)}const c=f(l).filter(a=>!s(a,o));return{read:c.filter(a=>!c.some(i=>i!==a&&b(a,i))),write:f(o)}}const oe=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 ye({engine:e="custom",home:t,env:n={},base:r={},carry:o=oe}={}){p(typeof t=="string"&&t.length>0,"windows env: home required");const s=t.replace(/\//g,"\\"),l=/^[a-z]:/i.test(s)?s.slice(0,2):"",c={USERPROFILE:s,...l?{HOMEDRIVE:l,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(n))typeof i=="string"&&(r[a]!==i||o.includes(a))&&(c[a]=i);return e==="codex"&&!c.CODEX_HOME&&(c.CODEX_HOME=s+"\\.codex"),c}function Ee(e,t){p(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;p(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let l=n+1;l<r;l++)e[l]==="--env"&&typeof e[l+1]=="string"&&o.add(e[l+1].split("=")[0].toUpperCase());const s=[];for(const[l,c]of Object.entries(t||{}))p(/^[A-Za-z_][A-Za-z0-9_]*$/.test(l),`srt-win env: bad key ${l}`),p(!/[\r\n]/.test(c),`srt-win env: ${l} holds a newline`),o.has(l.toUpperCase())||s.push("--env",`${l}=${c}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{C as CA_BUNDLE_RELPATH,ce as CA_BUNDLE_RELPATH_LEGACY,z as COMMON_WRITE,F as DEVELOPER_HOSTS,v as ENGINE_KITS,V as GATEWAY_FENCE,N as NETWORK_MODES,k as SANDBOX_LAYERS,ke as SANDBOX_READ_MODES,Ne as SANDBOX_RUNTIMES,S as SECRET_PATHS,j as SECRET_READ_GLOBS,Ie as SIGN_IN_LABELS,Re as SIGN_IN_NAMES,I as SIGN_IN_STORES,B as TOOLCHAIN_READ,oe as WINDOWS_CARRY_KEYS,le as caBundlePath,je as expandWrapper,ue as gatewayKit,W as isSecretWritePath,q as kitFor,Se as mergeGrants,Oe as mergePersonGrants,xe as normalizeGrant,Ae as parseHostList,We as parseWrapperTemplate,ae as readDenialFor,ge as sandboxEnvOverlay,pe as sandboxRecord,me as shellJoin,J as shellQuote,de as signInDenial,Y as signInHosts,D as signInRead,fe as toSrtSettings,b as underWindowsHome,$ as validateKit,he as windowsGrantsFor,ne as windowsInstallRoot,ye as windowsSandboxEnv,Ee as withSrtWinEnv,Z as writableRoots};
|
|
1
|
+
import{EventError as L}from"./event.js";import{normalizeGrant as y,SIGN_IN_NAMES as P,SIGN_IN_LABELS as x}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as T,SECRET_DIR_PAIRS as H}from"./secret-names.js";const k=Object.freeze(["none","process","container","kubernetes","external"]),N=Object.freeze(["open","allowlist","none","gateway"]),O=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},S=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),A=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},G=O.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function j(e,t=""){const n=m(g(S(g(e),t)));if(!n)return!1;for(const o of O)if(A(n,o)||t&&A(n,S(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return G.some(o=>{for(let s=0;s+o.length<=r.length;s+=1)if(o.every((l,c)=>l.toLowerCase()===r[s+c]))return!0;return!1})}const W=Object.freeze([...[...T].map(e=>`~/**/${e}`),...H.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 ae(e,{home:t="",globs:n=[...O,...W]}={}){const r=m(g(S(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),s=m(g(t));for(const l of n){const c=m(g(l));if(c){if(c.startsWith("~/**/")){if(s&&!A(r,s))continue;const a=c.slice(5).split("/").filter(Boolean).map(K);for(let i=0;i+a.length<=o.length;i+=1)if(a.every((d,u)=>d.test(o[i+u])))return l;continue}if(A(r,S(c,t)))return l}}return null}function K(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const C=".cache/chatpanel/ca-bundle.crt",ce=".cache/chatpanel/ca-bundle.pem";function le(e=""){const t=m(g(e));return t?`${t}/${C}`:`~/${C}`}const B=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"]),v=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"],keychain:!0,sockets:["/tmp/cc-socks","/private/tmp/cc-socks"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),opencode:Object.freeze({hosts:[],write:["~/.local/share/opencode","~/.config/opencode"]}),copilot:Object.freeze({hosts:["api.githubcopilot.com","*.githubcopilot.com","api.github.com","github.com"],write:["~/.copilot"]}),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:[]})}),M="~/Library/Keychains",U=/(^|\/)Keychains\/?$/,I=Object.freeze({aws:Object.freeze({label:x.aws,where:"~/.aws",read:["~/.aws","~/.aws/credentials","~/.aws/sso"],hosts:["*.amazonaws.com","*.api.aws"],failure:/could not load (aws )?credentials|unable to locate credentials|CredentialsProviderError|NoCredentialProviders|failed to refresh cached credentials|aws credentials? (not found|could not be)/i}),oci:Object.freeze({label:x.oci,where:"~/.oci",read:["~/.oci","~/.oci/**/*.pem"],hosts:["*.oraclecloud.com"],failure:/could not find config file at .*\.oci|ConfigFileNotFound|oci config(uration)? (file )?(was )?not found|\.oci[\\/]config.*(not found|no such file|not permitted|permission denied)/i}),gcloud:Object.freeze({label:x.gcloud,where:"~/.config/gcloud",read:["~/.config/gcloud"],hosts:["*.googleapis.com","accounts.google.com"],failure:/could not load the default credentials|DefaultCredentialsError|could not (automatically )?(find|determine) (default )?credentials|application default credentials (were|are) not (found|available)/i}),azure:Object.freeze({label:x.azure,where:"~/.azure",read:["~/.azure"],hosts:["*.azure.com","login.microsoftonline.com"],failure:/DefaultAzureCredential failed|CredentialUnavailableError|please run 'az login'|AzureCliCredential authentication (unavailable|failed)/i})});function D(e){return f((y(e).signIn||[]).flatMap(t=>I[t].read))}function Y(e){return f((y(e).signIn||[]).flatMap(t=>I[t].hosts))}function de(e,{grant:t=null,sandboxed:n=!0,agentLabel:r="This agent",agent:o=""}={}){if(!n)return null;let s=[];try{s=y(t).signIn||[]}catch{}const l=String(e||"");for(const c of P){const a=I[c];if(!(s.includes(c)||!a.failure.test(l)))return{store:c,line:`${r} could not sign in to ${a.label}: the ChatPanel sandbox keeps your ${a.label} sign-in (${a.where}) from every agent until you allow it. To allow it for this agent only, turn on ${a.label} under "May sign in with" in its Coding Agents settings${o?`, or run: chatpanel-gateway sandbox allow ${o} ${c}`:""}. Nothing else it is denied changes.`}}return null}const F=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"]),E=e=>!!e&&typeof e=="object"&&!Array.isArray(e),b=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),p=(e,t)=>{if(!e)throw new L("SHAPE",t)},f=e=>[...new Set(e)];function $(e){p(E(e),"kit: must be an object"),p(typeof e.id=="string"&&e.id.length>0,"kit: id required"),p(E(e.network)&&N.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${N.join(", ")}`),p(b(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),p(b(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),p(E(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])p(b(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return p(b(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),p(b(e.network.unixSockets||[])&&(e.network.unixSockets||[]).every(t=>t.startsWith("/")&&t.replace(/\/+$/,"")!==""),`kit ${e.id}: network.unixSockets must be absolute folders, never /`),e.image!=null&&p(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&p(Array.isArray(e.credentials)&&e.credentials.every(t=>E(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:f(e.network.allowedDomains||[]),deniedDomains:f(e.network.deniedDomains||[]),...(e.network.unixSockets||[]).length?{unixSockets:f(e.network.unixSockets)}:{}},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:E(e.limits)?{...e.limits}:{}}}import{normalizeGrant as xe,mergeGrants as Oe,mergePersonGrants as Se,parseHostList as Ae,SIGN_IN_NAMES as Re,SIGN_IN_LABELS as Ie}from"./sandbox-grant.js";import{SANDBOX_READ_MODES as ke,SANDBOX_RUNTIMES as Ne,parseWrapperTemplate as je,expandWrapper as We}from"./sandbox-choice.js";const X=e=>String(e).replace(/([\\/])\*$/,"$1**");function q({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:s=[],grant:l=null,home:c="",reads:a="enumerated",readOnly:i=!1,peers:d=!0}={}){const u=v[e]||v.custom;p(typeof t=="string"&&t.length>0,"kit: cwd required");const h=y(l);return $({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:f([...u.hosts,...F,...r,...h.hosts,...Y(h)]),deniedDomains:[],unixSockets:d?[...u.sockets||[]]:[]},filesystem:{allowWrite:f(i?[...z,...u.write]:[t,...z,...u.write,...[...o,...h.write].filter(R=>!j(R,c)).map(X)]),denyWrite:[],allowRead:f(a==="inverted"?[t,...B,...u.write,...u.keychain?[M]:[],...Z({grant:h,extraWrite:o,cwd:t,home:c}),...D(h)]:[t,...D(h)]),denyRead:f([...a==="inverted"?["~",...c?[c]:[]]:[],...[...O,...W].filter(R=>!(u.keychain&&U.test(R))),...s])}})}const V=Object.freeze({noWrite:Object.freeze(["runtime/sandbox-runtime","runtime/ort","bin","node_modules","package.json","package-lock.json","git-hooks","policy.json","bridge-token","agent-threads.json","update-check.json","launch.vbs","workspace","worktrees","channels","desktop","cli","actions-runner","release.env"]),noRead:Object.freeze(["channels","desktop","cli","actions-runner","release.env","workspace","worktrees"])});function ue({stateDir:e,codeDirs:t=[],home:n="",mode:r="open",hosts:o=[],scratch:s=[],fence:l=V}={}){p(typeof e=="string"&&e.length>1,"gateway kit: stateDir required");const c=q({engine:"custom",cwd:e,mode:r,extraHosts:o,home:n,reads:"inverted",peers:!1}),a=u=>typeof u=="string"&&u.startsWith("/")&&u.replace(/\/+$/,"")!==""&&u!==n,i=t.filter(a),d=u=>`${e.replace(/\/+$/,"")}/${u}`;return $({...c,id:`gateway:${r}`,filesystem:{...c.filesystem,allowWrite:f([e,"/tmp","/private/tmp",...s.filter(a)]),denyWrite:f([...i,...l.noWrite.map(d)]),allowRead:f([...c.filesystem.allowRead,...i]),denyRead:f([...c.filesystem.denyRead,...l.noRead.map(d)])}})}function Q(e){if(!/[*?[{]/.test(e))return e;const t=e.split(/[\\/]/),n=t.findIndex(s=>/[*?[{]/.test(s)),r=e.includes("\\")&&!e.includes("/")?"\\":"/",o=t.slice(0,n).join(r);return o&&o!=="~"?o:""}function Z({grant:e=null,extraWrite:t=[],cwd:n="",home:r=""}={}){const o=i=>r&&(i==="~"||i.startsWith("~/")||i.startsWith("~\\"))?r+i.slice(1):i,s=i=>{let d=String(i||"").trim();for(;d.length>1&&(d.endsWith("/")||d.endsWith("\\"));)d=d.slice(0,-1);return d},l=(i,d)=>i===d||i.startsWith(`${d}/`)||i.startsWith(`${d}\\`),c=s(o(n)),a=[];for(const i of[...y(e).write,...Array.isArray(t)?t:[]]){const d=Q(s(o(s(i))));if(d&&!j(d,r)&&!(c&&l(d,c))&&!a.some(u=>l(d,u))){for(let u=a.length-1;u>=0;u--)l(a[u],d)&&a.splice(u,1);a.push(d)}}return a}function fe(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=$(e),s=c=>n&&c.startsWith("~")?n+c.slice(1):c,l=o.network.mode==="none"?[]:t.map(c=>`127.0.0.1:${c}`);return{network:{allowedDomains:f([...o.network.allowedDomains,...l]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&l.length>0,...r==="darwin"&&o.network.unixSockets?.length?{allowUnixSockets:o.network.unixSockets}:{}},filesystem:{denyRead:o.filesystem.denyRead.map(s),allowRead:o.filesystem.allowRead.map(s),allowWrite:o.filesystem.allowWrite.map(s),denyWrite:o.filesystem.denyWrite.map(s)}}}function pe({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:s=null}={}){return p(k.includes(e),`sandbox record: layer must be one of ${k.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function J(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){p(!/[\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 s=0;for(;o<n.length&&n[o]==="\\";)s++,o++;if(o===n.length){r+="\\".repeat(s*2);break}n[o]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+n[o]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return n===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}const ee=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function ge(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of ee)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(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function me(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>J(r,{platform:n})).join(" ")}const we=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),te=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function _(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function ne(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 he({kit:e,files:t=[],home:n}){p(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 i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(p(!te(i)&&w(i)!==w(n),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),_(i,n)&&o.push(i))}const s=(a,i)=>i.some(d=>w(a)===w(d)||_(a,d)),l=[];for(const a of t){const i=ne(a);i&&_(i,n)&&l.push(i)}for(const a of e?.filesystem?.allowRead||[]){if(/[*?[]/.test(a))continue;const i=r(a);_(i,n)&&l.push(i)}const c=f(l).filter(a=>!s(a,o));return{read:c.filter(a=>!c.some(i=>i!==a&&_(a,i))),write:f(o)}}const oe=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 ye({engine:e="custom",home:t,env:n={},base:r={},carry:o=oe}={}){p(typeof t=="string"&&t.length>0,"windows env: home required");const s=t.replace(/\//g,"\\"),l=/^[a-z]:/i.test(s)?s.slice(0,2):"",c={USERPROFILE:s,...l?{HOMEDRIVE:l,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(n))typeof i=="string"&&(r[a]!==i||o.includes(a))&&(c[a]=i);return e==="codex"&&!c.CODEX_HOME&&(c.CODEX_HOME=s+"\\.codex"),c}function Ee(e,t){p(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;p(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let l=n+1;l<r;l++)e[l]==="--env"&&typeof e[l+1]=="string"&&o.add(e[l+1].split("=")[0].toUpperCase());const s=[];for(const[l,c]of Object.entries(t||{}))p(/^[A-Za-z_][A-Za-z0-9_]*$/.test(l),`srt-win env: bad key ${l}`),p(!/[\r\n]/.test(c),`srt-win env: ${l} holds a newline`),o.has(l.toUpperCase())||s.push("--env",`${l}=${c}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{C as CA_BUNDLE_RELPATH,ce as CA_BUNDLE_RELPATH_LEGACY,z as COMMON_WRITE,F as DEVELOPER_HOSTS,v as ENGINE_KITS,V as GATEWAY_FENCE,N as NETWORK_MODES,k as SANDBOX_LAYERS,ke as SANDBOX_READ_MODES,Ne as SANDBOX_RUNTIMES,O as SECRET_PATHS,W as SECRET_READ_GLOBS,Ie as SIGN_IN_LABELS,Re as SIGN_IN_NAMES,I as SIGN_IN_STORES,B as TOOLCHAIN_READ,oe as WINDOWS_CARRY_KEYS,le as caBundlePath,We as expandWrapper,ue as gatewayKit,j as isSecretWritePath,q as kitFor,Oe as mergeGrants,Se as mergePersonGrants,xe as normalizeGrant,Ae as parseHostList,je as parseWrapperTemplate,ae as readDenialFor,ge as sandboxEnvOverlay,pe as sandboxRecord,me as shellJoin,J as shellQuote,de as signInDenial,Y as signInHosts,D as signInRead,fe as toSrtSettings,_ as underWindowsHome,$ as validateKit,he as windowsGrantsFor,ne as windowsInstallRoot,ye as windowsSandboxEnv,Ee as withSrtWinEnv,Z as writableRoots};
|
package/src/mcp-local.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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
|
|
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 c=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[r,s]of Object.entries(n||{})){const o=String(s);t[r]=o==="~"?e:o.startsWith("~/")?k.join(e,o.slice(2)):o}return t}const T=n=>n.key||`${n.command}\0${(Array.isArray(n.args)?n.args.join(" "):n.args)||""}`,O=n=>JSON.stringify([n.command,Array.isArray(n.args)?n.args:String(n.args||""),n.env||{},n.cwd||null,n.sandbox||null]);function y(n,e){clearTimeout(n.idleTimer);for(const{reject:t,timer:r}of n.pending.values())clearTimeout(r),t(e);n.pending.clear(),c.get(n.key)===n&&c.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{}c.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
|
-
`).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function
|
|
5
|
-
`))>=0;){const I=
|
|
6
|
-
`);return e.id==null?(t(),Promise.resolve(null)):new Promise((
|
|
4
|
+
`).trim();return e?e.length>S?`…${e.slice(-S)}`:e:""}function M(n,e){const t=an(e?.stderr);return t?`${n}: ${t}`:n}const A=new Map,j=new Set;function Mn(){const n=[];for(const e of c.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=T(n),t=O(n);if(A.has(e)){const o=await A.get(e);if(o.sig===t)return o}const r=c.get(e);if(r&&r.child.exitCode==null&&!r.child.killed){if(r.sig===t)return f(r),r;y(r,new Error("local MCP server restarted: its configuration changed"))}const s=ln(n,e,t).finally(()=>A.delete(e));return A.set(e,s),s}async function ln(n,e,t=O(n)){const r=U(n.command);if(!r)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 d=a.indexOf("=");o[a.slice(0,d).trim()]=a.slice(d+1).trim()}const[p,h,u]=J(r,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 l=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,D,R]=[l.bin,l.argv,l.opts];l.record.layer==="none"&&!j.has(l.record.reason)&&(j.add(l.record.reason),console.error(`[bridge] local MCP "${n.command}" runs outside a sandbox — ${l.record.reason}`));const g=V(B(N,D,R),l,{kind:"mcp",label:e}),i={key:e,sig:t,child:g,command:n.command,sandbox:l.record,commandId:l.commandId,startedAt:Date.now(),pending:new Map,buf:"",stderr:"",idleTimer:null,initialized:!1,handshake:null,pendingSignIn:null,pendingSignInAt:0,signInIds:null},v=a=>y(i,a);return g.stdout.setEncoding("utf8"),g.stdout.on("data",a=>{i.buf+=a;let d;for(;(d=i.buf.indexOf(`
|
|
5
|
+
`))>=0;){const I=i.buf.slice(0,d).trim();if(i.buf=i.buf.slice(d+1),I[0]!=="{"&&I[0]!=="[")continue;let w;try{w=JSON.parse(I)}catch{continue}for(const m of Array.isArray(w)?w:[w]){m&&m.id!=null&&i.signInIds?.has(m.id)&&(i.signInIds.delete(m.id),i.signInIds.size||(i.pendingSignIn=null,i.signedInAt=Date.now(),f(i)));const P=m&&m.id!=null?i.pending.get(m.id):null;P&&(clearTimeout(P.timer),i.pending.delete(m.id),P.resolve(m))}}}),g.stderr.setEncoding("utf8"),g.stderr.on("data",a=>{i.stderr+=a,i.stderr.length>S*2&&(i.stderr=i.stderr.slice(-S*2)),i.pending.size&&(i.promptBuf=((i.promptBuf||"")+a).slice(-2e3),clearTimeout(i.promptTimer),i.promptTimer=setTimeout(()=>{const d=Q(i.promptBuf);d&&(i.promptBuf="",dn(i,d))},rn))}),g.on("error",a=>v(new Error(M(`local MCP "${n.command}" failed to start: ${a.message}`,i)))),g.on("close",(a,d)=>{const I=d?`exited with signal ${d}`:a==null?"exited":`exited with code ${a}`;v(new Error(M(`local MCP "${n.command}" ${I}`,i)))}),c.set(e,i),f(i),i}function dn(n,e){if(f(n),e.code&&(n.pendingSignIn=e,n.pendingSignInAt=Date.now(),n.signInIds=new Set(n.pending.keys()),f(n)),e.browser){for(const r of n.pending.values())clearTimeout(r.timer),r.timer=setTimeout(()=>{r.reject(new Error(M("local MCP call timed out waiting for the sign-in",n)))},tn);return}const t=x(e);for(const[r,s]of n.pending)clearTimeout(s.timer),n.pending.delete(r),s.resolve({jsonrpc:"2.0",id:r,error:t})}function _(n,e){const t=()=>n.child.stdin.write(JSON.stringify(e)+`
|
|
6
|
+
`);return e.id==null?(t(),Promise.resolve(null)):new Promise((r,s)=>{const o=setTimeout(()=>{n.pending.delete(e.id),s(new Error(M("local MCP call timed out",n)))},en);n.pending.set(e.id,{resolve:r,reject:s,timer:o}),t()})}function cn(n,e){return n.initialized?Promise.resolve():(n.handshake||(n.handshake=(async()=>{const t=await _(n,{jsonrpc:"2.0",id:`cp-init-${Date.now()}`,method:"initialize",params:e});if(t?.error)throw new Error(`local MCP re-initialize failed: ${t.error.message||t.error.code}`);await _(n,{jsonrpc:"2.0",method:"notifications/initialized"}),n.initialized=!0})().finally(()=>{n.handshake=null})),n.handshake)}async function An(n,{initializeParams:e=$}={}){const t=await z(n);if(t.pendingSignIn)return{state:"prompt",signIn:t.pendingSignIn,since:t.pendingSignInAt};await E(n,{jsonrpc:"2.0",id:`cp-si-init-${Date.now()}`,method:"initialize",params:e}).catch(()=>{});const s=(await E(n,{jsonrpc:"2.0",id:`cp-si-list-${Date.now()}`,method:"tools/list",params:{}}).catch(()=>null))?.result?.tools||[],o=Z(s);if(!o)return{state:"unsupported",error:"This server declares no read-only tool that takes no arguments, so there is nothing safe to call to make it sign in."};const p=await E(n,{jsonrpc:"2.0",id:`cp-si-${Date.now()}`,method:"tools/call",params:{name:o,arguments:{}}}).catch(l=>({error:{message:String(l?.message||l)}})),h=X(p?.error);if(h)return{state:"prompt",signIn:h,since:c.get(T(n))?.pendingSignInAt||Date.now(),probe:o};if(p?.error)return{state:"failed",error:p.error.message||"the server refused",probe:o};const u=c.get(T(n));return u&&(u.signedInAt=Date.now()),{state:"signed-in",probe:o}}function En(n){const e=c.get(T(n));return!e||e.child.exitCode!=null?{state:"gone"}:e.pendingSignIn?{state:"prompt",signIn:e.pendingSignIn,since:e.pendingSignInAt}:{state:e.signedInAt?"signed-in":"idle"}}function mn(n){const e=c.get(n);return e?(y(e,new Error("local MCP server stopped")),!0):!1}function Pn(){let n=0;for(const e of[...c.keys()])mn(e)&&(n+=1);return n}function bn(n){return c.get(n)||null}function _n(n){return b.has(n)}async function E(n,e){if(!n?.command)throw new Error("no command for local MCP server");const t=await z(n);if(f(t),e.method==="initialize")b.set(t.key,e.params||{}),t.initialized=!0;else if(e.method!=="notifications/initialized"){if(e.id!=null&&t.pendingSignIn&&Date.now()-t.pendingSignInAt<on)return{jsonrpc:"2.0",id:e.id,error:x(t.pendingSignIn)};if(e.id!=null&&t.pendingSignIn)return y(t,new Error("local MCP sign-in expired: starting a new one")),E(n,e);t.initialized||await cn(t,b.get(t.key)||$)}return _(t,e)}export{bn as _procForTest,E as callLocalMcp,_n as hasInitParams,Mn as localMcpStatus,An as signInLocalMcp,En as signInStatusLocalMcp,Pn as stopAllLocalMcp,mn as stopLocalMcp};
|
package/src/pii/pii-detect.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{assertEndpointUrl as
|
|
1
|
+
import{assertEndpointUrl as y}from"./net.js";const N=new Map,D=300;function J(){N.clear()}function w(n,t){let o=5381;const i=`${t?.backend}|${t?.url}|${t?.model}|${t?.strictness||""}|${JSON.stringify(t?.types||null)}|${n}`;for(let e=0;e<i.length;e++)o=(o<<5)+o+i.charCodeAt(e)|0;return`${i.length}:${o}`}function C(n,t,o){return new Promise((i,e)=>{const r=setTimeout(()=>e(new Error("detect timeout")),Math.max(200,t||1500)),a=()=>{clearTimeout(r),e(new Error("aborted"))};o&&o.addEventListener?.("abort",a,{once:!0}),n.then(s=>{clearTimeout(r),i(s)},s=>{clearTimeout(r),e(s)})})}function d(n){const t=String(n||"ENTITY").toUpperCase().replace(/[^A-Z0-9]/g,"")||"ENTITY";return{PER:"PERSON",PERSON:"PERSON",PERSONNAME:"PERSON",PRIVATEPERSON:"PERSON",GIVENNAME:"PERSON",FIRSTNAME:"PERSON",MIDDLENAME:"PERSON",SURNAME:"PERSON",LASTNAME:"PERSON",FULLNAME:"PERSON",ORG:"ORG",ORGANIZATION:"ORG",COMPANYNAME:"ORG",COMPANY:"ORG",GPE:"LOCATION",LOC:"LOCATION",LOCATION:"LOCATION",CITY:"LOCATION",STATE:"LOCATION",COUNTY:"LOCATION",COUNTRY:"LOCATION",STREET:"ADDRESS",BUILDINGNUM:"ADDRESS",BUILDINGNUMBER:"ADDRESS",ZIPCODE:"ADDRESS",POSTCODE:"ADDRESS",SECADDRESS:"ADDRESS",ADDRESS:"ADDRESS",PRIVATEADDRESS:"ADDRESS",NORP:"GROUP",EMAIL:"EMAIL",EMAILADDRESS:"EMAIL",PRIVATEEMAIL:"EMAIL",PHONE:"PHONE",PHONENUMBER:"PHONE",TELEPHONENUM:"PHONE",PRIVATEPHONE:"PHONE",PHONEIMEI:"ID",SOCIALNUM:"SSN",USSSN:"SSN",SSN:"SSN",CREDITCARDNUMBER:"CREDITCARD",CREDITCARD:"CREDITCARD",IBAN:"IBAN",IBANCODE:"IBAN",ACCOUNTNUM:"ID",ACCOUNTNUMBER:"ID",TAXNUM:"ID",IDCARDNUM:"ID",DRIVERLICENSENUM:"ID",PASSPORTNUM:"ID",VEHICLEVRM:"ID",DATEOFBIRTH:"ID",DOB:"ID",PRIVATEDATE:"ID",PRIVATEURL:"ID",USERNAME:"ID",USERID:"ID",IP:"ID",IPADDRESS:"ID",MAC:"ID",PASSWORD:"SECRET",APIKEY:"SECRET",SECRET:"SECRET"}[t]||t}const g=new Set(["EMAIL","PHONE","SSN","CREDITCARD","IBAN","ID","SECRET"]),R=new Set(["LOCATION","FAC","ADDRESS","GROUP","NRP"]),P=/(?:^|[\s$€£])\$?\d+(?:[.,]\d+)?\s?(?:[kmb]n?|mm|million|billion|thousand|%)(?=[\s.,;:!?)]|$)/i,L=/(?:^|\s)\d{1,6}(?=\s|,|$)/;function M(n){const t=String(n||"").trim();return P.test(t)&&!L.test(t)}const W=Object.freeze(["balanced","strict"]),b=n=>n?.strictness==="strict"||n?.detection?.strictness==="strict"?"strict":"balanced",p=new Set(["chap","chatpanel"]),U=new Set(["by","hey"]);function k(n){const t=String(n||"").toLowerCase().match(new RegExp("\\p{L}[\\p{L}\\p{N}]*","gu"))||[];return t.some(o=>p.has(o))&&t.every(o=>p.has(o)||U.has(o))}const O=new Set(["in","near","around","outside"]),$=new Set([...O,"at","the","a","an","to","from","for","and","of","on"]),v=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function x(n,t,o="",i=null){let e=String(n||"").trim(),r=t;const a=e.split(/\s+/);let s=!1;for(;a.length>1&&$.has(a[0].toLowerCase());)O.has(a[0].toLowerCase())&&(s=!0),a.shift();return e=a.join(" "),r!=="PERSON"||i?.location===!1||/['’]s$/i.test(e)?{value:e,type:r}:(!s&&o&&(s=new RegExp(`(?:^|[^\\p{L}])(?:${[...O].join("|")})\\s+${v(e)}(?!['’]s\\b)(?=$|[^\\p{L}])`,"iu").test(String(o))),{value:e,type:s?"LOCATION":r})}function H(n,t,o){if(Math.abs(n.length-t.length)>o)return!1;let i=Array.from({length:t.length+1},(e,r)=>r);for(let e=1;e<=n.length;e+=1){const r=[e];let a=e;for(let s=1;s<=t.length;s+=1)r[s]=Math.min(i[s]+1,r[s-1]+1,i[s-1]+(n[e-1]===t[s-1]?0:1)),a=Math.min(a,r[s]);if(a>o)return!1;i=r}return i[t.length]<=o}function X(n,t=null){const o=Array.isArray(n)?n:[];if(t?.location===!1)return o;const i=o.filter(e=>e&&R.has(e.type)).map(e=>String(e.value).toLowerCase());return i.length?o.map(e=>{if(!e||e.type!=="PERSON")return e;const r=String(e.value).toLowerCase();return/\s/.test(r)||r.length<5||/['’]s$/.test(r)?e:i.some(a=>a!==r&&!/\s/.test(a)&&a.length>=5&&H(r,a,2))?{...e,type:"LOCATION"}:e}):o}function B(n,t,o,i="balanced"){const e=a=>!o||o[a]!==!1;return(t==="PERSON"||t==="ORG")&&k(n)||i!=="strict"&&t==="ADDRESS"&&M(n)?!1:g.has(t)?!0:t==="PERSON"?e("person"):t==="ORG"?e("org"):R.has(t)?e("location"):(String(n).match(/\d/g)||[]).length>=7?e("number"):!1}function I(n,t,{strictness:o="balanced",text:i=""}={}){let e=[];Array.isArray(n)?e=n:n&&Array.isArray(n.entities)?e=n.entities:n&&Array.isArray(n.ents)?e=n.ents:n&&Array.isArray(n.results)&&(e=n.results);const r=[],a=new Set;for(const s of e){if(!s)continue;const c=x(String(s.value??s.text??s.entity??s.word??"").trim(),d(s.type??s.label??s.entity_group??s.entity_type??s.tag),i,t),l=c.value,u=c.type;if(!l||l.length>200||!B(l,u,t,o))continue;const S=`${u}:${l.toLowerCase()}`;a.has(S)||(a.add(S),r.push({value:l,type:u}))}return r}const G=new Set("a an the i am is are was were be been being to of in on at for and or but if so not no yes ok okay hi hello hey you your yours me my mine we us our ours they them their he him his she her it its this that these those what where when who whom why how which do does did done have has had having will would can could should may might must shall there here now then last next first time day days week month year today tomorrow yesterday see saw seen say said tell told go went gone come came get got give gave take took make made know knew think thought want need like just also very really with from into onto over under about after before between through during without within up down out off again still used use using live lived move moved work worked help please thanks thank sorry new old good bad more most some any all each because as than too so such only own same other another much many few both either neither every never always often".split(/\s+/));function Z(n){const t=String(n||"");let o=!1;return{text:t.replace(new RegExp("(^|[^\\p{L}\\p{N}'’])(\\p{Ll})(\\p{L}*)","gu"),(e,r,a,s)=>{const c=a+s;if(G.has(c))return e;const l=a.toUpperCase();return l.length!==1||l===a?e:(o=!0,r+l+s)}),changed:o}}function _(n){if(!n)return null;const t=String(n).indexOf("{"),o=String(n).lastIndexOf("}");if(t<0||o<=t)return null;try{return JSON.parse(String(n).slice(t,o+1))}catch{return null}}const Y="You extract sensitive entities from text for redaction. Copy each value exactly as it appears. Include people, organizations, locations, and account/ID numbers. No commentary, no code fences.",V='Return ONLY JSON: {"entities":[{"value":"<verbatim text>","type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. No commentary, no code fences.',m=Object.freeze({block:"",format:null,parse:null});async function j(n,t,o,i){const e=await i(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({text:n,...t.strictness==="strict"?{strict:!0}:{}}),signal:o});if(!e.ok)throw new Error(`detect HTTP ${e.status}`);return I(await e.json(),t.types,{strictness:t.strictness,text:n})}async function K(n,t,o,i,e=m){const r=String(t.url||"").replace(/\/$/,""),a=/\/chat\/completions$/.test(r)?r:/\/v\d+$/.test(r)?`${r}/chat/completions`:`${r}/v1/chat/completions`,s=`${Y}
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${e.block||V}`,c=async f=>{const h=e.format?e.format(f):null,E=await i(a,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({model:t.model||"local",temperature:0,max_tokens:t.maxTokens||256,messages:[{role:"system",content:s},{role:"user",content:n}],...h||{}}),signal:o});if(!E.ok){const A=new Error(`detect HTTP ${E.status}`);throw A.status=E.status,A}return E.json()};let l=null;if(e.format)for(const f of["schema","object","none"])try{l=await c(f);break}catch(h){if(f==="none"||h.status!==400&&h.status!==422)throw h}else l=await c("none");const u=l?.choices?.[0]?.message?.content??l?.content??"",S=e.parse?e.parse(u):_(u);return I(S,t.types,{strictness:t.strictness,text:n})}function T(n,t,o,i,e,r){if(typeof n=="function")try{n({backend:t.backend||"",host:z(t.url),chars:o.length,entities:e,ms:Date.now()-i,ok:!r,error:r?String(r.message||r).slice(0,200):""})}catch{}}const z=n=>{try{return new URL(String(n)).host}catch{return""}};async function q(n,t,{signal:o,fetchImpl:i=globalThis.fetch,strict:e=!1,structured:r=m,onEgress:a=null,onError:s=null}={}){const c=t?.detection?{...t.detection,strictness:b(t)}:null;if(!c||!c.backend||c.backend==="off"||!c.url||typeof i!="function")return[];const l=c.transport==="in-process";if(l&&i===globalThis.fetch)throw new Error("detection.transport 'in-process' needs an injected fetch; refusing to treat a network call as in-process");const u=String(n||"").slice(0,c.maxChars||8e3);if(u.trim().length<8)return[];const S=w(u,c);if(!e&&N.has(S))return N.get(S);const f=c.backend==="endpoint"?j:K;let h=[];try{l||y(c.url);const E=Date.now();try{h=await C(f(u,c,o,i,r),c.timeoutMs||1500,o),l||T(a,c,u,E,h.length,null)}catch(A){throw l||T(a,c,u,E,0,A),A}}catch(E){if(e)throw E;try{s?.(E)}catch{}return[]}return N.size>=D&&N.clear(),e||N.set(S,h),h}export{Y as EXTRACT_SYS,W as REDACTION_STRICTNESS,J as clearDetectCache,X as consistentPlaces,q as detectEntities,d as normType,I as normalizeEntities,k as ownName,_ as parseJsonLoose,x as placeInContext,M as quantityNotAddress,Z as recaseForDetection,b as strictnessOf,C as withTimeout};
|
package/src/server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as Ge}from"node:http";import O from"node:os";import{randomBytes as Ue,randomInt as Le,timingSafeEqual as We}from"node:crypto";import{mkdirSync as je,writeFileSync as Fe,readFileSync as re,existsSync as Je}from"node:fs";import{join as M}from"node:path";import*as Xe from"./engines/claude.js";import*as Ke from"./engines/codex.js";import*as ze from"./engines/antigravity.js";import{pi as Ye,opencode as Ve,kiro as Qe,copilot as Ze,deepseek as qe,hermes as et}from"./engines/cli-agents.js";import{connectorsFor as tt}from"./connectors.js";import*as nt from"./engines/custom.js";import{installService as ot,uninstallService as rt,serviceStatus as at,restartService as ae}from"./service.js";import{skillIndex as J,listRecords as it,readRecord as st,readPackageFile as ct,skillsHealth as lt,quarantinedSkills as dt,clearSkillCache as X}from"./skills.js";import{writeSkillPackage as ut,writeSkillFile as ht,deleteSkillPackage as pt,SkillWriteError as ft}from"./skill-write.js";import{agentDefRoots as mt,scanAgentDefs as gt,listAgentDefs as wt,readAgentDef as yt,planAgentExport as bt,exportAgentDef as St,agentDefsHealth as kt,AgentDefError as Tt}from"./agent-defs.js";import{capabilityToolSpecs as xt,runCapabilityTool as Et}from"./mcp-capabilities.js";import{createSession as vt,deleteSession as ie,getSession as se,activeSession as At,relayToolCall as Ot}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ct,isDefaultWorkdir as Pt,resolveWorkdir as $t,writeScopeNote as Rt}from"./workdir.js";import{sandbox as K,runSandboxCli as It,withGrant as ce,withAgentGrant as Nt,withoutOutsideWhenCapped as Dt,grantedWriteRoots as le,acceptRefusalReport as _t,liveProcesses as Ht,sandboxConfigFromEnv as Mt}from"./sandbox.js";import{createAccessGate as Bt,chatKeyOf as Gt,chatFolders as Ut}from"./access-gate.js";import{signInDenial as Lt}from"./events/sandbox-policy.js";import{gitState as Wt,gitDelta as jt}from"./scm.js";import{listConnections as Ft,putConnection as Jt,removeConnection as Xt,runEnvFor as Kt,testConnection as zt,secretBackend as de}from"./connections.js";import{worktreeFor as ue,listWorktrees as Yt,removeWorktree as Vt,withHook as Qt,WORKTREE_ROOT as he}from"./worktree.js";import{AGENT_CLIS as Zt,agentAvailable as qt,agentInstallDirs as en,enrichPath as tn,enrichAgentEnv as nn,findAgentBin as on,forgetMisses as rn,primeAgentLookups as an,resolveCommand as pe,isCompiledBinary as sn}from"./env.js";import"./sanitize.js";import{checkForUpdate as cn,selfUpdate as fe,isEmbedded as me}from"./update.js";import{callLocalMcp as ln,localMcpStatus as dn,signInLocalMcp as un,signInStatusLocalMcp as hn}from"./mcp-local.js";import{assertPublicHttpUrl as ge,assertPublicWebUrl as we}from"./ssrf.js";import{startRun as ye,endRun as z,cancelRun as pn,cancelAll as fn}from"./runs.js";import{closeWarmPools as mn,warmStatus as gn}from"./warm.js";import{SESSION_AGENTS as be,listSessions as wn,readSession as yn,adoptSession as bn,catchUp as Sn}from"./agent-sessions.js";import{agentContext as kn}from"./agent-context.js";import{normalizeThread as Se}from"./events/agent-thread.js";import{portClashPlan as Tn,serviceManagerOf as xn,STANDBY_POLL_MS as En}from"./events/service-standby.js";import{holdThread as ke}from"./threads.js";import{oneReply as vn}from"./one-reply.js";import{createSnapshot as An}from"./health-snapshot.js";import{CompatError as P,anthropicError as Y,anthropicStream as On,chatCompletionStream as Cn,completionStream as Pn,createAnthropicMessage as $n,createChatCompletion as Rn,createCompletion as In,createResponse as Nn,openAIError as S,parseAnthropicMessage as Dn,parseChatCompletion as _n,parseCompletion as Hn,parseResponse as Mn,responseStream as Bn}from"./api-compat.js";import{callerTrust as Gn,isPaired as I,parseExtensionIds as Un,capRunOptions as Ln,engineHonoursReach as Wn,createPairingStore as jn,formatPairingCode as Fn}from"./pii/trust.js";const y="0.47.
|
|
2
|
+
import{createServer as Ge}from"node:http";import O from"node:os";import{randomBytes as Ue,randomInt as Le,timingSafeEqual as We}from"node:crypto";import{mkdirSync as je,writeFileSync as Fe,readFileSync as re,existsSync as Je}from"node:fs";import{join as M}from"node:path";import*as Xe from"./engines/claude.js";import*as Ke from"./engines/codex.js";import*as ze from"./engines/antigravity.js";import{pi as Ye,opencode as Ve,kiro as Qe,copilot as Ze,deepseek as qe,hermes as et}from"./engines/cli-agents.js";import{connectorsFor as tt}from"./connectors.js";import*as nt from"./engines/custom.js";import{installService as ot,uninstallService as rt,serviceStatus as at,restartService as ae}from"./service.js";import{skillIndex as J,listRecords as it,readRecord as st,readPackageFile as ct,skillsHealth as lt,quarantinedSkills as dt,clearSkillCache as X}from"./skills.js";import{writeSkillPackage as ut,writeSkillFile as ht,deleteSkillPackage as pt,SkillWriteError as ft}from"./skill-write.js";import{agentDefRoots as mt,scanAgentDefs as gt,listAgentDefs as wt,readAgentDef as yt,planAgentExport as bt,exportAgentDef as St,agentDefsHealth as kt,AgentDefError as Tt}from"./agent-defs.js";import{capabilityToolSpecs as xt,runCapabilityTool as Et}from"./mcp-capabilities.js";import{createSession as vt,deleteSession as ie,getSession as se,activeSession as At,relayToolCall as Ot}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ct,isDefaultWorkdir as Pt,resolveWorkdir as $t,writeScopeNote as Rt}from"./workdir.js";import{sandbox as K,runSandboxCli as It,withGrant as ce,withAgentGrant as Nt,withoutOutsideWhenCapped as Dt,grantedWriteRoots as le,acceptRefusalReport as _t,liveProcesses as Ht,sandboxConfigFromEnv as Mt}from"./sandbox.js";import{createAccessGate as Bt,chatKeyOf as Gt,chatFolders as Ut}from"./access-gate.js";import{signInDenial as Lt}from"./events/sandbox-policy.js";import{gitState as Wt,gitDelta as jt}from"./scm.js";import{listConnections as Ft,putConnection as Jt,removeConnection as Xt,runEnvFor as Kt,testConnection as zt,secretBackend as de}from"./connections.js";import{worktreeFor as ue,listWorktrees as Yt,removeWorktree as Vt,withHook as Qt,WORKTREE_ROOT as he}from"./worktree.js";import{AGENT_CLIS as Zt,agentAvailable as qt,agentInstallDirs as en,enrichPath as tn,enrichAgentEnv as nn,findAgentBin as on,forgetMisses as rn,primeAgentLookups as an,resolveCommand as pe,isCompiledBinary as sn}from"./env.js";import"./sanitize.js";import{checkForUpdate as cn,selfUpdate as fe,isEmbedded as me}from"./update.js";import{callLocalMcp as ln,localMcpStatus as dn,signInLocalMcp as un,signInStatusLocalMcp as hn}from"./mcp-local.js";import{assertPublicHttpUrl as ge,assertPublicWebUrl as we}from"./ssrf.js";import{startRun as ye,endRun as z,cancelRun as pn,cancelAll as fn}from"./runs.js";import{closeWarmPools as mn,warmStatus as gn}from"./warm.js";import{SESSION_AGENTS as be,listSessions as wn,readSession as yn,adoptSession as bn,catchUp as Sn}from"./agent-sessions.js";import{agentContext as kn}from"./agent-context.js";import{normalizeThread as Se}from"./events/agent-thread.js";import{portClashPlan as Tn,serviceManagerOf as xn,STANDBY_POLL_MS as En}from"./events/service-standby.js";import{holdThread as ke}from"./threads.js";import{oneReply as vn}from"./one-reply.js";import{createSnapshot as An}from"./health-snapshot.js";import{CompatError as P,anthropicError as Y,anthropicStream as On,chatCompletionStream as Cn,completionStream as Pn,createAnthropicMessage as $n,createChatCompletion as Rn,createCompletion as In,createResponse as Nn,openAIError as S,parseAnthropicMessage as Dn,parseChatCompletion as _n,parseCompletion as Hn,parseResponse as Mn,responseStream as Bn}from"./api-compat.js";import{callerTrust as Gn,isPaired as I,parseExtensionIds as Un,capRunOptions as Ln,engineHonoursReach as Wn,createPairingStore as jn,formatPairingCode as Fn}from"./pii/trust.js";const y="0.47.5",x=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Xe,label:"Claude Code"},codex:{engine:Ke,label:"Codex"},antigravity:{engine:ze,label:"Antigravity",tools:!1},pi:{engine:Ye,label:"Pi"},opencode:{engine:Ve,label:"OpenCode"},hermes:{engine:et,label:"Hermes"},kiro:{engine:Qe,label:"Kiro"},copilot:{engine:Ze,label:"GitHub Copilot"},deepseek:{engine:qe,label:"DeepSeek Harness"},custom:{engine:nt,label:"Custom",hidden:!0}};function Te(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 Jn=Un(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Gn({origin:n.headers.origin||"",hasToken:Ae(n),extensionIds:Jn})),n.chatpanelTrust}function Xn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Kn(n,e){const t=n.headers.origin||"",o=Te(t);e.setHeader("Access-Control-Allow-Origin",o?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const V=new Set(["127.0.0.1","localhost","::1"]);function zn(n){if(!V.has(x))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return V.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let v="";function Yn(){try{Je(D)&&(v=re(D,"utf8").trim()),v||(v=Ue(32).toString("hex"),je(M(O.homedir(),".chatpanel"),{recursive:!0}),Fe(D,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const xe=jn({random:()=>Le(0,1e6)/1e6});function Vn(n){if(!v)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=xe.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function Qn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=xe.claim(t?.code);return o.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:v})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Zn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ee(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function ve(n,e,t){try{const o=await Ee(),r=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await o.status());if(t==="connect"){const a=await o.connect(r);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await o.pair()):t==="unpair"?i(e,200,await o.unpair(String(r.actorId||""))):t==="settings"?i(e,200,await o.update(r)):t==="disconnect"?i(e,200,await o.stop({forget:!!r.forget})):i(e,404,{error:"unknown channel action"})}catch(o){return i(e,400,{error:o?.message||String(o)})}}function Ae(n){if(!v)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const o=Buffer.from(t),r=Buffer.from(v);return o.length===r.length&&We(o,r)}const qn=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),eo=new Set(["/debug"]),to=n=>eo.has(n),no=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function oo(n,e){if(!zn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!Te(t))return"forbidden origin";const o=n.method==="POST"&&qn.has(e)||n.method==="GET"&&to(e)||no(n.method,e);return o&&!(Xn(t)||Ae(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!ao.has(e)?ro:null}const Oe=()=>me()?"chatpanel-gateway pair":"chatpanel-bridge pair",ro=`forbidden: this client is not paired with the bridge — run \`${Oe()}\` and enter the code in ChatPanel Settings`,ao=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Q(n,e,t){const o=N(n),r=Nt(e,Dt(Ln(t,o)));if(!Wn(e,r.reach))return{error:`${I(o)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(o)?"raise the tier":`pair this client (${Oe()})`} to use ${e}`};const a=r.reach,s=I(o)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:r,note:s}}async function Ce(n,e,t){const o=e?.message||String(e);try{const r=await K().status(),a=!!(r.enabled&&r.runtime)&&t?.outside!==!0,s=Lt(`${o}
|
|
3
3
|
${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:E[n]?.label||n||"This agent"});if(s)return s.line}catch{}return o}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let o="";n.on("data",r=>{o+=r,o.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(o?JSON.parse(o):{})}catch(r){t(r)}}),n.on("error",t)})}const Pe=An({compute:io});async function io(){await an();const n=await Promise.all(Object.entries(E).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:d}])=>{const l=await s.available().catch(w=>({ok:!1,reason:String(w?.message||w)})),p=await tt(a).catch(()=>[]);return{id:a,label:c,available:l.ok,reason:l.reason,connectors:p,...d===!1?{tools:!1}:{}}})),e=me()?{current:y,updateAvailable:!1,embedded:"gateway"}:await cn(y).catch(()=>({current:y,updateAvailable:!1})),t=await lt().catch(()=>null),o=await kt().catch(()=>null),r=await K().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function so(n,{fresh:e=!1}={}){e&&rn();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await Pe.get({fresh:e});i(n,200,{ok:!0,version:y,agents:o,update:r,checkedAt:t,workspace:Ct,sandbox:c,localMcp:dn(),processes:Ht(),worktrees:he,secretBackend:de(),warm:gn(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...s?{agentDefs:s}:{}})}async function co(n,e,t){const{index:o,problems:r}=await J({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:it(o),problems:r})}async function lo(n,e,t){i(n,200,{ok:!0,quarantined:await dt(e,t)})}async function uo(n,e,t,o){const{index:r}=await J({extraDirs:t,workdir:o}),a=st(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function ho(n,e,t,o,r){const{index:a}=await J({extraDirs:o,workdir:r}),s=await ct(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 po(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await ut({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return X(),i(e,200,o)}catch(o){return i(e,Z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function fo(n,e,t,o){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await ht({name:t,path:o,text:r?.text??""});return X(),i(e,200,a)}catch(a){return i(e,Z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function mo(n,e){try{const t=await pt({name:e});return X(),i(n,200,t)}catch(t){return i(n,Z(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function Z(n){return n instanceof ft?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function $e(n,e){return gt({roots:mt(process.env,O.homedir(),n,e)})}async function go(n,e,t){const{index:o,quarantined:r,problems:a}=await $e(e,t);i(n,200,{ok:!0,agents:wt(o),...r.length?{quarantined:r.map(s=>({id:s.agent.id,path:s.relPath,source:s.source,verdict:s.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function wo(n,e,t,o){const{index:r}=await $e(t,o),a=yt(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function yo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,{ok:!0,...await bt({agent:t?.agent,to:t?.to})})}catch(o){return i(e,Re(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function bo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{return i(e,200,await St({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,Re(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function Re(n){if(n instanceof Tt){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function So(){return(await Promise.all(Object.entries(E).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function Ie(n,e=""){const t=await So();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function ko(n){try{const e=await fe(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>ae(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function To(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=Q(n,t.agent,t.options||{});if(r.error)return i(e,403,{error:r.error});t.options=r.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
|
|
4
4
|
|
|
5
5
|
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,d=ye(c),l={signal:d.signal,abort:()=>d.cancel("client")},p=()=>{s=!0,d.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const w=h=>{s||a(h)};a({type:"run",id:c}),r.note&&a({type:"status",text:r.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(f=await ue({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),z(c),e.writableEnded||e.end();return}}const _=f?f.path:$t(t.options?.workingDir),W=Gt(t.agent,t.options),ee=W?Ut(W):[];ee.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...ee])]}});let C=null;{const h=_,T=!!f||!Pt(t.options?.workingDir),g=Rt(t.agent,t.options?.permissionMode,h,le(h,{grant:t.options?.sandbox}));a({type:"workdir",path:h,isDefault:!T,writeScope:g||void 0}),a({type:"status",text:`Working in ${h}${T?"":" (default)"}`}),g&&a({type:"status",text:g}),C=await Wt(h),C&&a({type:"scm",phase:"before",...C})}let j=null;if(C||f){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:T,connection:g}=Kt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=Qt(T),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...g?{connection:g}:{}}),g&&a({type:"status",text:`Git credential: ${g.kind} · ${g.host}${g.hasSecret?"":" (no token stored)"} · push: ${T.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:T.CHATPANEL_SCM_PUSH}`})}const F=t.approvals===!0,b={...t.options||{},...f?{workingDir:f.path}:{},...j?{runEnv:j}:{},approvals:F};let R=null;(t.pageTools?.specs?.length||F)&&(R=vt(w,t.pageTools?.specs||[]),b.permissionSession=R,t.pageTools?.specs?.length&&(b.mcp={url:`http://${x}:${k}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const Me=Mt();let te=b.sandbox||null;F&&Me.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&b.sandbox?.outside!==!0&&(b.accessGate=Bt({agent:t.agent,label:E[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>le(_,{grant:te})}));try{const h=vn(w),T=(g,H)=>ce(g.sandbox,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:H,options:g,images:Array.isArray(t.images)?t.images:[]},h.emit,{signal:l.signal}));await ke(t.agent,b,l.signal,async()=>{await T(b,t.system||"");let g=b;for(let H=0;H<2&&b.accessGate?.restart().length&&!l.signal.aborted;H++){const ne=b.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...ne])]}},te=g.sandbox;const oe=ne.map(Be=>b.accessGate.short(Be)).join(", ");h.seam(),w({type:"status",text:`Restarted with write access to ${oe} — carrying on`}),await T(g,`${t.system||""}
|