@chatpanel/bridge 0.45.2 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/scripts/sync-events.mjs +2 -2
- package/src/access-gate.js +1 -0
- package/src/engines/claude-warm.js +3 -3
- package/src/engines/claude.js +6 -6
- package/src/env.js +2 -2
- package/src/events/access-request.js +1 -0
- package/src/events/agent-permission.js +2 -2
- package/src/events/policy.js +1 -0
- package/src/events/runtime-host.js +1 -0
- package/src/events/sandbox-choice.js +1 -0
- package/src/events/sandbox-policy.js +1 -1
- package/src/sandbox-command.js +1 -0
- package/src/sandbox-host.js +1 -1
- package/src/sandbox-srt.js +1 -1
- package/src/sandbox.js +1 -1
- package/src/server.js +10 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.46.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
package/scripts/sync-events.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as r,writeFileSync as j,existsSync as i,mkdirSync as p}from"node:fs";import{fileURLToPath as m}from"node:url";import{dirname as h,join as
|
|
2
|
+
import{readFileSync as r,writeFileSync as j,existsSync as i,mkdirSync as p}from"node:fs";import{fileURLToPath as m}from"node:url";import{dirname as h,join as s}from"node:path";const c=s(h(m(import.meta.url)),".."),f=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","secret-names.js","sandbox-grant.js","runtime-host.js","sandbox-choice.js","harness-cards.js","agent-thread.js","compaction.js","context-window.js","mcp-errors.js","registries.js","mcp-signin.js","context-breakdown.js","mcp-config-import.js","toml-lite.js","frontmatter.js","skill-package.js","agent-portability.js","agent-dialects.js","agent-card.js","dialect-claude.js","dialect-codex.js","dialect-a2a.js","dialect-chatpanel.js","agent.js","team.js","engine.js","budget.js","mcp-args-env.js","mcp-launcher.js","agent-permission.js","access-request.js","policy.js","service-standby.js"];function u(){return[s(c,"node_modules","@chatpanel","events"),s(c,"..","chatpanel-events")].find(e=>i(s(e,"skill-manifest.js")))}const n=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";n&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=s(c,"src","events");n||p(l,{recursive:!0});const v=e=>`// GENERATED — do not edit.
|
|
3
3
|
// Source of truth: chatpanel-events/${e} (npm @chatpanel/events).
|
|
4
4
|
// Edit there, then run: npm run sync:events
|
|
5
5
|
//
|
|
@@ -7,4 +7,4 @@ import{readFileSync as r,writeFileSync as j,existsSync as i,mkdirSync as p}from"
|
|
|
7
7
|
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
8
8
|
// single-file binary has nothing to resolve.
|
|
9
9
|
|
|
10
|
-
`;let d=0;for(const e of f){const o=
|
|
10
|
+
`;let d=0;for(const e of f){const o=v(e)+r(s(a,e),"utf8"),t=s(l,e);if((i(t)?r(t,"utf8"):null)!==o){if(n){console.error(`sync-events --check: src/events/${e} differs from chatpanel-events`),d+=1;continue}j(t,o),console.log(`sync-events: updated src/events/${e}`)}}n&&(d&&(console.error("Run `npm run sync:events` and commit the result."),process.exit(1)),console.log("sync-events --check: src/events matches chatpanel-events ✓"));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{statSync as B,realpathSync as E}from"node:fs";import q from"node:os";import S from"node:path";import{decideAccess as I,rememberAccess as W,isTooBroadRoot as _,pathInside as A,describeDecision as j,permissionAccessTarget as z}from"./events/access-request.js";import{permissionRequestFromClaude as G,permissionAnswer as u,permissionAllowed as D}from"./events/agent-permission.js";import{normalizeThread as H}from"./events/agent-thread.js";import{COMMON_WRITE as J}from"./events/sandbox-policy.js";import{relayPermission as k}from"./mcp-sessions.js";const p=new Map;function nt(){p.clear()}function st(t,e={}){const o=H(e?.thread);return o&&e?.ephemeral!==!0?`${t}|${e.reach||"local"}|${o.id}`:""}function ot(t){return(p.get(t)||[]).filter(e=>e.allow&&e.what.kind==="path").map(e=>e.what.value)}const w=(t,e)=>t==="~"||t.startsWith("~/")?e+t.slice(1):t,v=t=>{try{return E(t)}catch{return t}},m=(t,e)=>e&&A(t,e)?`~${t.slice(e.length)}`:t;function K(t,{cwd:e,home:o,isDir:i=r=>{try{return B(r).isDirectory()}catch{return!1}}}){const r=S.resolve(e||o,w(String(t),o));return i(r)?r:S.dirname(r)}function L(t,{cwd:e,roots:o=[],home:i}){const r=q.tmpdir();return[e,...o,...J.map(c=>w(c,i)),r,v(r)].filter(Boolean).some(c=>A(t,w(c,i))||A(v(t),v(w(c,i))))}function M(t){return`Not run yet: ChatPanel's sandbox did not include ${t} when you started. The person has just allowed it, and ChatPanel restarts you with that access and resumes this conversation straight after this turn. End this turn now in one short sentence — do not retry, and do not try another way.`}function it({agent:t,label:e=t,key:o="",cwd:i,home:r=q.homedir(),roots:C=()=>[],enabled:c=!0,policy:N=null,now:O=Date.now}={}){let y=o?p.get(o)||[]:[];const a=[],g=[],P=n=>{try{return`${n.tool}\0${JSON.stringify(n.input||{})}`}catch{return""}},F=n=>{y=n,o&&p.set(o,n)},f=(n,d)=>{try{n?.emit?.({type:"status",text:d})}catch{}};return{async ask(n,d,{request:R=null}={}){const l=R||G(d),b=g.indexOf(P(l));if(b>=0&&!a.length)return g.splice(b,1),f(n,"Allowed (you allowed this before the restart)"),u("allow");const T=c?z(l):null;if(!T)return k(n,d,{request:l});const s=K(T,{cwd:i,home:r});if(L(s,{cwd:i,roots:C(),home:r}))return k(n,d,{request:l});if(_(s,r))return f(n,`${e} asked to write in ${m(s,r)} — not offered: ChatPanel never opens a whole home folder or disk to an agent`),u("deny",`ChatPanel's sandbox will not open ${s} — it is a whole home folder or disk. Ask the person for a folder inside it, or write in your working folder.`);const $={what:{kind:"path",value:s,mode:"write"},engine:e,asked:"ahead",scope:"session"},h=I({request:$,grants:y,policy:N,home:r,now:O()});if(h.verdict==="deny")return f(n,j($,h)),u("deny",`ChatPanel's sandbox does not allow writing in ${s} (${h.reason}). Do not retry; tell the person.`);if(h.verdict==="grant")return a.includes(s)||a.push(s),u("deny",M(s));const x=await k(n,d,{request:{...l,access:{folder:m(s,r),mode:"write"}}});return F(W(y,$,D(x)?"allow":"deny",{now:O(),home:r})),D(x)?(a.includes(s)||a.push(s),g.push(P(l)),f(n,`${m(s,r)} is open to ${e} for this chat — restarting it with that access`),u("deny",M(s))):x},restart(){return[...a]},take(){return a.splice(0)},short:n=>m(n,r)}}export{nt as _resetAccessForTest,ot as chatFolders,st as chatKeyOf,it as createAccessGate,K as folderOf,M as restartMessage,L as writableNow};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{unlink as z}from"node:fs/promises";import{spawnRpcChild as K}from"../rpc-child.js";import{spawn as Q}from"node:child_process";import{track as V,sandbox as X}from"../sandbox.js";import{createWarmPool as Y}from"../warm-pool.js";import{registerWarmPool as Z}from"../warm.js";import{createSession as
|
|
2
|
-
`).pop()}`:""}`),
|
|
3
|
-
`).pop().slice(0,200)}`:""}`;
|
|
1
|
+
import{unlink as z}from"node:fs/promises";import{spawnRpcChild as K}from"../rpc-child.js";import{spawn as Q}from"node:child_process";import{track as V,sandbox as X}from"../sandbox.js";import{createWarmPool as Y}from"../warm-pool.js";import{registerWarmPool as Z}from"../warm.js";import{createSession as O,deleteSession as D,rebindSession as ee,releaseSession as re,relayPermission as W}from"../mcp-sessions.js";import{resolveClaude as se,buildSpawnSpec as te}from"../env.js";import{loginRequired as U,signInMessage as B}from"../sign-in.js";import{pushExtraArgs as q,FORBIDDEN as G}from"./args.js";import{buildClaudeLaunch as H,claudePrompt as ae,handleMessage as ne,harnessChars as le,writeImages as oe,answerControlRequest as ie}from"./claude.js";const F=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,ue=5e3,u=Z("claude",Y({log:o=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${o}`)}}));function ce(o={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||o.warm===!1)}async function j({spec:o,args:A,cwd:e,env:$,spawnImpl:w,log:g=()=>{},ask:T=null,peers:y=!0}){const c=[...A,"--input-format","stream-json"],[p,d,E]=te(o,c,e,$),f=await X().wrap(p,d,E,{engine:"claude",cwd:e,peers:y});f.record.layer==="none"&&g(`sandbox: claude session runs outside a sandbox — ${f.record.reason}`);const[i,m,S]=[f.bin,f.argv,f.opts];let r=null;const b=new Set;let x="",I=0,M=0,l=null;const h=K(i,m,{spawnOpts:S,spawnImpl:(s,t,a)=>V((w||Q)(s,t,a),f,{kind:"warm"}),jsonrpc:!1,onStderr:s=>{x=(x+s).slice(-2e3),r&&r.touch()},onExit:s=>{if(g(`claude exited: ${s.signal||s.code}${x?` — ${x.trim().split(`
|
|
2
|
+
`).pop()}`:""}`),r){const t=r.apiError&&U(r.apiError)?B("Claude Code","claude"):r.apiError?`Claude Code reported an error: ${r.apiError}`:`Claude Code exited (${s.signal||s.code})${x?`: ${x.trim().split(`
|
|
3
|
+
`).pop().slice(0,200)}`:""}`;r.finish({status:"died",error:t})}for(const t of b)try{t(s)}catch{}},onMessage:s=>{if(!r||(r.touch(),s.type==="control_response"))return;if(s.type==="control_request"){const a=r;a.asking++,a.touch(),ie(s,T,_=>{try{h.send(_)}catch{}}).catch(()=>{}).finally(()=>{a.asking--,r===a&&a.touch()});return}const t=ne(s,r.emit,r.streamedAny,e,r.flow);t.sessionId&&(l=t.sessionId),t.streamed&&(r.streamedAny=!0),t.result!=null&&(r.resultText=t.result),t.apiError&&(r.apiError=t.apiError),s.type==="result"&&(r.apiError&&U(r.apiError)?r.finish({status:"failed",error:B("Claude Code","claude")}):r.apiError?r.finish({status:"failed",error:`Claude Code reported an error: ${r.apiError}`}):r.finish({status:"completed",error:null}))}});return{get pid(){return h.pid},get alive(){return!h.exited},expiresAt:f.expiresAt||0,get sessionId(){return l},onExit(s){b.add(s)},close(){h.close()},async turn({prompt:s,emit:t,signal:a,harness:_=null}){if(h.exited)throw new Error("Claude Code process is gone");if(r)throw new Error("a turn is already running on this process");let v=null,k;const R=new Promise(L=>{k=L}),n={emit:t,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:M,harnessChars:_},streamedAny:!1,resultText:"",apiError:null,asking:0,touch(){clearTimeout(v),!n.asking&&(v=setTimeout(()=>n.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(F/1e3)}s.`}),F))},finish(L){r===n&&(clearTimeout(v),r=null,k(L))}};r=n,n.touch();const P=()=>{if(r===n){n.interrupted=!0;try{h.send({type:"control_request",request_id:`stop_${++I}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{r===n&&(n.finish({status:"killed",error:null}),h.kill())},ue).unref?.()}};if(a?.aborted)return n.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};a?.addEventListener("abort",P,{once:!0});try{h.send({type:"user",message:{role:"user",content:s}})}catch(L){n.finish({status:"failed",error:L.message})}const C=await R;n.flow.costUsdTotal!=null&&(M=n.flow.costUsdTotal),a?.removeEventListener("abort",P),C.status==="timeout"&&h.kill();const J=C.status==="killed"?"killed":n.interrupted?"interrupted":C.status;return{streamedAny:n.streamedAny,resultText:n.resultText,status:J,error:C.error,sessionId:l}}}}const N=new Set;async function de({key:o,spec:A,options:e,label:$,launch:w=j,log:g=()=>{},force:T=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!T||!o||!A||e?.ephemeral===!0||N.has(o)||u.peek({key:o,messages:[{role:"user",content:""}]}))return!1;N.add(o);const y=u.reserve({key:o,label:`${$} (spare)`,evict:!1});if(!y)return N.delete(o),!1;let c=null,p=null;try{let d=e.mcp;const E=e.mcp?.specs||[];(d?.url&&E.length||e.approvals===!0)&&(c=O(()=>{},E),d?.url&&E.length&&(d={...d,url:`${d.url.replace(/\/[^/]*$/,"")}/${c.id}`})),p=await H({system:"",options:{...e,mcp:d},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const f=[...p.args];q(f,e.extraArgs,G.claude,()=>{});const i=c,m=await w({spec:A,args:f,cwd:p.cwd,env:p.runEnv,ask:p.approvals&&i?r=>W(i,r):null,peers:p.peers});m.mcpSession=c,m.systemSent="",u.attach(y,m);const S=p.cleanup;return m.onExit(()=>{c&&D(c.id),S()}),u.release(y,{user:null,answered:!1}),g(`warm ${$}: spare ready`),!0}catch(d){return c&&D(c.id),p?.cleanup?.(),u.drop(y,`spare launch failed: ${d.message}`),!1}finally{N.delete(o)}}async function be({messages:o,system:A,options:e,images:$,thread:w=null},g,{signal:T,launch:y=j}={}){if(!ce(e))return{handled:!1,reason:"not eligible"};const c=se();if(!c)return{handled:!1,reason:"claude not resolvable"};const p=`${Date.now()}-${Math.random().toString(36).slice(2)}`,d=(e.mcp?.specs||[]).map(s=>s?.name).filter(Boolean),E=[];q(E,e.extraArgs,G.claude,()=>{});const f=JSON.stringify({agent:"claude",cwd:e.workingDir||"",mode:e.permissionMode||"default",model:e.model||"",local:e.useLocalConfig!==!1,reach:e.reach||"",tools:[...d].sort(),extra:E,approvals:e.approvals===!0,env:e.runEnv?Object.keys(e.runEnv).sort().map(s=>`${s}=${e.runEnv[s]}`):[],hosts:e.sandbox?.hosts?(Array.isArray(e.sandbox.hosts)?e.sandbox.hosts:String(e.sandbox.hosts).split(/[\s,;]+/)).map(s=>String(s).trim().toLowerCase()).filter(Boolean).sort():[],outside:e.sandbox?.outside===!0,...Array.isArray(e.sandbox?.signIn)&&e.sandbox.signIn.length?{signIn:[...e.sandbox.signIn].sort()}:{},ephemeral:e.ephemeral===!0,...Array.isArray(e.sandbox?.write)&&e.sandbox.write.length?{write:[...e.sandbox.write].map(String).sort()}:{}});let i=u.acquire({key:f,messages:o}),m=!1;const S=!i&&w?.plan.mode==="resume"?w.plan.sessionId:null;if(!i){if(i=u.reserve({key:f,label:`claude ${e.workingDir||"home"}`,evict:e.ephemeral!==!0}),!i)return{handled:!1,reason:"all warm slots busy"};m=!0;let s=null,t=null;try{let a=e.mcp;(a?.url&&d.length||e.approvals===!0)&&(s=O(g,a?.specs||[]),a?.url&&d.length&&(a={...a,url:`${a.url.replace(/\/[^/]*$/,"")}/${s.id}`})),t=await H({system:A,options:{...e,mcp:a},tag:p,resume:S,name:w?.thread.title||""});const _=[...t.args];q(_,e.extraArgs,G.claude,g);const v=s;let k=null;const R=t.approvals&&v?C=>k?.accessGate?k.accessGate.ask(v,C):W(v,C):null,n=await y({spec:c,args:_,cwd:t.cwd,env:t.runEnv,ask:R,peers:t.peers});k=n,n.mcpSession=s,n.systemSent=String(A||""),u.attach(i,n),S&&u.holds(i,o);const P=t.cleanup;n.onExit(()=>{s&&D(s.id),P()})}catch(a){return s&&D(s.id),t?.cleanup(),u.drop(i,`launch failed: ${a.message}`),{handled:!1,reason:a.message}}}const r=i.session;r.accessGate=e.accessGate||null,r.mcpSession&&ee(r.mcpSession,g,e.mcp?.specs);const b=o[o.length-1],x=await oe($,p),I=String(A||""),M=ae(m&&!S?o:S?w.plan.tail?.length?w.plan.tail:[b]:[b],x,!m&&I!==r.systemSent?I:"");r.systemSent=I;let l;try{l=await r.turn({prompt:M,emit:g,signal:T,harness:le({prompt:M,system:m?I:"",specs:m?e.mcp?.specs:null})})}finally{x.forEach(s=>z(s).catch(()=>{})),r.mcpSession&&re(r.mcpSession)}if(T?.aborted||l.status==="interrupted")return l.status==="interrupted"&&r.alive?u.release(i,{user:String(b?.content||""),answered:l.streamedAny}):u.drop(i,"stopped"),{handled:!0};if(l.status!=="completed"){if(u.drop(i,l.error||l.status),!l.streamedAny)return{handled:!1,reason:l.error||l.status};throw new Error(l.error||`Claude Code ${l.status}`)}if(g({type:"done",text:l.streamedAny?"":l.resultText}),e.accessGate?.restart().length)return u.drop(i,"a folder was opened to it"),r.accessGate=null,{handled:!0,completed:!0,sessionId:l.sessionId||r.sessionId||null};r.accessGate=null,u.release(i,{user:String(b?.content||""),answered:!0});const h=l.sessionId||r.sessionId||null;return setTimeout(()=>{de({key:f,spec:c,options:e,label:`claude ${e.workingDir||"home"}`,launch:y}).catch(()=>{})},250).unref?.(),{handled:!0,completed:!0,sessionId:h}}export{be as chatWarm,j as launchClaudeSession,u as pool,de as prewarmClaude,ce as warmEligible};
|
package/src/engines/claude.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{spawn as z}from"node:child_process";import{writeFile as R,unlink as G}from"node:fs/promises";import P from"node:os";import D from"node:path";import{resolveClaude as v,buildSpawnSpec as J,isCompiledBinary as ue,selfMcpStdio as de}from"../env.js";import{signInStatus as pe,signInMessage as Y,loginRequired as fe}from"../sign-in.js";import{buildCliPrompt as K}from"./prompt.js";import{cliError as he}from"../cli-errors.js";import{killOnAbort as me}from"../proc.js";import{sandbox as ye,noteSandbox as _e,track as be,grantedWriteRoots as we}from"../sandbox.js";import{harnessDirArgs as Te,harnessSessionArgs as j}from"../events/harness-cards.js";import{threadTurn as ge}from"../threads.js";import{liveClaudeSessions as Ee}from"../agent-sessions.js";import{pushExtraArgs as xe,FORBIDDEN as Ce}from"./args.js";import{relayTimeoutMax as Se}from"../relay-timeout.js";import{displayPath as ke,resolveWorkdir as F}from"../workdir.js";import{connectorsFor as Ae}from"../connectors.js";import{chatWarm as ve}from"./claude-warm.js";import{claudePermissionResponse as Ne,permissionAnswer as Me}from"../events/agent-permission.js";import{relayPermission as Pe}from"../mcp-sessions.js";async function Oe(e,t){const r=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const o=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",n=D.join(P.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await R(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const X=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,V=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task","ListAgents"],Q=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),Ie=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch","ListAgents","SendMessage"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch","SendMessage"])}),Le=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),$e=Object.freeze(["remember","forget"]),We=Object.freeze(["ask_model","ask_status"]),Z=Object.freeze({device:Object.freeze([]),trusted:Le});function Re(e,t=[]){const r=Z[e]||Z.device,i=(t||[]).filter(n=>typeof n=="string"&&/^chatpanel/i.test(n)),s=[],o=[];for(const n of i){for(const a of r)s.push(`mcp__${n}__${a}`);for(const a of[...$e,...We])o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function De(e){if(!e||e==="any")return null;const t=Q[e]?e:"device";return{allow:[...Q[t]],deny:[...Ie[t]]}}let O="Claude Code not found.",ee=0,k=!1;async function yt(){if(Date.now()-ee>(k?3e4:4e3)){ee=Date.now();try{v({probe:"async"})||!ue()&&await q()?k=!0:(k=!1,O=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{k=!1}}return k?await pe("claude",v()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:Y("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:O}}async function _t(){return["opus","sonnet","haiku"]}function je(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=de(e.url),s=[...new Set(e.specs.map(o=>o?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:r,args:i}}},allowedTools:s.map(o=>`mcp__${t}__${o}`)}}async function Fe(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):Me("deny","This run has no approval surface.");return r(Ne(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function te({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:c=null,peers:u=!0}){const d=v();if(!d)return null;const[y,g,w]=J(d,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((_,
|
|
1
|
+
import{spawn as z}from"node:child_process";import{writeFile as R,unlink as G}from"node:fs/promises";import P from"node:os";import D from"node:path";import{resolveClaude as v,buildSpawnSpec as J,isCompiledBinary as ue,selfMcpStdio as de}from"../env.js";import{signInStatus as pe,signInMessage as Y,loginRequired as fe}from"../sign-in.js";import{buildCliPrompt as K}from"./prompt.js";import{cliError as he}from"../cli-errors.js";import{killOnAbort as me}from"../proc.js";import{sandbox as ye,noteSandbox as _e,track as be,grantedWriteRoots as we}from"../sandbox.js";import{harnessDirArgs as Te,harnessSessionArgs as j}from"../events/harness-cards.js";import{threadTurn as ge}from"../threads.js";import{liveClaudeSessions as Ee}from"../agent-sessions.js";import{pushExtraArgs as xe,FORBIDDEN as Ce}from"./args.js";import{relayTimeoutMax as Se}from"../relay-timeout.js";import{displayPath as ke,resolveWorkdir as F}from"../workdir.js";import{connectorsFor as Ae}from"../connectors.js";import{chatWarm as ve}from"./claude-warm.js";import{claudePermissionResponse as Ne,permissionAnswer as Me}from"../events/agent-permission.js";import{relayPermission as Pe}from"../mcp-sessions.js";async function Oe(e,t){const r=[];for(let i=0;i<(e?.length||0);i++){const s=/^data:([^;]+);base64,(.+)$/s.exec(e[i]?.dataUrl||"");if(!s)continue;const o=(s[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",n=D.join(P.tmpdir(),`chatpanel-claude-img-${t}-${i}.${o}`);await R(n,Buffer.from(s[2],"base64")),r.push(n)}return r}const X=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,V=["Read","Grep","Glob","WebFetch","WebSearch","TodoWrite","Task","ListAgents"],Q=Object.freeze({device:Object.freeze(["TodoWrite"]),trusted:Object.freeze(["Read","Grep","Glob","TodoWrite","Task"])}),Ie=Object.freeze({device:Object.freeze(["Read","Glob","Grep","LS","NotebookRead","NotebookEdit","Bash","Edit","Write","MultiEdit","WebFetch","WebSearch","Task","ToolSearch","ListAgents","SendMessage"]),trusted:Object.freeze(["Bash","Edit","Write","MultiEdit","NotebookEdit","WebFetch","WebSearch","SendMessage"])}),Le=Object.freeze(["search_history","smart_search","get_record","list_history","find_related","recall","list_skills","open_skill","read_skill_file"]),$e=Object.freeze(["remember","forget"]),We=Object.freeze(["ask_model","ask_status"]),Z=Object.freeze({device:Object.freeze([]),trusted:Le});function Re(e,t=[]){const r=Z[e]||Z.device,i=(t||[]).filter(n=>typeof n=="string"&&/^chatpanel/i.test(n)),s=[],o=[];for(const n of i){for(const a of r)s.push(`mcp__${n}__${a}`);for(const a of[...$e,...We])o.push(`mcp__${n}__${a}`)}return{allow:s,deny:o}}function De(e){if(!e||e==="any")return null;const t=Q[e]?e:"device";return{allow:[...Q[t]],deny:[...Ie[t]]}}let O="Claude Code not found.",ee=0,k=!1;async function yt(){if(Date.now()-ee>(k?3e4:4e3)){ee=Date.now();try{v({probe:"async"})||!ue()&&await q()?k=!0:(k=!1,O=process.platform==="win32"?"Claude Code not found on Windows PATH or in WSL. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in — in Windows or in your WSL distro.":"Claude Code not found on PATH. Install it (npm i -g @anthropic-ai/claude-code) and run `claude` once to log in.")}catch{k=!1}}return k?await pe("claude",v()).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:Y("Claude Code","claude")}:{ok:!0}:{ok:!1,reason:O}}async function _t(){return["opus","sonnet","haiku"]}function je(e){if(!e?.url||!Array.isArray(e.specs)||!e.specs.length)return null;const t=e.serverName||"chatpanel_browser",{command:r,args:i}=de(e.url),s=[...new Set(e.specs.map(o=>o?.name).filter(Boolean))];return{serverName:t,config:{mcpServers:{[t]:{command:r,args:i}}},allowedTools:s.map(o=>`mcp__${t}__${o}`)}}async function Fe(e,t,r){const i=e?.request_id,s=e?.request?.subtype;if(s==="can_use_tool"){const o=t?await t(e.request):Me("deny","This run has no approval surface.");return r(Ne(i,o,e.request)),!0}return r({type:"control_response",response:{subtype:"error",request_id:i,error:`unsupported control request: ${s||"unknown"}`}}),!1}function te({prompt:e,args:t,cwd:r,env:i=null,emit:s,signal:o,harness:n=null,host:a=!1,ask:c=null,peers:u=!0}){const d=v();if(!d)return null;const[y,g,w]=J(d,a?[...t,"--input-format","stream-json"]:t,r,i);return new Promise((_,f)=>{ye().wrap(y,g,w,{engine:"claude",cwd:r,peers:u}).then(T=>{_e(s,T.record);let l;try{l=be(z(T.bin,T.argv,T.opts),T,{kind:"agent"})}catch(m){return f(new Error(`Failed to start claude: ${m.message}`))}const h=me(l,o);let b="",E="",p=!1,C=null;const le={sawText:!1,tail:"",boundary:!1,harnessChars:n};let I="",L=null,A,$=0;const M=()=>{clearTimeout(A),!$&&(A=setTimeout(()=>{l.kill("SIGKILL"),f(new Error(`Claude Code timed out — no output for ${Math.round(X/1e3)}s.`))},X))};M();const ce=m=>{try{l.stdin.write(`${JSON.stringify(m)}
|
|
2
2
|
`)}catch{}};l.stdout.on("data",m=>{M(),b+=m.toString();let W;for(;(W=b.indexOf(`
|
|
3
|
-
`))>=0;){const B=b.slice(0,W).trim();if(b=b.slice(W+1),!B.startsWith("{"))continue;let S;try{S=JSON.parse(B)}catch{continue}if(S.type==="control_request"){$++,clearTimeout(A),Fe(S,c,ce).catch(()=>{}).finally(()=>{$--,M()});continue}if(S.type==="control_response")continue;const x=
|
|
4
|
-
`):(l.stdin.write(e),l.stdin.end())}).catch(
|
|
3
|
+
`))>=0;){const B=b.slice(0,W).trim();if(b=b.slice(W+1),!B.startsWith("{"))continue;let S;try{S=JSON.parse(B)}catch{continue}if(S.type==="control_request"){$++,clearTimeout(A),Fe(S,c,ce).catch(()=>{}).finally(()=>{$--,M()});continue}if(S.type==="control_response")continue;const x=se(S,s,p,r,le);x.streamed&&(p=!0),x.result!=null&&(I=x.result),x.apiError&&(C=x.apiError),x.sessionId&&(L=x.sessionId),a&&S.type==="result"&&l.stdin.end()}}),l.stderr.on("data",m=>{M(),E+=m.toString()}),l.on("error",m=>{clearTimeout(A),h(),f(new Error(`Failed to start claude (${y}): ${m.message}`))}),l.on("close",m=>{if(clearTimeout(A),h(),o?.aborted){_({streamedAny:p,resultText:I,sessionId:L,stopped:!0});return}if(C&&fe(C))return f(new Error(Y("Claude Code","claude")));if(m===0&&C)return f(new Error(`Claude Code reported an error: ${C}`));m===0?_({streamedAny:p,resultText:I,sessionId:L}):f(he("Claude Code",m,E,C||"",{agentId:"claude"}))}),a?l.stdin.write(`${JSON.stringify({type:"user",message:{role:"user",content:e}})}
|
|
4
|
+
`):(l.stdin.write(e),l.stdin.end())}).catch(f)})}function He(e){let t="";return typeof e=="string"?t=e:Array.isArray(e)&&(t=e.map(r=>typeof r=="string"?r:r?.text||"").filter(Boolean).join(`
|
|
5
5
|
`)),t.length>4e3?`${t.slice(0,4e3)}…`:t}function re(e,t){e&&(e.boundary&&e.sawText&&!/\n$/.test(e.tail)&&t({type:"delta",text:`
|
|
6
6
|
|
|
7
|
-
`}),e.boundary=!1)}function ne(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function
|
|
8
|
-
`)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:Je(n,i),...typeof e.parent_tool_use_id=="string"&&e.parent_tool_use_id?{parent:e.parent_tool_use_id}:{}})):n.type==="text"&&!r&&(o.streamed=!0,re(s,t),t({type:"delta",text:n.text}),ne(s,n.text))}else if(e.type==="user")for(const n of e.message?.content||[])n.type==="tool_result"&&t({type:"tool",phase:"done",callId:n.tool_use_id,status:n.is_error?"error":"ok",result:He(n.content)});else if(e.type==="result"){e.is_error?o.apiError=o.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?o.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const n=e.usage||e.message?.usage;if(n){const a=Number.isFinite(Number(e.total_cost_usd))?Number(e.total_cost_usd):null,c=Number(s?.costUsdBefore)||0;s&&a!=null&&(s.costUsdTotal=a),t({type:"usage",provider:"bridge",inputTokens:n.input_tokens||0,outputTokens:n.output_tokens||0,cacheReadTokens:n.cache_read_input_tokens||0,cacheWriteTokens:n.cache_creation_input_tokens||0,costUsd:a!=null?Math.max(0,a-c):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return o}const
|
|
7
|
+
`}),e.boundary=!1)}function ne(e,t){!e||!t||(e.sawText=!0,e.tail=t.slice(-2))}function se(e,t,r,i="",s=null){const o={streamed:!1,result:null};if(typeof e?.session_id=="string"&&e.session_id&&(o.sessionId=e.session_id),e.type==="stream_event"){const n=e.event;n?.type==="content_block_delta"&&(n.delta?.type==="text_delta"?(o.streamed=!0,re(s,t),t({type:"delta",text:n.delta.text}),ne(s,n.delta.text)):n.delta?.type==="thinking_delta"&&t({type:"reasoning",text:n.delta.thinking||""}))}else if(e.type==="assistant"){if(e.is_api_error_message||e.error)return o.apiError=(e.message?.content||[]).filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
8
|
+
`)||String(e.error||"api error"),o;for(const n of e.message?.content||[])n.type==="tool_use"?(s&&(s.boundary=!0),t({type:"tool",name:n.name,phase:"start",callId:n.id,input:n.input,summary:Je(n,i),...typeof e.parent_tool_use_id=="string"&&e.parent_tool_use_id?{parent:e.parent_tool_use_id}:{}})):n.type==="text"&&!r&&(o.streamed=!0,re(s,t),t({type:"delta",text:n.text}),ne(s,n.text))}else if(e.type==="user")for(const n of e.message?.content||[])n.type==="tool_result"&&t({type:"tool",phase:"done",callId:n.tool_use_id,status:n.is_error?"error":"ok",result:He(n.content)});else if(e.type==="result"){e.is_error?o.apiError=o.apiError||String(e.result||e.subtype||"error"):e.subtype==="success"?o.result=e.result||"":t({type:"status",text:`(${e.subtype})`});const n=e.usage||e.message?.usage;if(n){const a=Number.isFinite(Number(e.total_cost_usd))?Number(e.total_cost_usd):null,c=Number(s?.costUsdBefore)||0;s&&a!=null&&(s.costUsdTotal=a),t({type:"usage",provider:"bridge",inputTokens:n.input_tokens||0,outputTokens:n.output_tokens||0,cacheReadTokens:n.cache_read_input_tokens||0,cacheWriteTokens:n.cache_creation_input_tokens||0,costUsd:a!=null?Math.max(0,a-c):null,costBasis:"list",...s?.harnessChars!=null?{harnessChars:s.harnessChars}:{}})}}return o}const oe=process.env.CHATPANEL_CLAUDE_EFFORT??"low";let N=null;function ae({probe:e=null}={}){return N||(N=(async()=>{try{return String(await(e?e():new Promise(t=>{const[r,i,s]=J(v(),["--help"],null),o=z(r,i,{...s,stdio:["ignore","pipe","pipe"]});let n="";o.stdout.on("data",a=>{n+=a}),o.on("error",()=>t("")),o.on("close",()=>t(n)),setTimeout(()=>{try{o.kill()}catch{}t(n)},8e3).unref?.()}))||"")}catch{return""}})(),N)}async function Ue(e={}){return/--effort\b/.test(await ae(e))}async function qe(e={}){return/--append-system-prompt(?:-file\b|\[-file\])/.test(await ae(e))}function bt(){N=null}async function Be({system:e,options:t,tag:r,resume:i=null,name:s=""}){const o=t.permissionMode||"default",n=F(t.workingDir),a=["--print","--output-format","stream-json","--include-partial-messages","--verbose"];oe&&await Ue()&&a.push("--effort",oe),a.push(...Te({harness:"claude",roots:we(n),dirs:t.dirs}));const c=[],u=[],d=je(t.mcp);if(d){const l=D.join(P.tmpdir(),`chatpanel-mcp-${r}.json`);await R(l,JSON.stringify(d.config)),c.push(l),a.push("--mcp-config",l),u.push(...d.allowedTools)}const y=De(t.reach);if(y){const l=Re(t.reach,await Ae("claude").catch(()=>[]));a.push("--allowedTools",...y.allow,...u,...l.allow),a.push("--disallowedTools",...y.deny,...l.deny)}else o==="bypassPermissions"?a.push("--permission-mode","bypassPermissions"):o==="acceptEdits"?(a.push("--permission-mode","acceptEdits"),u.length&&a.push("--allowedTools",...u)):a.push("--allowedTools",...V,...u);const g=!y&&t.approvals===!0;if(g&&a.push("--permission-prompt-tool","stdio"),e)if(v()?.kind!=="wsl"&&await qe()){const h=D.join(P.tmpdir(),`chatpanel-system-${r}.md`);await R(h,e,{mode:384}),c.push(h),a.push("--append-system-prompt-file",h)}else a.push("--append-system-prompt",e);t.model&&a.push("--model",t.model),t.useLocalConfig===!1&&a.push("--setting-sources",""),i?a.push(...j({harness:"claude",mode:"resume",id:i})):t.ephemeral===!0&&a.push(...j({harness:"claude",mode:"off"})),t.ephemeral||a.push(...j({harness:"claude",mode:"name",name:s}));const w=d&&!process.env.MCP_TOOL_TIMEOUT?{MCP_TOOL_TIMEOUT:String(Se(t.mcp?.specs))}:null,_=t.askDepth?{CHATPANEL_ASK_DEPTH:String(Math.max(0,Math.min(8,Number(t.askDepth)||0)))}:null,f=w||_||t.runEnv?{...t.runEnv||{},...w||{},..._||{}}:null;return{args:a,cwd:n,runEnv:f,cleanup:()=>c.forEach(l=>G(l).catch(()=>{})),hasMcp:!!d,approvals:g,peers:!y}}function ie({prompt:e="",system:t="",specs:r=null}={}){const i=Array.isArray(r)&&r.length?JSON.stringify(r).length:0;return String(e).length+String(t).length+i}function ze(e,t=[],r=""){let i=K(e,r);return t.length&&(i+=`
|
|
9
9
|
|
|
10
|
-
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}const Ge="This Claude Code session is in the middle of a turn in another window (VS Code or a terminal). Send again when it finishes — both sides continue the same session.";async function wt({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=ge("claude",e,r,{cwd:F(r.workingDir)}),a=n?.plan.mode==="resume"?Ee().get(n.plan.sessionId):void 0;if(a==="busy")throw new Error(Ge);if(a){const d=await H({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o});d?.completed&&d.thread?.record(d.sessionId);return}const c=await ve({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o}).catch(d=>({handled:!1,reason:d?.message||String(d),thrown:!0}));if(c.handled){c.completed&&n?.record(c.sessionId);return}if(o?.aborted)return;if(c.thrown)throw new Error(c.reason);const u=await H({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o});u?.completed&&u.thread?.record(u.sessionId)}async function H({messages:e,system:t,options:r,images:i,thread:s=null},o,{signal:n}={}){const a=`${Date.now()}-${Math.random().toString(36).slice(2)}`,c=s?.plan.mode==="resume"?s.plan.sessionId:null,u=await Be({system:t,options:r,tag:a,resume:c,name:s?.thread.title||""}),{args:d,cwd:y,runEnv:g}=u,w=await Oe(i,a),_=()=>{w.forEach(
|
|
10
|
+
The user attached ${t.length} image file(s). Use the Read tool to view ${t.length===1?"it":"them"}: ${t.join(", ")}`),i}const Ge="This Claude Code session is in the middle of a turn in another window (VS Code or a terminal). Send again when it finishes — both sides continue the same session.";async function wt({messages:e,system:t,options:r,images:i},s,{signal:o}={}){const n=ge("claude",e,r,{cwd:F(r.workingDir)}),a=n?.plan.mode==="resume"?Ee().get(n.plan.sessionId):void 0;if(a==="busy")throw new Error(Ge);if(a){const d=await H({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o});d?.completed&&d.thread?.record(d.sessionId);return}const c=await ve({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o}).catch(d=>({handled:!1,reason:d?.message||String(d),thrown:!0}));if(c.handled){c.completed&&n?.record(c.sessionId);return}if(o?.aborted)return;if(c.thrown)throw new Error(c.reason);const u=await H({messages:e,system:t,options:r,images:i,thread:n},s,{signal:o});u?.completed&&u.thread?.record(u.sessionId)}async function H({messages:e,system:t,options:r,images:i,thread:s=null},o,{signal:n}={}){const a=`${Date.now()}-${Math.random().toString(36).slice(2)}`,c=s?.plan.mode==="resume"?s.plan.sessionId:null,u=await Be({system:t,options:r,tag:a,resume:c,name:s?.thread.title||""}),{args:d,cwd:y,runEnv:g}=u,w=await Oe(i,a),_=()=>{w.forEach(p=>G(p).catch(()=>{})),u.cleanup()},f=ze(c?s.plan.tail?.length?s.plan.tail:e.slice(-1):e,w);xe(d,r.extraArgs,Ce.claude,o);const T=u.approvals&&r.permissionSession?p=>r.accessGate?r.accessGate.ask(r.permissionSession,p):Pe(r.permissionSession,p):null;let l=!1;const b=te({prompt:f,args:d,cwd:y,env:g,emit:c?p=>{(p?.type==="delta"||p?.type==="tool")&&(l=!0),o(p)}:o,signal:n,harness:ie({prompt:f,system:t,specs:r.mcp?.specs}),host:u.approvals,ask:T,peers:u.peers});if(b===null)return _(),await Ye({messages:e,system:t,options:r},o,{signal:n}),null;let E;try{E=await b}catch(p){if(_(),c&&!l&&!n?.aborted)return s.forget(),H({messages:e,system:t,options:r,images:i,thread:s.restart()},o,{signal:n});throw p}return _(),E.stopped?{completed:!1,thread:s}:(o({type:"done",text:E.streamedAny?"":E.resultText}),{completed:!0,sessionId:E.sessionId,thread:s})}async function Tt({prompt:e,system:t,model:r}){const i=["--print","--output-format","stream-json","--verbose","--disallowedTools","Read","Grep","Glob","WebFetch","WebSearch","Bash","Edit","Write","Task","TodoWrite","--setting-sources","","--model",r||"haiku","--system-prompt",t||"Continue the user's text briefly. Reply with only the continuation.","--no-session-persistence"];let s="";const o=te({prompt:e,args:i,cwd:null,peers:!1,emit:a=>{a.type==="delta"&&(s+=a.text)}});if(o===null)return Ke({prompt:e,system:t,model:r});const{resultText:n}=await o;return(s||n||"").trim()}function Je(e,t=""){const r=e.input||{};return r.command?String(r.command).slice(0,60):r.file_path?ke(r.file_path,t):r.pattern?r.pattern:r.url?r.url:r.description?String(r.description).slice(0,80):r.query?String(r.query).slice(0,80):r.prompt?String(r.prompt).slice(0,80):""}let U=null;function q(){return U||(U=import("@anthropic-ai/claude-agent-sdk").catch(()=>null)),U}async function Ye({messages:e,system:t,options:r},i,{signal:s}={}){const o=await q();if(!o)throw new Error(O);const{query:n}=o,a=new AbortController;s&&(s.aborted?a.abort():s.addEventListener("abort",()=>a.abort(),{once:!0}));const c=r.permissionMode||"default",u=F(r.workingDir),d=c==="acceptEdits"||c==="bypassPermissions",y=new Set(V),g=async h=>y.has(h)||d?{behavior:"allow",updatedInput:void 0}:{behavior:"deny",message:`${h} blocked — set this agent's permission mode in ChatPanel to enable it.`};let w=!1;const _=K(e),f={sawText:!1,tail:"",boundary:!1,harnessChars:ie({prompt:_,system:t})};let T="";const l=n({prompt:_,options:{cwd:u,permissionMode:c,includePartialMessages:!0,canUseTool:g,abortController:a,settingSources:r.useLocalConfig===!1?[]:["user","project"],systemPrompt:t?{type:"preset",preset:"claude_code",append:t}:{type:"preset",preset:"claude_code"},...r.model?{model:r.model}:{},...process.env.CHATPANEL_MAX_TURNS?{maxTurns:Number(process.env.CHATPANEL_MAX_TURNS)}:{}}});try{for await(const h of l){const b=se(h,i,w,u,f);b.streamed&&(w=!0),b.result!=null&&(T=b.result)}}catch(h){if(s?.aborted||a.signal.aborted)return;throw h}i({type:"done",text:w?"":T})}async function Ke({prompt:e,system:t,model:r}){const i=await q();if(!i)throw new Error(O);const{query:s}=i;let o="";const n=s({prompt:e,options:{cwd:P.homedir(),permissionMode:"default",allowedTools:[],maxTurns:1,settingSources:[],systemPrompt:t||"Continue the user's text briefly. Reply with only the continuation.",model:r||"haiku"}});for await(const a of n)if(a.type==="assistant")for(const c of a.message.content)c.type==="text"&&(o+=c.text);else a.type==="result"&&a.subtype==="success"&&!o&&(o=a.result||"");return o.trim()}export{Ge as SESSION_BUSY,bt as _resetEffortProbe,Fe as answerControlRequest,yt as available,Be as buildClaudeLaunch,Re as channelMcpTools,De as channelToolPolicy,wt as chat,H as chatCold,je as claudeMcpConfig,ze as claudePrompt,Ue as claudeSupportsEffort,qe as claudeSupportsSystemPromptFile,Tt as complete,se as handleMessage,ie as harnessChars,_t as listModels,Oe as writeImages};
|
package/src/env.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import j from"node:os";import{spawnGroupOpts as U}from"./proc.js";import c from"node:path";import{spawn as X,spawnSync as w}from"node:child_process";import{readdirSync as M,readFileSync as D,existsSync as f}from"node:fs";let z=!1,Q=!1;const R=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function jn(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(f(c.join(o,n))||f(c.join(o,n+".exe"))))}function hn(n){const t=I(n);if(t)return t;if(k()){const o=I(n);if(o)return o}return _n(n)||null}function Jn(n){return!!B(n,{probe:"async"})}function I(n){for(const t of dn(n))if(f(t))return t;return null}function $(){const n=c.basename(process.execPath).toLowerCase();return!(n.startsWith("node")||n.startsWith("bun"))}function Zn(n){const t=["--mcp-stdio",n];if($())return{command:process.execPath,args:t};const o=process.argv[1]||c.join(process.cwd(),"src","server.js"),e=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...e,...t]}}const b="CHATPANEL_ENV",W=6e3;function T(n){for(const t of String(n||"").split(/\r?\n/)){const o=t.indexOf(" ");if(o>0&&t.slice(0,o).trim().endsWith(b))return t.slice(o+1).trim()}return""}function q(n){return/^[\w.+-]+$/.test(String(n||""))}function v(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=j.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function J(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const o=t?["-l","-i","-c"]:["-l","-c"];return w(v(),[...o,n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function wn(n){let t="";for(const o of String(n||"").split(/\r?\n/))o.startsWith("PATH=")&&(t=o.slice(5).trim());return t}function bn({interactive:n=!0,ask:t=J}={}){const o=T(t(`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,{interactive:n}));return d(o||wn(t("/usr/bin/env",{interactive:n})),process.platform)}const y=1e4,Pn=3e5;let L=0,x=y;function k({force:n=!1,now:t=Date.now(),read:o=bn,env:e=process.env}={}){if(process.platform==="win32"||!n&&(t-L<x||t<_))return!1;L=t;const i=d(e.PATH||"",process.platform),r=Y(m([...o({interactive:!0}),...i])),s=r.length>i.length;return x=s?y:Math.min(x*2,Pn),s?(e.PATH=r.join(c.delimiter),!0):!1}function nt(){L=0,x=y,h.clear(),_=0,A=H,O=!1}const h=new Map,gn=15e3;function _n(n){if(process.platform==="win32"||!q(n))return"";const t=h.get(n);if(t&&(t.bin||Date.now()-t.at<gn||Date.now()<_))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${b} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let e="";for(const i of[!1,!0]){for(const r of o){const s=J(r,{interactive:i}),l=T(s)||String(s||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&f(l)){e=l;break}}if(e)break}return h.set(n,{bin:e,at:Date.now()}),e}const H=15e3,An=3e5;let _=0,A=H,O=!1,E=null;function xn(n,{interactive:t}={}){return new Promise(o=>{let e="",i;try{i=X(v(),[...t?["-l","-i","-c"]:["-l","-c"],n],{stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}})}catch{o("");return}const r=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},W);i.stdout.on("data",s=>{e+=s}),i.on("error",()=>{clearTimeout(r),o("")}),i.on("close",()=>{clearTimeout(r),o(e)})})}const En=new RegExp(`${b}=([\\w.+-]+)$`);function Z(n){const t=new Map;for(const o of String(n||"").split(/\r?\n/)){const e=o.indexOf(" ");if(e<=0)continue;const i=En.exec(o.slice(0,e).trim());i&&t.set(i[1],o.slice(e+1).trim())}return t}function tt({names:n=R,ask:t=xn,now:o=()=>Date.now()}={}){if(process.platform==="win32"||O)return Promise.resolve(!1);if(E)return E;if(o()<_)return Promise.resolve(!1);const e=m([...n,...h.keys()]).filter(r=>q(r)&&!I(r)&&!h.get(r)?.bin);if(!e.length)return Promise.resolve(!1);const i=[`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,...e.map(r=>`command -p printf '%s\\t%s\\n' ${b}=${r} "$(command -v ${r} 2>/dev/null)"`)].join("; ");return E=(async()=>{let r=await t(i,{interactive:!0}),s=Z(r);if(s.size||(r=await t(i,{interactive:!1}),s=Z(r)),!s.size)return O=!0,!0;const l=o();let a=!1;const u=d(T(r),process.platform);u.length&&k({force:!0,now:l,read:()=>u})&&(a=!0);for(const p of e){if(!s.has(p))continue;const P=s.get(p),g=P.startsWith("/")&&f(P)?P:"";(g||I(p))&&(a=!0),h.set(p,{bin:g,at:l})}return a&&(A=H),_=l+A,a||(A=Math.min(A*2,An)),!0})().catch(()=>!0).finally(()=>{E=null}),E}function et(){_=0,A=H,O=!1,L=0,x=y,F=0;for(const[n,t]of h)t.bin||h.delete(n);for(const[n,t]of S)t.ok||S.delete(n)}function ot({probe:n="sync"}={}){return process.env.CHATPANEL_CLAUDE_PATH?B(process.env.CHATPANEL_CLAUDE_PATH,{probe:n}):B("claude",{probe:n})}function B(n,{probe:t="sync"}={}){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!f(n))return null;const i=c.extname(n).toLowerCase();return!$()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&i===""&&!fn(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const i=On(n);return i||(/^[\w.-]+$/.test(n)&&kn(n,{probe:t})?{kind:"wsl",command:n}:null)}const e=hn(n);return e?{kind:"native",bin:e}:null}const Sn="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",Cn="HKCU\\Environment",Mn=4e3,In=3e5;let F=0,nn=0;function Tn(n,t="Path"){const o=String(t).toLowerCase();for(const e of String(n||"").split(/\r?\n/)){const i=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(e);if(i&&i[1].toLowerCase()===o)return i[2]}return""}function tn(n,t=process.env){const o=new Map(Object.keys(t||{}).map(e=>[e.toLowerCase(),t[e]]));return String(n||"").replace(/%([^%]+)%/g,(e,i)=>{const r=o.get(String(i).toLowerCase());return r==null?e:String(r)})}function vn(n,t){try{const o=c.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),e=w(f(o)?o:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return e.status===0?Tn(e.stdout,t):""}catch{return""}}function yn({query:n=vn,env:t=process.env}={}){const o=tn(n(Sn,"Path"),t),e=tn(n(Cn,"Path"),t);return m([...d(o,"win32"),...d(e,"win32")])}function Ln({run:n=Hn}={}){const t=n(`[Console]::Out.Write("${b}\`t" + $env:PATH + "\`n")`);return d(T(t),"win32")}function Hn(n){for(const t of["pwsh.exe","powershell.exe"])try{const o=w(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],windowsHide:!0}),e=K(o.stdout||"");if(e)return e}catch{}return""}function en({force:n=!1,now:t=Date.now(),registry:o=yn,profile:e=Ln,env:i=process.env,home:r=j.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-nn<Mn)return!1;nn=t;const s=d(i.PATH||"","win32"),l=m([...s,...o({env:i}),...G(r,"win32",i)]);t-F>=In&&R.some(u=>!l.some(p=>f(c.win32.join(p,`${u}.cmd`))||f(c.win32.join(p,`${u}.exe`))))&&(F=t,l.push(...e()));const a=Y(m(l),"win32");return a.length===s.length?!1:(i.PATH=a.join(V("win32")),!0)}function On(n){return on(n)||(en()?on(n):null)}function on(n){const t=C("win32");for(const o of dn(n,j.homedir(),"win32",process.env)){if(!f(o))continue;const e=t.dirname(o),i=t.extname(o).toLowerCase(),r=n==="claude"&&Dn(e)||Rn(e,n)||(/^\.(c?js|mjs)$/.test(i)?o:null);if(r){if(!$())return{kind:"script",script:r};const s=Nn(e);if(s)return{kind:"script",script:r,runtime:s}}if(i===".exe")return{kind:"native",bin:o};if(i===".cmd"||i===".bat")return{kind:"cmd",bin:o};if(i===""&&fn(o))return{kind:"native",bin:o}}return null}function Nn(n,{env:t=process.env,exists:o=f}={}){const e=c.win32,i=m([n,...d(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],e.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of i){const s=e.join(r,"node.exe");if(o(s))return s}return null}function Dn(n){const t=[["node_modules","@anthropic-ai","claude-code","cli.js"],["..","node_modules","@anthropic-ai","claude-code","cli.js"],["..","lib","node_modules","@anthropic-ai","claude-code","cli.js"]];for(const o of t){const e=c.join(n,...o);if(f(e))return e}return null}function Rn(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let e;try{e=D(c.join(n,o),"utf8")}catch{continue}const i=e.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(i){const r=c.join(n,i[1].replace(/[\\/]+/g,c.sep));if(f(r))return r}}return null}const S=new Map,N=new Map,$n=15e3,Wn=3e5,rn=8e3,sn=n=>["-e","bash","-lic",`command -v ${n}`];function cn(n,t){return n!==0?!1:(K(String(t||"")).replace(/\0/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).pop()||"").startsWith("/")}function ln(n,t,o){const e=S.get(n),i=t?0:Math.min(e&&!e.ok&&e.ttl?e.ttl*2:$n,Wn);S.set(n,{ok:t,at:o,ttl:i})}function kn(n,{probe:t="sync",now:o=Date.now(),spawnSyncImpl:e=w,spawnImpl:i=X}={}){const r=S.get(n);if(r&&(r.ok||o-r.at<r.ttl))return r.ok;if(t==="async"){if(!N.has(n)){const l=new Promise(a=>{let u="",p;try{p=i("wsl.exe",sn(n),{windowsHide:!0,stdio:["ignore","pipe","ignore"]})}catch{a(!1);return}const P=setTimeout(()=>{try{p.kill()}catch{}},rn);p.stdout?.on("data",g=>{u+=g}),p.on("error",()=>{clearTimeout(P),a(!1)}),p.on("close",g=>{clearTimeout(P),a(cn(g,u))})}).then(a=>(ln(n,a,Date.now()),a)).finally(()=>N.delete(n));N.set(n,l)}return!1}let s=!1;try{const l=e("wsl.exe",sn(n),{encoding:"utf8",timeout:rn,windowsHide:!0});s=cn(l.status,l.stdout)}catch{s=!1}return ln(n,s,o),s}function it(n){return N.get(n)||null}function rt(n,t,o,e=null){const i=e&&typeof e=="object"&&Object.keys(e).length?{...process.env,...e}:process.env;if(n.kind==="wsl"){const s=[];if(o){const a=Bn(o);a&&s.push("--cd",a)}return["wsl.exe",[...s,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U}]}const r={cwd:o||j.homedir(),stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U};return n.kind==="script"?[n.runtime||process.execPath,[n.script,...t],r]:n.kind==="cmd"?["cmd.exe",["/d","/s","/c",n.bin,...t],r]:[n.bin,t,r]}function Bn(n){try{const t=w("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=K(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function K(n){return n.replace(/^/,"").trim()}function Fn(n=j.homedir(),t=process.env){const o=c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node");let e;try{e=M(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!e.length)return null;const i=(r,s)=>{const l=r.slice(1).split(".").map(Number),a=s.slice(1).split(".").map(Number);for(let u=0;u<3;u+=1)if((l[u]||0)!==(a[u]||0))return(a[u]||0)-(l[u]||0);return 0};try{const r=D(c.join(t.NVM_DIR||c.join(n,".nvm"),"alias","default"),"utf8").trim(),s=r.startsWith("v")?r:`v${r}`;if(e.includes(s))return c.join(o,s,"bin")}catch{}return c.join(o,e.sort(i)[0],"bin")}function Kn(n,t=process.env){return[c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"shims"),c.join(n,".local","share","rtx","shims"),c.join(t.ASDF_DATA_DIR||c.join(n,".asdf"),"shims"),c.join(t.PYENV_ROOT||c.join(n,".pyenv"),"shims"),c.join(t.RBENV_ROOT||c.join(n,".rbenv"),"shims"),c.join(t.NODENV_ROOT||c.join(n,".nodenv"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"bin"),c.join(t.VOLTA_HOME||c.join(n,".volta"),"bin")]}function Vn(n,t=process.env){const o=[],e=(i,r)=>{try{for(const s of M(i))o.push(c.join(i,s,r))}catch{}};return e(c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node"),"bin"),e(c.join(n,".local","share","fnm","node-versions"),c.join("installation","bin")),e(c.join(n,"Library","Application Support","fnm","node-versions"),c.join("installation","bin")),e(c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"installs","node"),"bin"),o}function C(n){return n==="win32"?c.win32:c}function V(n){return n==="win32"?";":c.delimiter}function d(n,t){return(n||"").split(V(t)).filter(Boolean)}function m(n){return[...new Set(n.filter(Boolean))]}const an={win32:3e4,other:65536};function Y(n,t=process.platform){const o=t==="win32"?an.win32:an.other,e=V(t),i=[];let r=0;for(const s of n){const l=s.length+(i.length?e.length:0);if(r+l>o)break;i.push(s),r+=l}return i}function G(n,t=process.platform,o=process.env){const e=C(t);if(t==="win32"){const i=o.APPDATA||e.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||e.join(n,"AppData","Local"),s=o.ProgramFiles||"C:\\Program Files",l=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=o.ProgramData||"C:\\ProgramData";return[e.join(n,".local","bin"),e.join(n,".codex","bin"),e.join(n,".claude","bin"),e.join(n,".claude","local"),e.join(n,".claude","local","bin"),e.join(i,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],e.join(s,"nodejs"),...Yn(i,r),e.join(r,"pnpm"),e.join(r,"Yarn","bin"),e.join(r,"Volta","bin"),e.join(n,".yarn","bin"),e.join(n,".bun","bin"),e.join(n,".deno","bin"),e.join(o.SCOOP||e.join(n,"scoop"),"shims"),e.join(a,"chocolatey","bin"),e.join(r,"Microsoft","WindowsApps"),e.join(r,"Microsoft","WinGet","Links"),e.join(o.MISE_DATA_DIR||e.join(r,"mise"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"bin"),e.join(r,"Programs","Claude Code"),e.join(r,"Anthropic","Claude Code"),e.join(s,"Claude Code"),e.join(s,"Anthropic","Claude Code"),e.join(l,"Claude Code"),e.join(l,"Anthropic","Claude Code")]}return[c.join(n,".local","bin"),c.join(n,".opencode","bin"),c.join(n,".codex","bin"),c.join(n,".claude","bin"),c.join(n,".claude","local"),c.join(n,".claude","local","bin"),o.PNPM_HOME||c.join(n,"Library","pnpm"),c.join(n,".local","share","pnpm"),c.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",c.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...Kn(n,o)]}function Yn(n,t){const o=c.win32,e=[];for(const i of[o.join(t,"fnm"),o.join(n,"fnm")]){let r=[];try{r=M(o.join(i,"node-versions")).filter(s=>/^v?\d+\.\d+\.\d+/.test(s)).sort((s,l)=>l.localeCompare(s,void 0,{numeric:!0}))}catch{}for(const s of r)e.push(o.join(i,"node-versions",s,"installation"))}return e}function un(n,t=process.platform){const o=C(t),e=o.join(n,".local","share","claude","versions");let i=[];try{i=M(e).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,s)=>s.localeCompare(r,void 0,{numeric:!0}))}catch{}return i.map(r=>o.join(e,r))}function pn(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function fn(n,t=D){try{const o=t(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function Gn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=i.join(t,".local","bin",n),s=o==="win32"?e.LOCALAPPDATA||i.join(t,"AppData","Local"):null,l=o==="win32"?e.ProgramFiles||"C:\\Program Files":null,a=o==="win32"?e["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,u={claude:[r,i.join(t,".claude","bin","claude"),i.join(t,".claude","local","claude"),i.join(t,".claude","local","bin","claude"),...o==="win32"?[i.join(s,"Microsoft","WindowsApps","claude.exe"),i.join(s,"Programs","Claude Code","claude.exe"),i.join(s,"Anthropic","Claude Code","claude.exe"),i.join(l,"Claude Code","claude.exe"),i.join(l,"Anthropic","Claude Code","claude.exe"),i.join(a,"Claude Code","claude.exe"),i.join(a,"Anthropic","Claude Code","claude.exe"),...un(t,o)]:un(t,o)],codex:[r,i.join(t,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[i.join(t,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return m((u[n]||[r]).flatMap(p=>pn(p,o)))}function dn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=m([...d(e.PATH||"",o),...G(t,o,e)]).flatMap(s=>pn(i.join(s,n),o));return m([...r,...Gn(n,t,o,e)])}const mn=["DEEPSEEK_API_KEY","DSH_HOME","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","GEMINI_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"];function st(){if(Q||(Q=!0,process.platform==="win32"))return;const n=mn.filter(t=>!process.env[t]);if(n.length)try{const t=v(),o=`${n.map(i=>`[ -n "\${${i}:-}" ] && printf '%s\\t%s\\n' ${i} "$${i}"`).join("; ")}; true`,e=w(t,["-l","-i","-c",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const i of String(e.stdout||"").split(`
|
|
2
|
-
`)){const r=i.indexOf(" ");if(r<=0)continue;const s=i.slice(0,r).trim(),l=i.slice(r+1);mn.includes(s)&&!process.env[s]&&l&&(process.env[s]=l)}}catch{}}function
|
|
1
|
+
import{isCompiledBinary as jn,hostFacts as wn}from"./events/runtime-host.js";import j from"node:os";import{spawnGroupOpts as U}from"./proc.js";import c from"node:path";import{spawn as X,spawnSync as h}from"node:child_process";import{readdirSync as M,readFileSync as D,existsSync as f}from"node:fs";let z=!1,Q=!1;const R=["codex","claude","agy","pi","opencode","kiro-cli","copilot","dsh"];function hn(n){return d(process.env.PATH||"",process.platform).some(o=>o&&(f(c.join(o,n))||f(c.join(o,n+".exe"))))}function bn(n){const t=I(n);if(t)return t;if(k()){const o=I(n);if(o)return o}return xn(n)||null}function tt(n){return!!B(n,{probe:"async"})}function I(n){for(const t of dn(n))if(f(t))return t;return null}function $(){return jn(wn())}function et(n){const t=["--mcp-stdio",n];if($())return{command:process.execPath,args:t};const o=process.argv[1]||c.join(process.cwd(),"src","server.js"),e=process.env.CHATPANEL_BRIDGE_EMBEDDED==="1"?["--bridge"]:[];return{command:process.execPath,args:[o,...e,...t]}}const b="CHATPANEL_ENV",W=6e3;function T(n){for(const t of String(n||"").split(/\r?\n/)){const o=t.indexOf(" ");if(o>0&&t.slice(0,o).trim().endsWith(b))return t.slice(o+1).trim()}return""}function q(n){return/^[\w.+-]+$/.test(String(n||""))}function v(){if(process.env.SHELL)return process.env.SHELL;try{const{shell:n}=j.userInfo();if(n&&n!=="/usr/bin/false"&&n!=="/sbin/nologin")return n}catch{}return"/bin/sh"}function J(n,{interactive:t}={}){if(process.platform==="win32")return"";try{const o=t?["-l","-i","-c"]:["-l","-c"];return h(v(),[...o,n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}}).stdout||""}catch{return""}}function gn(n){let t="";for(const o of String(n||"").split(/\r?\n/))o.startsWith("PATH=")&&(t=o.slice(5).trim());return t}function Pn({interactive:n=!0,ask:t=J}={}){const o=T(t(`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,{interactive:n}));return d(o||gn(t("/usr/bin/env",{interactive:n})),process.platform)}const y=1e4,_n=3e5;let L=0,x=y;function k({force:n=!1,now:t=Date.now(),read:o=Pn,env:e=process.env}={}){if(process.platform==="win32"||!n&&(t-L<x||t<_))return!1;L=t;const i=d(e.PATH||"",process.platform),r=Y(m([...o({interactive:!0}),...i])),s=r.length>i.length;return x=s?y:Math.min(x*2,_n),s?(e.PATH=r.join(c.delimiter),!0):!1}function ot(){L=0,x=y,w.clear(),_=0,A=H,O=!1}const w=new Map,An=15e3;function xn(n){if(process.platform==="win32"||!q(n))return"";const t=w.get(n);if(t&&(t.bin||Date.now()-t.at<An||Date.now()<_))return t.bin;const o=[`command -p printf '%s\\t%s\\n' ${b} "$(command -v ${n} 2>/dev/null)"`,`type -p ${n}`];let e="";for(const i of[!1,!0]){for(const r of o){const s=J(r,{interactive:i}),l=T(s)||String(s||"").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.startsWith("/")).pop()||"";if(l.startsWith("/")&&f(l)){e=l;break}}if(e)break}return w.set(n,{bin:e,at:Date.now()}),e}const H=15e3,En=3e5;let _=0,A=H,O=!1,E=null;function Sn(n,{interactive:t}={}){return new Promise(o=>{let e="",i;try{i=X(v(),[...t?["-l","-i","-c"]:["-l","-c"],n],{stdio:["ignore","pipe","ignore"],env:{...process.env,TERM:"dumb"}})}catch{o("");return}const r=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},W);i.stdout.on("data",s=>{e+=s}),i.on("error",()=>{clearTimeout(r),o("")}),i.on("close",()=>{clearTimeout(r),o(e)})})}const Cn=new RegExp(`${b}=([\\w.+-]+)$`);function Z(n){const t=new Map;for(const o of String(n||"").split(/\r?\n/)){const e=o.indexOf(" ");if(e<=0)continue;const i=Cn.exec(o.slice(0,e).trim());i&&t.set(i[1],o.slice(e+1).trim())}return t}function it({names:n=R,ask:t=Sn,now:o=()=>Date.now()}={}){if(process.platform==="win32"||O)return Promise.resolve(!1);if(E)return E;if(o()<_)return Promise.resolve(!1);const e=m([...n,...w.keys()]).filter(r=>q(r)&&!I(r)&&!w.get(r)?.bin);if(!e.length)return Promise.resolve(!1);const i=[`command -p printf '%s\\t%s\\n' ${b} "$PATH"`,...e.map(r=>`command -p printf '%s\\t%s\\n' ${b}=${r} "$(command -v ${r} 2>/dev/null)"`)].join("; ");return E=(async()=>{let r=await t(i,{interactive:!0}),s=Z(r);if(s.size||(r=await t(i,{interactive:!1}),s=Z(r)),!s.size)return O=!0,!0;const l=o();let a=!1;const u=d(T(r),process.platform);u.length&&k({force:!0,now:l,read:()=>u})&&(a=!0);for(const p of e){if(!s.has(p))continue;const g=s.get(p),P=g.startsWith("/")&&f(g)?g:"";(P||I(p))&&(a=!0),w.set(p,{bin:P,at:l})}return a&&(A=H),_=l+A,a||(A=Math.min(A*2,En)),!0})().catch(()=>!0).finally(()=>{E=null}),E}function rt(){_=0,A=H,O=!1,L=0,x=y,F=0;for(const[n,t]of w)t.bin||w.delete(n);for(const[n,t]of S)t.ok||S.delete(n)}function st({probe:n="sync"}={}){return process.env.CHATPANEL_CLAUDE_PATH?B(process.env.CHATPANEL_CLAUDE_PATH,{probe:n}):B("claude",{probe:n})}function B(n,{probe:t="sync"}={}){if(!n)return null;if(n.includes("/")||n.includes("\\")||/\.[a-z0-9]+$/i.test(n)){if(!f(n))return null;const i=c.extname(n).toLowerCase();return!$()&&/^\.(c?js|mjs)$/.test(i)?{kind:"script",script:n}:process.platform==="win32"&&(i===".cmd"||i===".bat")?{kind:"cmd",bin:n}:process.platform==="win32"&&i===""&&!fn(n)?null:{kind:"native",bin:n}}if(process.platform==="win32"){const i=Dn(n);return i||(/^[\w.-]+$/.test(n)&&Fn(n,{probe:t})?{kind:"wsl",command:n}:null)}const e=bn(n);return e?{kind:"native",bin:e}:null}const Mn="HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",In="HKCU\\Environment",Tn=4e3,vn=3e5;let F=0,nn=0;function yn(n,t="Path"){const o=String(t).toLowerCase();for(const e of String(n||"").split(/\r?\n/)){const i=/^\s*(\S+)\s+REG_(?:EXPAND_)?SZ\s+(.*?)\s*$/.exec(e);if(i&&i[1].toLowerCase()===o)return i[2]}return""}function tn(n,t=process.env){const o=new Map(Object.keys(t||{}).map(e=>[e.toLowerCase(),t[e]]));return String(n||"").replace(/%([^%]+)%/g,(e,i)=>{const r=o.get(String(i).toLowerCase());return r==null?e:String(r)})}function Ln(n,t){try{const o=c.win32.join(process.env.SystemRoot||"C:\\Windows","System32","reg.exe"),e=h(f(o)?o:"reg",["query",n,"/v",t],{encoding:"utf8",timeout:3e3,windowsHide:!0});return e.status===0?yn(e.stdout,t):""}catch{return""}}function Hn({query:n=Ln,env:t=process.env}={}){const o=tn(n(Mn,"Path"),t),e=tn(n(In,"Path"),t);return m([...d(o,"win32"),...d(e,"win32")])}function On({run:n=Nn}={}){const t=n(`[Console]::Out.Write("${b}\`t" + $env:PATH + "\`n")`);return d(T(t),"win32")}function Nn(n){for(const t of["pwsh.exe","powershell.exe"])try{const o=h(t,["-NoLogo","-NonInteractive","-ExecutionPolicy","Bypass","-Command",n],{encoding:"utf8",timeout:W,stdio:["ignore","pipe","ignore"],windowsHide:!0}),e=K(o.stdout||"");if(e)return e}catch{}return""}function en({force:n=!1,now:t=Date.now(),registry:o=Hn,profile:e=On,env:i=process.env,home:r=j.homedir()}={}){if(process.platform!=="win32"&&!n||!n&&t-nn<Tn)return!1;nn=t;const s=d(i.PATH||"","win32"),l=m([...s,...o({env:i}),...G(r,"win32",i)]);t-F>=vn&&R.some(u=>!l.some(p=>f(c.win32.join(p,`${u}.cmd`))||f(c.win32.join(p,`${u}.exe`))))&&(F=t,l.push(...e()));const a=Y(m(l),"win32");return a.length===s.length?!1:(i.PATH=a.join(V("win32")),!0)}function Dn(n){return on(n)||(en()?on(n):null)}function on(n){const t=C("win32");for(const o of dn(n,j.homedir(),"win32",process.env)){if(!f(o))continue;const e=t.dirname(o),i=t.extname(o).toLowerCase(),r=n==="claude"&&$n(e)||Wn(e,n)||(/^\.(c?js|mjs)$/.test(i)?o:null);if(r){if(!$())return{kind:"script",script:r};const s=Rn(e);if(s)return{kind:"script",script:r,runtime:s}}if(i===".exe")return{kind:"native",bin:o};if(i===".cmd"||i===".bat")return{kind:"cmd",bin:o};if(i===""&&fn(o))return{kind:"native",bin:o}}return null}function Rn(n,{env:t=process.env,exists:o=f}={}){const e=c.win32,i=m([n,...d(t.PATH||"","win32"),...t.NVM_SYMLINK?[t.NVM_SYMLINK]:[],e.join(t.ProgramFiles||"C:\\Program Files","nodejs")]);for(const r of i){const s=e.join(r,"node.exe");if(o(s))return s}return null}function $n(n){const t=[["node_modules","@anthropic-ai","claude-code","cli.js"],["..","node_modules","@anthropic-ai","claude-code","cli.js"],["..","lib","node_modules","@anthropic-ai","claude-code","cli.js"]];for(const o of t){const e=c.join(n,...o);if(f(e))return e}return null}function Wn(n,t){for(const o of[`${t}.cmd`,t,`${t}.ps1`]){let e;try{e=D(c.join(n,o),"utf8")}catch{continue}const i=e.match(/(?:%~?dp0%|\$basedir|\$\{basedir\})[\\/]+([^"'\s]+\.[cm]?js)/i);if(i){const r=c.join(n,i[1].replace(/[\\/]+/g,c.sep));if(f(r))return r}}return null}const S=new Map,N=new Map,kn=15e3,Bn=3e5,rn=8e3,sn=n=>["-e","bash","-lic",`command -v ${n}`];function cn(n,t){return n!==0?!1:(K(String(t||"")).replace(/\0/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).pop()||"").startsWith("/")}function ln(n,t,o){const e=S.get(n),i=t?0:Math.min(e&&!e.ok&&e.ttl?e.ttl*2:kn,Bn);S.set(n,{ok:t,at:o,ttl:i})}function Fn(n,{probe:t="sync",now:o=Date.now(),spawnSyncImpl:e=h,spawnImpl:i=X}={}){const r=S.get(n);if(r&&(r.ok||o-r.at<r.ttl))return r.ok;if(t==="async"){if(!N.has(n)){const l=new Promise(a=>{let u="",p;try{p=i("wsl.exe",sn(n),{windowsHide:!0,stdio:["ignore","pipe","ignore"]})}catch{a(!1);return}const g=setTimeout(()=>{try{p.kill()}catch{}},rn);p.stdout?.on("data",P=>{u+=P}),p.on("error",()=>{clearTimeout(g),a(!1)}),p.on("close",P=>{clearTimeout(g),a(cn(P,u))})}).then(a=>(ln(n,a,Date.now()),a)).finally(()=>N.delete(n));N.set(n,l)}return!1}let s=!1;try{const l=e("wsl.exe",sn(n),{encoding:"utf8",timeout:rn,windowsHide:!0});s=cn(l.status,l.stdout)}catch{s=!1}return ln(n,s,o),s}function ct(n){return N.get(n)||null}function lt(n,t,o,e=null){const i=e&&typeof e=="object"&&Object.keys(e).length?{...process.env,...e}:process.env;if(n.kind==="wsl"){const s=[];if(o){const a=Kn(o);a&&s.push("--cd",a)}return["wsl.exe",[...s,"-e","bash","-lic",`exec ${n.command} "$@"`,"chatpanel",...t],{stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U}]}const r={cwd:o||j.homedir(),stdio:["pipe","pipe","pipe"],env:i,windowsHide:!0,...U};return n.kind==="script"?[n.runtime||process.execPath,[n.script,...t],r]:n.kind==="cmd"?["cmd.exe",["/d","/s","/c",n.bin,...t],r]:[n.bin,t,r]}function Kn(n){try{const t=h("wsl.exe",["-e","wslpath","-a",n],{encoding:"utf8",timeout:5e3,windowsHide:!0}),o=K(t.stdout||"").trim();return o.startsWith("/")?o:null}catch{return null}}function K(n){return n.replace(/^/,"").trim()}function Vn(n=j.homedir(),t=process.env){const o=c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node");let e;try{e=M(o).filter(r=>/^v\d+\./.test(r))}catch{return null}if(!e.length)return null;const i=(r,s)=>{const l=r.slice(1).split(".").map(Number),a=s.slice(1).split(".").map(Number);for(let u=0;u<3;u+=1)if((l[u]||0)!==(a[u]||0))return(a[u]||0)-(l[u]||0);return 0};try{const r=D(c.join(t.NVM_DIR||c.join(n,".nvm"),"alias","default"),"utf8").trim(),s=r.startsWith("v")?r:`v${r}`;if(e.includes(s))return c.join(o,s,"bin")}catch{}return c.join(o,e.sort(i)[0],"bin")}function Yn(n,t=process.env){return[c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"shims"),c.join(n,".local","share","rtx","shims"),c.join(t.ASDF_DATA_DIR||c.join(n,".asdf"),"shims"),c.join(t.PYENV_ROOT||c.join(n,".pyenv"),"shims"),c.join(t.RBENV_ROOT||c.join(n,".rbenv"),"shims"),c.join(t.NODENV_ROOT||c.join(n,".nodenv"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"shims"),c.join(t.PROTO_HOME||c.join(n,".proto"),"bin"),c.join(t.VOLTA_HOME||c.join(n,".volta"),"bin")]}function Gn(n,t=process.env){const o=[],e=(i,r)=>{try{for(const s of M(i))o.push(c.join(i,s,r))}catch{}};return e(c.join(t.NVM_DIR||c.join(n,".nvm"),"versions","node"),"bin"),e(c.join(n,".local","share","fnm","node-versions"),c.join("installation","bin")),e(c.join(n,"Library","Application Support","fnm","node-versions"),c.join("installation","bin")),e(c.join(t.MISE_DATA_DIR||c.join(n,".local","share","mise"),"installs","node"),"bin"),o}function C(n){return n==="win32"?c.win32:c}function V(n){return n==="win32"?";":c.delimiter}function d(n,t){return(n||"").split(V(t)).filter(Boolean)}function m(n){return[...new Set(n.filter(Boolean))]}const an={win32:3e4,other:65536};function Y(n,t=process.platform){const o=t==="win32"?an.win32:an.other,e=V(t),i=[];let r=0;for(const s of n){const l=s.length+(i.length?e.length:0);if(r+l>o)break;i.push(s),r+=l}return i}function G(n,t=process.platform,o=process.env){const e=C(t);if(t==="win32"){const i=o.APPDATA||e.join(n,"AppData","Roaming"),r=o.LOCALAPPDATA||e.join(n,"AppData","Local"),s=o.ProgramFiles||"C:\\Program Files",l=o["ProgramFiles(x86)"]||"C:\\Program Files (x86)",a=o.ProgramData||"C:\\ProgramData";return[e.join(n,".local","bin"),e.join(n,".codex","bin"),e.join(n,".claude","bin"),e.join(n,".claude","local"),e.join(n,".claude","local","bin"),e.join(i,"npm"),...o.NVM_SYMLINK?[o.NVM_SYMLINK]:[],e.join(s,"nodejs"),...Un(i,r),e.join(r,"pnpm"),e.join(r,"Yarn","bin"),e.join(r,"Volta","bin"),e.join(n,".yarn","bin"),e.join(n,".bun","bin"),e.join(n,".deno","bin"),e.join(o.SCOOP||e.join(n,"scoop"),"shims"),e.join(a,"chocolatey","bin"),e.join(r,"Microsoft","WindowsApps"),e.join(r,"Microsoft","WinGet","Links"),e.join(o.MISE_DATA_DIR||e.join(r,"mise"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"shims"),e.join(o.PROTO_HOME||e.join(n,".proto"),"bin"),e.join(r,"Programs","Claude Code"),e.join(r,"Anthropic","Claude Code"),e.join(s,"Claude Code"),e.join(s,"Anthropic","Claude Code"),e.join(l,"Claude Code"),e.join(l,"Anthropic","Claude Code")]}return[c.join(n,".local","bin"),c.join(n,".opencode","bin"),c.join(n,".codex","bin"),c.join(n,".claude","bin"),c.join(n,".claude","local"),c.join(n,".claude","local","bin"),o.PNPM_HOME||c.join(n,"Library","pnpm"),c.join(n,".local","share","pnpm"),c.join(n,".nix-profile","bin"),"/nix/var/nix/profiles/default/bin",c.join(n,".guix-profile","bin"),"/home/linuxbrew/.linuxbrew/bin","/snap/bin",...Yn(n,o)]}function Un(n,t){const o=c.win32,e=[];for(const i of[o.join(t,"fnm"),o.join(n,"fnm")]){let r=[];try{r=M(o.join(i,"node-versions")).filter(s=>/^v?\d+\.\d+\.\d+/.test(s)).sort((s,l)=>l.localeCompare(s,void 0,{numeric:!0}))}catch{}for(const s of r)e.push(o.join(i,"node-versions",s,"installation"))}return e}function un(n,t=process.platform){const o=C(t),e=o.join(n,".local","share","claude","versions");let i=[];try{i=M(e).filter(r=>/^\d+\.\d+\.\d+/.test(r)).sort((r,s)=>s.localeCompare(r,void 0,{numeric:!0}))}catch{}return i.map(r=>o.join(e,r))}function pn(n,t){return t!=="win32"?[n]:/\.(cmd|exe|bat|ps1)$/i.test(n)?[n]:[`${n}.exe`,`${n}.cmd`,`${n}.bat`,n,`${n}.ps1`]}function fn(n,t=D){try{const o=t(n).subarray(0,2);return o.length===2&&o[0]===77&&o[1]===90}catch{return!1}}function Xn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=i.join(t,".local","bin",n),s=o==="win32"?e.LOCALAPPDATA||i.join(t,"AppData","Local"):null,l=o==="win32"?e.ProgramFiles||"C:\\Program Files":null,a=o==="win32"?e["ProgramFiles(x86)"]||"C:\\Program Files (x86)":null,u={claude:[r,i.join(t,".claude","bin","claude"),i.join(t,".claude","local","claude"),i.join(t,".claude","local","bin","claude"),...o==="win32"?[i.join(s,"Microsoft","WindowsApps","claude.exe"),i.join(s,"Programs","Claude Code","claude.exe"),i.join(s,"Anthropic","Claude Code","claude.exe"),i.join(l,"Claude Code","claude.exe"),i.join(l,"Anthropic","Claude Code","claude.exe"),i.join(a,"Claude Code","claude.exe"),i.join(a,"Anthropic","Claude Code","claude.exe"),...un(t,o)]:un(t,o)],codex:[r,i.join(t,".codex","bin","codex")],agy:[r,"/Applications/Antigravity.app/Contents/MacOS/agy","/Applications/Antigravity IDE.app/Contents/MacOS/agy"],pi:[r],opencode:[i.join(t,".opencode","bin","opencode"),r],"kiro-cli":[r,"/Applications/Kiro CLI.app/Contents/MacOS/kiro-cli"]};return m((u[n]||[r]).flatMap(p=>pn(p,o)))}function dn(n,t=j.homedir(),o=process.platform,e=process.env){const i=C(o),r=m([...d(e.PATH||"",o),...G(t,o,e)]).flatMap(s=>pn(i.join(s,n),o));return m([...r,...Xn(n,t,o,e)])}const mn=["DEEPSEEK_API_KEY","DSH_HOME","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","GEMINI_API_KEY","GOOGLE_API_KEY","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"];function at(){if(Q||(Q=!0,process.platform==="win32"))return;const n=mn.filter(t=>!process.env[t]);if(n.length)try{const t=v(),o=`${n.map(i=>`[ -n "\${${i}:-}" ] && printf '%s\\t%s\\n' ${i} "$${i}"`).join("; ")}; true`,e=h(t,["-l","-i","-c",o],{encoding:"utf8",timeout:6e3,env:{...process.env,TERM:"dumb"}});for(const i of String(e.stdout||"").split(`
|
|
2
|
+
`)){const r=i.indexOf(" ");if(r<=0)continue;const s=i.slice(0,r).trim(),l=i.slice(r+1);mn.includes(s)&&!process.env[s]&&l&&(process.env[s]=l)}}catch{}}function ut(){if(z)return;z=!0;const n=j.homedir();if(process.platform==="win32"){en({force:!0,home:n});return}const t=Vn(n),o=[...t?[t]:[],"/opt/homebrew/bin","/opt/homebrew/sbin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",c.join(n,".local","bin"),c.join(n,"bin"),c.join(n,".npm-global","bin"),c.join(n,".cargo","bin"),c.join(n,".deno","bin"),c.join(n,".bun","bin"),...G(n),...Gn(n)];let e="";try{const s=v(),l=h(s,["-l","-c",'command -p echo "$PATH"'],{encoding:"utf8",timeout:4e3});l.status===0&&(e=(l.stdout||"").trim())}catch{}const i=new Set,r=[...t?[t]:[],...e?e.split(":"):[],...process.env.PATH?process.env.PATH.split(c.delimiter):[],...o].filter(s=>s&&!i.has(s)&&(i.add(s),!0));process.env.PATH=Y(r).join(c.delimiter),R.some(s=>!hn(s))&&k({force:!0})}export{R as AGENT_CLIS,tt as agentAvailable,Xn as agentCandidateBins,G as agentInstallDirs,lt as buildSpawnSpec,Y as capPathList,dn as commandCandidateFiles,Fn as commandInWsl,at as enrichAgentEnv,ut as enrichPath,tn as expandWindowsEnv,bn as findAgentBin,rt as forgetMisses,$ as isCompiledBinary,fn as isWindowsExecutable,Rn as nodeRuntimeWindows,Vn as nvmCurrentBin,gn as parseEnvPath,yn as parseRegValue,T as parseSentinel,Z as parseWhich,it as primeAgentLookups,On as profilePathWindows,k as refreshShellPath,en as refreshWindowsPath,Hn as registryPathWindows,ot as resetShellProbes,st as resolveClaude,B as resolveCommand,et as selfMcpStdio,Pn as shellPath,Kn as toWslPath,cn as wslAnswer,ct as wslProbeInFlight};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{EventError as j}from"./event.js";import{SECRET_PATHS as z}from"./sandbox-policy.js";import{egressAllowed as N}from"./policy.js";const p=e=>!!e&&typeof e=="object"&&!Array.isArray(e),c=(e,n)=>{if(!e)throw new j("SHAPE",n)},R=e=>[...new Set(e)],f=Object.freeze(["path","host"]),v=Object.freeze(["once","session","always"]),x=Object.freeze(["read","write"]),I=Object.freeze(["refused","ahead"]),H=Object.freeze(["grant","deny","ask"]),O=500,u=e=>{let n=String(e||"").trim();for(;n.length>1&&(n.endsWith("/")||n.endsWith("\\"));)n=n.slice(0,-1);return n},w=(e,n)=>n&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?n+e.slice(1):e;function g(e,n){const t=u(e),s=u(n);return!t||!s?!1:t===s||t.startsWith(`${s}/`)||t.startsWith(`${s}\\`)}function E(e,n=""){const t=u(w(u(e),n));return z.some(s=>g(t,u(s))||g(t,u(w(s,n))))}function M(e,n=""){const t=u(w(u(e),n));if(!t||t==="/"||t==="~"||/^[a-z]:$/i.test(t)||/^[a-z]:\\?$/i.test(t)||n&&t===u(n))return!0;const s=t.split(/[/\\]/).filter(Boolean).length;return t.startsWith("/")&&s<2}function b(e){c(p(e),"access request: must be an object");const n=e.what;c(p(n),"access request: what { kind, value, mode } required");const t=String(n.kind||"");c(f.includes(t),`access request: kind must be one of ${f.join(", ")}`);const s=t==="path"?u(n.value):String(n.value||"").trim().toLowerCase();c(s.length>0&&s.length<1024&&!s.includes("\0"),`access request: not a ${t}: ${JSON.stringify(n.value)}`);const o=n.mode==null?"write":String(n.mode);c(x.includes(o),`access request: mode must be one of ${x.join(", ")}`);const a=e.scope==null?"session":String(e.scope);c(v.includes(a),`access request: scope must be one of ${v.join(", ")}`);const i=e.asked==null?"refused":String(e.asked);return c(I.includes(i),`access request: asked must be one of ${I.join(", ")}`),{id:String(e.id||""),at:Number(e.at)||0,commandId:String(e.commandId||""),engine:String(e.engine||""),agentId:String(e.agentId||""),runId:String(e.runId||""),what:{kind:t,value:s,mode:o},why:String(e.why||"").slice(0,O),scope:a,asked:i,state:"pending"}}function P(e,{home:n=""}={}){c(p(e),"delegation: must be an object");const t=e.what;c(p(t),"delegation: what { kind, under | host, mode } required");const s=String(t.kind||"");c(f.includes(s),`delegation: kind must be one of ${f.join(", ")}`);const o=t.mode==null?"write":String(t.mode);c(x.includes(o),`delegation: mode must be one of ${x.join(", ")}`);const a=e.scope==null?"session":String(e.scope);c(a==="once"||a==="session","delegation: scope must be once or session — a standing grant is a person's decision, not a rule's");const i={id:String(e.id||""),label:String(e.label||"").slice(0,120),enabled:e.enabled!==!1,what:{kind:s,mode:o},scope:a};if(s==="path"){const r=u(t.under);c(r.length>0,"delegation: what.under is required — a rule without a root is not a bounded rule"),c(!E(r,n),`delegation: ${r} is a secret path and can never be granted`),c(!M(r,n),`delegation: ${r} is too broad to delegate — name the project folder, not the disk`),i.what.under=r}else{const r=String(t.host||t.under||"").trim().toLowerCase();c(/^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i.test(r)&&r!=="*",`delegation: not a host pattern: ${JSON.stringify(t.host)}`),i.what.host=r}return i.ttlMs=Math.max(0,Math.min(Number(e.ttlMs)||0,365*24*3600*1e3)),i.maxPerRun=e.maxPerRun==null?0:Math.max(0,Math.min(Number(e.maxPerRun)||0,1e3)),i.agents=R((Array.isArray(e.agents)?e.agents:[]).map(r=>String(r).trim()).filter(Boolean)),i.expiresAt=Number(e.expiresAt)||0,i.createdBy=String(e.createdBy||""),i}function _(e,n,{home:t=""}={}){if(!e?.enabled||e.what.kind!==n.what.kind||e.what.mode==="read"&&n.what.mode==="write"||e.agents.length&&!e.agents.includes(n.engine)&&!e.agents.includes(n.agentId))return!1;if(e.what.kind==="path")return g(w(n.what.value,t),w(e.what.under,t));const s=n.what.value;return e.what.host.startsWith("*.")?s===e.what.host.slice(2)||s.endsWith(e.what.host.slice(1)):s===e.what.host}const k=Object.freeze({ALLOW:"allow",ALWAYS:"allow_always",DENY:"deny"});function D(e){return e===k.ALWAYS?"always":"session"}function C(e,{home:n=""}={}){c(p(e),"access grant: must be an object");const t=e.what;c(p(t),"access grant: what required");const s=String(t.kind||"");c(f.includes(s),`access grant: kind must be one of ${f.join(", ")}`);const o=s==="path"?u(t.value):String(t.value||"").trim().toLowerCase();c(o.length>0,"access grant: what.value required"),c(!(s==="path"&&E(o,n)),`access grant: ${o} is a secret path and can never be granted`);const a=String(e.scope||"session");return c(v.includes(a),`access grant: scope must be one of ${v.join(", ")}`),{id:String(e.id||""),what:{kind:s,value:o,mode:t.mode==="read"?"read":"write"},scope:a,allow:e.allow!==!1,at:Number(e.at)||0,expiresAt:Number(e.expiresAt)||0,by:String(e.by||""),label:String(e.label||"").slice(0,200)}}function F(e,n,t,{now:s=0,newId:o=()=>"",home:a=""}={}){const i=b(n);if(t===k.DENY)return[...y(e,a),C({id:o(),what:i.what,scope:"session",allow:!1,at:s,by:"person"},{home:a})];const r=D(t),d=C({id:o(),what:i.what,scope:r,allow:!0,at:s,by:"person",label:i.what.value},{home:a}),m=[];for(const h of y(e,a)){if(h.allow&&W(h,i,{home:a,now:s})&&$(h.scope)>=$(r))return y(e,a);h.allow===d.allow&&h.what.kind===d.what.kind&&$(h.scope)<=$(r)&&W(d,{what:h.what,engine:i.engine},{home:a})||m.push(h)}return[...m,d]}const $=e=>e==="always"?2:e==="session"?1:0,y=(e,n="")=>(Array.isArray(e)?e:[]).map(t=>{try{return C(t,{home:n})}catch{return null}}).filter(Boolean);function W(e,n,{home:t="",now:s=0}={}){if(!e||e.expiresAt&&s&&s>e.expiresAt||e.what.kind!==n.what.kind||e.allow&&e.what.mode==="read"&&n.what.mode==="write")return!1;if(e.what.kind==="path")return g(w(n.what.value,t),w(e.what.value,t));const o=n.what.value;return e.what.value.startsWith("*.")?o===e.what.value.slice(2)||o.endsWith(e.what.value.slice(1)):o===e.what.value}function L(e,n,{home:t="",now:s=0}={}){const o=b(n),a=y(e,t).filter(r=>W(r,o,{home:t,now:s}));if(!a.length)return null;const i=a.find(r=>r.allow);return i?{verdict:"grant",by:{kind:"person",id:i.by},ruleId:i.id,reason:i.scope==="always"?"you allowed this folder":"you allowed this earlier in this chat",scope:i.scope,expiresAt:i.expiresAt||0}:{verdict:"deny",by:{kind:"person",id:a[0].by},ruleId:a[0].id,reason:"you denied this earlier in this chat",scope:"session"}}function G(e,n,{home:t=""}={}){return y(e,t).filter(s=>s.id!==String(n))}function J(e,{now:n=0,home:t=""}={}){return y(e,t).filter(s=>s.allow&&s.scope==="always"&&!(s.expiresAt&&n&&n>s.expiresAt))}const S=(e,n,t={})=>({verdict:e,by:n,ruleId:"",reason:"",...t});function K({request:e,delegations:n=[],policy:t=null,now:s=0,usedPerRule:o={},home:a="",canAsk:i=!0,grants:r=[]}={}){const d=b(e);if(d.what.kind==="path"&&E(d.what.value,a))return S("deny",{kind:"floor"},{reason:`${d.what.value} holds credentials or ChatPanel's own store, and is never grantable`});if(t&&d.what.kind==="host"&&!N(t,d.what.value))return S("deny",{kind:"policy"},{reason:`your organisation does not allow ${d.what.value}`});if(t&&d.what.kind==="path"&&Array.isArray(t.access?.deny)){const A=t.access.deny.find(l=>g(w(d.what.value,a),w(u(l),a)));if(A)return S("deny",{kind:"policy"},{reason:`your organisation does not allow access under ${A}`})}const m=L(r,d,{home:a,now:s});if(m)return m;const h=t?.access?.delegation!=="never";if(h)for(const A of n){let l;try{l=P(A,{home:a})}catch{continue}if(_(l,d,{home:a})&&!(l.expiresAt&&s&&s>l.expiresAt)&&!(l.maxPerRun&&(o[l.id]||0)>=l.maxPerRun))return S("grant",{kind:"delegation",id:l.createdBy||""},{ruleId:l.id,reason:l.label?`allowed by your rule “${l.label}”`:"allowed by a rule you set",scope:l.scope,expiresAt:l.ttlMs&&s?s+l.ttlMs:0})}return i?S("ask",{kind:"person"},{scope:d.scope}):S("deny",{kind:"floor"},{reason:h?"nothing here can approve this, and an unanswered request is a denial":"your organisation requires a person to approve this, and this run has nobody to ask"})}function V(e={},{newId:n=()=>"",now:t=0}={}){const s=e.path?"path":"host";return b({id:e.id||n()||"",at:e.at||t||0,commandId:e.commandId||"",engine:e.engine||"",agentId:e.agentId||"",runId:e.runId||"",what:{kind:s,value:s==="path"?e.path:e.host,mode:e.mode||"write"},why:e.why||"",scope:"session",asked:"refused"})}function X(e={}){const n=p(e.input)?e.input:{},t=String(e.tool||"");let o=((/^(Write|Edit|MultiEdit|NotebookEdit)$/.test(t)?String(n.file_path||n.notebook_path||""):"")||String(e.path||"")).trim();if(!o)for(const a of Array.isArray(e.rules)?e.rules:[]){if(!/^(Read|Edit|Write|MultiEdit|NotebookEdit)$/.test(String(a?.tool||"")))continue;const i=String(a.content||"").trim().replace(/\/\*\*$|\/\*$/,"");if(i.startsWith("//")){o=i.slice(1);break}if(i==="~"||i.startsWith("~/")){o=i;break}}return o&&!o.includes("\0")?o:null}function Q(e,{home:n=""}={}){const t=b(e),s=t.engine||t.agentId||"This agent",o=d=>n&&g(d,u(n))?`~${d.slice(u(n).length)}`:d,a=t.what.kind==="path",i=a?o(t.what.value):t.what.value,r=t.what.mode==="read"?"read":a?"write in":"reach";return{title:`${s} wants to ${r} ${a&&i.split(/[/\\]/).filter(Boolean).pop()||i}`,detail:i,kind:t.what.kind,why:t.why,answers:[{id:k.ALLOW,label:"Allow",hint:"for the rest of this chat"},{id:k.ALWAYS,label:`Always allow ${i}`,hint:"revoke any time in Settings › Runtime"},{id:k.DENY,label:"Deny",hint:""}]}}function U(e,n){const t=b(e),s=(t.what.kind==="path",t.what.value),o=t.engine||t.agentId||"the agent",a=t.what.mode==="read"?"read":"write in";if(n?.verdict==="grant"){const i=n.by?.kind==="delegation"?n.reason||"allowed by a rule you set":"allowed by you";return`${o} asked to ${a} ${s} — ${i}`}return n?.verdict==="deny"?`${o} asked to ${a} ${s} — denied${n.reason?` (${n.reason})`:""}`:`${o} is asking to ${a} ${s}`}export{k as ACCESS_ANSWERS,I as ACCESS_ASKED,f as ACCESS_KINDS,x as ACCESS_MODES,v as ACCESS_SCOPES,H as ACCESS_VERDICTS,O as WHY_MAX,V as accessRequestFromRefusal,K as decideAccess,_ as delegationCovers,Q as describeAccessCard,U as describeDecision,W as grantCovers,E as isSecretPath,M as isTooBroadRoot,C as normalizeAccessGrant,b as normalizeAccessRequest,P as normalizeDelegation,g as pathInside,X as permissionAccessTarget,L as recallAccess,F as rememberAccess,G as revokeAccess,D as scopeForAnswer,J as standingGrants};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
2
|
-
`);let
|
|
1
|
+
const T="permission_request",u=Object.freeze({ALLOW:"allow",ALLOW_CHAT:"allow_chat",DENY:"deny"}),W=600*1e3,w="permission_prompt";function E(){return{name:w,description:"Chap-internal: the person answers the agent's permission prompt. Not for the model.",parameters:{type:"object",properties:{tool:{type:"string"},input:{type:"object"},description:{type:"string"},path:{type:"string"},rules:{type:"array"}}}}}const k=t=>t===w,p=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),a=t=>typeof t=="string"?t:t==null?"":String(t);function R(t={}){const e=p(t)?t:{},o=a(e.tool_name||e.toolName||e.tool),s=[];for(const n of Array.isArray(e.permission_suggestions)?e.permission_suggestions:[])if(!(!p(n)||n.type!=="addRules"||n.behavior==="deny"))for(const l of Array.isArray(n.rules)?n.rules:[]){if(!p(l))continue;const c=a(l.toolName||o),i=a(l.ruleContent);c&&!s.some(f=>f.tool===c&&f.content===i)&&s.push({tool:c,content:i})}return{tool:o,displayName:a(e.display_name||e.displayName)||o,input:p(e.input)?e.input:{},description:a(e.description),path:a(e.blocked_path||e.path)||null,rules:s,toolUseId:a(e.tool_use_id||e.toolUseId)||null}}function A(t={}){const e=Array.isArray(t.rules)?t.rules.filter(o=>o&&o.tool):[];return e.length?e.map(o=>o.content?`${o.tool}(${o.content})`:o.tool):t.tool?[String(t.tool)]:[]}function L(t={}){const e=a(t.tool),o=p(t.input)?t.input:{},s=(r,d=240)=>r.length>d?`${r.slice(0,d-1)}…`:r;let n,l;if(e==="Bash")n="Run a command",l=s(a(o.command).trim()||a(t.description)||"a shell command");else if(e==="Edit"||e==="MultiEdit"||e==="NotebookEdit")n="Edit a file",l=a(o.file_path||o.notebook_path||t.path)||"a file";else if(e==="Write"){n="Write a file";const r=a(o.file_path||t.path)||"a file",d=a(o.content).length;l=d?`${r} (${d.toLocaleString()} chars)`:r}else if(/^mcp__/.test(e))n="Use a connected server",l=e.replace(/^mcp__/,"").replace(/__/," › ");else{n=`Use ${t.displayName||e||"a tool"}`;let r="";try{r=JSON.stringify(o)}catch{r=""}l=a(t.description)||(r&&r!=="{}"?s(r,200):e)}const c=A(t),i=Array.isArray(t.rules)?t.rules.filter(r=>r?.content):[],f=i.length&&i.some(r=>r.content!==l)?i.map(r=>r.content).join(", "):c.length&&!i.length?`every ${e} call`:null,h=p(t.access)?a(t.access.folder):"",g=h?`This works in ${h}, outside the folders it may change. Allowing it opens ${h} to it for the rest of this chat.`:null;return{title:n,detail:l,scope:f,description:a(t.description)||null,access:g}}function m(t,e=""){return t===u.ALLOW?{behavior:"allow",scope:"once"}:t===u.ALLOW_CHAT?{behavior:"allow",scope:"chat"}:{behavior:"deny",scope:"once",...e?{message:String(e)}:{}}}function b(t){return p(t)&&t.behavior==="allow"}function O(t,e){const o=new Set(Array.isArray(t)?t:[]);for(const s of A(e))o.add(s);return[...o].sort()}const S="*";function x(t,e){const o=new Set(Array.isArray(t)?t:[]);if(o.has(S))return m(u.ALLOW);const s=A(e);return s.length&&s.every(n=>o.has(n))?m(u.ALLOW):null}function C(t,e,o={}){const s=p(o)?o:{},n=b(e);let l;if(n){if(l={behavior:"allow",updatedInput:p(s.input)?s.input:{}},e.scope==="chat"){const c=(Array.isArray(s.permission_suggestions)?s.permission_suggestions:[]).filter(i=>p(i)&&i.type==="addRules"&&i.behavior!=="deny"&&Array.isArray(i.rules)&&i.rules.length).map(i=>({type:"addRules",rules:i.rules,behavior:"allow",destination:"session"}));c.length&&(l.updatedPermissions=c)}}else l={behavior:"deny",message:a(e?.message)||"The user declined this action in Chap. Continue without it, or explain what it was for and ask."};return{type:"control_response",response:{subtype:"success",request_id:String(t),response:l}}}function P(t,e){const{detail:o}=L(t),s=b(e),n=s&&e.scope==="chat"?" for this chat":"";return`${s?"Allowed":"Declined"}${n}: ${o}`}function $(t){return t==="Bash"?"code":/^(Edit|MultiEdit|NotebookEdit)$/.test(String(t))?"pencil":t==="Write"?"file":/^mcp__/.test(String(t))?"plug":"bot"}function I({memory:t=new Map}={}){const e=t;async function o(s,{convId:n=null,confirm:l,agentName:c="The agent"}={}){const i=p(s.access)?null:x(await e.get(n)||[],s);if(i)return i;const{title:f,detail:h,scope:g,description:r,access:d}=L(s),N=[d,h,r&&r!==h?r:"",g?`“Allow for this chat” also covers: ${g}`:""].filter(Boolean).join(`
|
|
2
|
+
`);let y;try{if(typeof l!="function")throw new Error("no card");y=await l(N,{title:`${c} asks — ${f.toLowerCase()}?`,iconName:$(s.tool),scopeLabel:"Allow for this chat",allLabel:"Allow all in this chat"})}catch(_){return m(u.DENY,`Chap could not show the permission card (${_?.message||_}).`)}return y==="all"?(await e.set(n,[S]),m(u.ALLOW_CHAT)):y==="site"||y==="always"?(await e.set(n,O(await e.get(n)||[],s)),m(u.ALLOW_CHAT)):m(y==="allow"?u.ALLOW:u.DENY)}return{ask:o,forget(s){e.delete(s)},standing(s){return e.get(s)||[]},provider({convId:s=null,confirm:n,agentName:l="The agent"}={}){return{id:"permission",specs:[E()],execute:async(c,i)=>JSON.stringify(await o(i&&typeof i=="object"?i:{},{convId:s,confirm:n,agentName:l}))}}}}export{S as ALLOW_ALL,u as PERMISSION_ANSWERS,T as PERMISSION_EVENT,W as PERMISSION_TIMEOUT_MS,w as PERMISSION_TOOL_NAME,C as claudePermissionResponse,I as createPermissionDesk,L as describePermission,k as isPermissionTool,b as permissionAllowed,m as permissionAnswer,$ as permissionIcon,A as permissionKeys,P as permissionLine,R as permissionRequestFromClaude,E as permissionToolSpec,x as recallPermission,O as rememberPermission};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SANDBOX_RUNTIMES as A,SANDBOX_READ_MODES as $,parseWrapperTemplate as R}from"./sandbox-choice.js";class l extends Error{constructor(r){super(r),this.name="PolicyError"}}const O=1,z="policy",w=Object.freeze(["off","basic","full"]),k=Object.freeze({off:0,basic:1,full:2}),E=Object.freeze(["gateway","endpoints","redaction","features","agents"]),S=Object.freeze(["webllm","meetings","channels","agents"]),m=Object.freeze(["plan","default","acceptEdits","bypassPermissions"]),U=Object.freeze({plan:0,default:1,acceptEdits:2,bypassPermissions:3}),L=Object.freeze(["api.chatpanel.net","dl.chatpanel.net","huggingface.co","registry.npmjs.org","api.github.com"]),f=e=>typeof e=="string"?e.trim():"",c=e=>Array.isArray(e)?e.map(f).filter(Boolean):[];function b(e){const r=f(e).toLowerCase().replace(/^https?:\/\//,"").replace(/\/.*$/,"");if(!r)return"";if(!/^(\*\.)?[a-z0-9.-]+(:\d{1,5})?$/.test(r)&&!/^\[[0-9a-f:]+\](:\d{1,5})?$/.test(r)&&r!=="*")throw new l(`invalid host pattern "${e}"`);return r}function y(e){if(e==null)return y({});if(typeof e!="object"||Array.isArray(e))throw new l("policy must be an object");const r=e.v==null?O:Number(e.v);if(r!==O)throw new l(`unsupported policy version ${e.v}`);const n={v:r};if(e.org!=null){const t=f(e.org.id);if(!t||!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(t))throw new l("org.id must be a short identifier");n.org={id:t,name:f(e.org.name)||t}}const o=(t,s)=>{if(t==null)return;if(typeof t!="object")throw new l(`${s} must be an object`);const u={};return t.allow!=null&&(u.allow=c(t.allow).map(b).filter(Boolean)),t.deny!=null&&(u.deny=c(t.deny).map(b).filter(Boolean)),u},a=o(e.endpoints,"endpoints");a&&(n.endpoints=a);const i=o(e.egress,"egress");if(i&&(n.egress=i),e.models!=null){if(typeof e.models!="object")throw new l("models must be an object");n.models={},e.models.allow!=null&&(n.models.allow=c(e.models.allow)),e.models.deny!=null&&(n.models.deny=c(e.models.deny))}if(e.agents!=null){if(typeof e.agents!="object")throw new l("agents must be an object");const t={};if(e.agents.allow!=null&&(t.allow=c(e.agents.allow).map(s=>s.toLowerCase())),e.agents.deny!=null&&(t.deny=c(e.agents.deny).map(s=>s.toLowerCase())),e.agents.permissionModeCap!=null){const s=f(e.agents.permissionModeCap);if(!m.includes(s))throw new l(`agents.permissionModeCap must be one of ${m.join(", ")}`);t.permissionModeCap=s}n.agents=t}if(e.routing!=null){if(typeof e.routing!="object")throw new l("routing must be an object");const t=Array.isArray(e.routing.rules)?e.routing.rules:[];n.routing={rules:t.map((s,u)=>{if(!s||typeof s!="object")throw new l(`routing.rules[${u}] must be an object`);const p=c(s.models),j=c(s.endpoints).map(b).filter(Boolean);if(!p.length)throw new l(`routing.rules[${u}] needs at least one model pattern`);if(!j.length)throw new l(`routing.rules[${u}] needs at least one endpoint`);return{models:p,endpoints:j}})}}if(e.redaction!=null){if(typeof e.redaction!="object")throw new l("redaction must be an object");const t={};if(e.redaction.floor!=null){const s=f(e.redaction.floor).toLowerCase();if(!w.includes(s))throw new l(`redaction.floor must be one of ${w.join(", ")}`);t.floor=s}e.redaction.dictionary!=null&&(t.dictionary=c(e.redaction.dictionary)),e.redaction.requireBeforeCloud!=null&&(t.requireBeforeCloud=!!e.redaction.requireBeforeCloud),n.redaction=t}if(e.client!=null){if(typeof e.client!="object")throw new l("client must be an object");const t={};if(e.client.gatewayUrl!=null){const s=f(e.client.gatewayUrl);if(s&&!/^https?:\/\/[^\s/]+(\/.*)?$/.test(s))throw new l("client.gatewayUrl must be an http(s) URL");t.gatewayUrl=s.replace(/\/+$/,"")}if(e.client.managedRequired!=null&&(t.managedRequired=!!e.client.managedRequired),e.client.lock!=null){const s=c(e.client.lock);for(const u of s)if(!E.includes(u))throw new l(`client.lock: unknown setting "${u}" (one of ${E.join(", ")})`);t.lock=[...new Set(s)]}if(e.client.features!=null){if(typeof e.client.features!="object")throw new l("client.features must be an object");t.features={};for(const[s,u]of Object.entries(e.client.features)){if(!S.includes(s))throw new l(`client.features: unknown feature "${s}" (one of ${S.join(", ")})`);t.features[s]=!!u}}n.client=t}if(e.sandbox!=null){if(typeof e.sandbox!="object"||Array.isArray(e.sandbox))throw new l("sandbox must be an object");const t={};if(e.sandbox.required!=null&&(t.required=!!e.sandbox.required),e.sandbox.runtime!=null){const s=f(e.sandbox.runtime);if(!A.includes(s))throw new l(`sandbox.runtime must be one of ${A.join(", ")}`);t.runtime=s}if(e.sandbox.command!=null)try{t.command=R(e.sandbox.command)}catch(s){throw new l(s.message)}if(e.sandbox.image!=null){const s=f(e.sandbox.image);if(!/^[A-Za-z0-9][A-Za-z0-9._\/:@-]{0,254}$/.test(s))throw new l("sandbox.image must be an image reference");t.image=s}if(e.sandbox.reads!=null){const s=f(e.sandbox.reads);if(!$.includes(s))throw new l(`sandbox.reads must be one of ${$.join(", ")}`);t.reads=s}if(e.sandbox.mode!=null){const s=f(e.sandbox.mode);if(!["open","allowlist"].includes(s))throw new l("sandbox.mode must be open or allowlist (an org that sandboxes agents itself sets runtime: managed)");t.mode=s}if(t.runtime==="command"&&!t.command)throw new l("sandbox.runtime command needs sandbox.command");if(t.runtime==="container"&&!t.image)throw new l("sandbox.runtime container needs sandbox.image");Object.keys(t).length&&(n.sandbox=t)}if(e.gateway!=null){if(typeof e.gateway!="object"||Array.isArray(e.gateway))throw new l("gateway must be an object");e.gateway.confined!=null&&(n.gateway={confined:!!e.gateway.confined})}if(e.access!=null){if(typeof e.access!="object"||Array.isArray(e.access))throw new l("access must be an object");const t={};if(e.access.delegation!=null){const s=f(e.access.delegation);if(!C.includes(s))throw new l(`access.delegation must be one of ${C.join(", ")}`);t.delegation=s}for(const s of["deny","allow"]){if(e.access[s]==null)continue;const u=c(e.access[s]).map(p=>String(p).trim()).filter(Boolean);for(const p of u)if(p.length>1024||p.includes("\0"))throw new l(`access.${s}: not a path`);t[s]=u}Object.keys(t).length&&(n.access=t)}return n}function I(e={},r=null){const n=r?.sandbox||{},o={...e},a=[];for(const i of["runtime","command","image","reads","mode"])n[i]!==void 0&&(o[i]=n[i],a.push(i));return n.required!==void 0&&(o.required=n.required?"policy":!1,a.push("required")),{sandbox:o,locked:a}}const C=Object.freeze(["allowed","never"]);function D(e){return e?.access?.delegation==="never"?"never":"allowed"}function d(e){const r=f(e).toLowerCase();if(!r)return{host:"",port:""};try{const n=new URL(/^[a-z][a-z0-9+.-]*:\/\//.test(r)?r:`http://${r}`);return{host:n.hostname.replace(/^\[|\]$/g,""),port:n.port||(n.protocol==="https:"?"443":n.protocol==="http:"?"80":"")}}catch{return{host:r.split(":")[0],port:""}}}function P(e,r,n){if(e==="*")return!0;const[o,a]=e.startsWith("[")?[e.replace(/^\[([^\]]+)\].*$/,"$1"),e.replace(/^\[[^\]]+\]:?/,"")]:(()=>{const i=e.lastIndexOf(":");return i>0?[e.slice(0,i),e.slice(i+1)]:[e,""]})();if(a&&a!==n)return!1;if(o.startsWith("*.")){const i=o.slice(1);return r.endsWith(i)&&r.length>i.length}return r===o}function g(e,r,n){return(e||[]).some(o=>P(o,r,n))}function h(e){return new RegExp(`^${String(e).split("*").map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`,"i")}function T(e,r){const n=e?.endpoints;if(!n)return!0;const{host:o,port:a}=d(r);return!o||g(n.deny,o,a)?!1:n.allow&&n.allow.length?g(n.allow,o,a):!0}function M(e,r){const n=e?.models;if(!n)return!0;const o=f(r);return(n.deny||[]).some(a=>h(a).test(o))?!1:n.allow&&n.allow.length?n.allow.some(a=>h(a).test(o)):!0}function _(e,r){const n=e?.agents;if(!n)return!0;const o=f(r).toLowerCase();return(n.deny||[]).includes(o)?!1:n.allow&&n.allow.length?n.allow.includes(o):!0}function v(e,r){const n=e?.agents?.permissionModeCap,o=m.includes(r)?r:"default";return n?U[o]<=U[n]?o:n:o}function H(e,{model:r="",endpoint:n=""}={}){if(!e)return{ok:!0,reason:""};if(r&&!M(e,r))return{ok:!1,reason:`model "${r}" is not allowed by your organisation's policy`};if(n&&!T(e,n))return{ok:!1,reason:`endpoint ${d(n).host} is not allowed by your organisation's policy`};const o=e.routing?.rules||[];if(r&&n&&o.length){const a=o.find(i=>i.models.some(t=>h(t).test(r)));if(a){const{host:i,port:t}=d(n);if(!g(a.endpoints,i,t))return{ok:!1,reason:`model "${r}" may only be sent to ${a.endpoints.join(", ")} under your organisation's policy`}}}return{ok:!0,reason:""}}function q(e,r){const n=e?.redaction?.floor,o=w.includes(r)?r:"basic";return n?k[o]>=k[n]?o:n:o}function W(e,r,{local:n=!1}={}){const o=e?.egress;if(!o)return!0;const{host:a,port:i}=d(r);return!a||g(o.deny,a,i)?!1:n||L.includes(a)||e.endpoints?.allow?.length&&g(e.endpoints.allow,a,i)&&!g(e.endpoints?.deny,a,i)?!0:g(o.allow,a,i)}function K(e,r){return!!e?.client?.lock?.includes(r)}function N(e,r){const n=e?.client?.features;return!n||n[r]==null?!0:!!n[r]}function Y(e,r){const n={...r||{}},o=[];if(!e)return{settings:n,changed:o};const a=e.client||{};if(a.gatewayUrl&&n.gatewayUrl!==a.gatewayUrl&&(n.gatewayUrl=a.gatewayUrl,o.push("gatewayUrl")),Array.isArray(n.endpoints)&&e.endpoints){const i=n.endpoints.filter(t=>!t||typeof t!="object"?!1:!t.baseUrl||a.gatewayUrl&&d(t.baseUrl).host===d(a.gatewayUrl).host&&d(t.baseUrl).port===d(a.gatewayUrl).port?!0:T(e,t.baseUrl));i.length!==n.endpoints.length&&(n.endpoints=i,o.push("endpoints"))}if(Array.isArray(n.endpoints)&&e.agents){const i=n.endpoints.filter(t=>t?.kind!=="bridge"||_(e,t.bridgeAgent||t.agent||t.id));i.length!==n.endpoints.length&&(n.endpoints=i,o.push("agents"))}if(Array.isArray(n.endpoints)&&!N(e,"webllm")){const i=n.endpoints.filter(t=>t?.kind!=="webllm");i.length!==n.endpoints.length&&(n.endpoints=i,o.push("webllm"))}if(e.redaction?.floor&&(n.redaction?.tier!=null||n.redactionTier!=null)){const i=n.redaction?.tier!=null?n.redaction.tier:n.redactionTier,t=q(e,i);t!==i&&(n.redaction?.tier!=null?n.redaction={...n.redaction,tier:t}:n.redactionTier=t,o.push("redaction"))}return{settings:n,changed:o}}function J(e){const r=e?.org?.name||e?.org?.id;return r?`Managed by ${r}`:"Managed"}function x(e){return Array.isArray(e)?`[${e.map(x).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${x(e[r])}`).join(",")}}`:JSON.stringify(e)}async function X(e,{subtle:r=null}={}){const n=r||globalThis.crypto?.subtle;if(!n)throw new l("no WebCrypto available on this runtime");const o=new TextEncoder().encode(x(y(e))),a=await n.digest("SHA-256",o);return[...new Uint8Array(a)].map(i=>i.toString(16).padStart(2,"0")).join("")}async function Z(e,{verify:r,...n}={}){if(typeof r!="function")throw new l("verifyPolicyToken needs a verify function (entitlement.js verifySignedToken)");const o=await r(e,{...n,typ:z});if(!o||!o.policy)return null;try{return y(o.policy)}catch{return null}}export{C as ACCESS_DELEGATION,S as FEATURES,E as LOCKABLE,m as PERMISSION_MODES,z as POLICY_TOKEN_TYPE,O as POLICY_VERSION,L as PRODUCT_HOSTS,l as PolicyError,w as REDACTION_TIERS,D as accessDelegation,_ as agentAllowed,Y as applyPolicyToSettings,W as egressAllowed,T as endpointAllowed,N as featureEnabled,h as globToRegExp,M as modelAllowed,y as normalizeOrgPolicy,v as permissionMode,X as policyHash,J as policyLabel,q as redactionTier,H as routeAllowed,I as sandboxUnderPolicy,K as settingLocked,Z as verifyPolicyToken};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function r({bunMain:t="",versions:e={},execPath:i=""}={}){if(e.electron)return!1;const n=String(t||"");if(n)return n.startsWith("/$bunfs/")||/^[A-Za-z]:[\\/]~BUN[\\/]/.test(n);const s=String(i||"").split(/[\\/]/).pop().toLowerCase();return e.bun?!1:!(s.startsWith("node")||s.startsWith("bun"))}function o(){const t=globalThis.process;return{bunMain:typeof globalThis.Bun<"u"?String(globalThis.Bun.main||""):"",versions:t?.versions||{},execPath:t?.execPath||""}}export{o as hostFacts,r as isCompiledBinary};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=(o,e)=>{if(!o)throw Object.assign(new Error(e),{code:"SHAPE"})},c=Object.freeze(["enumerated","inverted"]),h=Object.freeze(["srt","container","command","managed"]);function u(o){const e=Array.isArray(o)?null:String(o??"").trim();let n;if(Array.isArray(o))n=o.map(String);else if(e.startsWith("[")){try{n=JSON.parse(e)}catch{r(!1,"sandbox command: not a JSON array")}r(Array.isArray(n)&&n.every(t=>typeof t=="string"),"sandbox command: a JSON array of strings")}else n=e.split(/\s+/).filter(Boolean);return r(n.length>0&&n.length<=128,"sandbox command: 1–128 words"),r(n.every(t=>t.length<=1024&&!t.includes("\0")),"sandbox command: a word too long or with a NUL"),r(!n[0].includes("{"),"sandbox command: the first word is the wrapper program, not a placeholder"),r(n.filter(t=>t==="{cmd}").length===1,"sandbox command: exactly one {cmd} word, where the command goes"),n}function m(o,{bin:e,argv:n=[],workdir:t="",home:i="",hosts:d=[],mode:a=""}={}){const l=s=>s.replaceAll("{workdir}",t).replaceAll("{home}",i).replaceAll("{hosts}",d.join(",")).replaceAll("{mode}",a);return o.flatMap(s=>s==="{cmd}"?[e,...n]:[l(s)])}function p(o){if(!o?.ok)return{cls:"off",text:"The local runtime (bridge) is not running — nothing is sandboxed because nothing is running."};const e=o.sandbox;if(!e)return{cls:"warn",text:`This bridge (v${o.version||"?"}) predates the sandbox — update the gateway.`};const n=e.required==="policy"?" Your organisation requires it: anything it cannot be applied to is refused, and nothing runs outside it.":e.required?" Required: anything it cannot be applied to is refused rather than run as you.":"";if(e.enabled===!1)return e.required?{cls:"bad",text:`The sandbox is required but switched off, so nothing runs.${n}`}:{cls:"warn",text:"Sandbox off — agents, MCP servers and workers run as you, with your files and your network."};if(!e.runtime){const a=`${e.reason||"no runtime"}${e.install?` (${e.install})`:""}`;return e.required?{cls:"bad",text:`Nothing runs — the sandbox is required and cannot be applied here: ${a}.`}:{cls:"warn",text:`Not sandboxed — ${a}`}}const t=String(e.runtime);if(t==="managed")return{cls:"ok",text:`Managed by your organisation — your agents run inside its sandbox, so ChatPanel does not add one of its own.${n}`};if(t.startsWith("command:"))return{cls:"ok",text:`Sandboxed by your own command (${t.slice(8)}) — it decides what each process may touch; ChatPanel hands it the working folder and the hosts each one is allowed.${n}`};if(t.startsWith("container:"))return{cls:"ok",text:`Sandboxed in containers (${t.slice(10)}) — each process sees only its working folder, with no capabilities${e.mode==="none"?" and no network":""}.${n}`};const i=e.mode==="allowlist"?"only its own service, the developer hosts and what you allow":e.mode==="none"?"nothing":"any public host through the sandbox proxy — never your machine, your network or a cloud metadata address",d=e.mode==="allowlist"?e.ownSessions?" A process granted hosts of its own gets a session of its own.":" Hosts granted on a card need a session of their own, which is not available here, so they share the allow list.":"";return{cls:"ok",text:`Sandboxed (${t}, ${e.platform||""}): the working directory writable, your secrets unreadable, the network ${i}.${d}${n}`}}export{c as SANDBOX_READ_MODES,h as SANDBOX_RUNTIMES,m as expandWrapper,u as parseWrapperTemplate,p as sandboxStatus};
|
|
@@ -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 $=Object.freeze(["none","process","container","kubernetes"]),N=Object.freeze(["open","allowlist","none","gateway"]),S=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),p=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(p(e)),r=m(p(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},G=S.map(e=>m(p(e)).replace(/^~\//,"").split("/").filter(Boolean));function C(e,t=""){const n=m(p(O(p(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 z=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 se(e,{home:t="",globs:n=[...S,...z]}={}){const r=m(p(O(p(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),s=m(p(t));for(const l of n){const c=m(p(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,g)=>d.test(o[i+g])))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 D=".cache/chatpanel/ca-bundle.crt",ie=".cache/chatpanel/ca-bundle.pem";function ae(e=""){const t=m(p(e));return t?`${t}/${D}`:`~/${D}`}const U=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"]),W=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),j=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:[]})}),Y="~/Library/Keychains",B=/(^|\/)Keychains\/?$/,R=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 k(e){return f((y(e).signIn||[]).flatMap(t=>R[t].read))}function M(e){return f((y(e).signIn||[]).flatMap(t=>R[t].hosts))}function ce(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=R[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),u=(e,t)=>{if(!e)throw new L("SHAPE",t)},f=e=>[...new Set(e)];function v(e){u(E(e),"kit: must be an object"),u(typeof e.id=="string"&&e.id.length>0,"kit: id required"),u(E(e.network)&&N.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${N.join(", ")}`),u(_(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),u(_(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),u(E(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])u(_(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return u(_(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),u(_(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&&u(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&u(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 _e,mergeGrants as be,mergePersonGrants as xe,parseHostList as Se,SIGN_IN_NAMES as Oe,SIGN_IN_LABELS as Ae}from"./sandbox-grant.js";const q=e=>String(e).replace(/([\\/])\*$/,"$1**");function le({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 g=j[e]||j.custom;u(typeof t=="string"&&t.length>0,"kit: cwd required");const h=y(l);return v({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:f([...g.hosts,...F,...r,...h.hosts,...M(h)]),deniedDomains:[],unixSockets:d?[...g.sockets||[]]:[]},filesystem:{allowWrite:f(i?[...W,...g.write]:[t,...W,...g.write,...[...o,...h.write].filter(I=>!C(I,c)).map(q)]),denyWrite:[],allowRead:f(a==="inverted"?[t,...U,...g.write,...g.keychain?[Y]:[],...V({grant:h,extraWrite:o,cwd:t,home:c}),...k(h)]:[t,...k(h)]),denyRead:f([...a==="inverted"?["~",...c?[c]:[]]:[],...[...S,...z].filter(I=>!(g.keychain&&B.test(I))),...s])}})}function X(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 V({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=X(s(o(s(i))));if(d&&!C(d,r)&&!(c&&l(d,c))&&!a.some(g=>l(d,g))){for(let g=a.length-1;g>=0;g--)l(a[g],d)&&a.splice(g,1);a.push(d)}}return a}function de(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=v(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 ue({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:s=null}={}){return u($.includes(e),`sandbox record: layer must be one of ${$.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function Q(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){u(!/[\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 Z=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function fe(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of Z)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 ge(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>Q(r,{platform:n})).join(" ")}const pe=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),J=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 ee(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 me({kit:e,files:t=[],home:n}){u(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("\\\\")||(u(!J(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=ee(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 te=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 we({engine:e="custom",home:t,env:n={},base:r={},carry:o=te}={}){u(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 he(e,t){u(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;u(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||{}))u(/^[A-Za-z_][A-Za-z0-9_]*$/.test(l),`srt-win env: bad key ${l}`),u(!/[\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{D as CA_BUNDLE_RELPATH,ie as CA_BUNDLE_RELPATH_LEGACY,W as COMMON_WRITE,F as DEVELOPER_HOSTS,j as ENGINE_KITS,N as NETWORK_MODES,$ as SANDBOX_LAYERS,S as SECRET_PATHS,z as SECRET_READ_GLOBS,Ae as SIGN_IN_LABELS,Oe as SIGN_IN_NAMES,R as SIGN_IN_STORES,U as TOOLCHAIN_READ,te as WINDOWS_CARRY_KEYS,ae as caBundlePath,C as isSecretWritePath,le as kitFor,be as mergeGrants,xe as mergePersonGrants,_e as normalizeGrant,Se as parseHostList,se as readDenialFor,fe as sandboxEnvOverlay,ue as sandboxRecord,ge as shellJoin,Q as shellQuote,ce as signInDenial,M as signInHosts,k as signInRead,de as toSrtSettings,b as underWindowsHome,v as validateKit,me as windowsGrantsFor,ee as windowsInstallRoot,we as windowsSandboxEnv,he as withSrtWinEnv,V 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"]),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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawnSync as M}from"node:child_process";import{existsSync as x}from"node:fs";import c from"node:path";import A from"node:os";import{defineSandboxRuntime as b,registerSandboxRuntime as w}from"./sandbox-runtime.js";import{sandboxRecord as _,parseWrapperTemplate as I,expandWrapper as D}from"./events/sandbox-policy.js";function h(n){if(c.isAbsolute(n))return x(n);try{const r=M(process.platform==="win32"?"where":"which",[n],{encoding:"utf8",timeout:3e3});return r.status===0&&String(r.stdout||"").trim().length>0}catch{return!1}}function y({config:n={},home:r=A.homedir(),isInstalled:s=h}={}){let e=null,t=null;function i(){if(!(e||t)){if(!n.command){t="no sandbox command is set — Settings › Runtime › Sandbox command";return}try{e=I(n.command)}catch(o){t=`the sandbox command is not usable: ${o.message.replace(/^sandbox command: /,"")}`;return}s(e[0])||(t=`${e[0]} (your sandbox command) is not installed on this computer`,e=null)}}return b({id:"command",label:"Your own sandbox command",async detect(){return i(),{ok:!!e,runtime:e?`command:${c.basename(e[0])}`:null,reason:t,ownSessions:!!e}},async wrap({kit:o,grant:a,bin:S,argv:d,opts:m,workdir:f,commandId:u}){if(i(),!e)return{passReason:t};const l=D(e,{bin:S,argv:d,workdir:f,home:r,hosts:a?.hosts||[],mode:o.network.mode}),g=_({layer:"process",runtime:`command:${c.basename(e[0])}`,kitId:o.id,mode:o.network.mode,hosts:a?.hosts||[]});return{bin:l[0],argv:l.slice(1),opts:{...m,shell:!1},record:g,commandId:u}}})}const T=/^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TMP|TEMP|PWD|OLDPWD|SHLVL|TERM_PROGRAM.*|TERM_SESSION_ID|SSH_AUTH_SOCK|SSH_AGENT_PID|DISPLAY|XPC_.*|__CF.*|SECURITYSESSIONID|LaunchInstanceID|Apple_.*|COMMAND_MODE|MallocNanoZone|ELECTRON_.*|_|NODE_OPTIONS)$/;function R({config:n={},isInstalled:r=h,platform:s=process.platform}={}){let e=null,t=null;function i(){if(e||t)return;if(!n.image){t="no container image is set — Settings › Runtime › Container image";return}const o=n.engine?[n.engine]:["podman","docker"];e=o.find(a=>r(a))||null,e||(t=`${o.join(" or ")} is not installed on this computer`)}return b({id:"container",label:"A container (Podman or Docker)",async detect(){return i(),{ok:!!e,runtime:e?`container:${e}`:null,reason:t,ownSessions:!!e}},async wrap({kit:o,bin:a,argv:S,opts:d,workdir:m,commandId:f}){if(i(),!e)return{passReason:t};const u=d?.env||process.env,l=Object.keys(u).filter(p=>!T.test(p)&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(p)).sort(),g=["run","--rm","-i","--init","--cap-drop","ALL","--security-opt","no-new-privileges",...o.network.mode==="none"?["--network","none"]:[],...e==="docker"&&s==="linux"&&process.getuid?["--user",`${process.getuid()}:${process.getgid()}`]:[],"-v",`${m}:${m}`,"-w",m,...l.flatMap(p=>["-e",p]),n.image,c.isAbsolute(a)?c.basename(a):a,...S],O=_({layer:"container",runtime:`container:${e}`,kitId:o.id,mode:o.network.mode});return{bin:e,argv:g,opts:{...d,env:u,shell:!1},record:O,commandId:f}}})}function E(){return b({id:"managed",label:"Managed by your organisation",async detect(){return{ok:!0,runtime:"managed",reason:null,ownSessions:!1}},async wrap({kit:n,bin:r,argv:s,opts:e,commandId:t}){return{bin:r,argv:s,opts:e,record:_({layer:"external",runtime:"managed",kitId:n.id,mode:n.network.mode}),commandId:t}}})}w("command",n=>y(n)),w("container",n=>R(n)),w("managed",()=>E());export{y as createCommandRuntime,R as createContainerRuntime,E as createManagedRuntime};
|
package/src/sandbox-host.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as
|
|
1
|
+
import{readFileSync as f,unlinkSync as u,realpathSync as i}from"node:fs";import{spawn as g}from"node:child_process";import{fileURLToPath as y}from"node:url";import{createSandbox as b}from"./sandbox.js";async function x(n,{compiled:l=!1}={}){n||(console.error("sandbox-host: a spec file is required"),process.exit(2));let r;try{r=JSON.parse(f(n,"utf8"))}catch(o){console.error(`sandbox-host: cannot read the spec: ${o.message}`),process.exit(2)}try{u(n)}catch{}const m=(o,t,h)=>{r.report?.url&&fetch(r.report.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:r.report.token,commandId:r.commandId,host:o,port:t,reason:h}),signal:AbortSignal.timeout(2e3)}).catch(()=>{})},a=b({config:r.config,loadSrt:()=>import(r.srt),compiled:l,loopback:r.loopback||[],onRefusal:o=>m(o.host,o.port,o.reason),log:o=>console.error(`[sandbox-host] ${o}`)});let e;try{e=await a.wrap(r.bin,r.argv,{cwd:r.cwd||void 0,env:process.env},{engine:r.engine,cwd:r.workdir,grant:r.grant,commandId:r.commandId})}catch(o){console.error(`[sandbox-host] ${o.message}`),process.exit(126)}e.record.layer==="none"&&console.error(`[sandbox-host] running outside the sandbox — ${e.record.reason}`);const s=g(e.bin,e.argv,{...e.opts,stdio:"inherit"}),c=o=>{try{s.kill(o)}catch{}};process.on("SIGTERM",()=>c("SIGTERM")),process.on("SIGINT",()=>c("SIGINT")),process.on("SIGHUP",()=>c("SIGHUP")),s.on("error",o=>{console.error(`[sandbox-host] could not start ${r.bin}: ${o.message}`),process.exit(127)}),s.on("exit",async(o,t)=>{try{a.close()}catch{}try{await(await import(r.srt)).SandboxManager.reset()}catch{}if(t)try{process.kill(process.pid,t)}catch{}process.exit(o??1)})}const p=(()=>{try{return i(y(import.meta.url))}catch{return""}})(),d=(()=>{try{return process.argv[1]?i(process.argv[1]):""}catch{return""}})();p&&d&&p===d&&await x(process.argv[2]);export{x as runSandboxHost};
|
package/src/sandbox-srt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as ke}from"node:child_process";import{writeFileSync as oe,mkdirSync as re,existsSync as De}from"node:fs";import{createHash as Ee,randomBytes as Oe}from"node:crypto";import{fileURLToPath as $e}from"node:url";import M from"node:os";import $ from"node:path";import{toSrtSettings as ie,sandboxRecord as Le,shellJoin as ae,sandboxEnvOverlay as F,windowsGrantsFor as Ce,windowsSandboxEnv as Re,withSrtWinEnv as Te,ENGINE_KITS as ce,DEVELOPER_HOSTS as de,SECRET_PATHS as Ne,COMMON_WRITE as He}from"./events/sandbox-policy.js";import{defineSandboxRuntime as _e,registerSandboxRuntime as Pe}from"./sandbox-runtime.js";function je(n=process.env.CHATPANEL_SRT_MODULE){if(!n)return"";try{const o=n.startsWith("file:")?$e(new URL("./cli.js",n)):$.join($.dirname(n),"cli.js");return De(o)?o:""}catch{return""}}const le=new Set;function ue(n,o=$.join(M.tmpdir(),"chatpanel-srt")){const y=JSON.stringify(n),p=$.join(o,`${Ee("sha256").update(y).digest("hex").slice(0,16)}.json`);return le.has(p)||(re(o,{recursive:!0,mode:448}),oe(p,y,{mode:384}),le.add(p)),p}function Me(){try{const n=ke(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return n.status===0&&String(n.stdout||"").trim().length>0}catch{return!1}}const z="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)";function Ue({config:n,platform:o=process.platform,home:y=M.homedir(),loopback:p=[],compiled:W=!1,selfFiles:he=[process.execPath,process.argv[1]||""],onExit:we=_=>process.on("exit",_),hostEntry:B=null,reportUrl:J="",mintReportToken:fe=()=>"",onRefusal:be=()=>{},parseRefusal:xe=()=>null,loadSrt:X=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:G=Me,cliEntry:K=je(),hostEntryFor:q=()=>"",log:L=()=>{}}={}){const _=new Set;let c=null,w=null,a=null,U=null,C=null,g=null,A=null;const R=new Set;let Q=!1;const me="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",pe="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function Se(){if(!n.windows){w=me;return}if(W){w=pe;return}try{a=await X()}catch(t){w=`sandbox-runtime is not installed — it ships with the gateway (${t.message})`;return}if(!a?.SandboxManager?.wrapWithSandboxArgv||typeof a.grantWindowsAcl!="function"||typeof a.getWindowsSandboxUserStatusAsync!="function"){w="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{g=a.resolveSrtWin({path:a.VENDORED_SRT_WIN_EXE})}catch(t){w=`Windows: srt-win.exe is not beside sandbox-runtime (${t.message})`;return}let e;try{e=await a.getWindowsSandboxUserStatusAsync({srtWin:g})}catch(t){A=!1,w=`Windows: srt-win could not be asked whether the sandbox account exists (${t.message}) — ${z}`;return}if(A=!!(e?.provisioned&&e.sid),!A){w=`Windows: the sandbox account is not installed — ${z}`;return}C=e.sid,c="srt-lib"}async function ye(){if(!(c||w)){if(!n.enabled){w="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(o==="win32")return Se();if(!W)try{if(a=await X(),a?.SandboxManager?.wrapWithSandboxArgv){c="srt-lib";return}}catch(e){L(`sandbox: library not available (${e.message})`)}if(G()){c="srt-cli";return}w=W?"srt is not on PATH — the compiled bridge cannot carry it: npm i -g @anthropic-ai/sandbox-runtime":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}}let Y=!1;function Z(e,{hosts:t=[],sockets:s=[]}={}){const r={...e.network};let i=!1;if((r.allowedDomains||[]).includes("*")){const d=r.allowedDomains.filter(l=>l.startsWith("127.0.0.1:"));r.allowedDomains=[...new Set([...Object.values(ce).flatMap(l=>l.hosts),...de,...n.extraHosts,...t,...d])],i=!0}return o==="darwin"&&s.length&&(r.allowUnixSockets=s),{settings:{...e,network:r},narrowed:i}}const ee=(e,{narrowed:t},s)=>(t&&(e.narrowed=`open → allowlist: the srt CLI refuses "*" — the gateway's embedded bridge runs open`),s.length&&o==="darwin"&&(e.sockets=s,delete e.socketsDropped),e);function I(){return K&&!W?{bin:process.execPath,argv:[K]}:c==="srt-cli"||G()?{bin:"srt",argv:[]}:null}function ge(){const e=Array.isArray(n.exactHosts)?n.exactHosts:n.mode==="open"?["*"]:n.mode==="none"?[]:[...new Set([...Object.values(ce).flatMap(r=>r.hosts),...de,...n.extraHosts])],t={id:`session:${n.mode}`,network:{mode:n.mode,allowedDomains:e},filesystem:{allowWrite:[M.tmpdir(),...He,...n.extraWrite],denyRead:[...Ne,...n.extraDenyRead]}},s=ie(t,{loopback:p,home:o==="linux"?y:"",platform:o});return o==="darwin"&&Array.isArray(n.exactSockets)&&n.exactSockets.length&&(s.network.allowUnixSockets=n.exactSockets),g?{...s,windows:{srtWin:{path:g.exe}}}:s}async function te(){return U||(U=a.SandboxManager.initialize(ge()).then(()=>{try{a.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(e=>{for(const t of e||[]){const s=xe(t?.line);if(!s||!t?.encodedCommand)continue;let r="";try{r=Buffer.from(t.encodedCommand,"base64").toString("utf8")}catch{continue}const i=`${r}|${s.host}|${t.timestamp instanceof Date?t.timestamp.getTime():String(t.timestamp)}`;_.has(i)||(_.add(i),be({commandId:r,...s,at:t.timestamp instanceof Date?t.timestamp.getTime():Date.now()}))}})}catch(e){L(`sandbox: violations not subscribed (${e.message})`)}})),U}function ve(e){const t=$.join(M.tmpdir(),"chatpanel-srt");re(t,{recursive:!0,mode:448});const s=$.join(t,`host-${Oe(8).toString("hex")}.json`);return oe(s,JSON.stringify(e),{mode:384}),s}function We(e,t){const s=(d,l)=>a.expandWindowsFsPaths(d,{mode:l}).filter(u=>!R.has(`${l}:${u.toLowerCase()}`)),r=s(e,"grant"),i=s(t,"grant");if(!(!r.length&&!i.length)){a.grantWindowsAcl({sandboxUserSid:C,read:r,write:i,srtWin:g});for(const d of r)R.add(`grant:${d.toLowerCase()}`);for(const d of i)R.add(`grant:${d.toLowerCase()}`);Q||(Q=!0,we(()=>{try{a.revokeWindowsAcl({sandboxUserSid:C,srtWin:g})}catch{}}))}}async function Ae(e,t,s,{engine:r,workdir:i,kit:d,settings:l,commandId:u,record:T,caBundle:S=""}){await te();const k=h=>typeof h=="string"&&/^[a-z]:\\/i.test(h),{read:P,write:D}=Ce({kit:d,files:[e,...k(t[0])?[t[0]]:[],...he].filter(Boolean),home:y});We(P,D);const f=ae(e,t,{platform:"win32"}),E=await a.SandboxManager.wrapWithSandboxArgv(f,void 0,{filesystem:{denyRead:l.filesystem.denyRead,denyWrite:l.filesystem.denyWrite}},void 0,i,{commandId:u,commandText:f}),x=s?.env||process.env,v={...Re({engine:r,home:y,env:x,base:process.env}),...F({},{platform:o,caBundle:S})},N=Te(E.argv,v),b={};for(const[h,H]of Object.entries(E.env||{}))process.env[h]!==H&&(b[h]=H);return{bin:N[0],argv:N.slice(1),opts:{...s,env:{...x,...b},shell:!1},record:T,commandId:u}}return _e({id:"srt",label:"Anthropic sandbox-runtime",async detect(){return await ye(),{ok:!!c,runtime:c,reason:w,ownSessions:!!(c&&(c==="srt-lib"&&(B??q(W))||o!=="win32"&&I())),...o==="win32"&&A!==null?{provisioned:A,...A?{}:{install:z}}:{}}},async wrap({kit:e,grant:t,bin:s,argv:r,opts:i,engine:d,workdir:l,commandId:u,caBundle:T=""}){const S=ie(e,{loopback:p,home:o==="linux"?y:"",platform:o}),k=ae(s,r),P=Array.isArray(n.exactHosts),D=n.mode==="allowlist"&&t.hosts.length>0&&!P,f=S.network.allowUnixSockets||[],E=f.length>0&&!P;delete S.network.allowUnixSockets;const x=(D||E)&&c==="srt-lib"?B??q(W):"",v=D&&!x&&o!=="win32"?I():null,N=!!(x||v),b=Le({layer:"process",runtime:x?"srt-host":v?"srt-cli":c,kitId:e.id,mode:e.network.mode,hosts:N||!D?t.hosts:[]});D&&!N&&(b.hostsDropped=t.hosts,Y||(Y=!0,L(`sandbox: hosts granted to ${d} (${t.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`))),E&&!x?b.socketsDropped=f:E&&(b.sockets=f);try{if(x){const m=fe(u),O={bin:s,argv:r,cwd:i?.cwd||null,engine:d,workdir:l,grant:t,commandId:u,config:{enabled:!0,mode:n.mode,extraHosts:[],extraWrite:n.extraWrite,extraDenyRead:n.extraDenyRead,windows:n.windows,exactHosts:e.network.allowedDomains,exactSockets:f},loopback:p,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:J?{url:J,token:m}:null},j={...i?.env||process.env};return{bin:process.execPath,argv:[x,ve(O)],opts:{...i,env:j,shell:!1},record:b,commandId:u}}if(v){const m={...i?.env||process.env};Object.assign(m,F(m,{platform:o,caBundle:T}));const O=Z(S,{hosts:t.hosts,sockets:f});return{bin:v.bin,argv:[...v.argv,"-s",ue(O.settings),"-c",k],opts:{...i,env:m,shell:!1},record:ee(b,O,f),commandId:u}}if(c==="srt-lib"&&o==="win32")return{...await Ae(s,r,i,{engine:d,workdir:l,kit:e,settings:S,commandId:u,record:b,caBundle:T})};if(c==="srt-lib"){await te();const m=await a.SandboxManager.wrapWithSandboxArgv(k,void 0,{filesystem:S.filesystem},void 0,l,{commandId:u,commandText:k}),O=i?.env||process.env,j={};for(const[ne,se]of Object.entries(m.env||{}))process.env[ne]!==se&&(j[ne]=se);const V={...O,...j};return Object.assign(V,F(V,{platform:o,caBundle:T})),{bin:m.argv[0],argv:m.argv.slice(1),opts:{...i,env:V,shell:!1},record:b,commandId:u}}const h=I(),H=Z(S,{hosts:t.hosts,sockets:f});return{bin:h.bin,argv:[...h.argv,"-s",ue(H.settings),"-c",k],opts:{...i,shell:!1},record:ee(b,H,f),commandId:u}}catch(h){return L(`sandbox: could not wrap ${s}: ${h.message}`),{passReason:h?.code==="SHAPE"?`the sandbox policy refused this run: ${h.message}`:`sandbox-runtime failed to wrap the command: ${h.message}`}}},violations(e){try{return a?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(e)||[]}catch{return[]}},close(){if(!(!C||!R.size)){try{a.revokeWindowsAcl({sandboxUserSid:C,srtWin:g})}catch(e){L(`sandbox: could not release the Windows grants: ${e.message}`)}R.clear()}}})}Pe("srt",n=>Ue(n));export{Ue as createSrtRuntime};
|
|
1
|
+
import{spawnSync as Te}from"node:child_process";import{writeFileSync as ae,mkdirSync as ce,existsSync as de}from"node:fs";import{createHash as Ce,randomBytes as _e}from"node:crypto";import{fileURLToPath as le}from"node:url";import M from"node:os";import $ from"node:path";import{toSrtSettings as ue,sandboxRecord as Ne,shellJoin as he,sandboxEnvOverlay as V,windowsGrantsFor as He,windowsSandboxEnv as Pe,withSrtWinEnv as je,ENGINE_KITS as we,DEVELOPER_HOSTS as fe,SECRET_PATHS as Me,COMMON_WRITE as Ue}from"./events/sandbox-policy.js";import{defineSandboxRuntime as Ie,registerSandboxRuntime as Fe}from"./sandbox-runtime.js";function Ve(t=process.env.CHATPANEL_SRT_MODULE){if(!t)return"";try{const r=t.startsWith("file:")?le(new URL("./cli.js",t)):$.join($.dirname(t),"cli.js");return de(r)?r:""}catch{return""}}const be=new Set;function pe(t,r=$.join(M.tmpdir(),"chatpanel-srt")){const y=JSON.stringify(t),S=$.join(r,`${Ce("sha256").update(y).digest("hex").slice(0,16)}.json`);return be.has(S)||(ce(r,{recursive:!0,mode:448}),ae(S,y,{mode:384}),be.add(S)),S}function ze(t=process.env.CHATPANEL_SRT_MODULE){if(!t||!String(t).startsWith("file:"))return!1;try{return de(le(t))}catch{return!1}}function Be(){try{const t=Te(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return t.status===0&&String(t.stdout||"").trim().length>0}catch{return!1}}const z="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)";function Je({config:t,platform:r=process.platform,home:y=M.homedir(),loopback:S=[],compiled:W=!1,selfFiles:xe=[process.execPath,process.argv[1]||""],onExit:Se=H=>process.on("exit",H),hostEntry:B=null,reportUrl:J="",mintReportToken:me=()=>"",onRefusal:ye=()=>{},parseRefusal:ge=()=>null,loadSrt:X=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:q=Be,cliEntry:G=Ve(),hostEntryFor:K=()=>"",onDisk:Y=ze,now:Q=()=>Date.now(),log:L=()=>{}}={}){const H=new Set;let d=null,c=null,Z=0,a=null,U=null,R=null,g=null,A=null;const T=new Set;let ee=!1;const ve="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",We="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function Ae(){if(!t.windows){c=ve;return}if(W&&!Y()){c=We;return}try{a=await X()}catch(n){c=`sandbox-runtime is not installed — it ships with the gateway (${n.message})`;return}if(!a?.SandboxManager?.wrapWithSandboxArgv||typeof a.grantWindowsAcl!="function"||typeof a.getWindowsSandboxUserStatusAsync!="function"){c="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{g=a.resolveSrtWin({path:a.VENDORED_SRT_WIN_EXE})}catch(n){c=`Windows: srt-win.exe is not beside sandbox-runtime (${n.message})`;return}let e;try{e=await a.getWindowsSandboxUserStatusAsync({srtWin:g})}catch(n){A=!1,c=`Windows: srt-win could not be asked whether the sandbox account exists (${n.message}) — ${z}`;return}if(A=!!(e?.provisioned&&e.sid),!A){c=`Windows: the sandbox account is not installed — ${z}`;return}R=e.sid,d="srt-lib"}const De=6e4;async function ke(){d||c&&Q()-Z<De||(c=null,await Ee(),c&&(Z=Q()))}async function Ee(){if(!t.enabled){c="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(r==="win32")return Ae();if(!W||Y())try{if(a=await X(),a?.SandboxManager?.wrapWithSandboxArgv){const e=await a.SandboxManager.checkDependenciesAsync?.().catch(()=>null);if(e?.errors?.length){c=`the sandbox needs ${e.errors.join(", ")} on this computer${r==="linux"?" — install them (Debian/Ubuntu: sudo apt install bubblewrap socat ripgrep; Fedora: sudo dnf install bubblewrap socat ripgrep)":""}`,a=null;return}d="srt-lib";return}}catch(e){L(`sandbox: library not available (${e.message})`)}if(q()){d="srt-cli";return}c=W?"the sandbox runtime is not on this computer — the gateway binary unpacks the one it carries when it starts (chatpanel-gateway 0.94.0 or later); an older binary needs `srt` on PATH":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}let te=!1;function ne(e,{hosts:n=[],sockets:s=[]}={}){const o={...e.network};let i=!1;if((o.allowedDomains||[]).includes("*")){const l=o.allowedDomains.filter(u=>u.startsWith("127.0.0.1:"));o.allowedDomains=[...new Set([...Object.values(we).flatMap(u=>u.hosts),...fe,...t.extraHosts,...n,...l])],i=!0}return r==="darwin"&&s.length&&(o.allowUnixSockets=s),{settings:{...e,network:o},narrowed:i}}const se=(e,{narrowed:n},s)=>(n&&(e.narrowed=`open → allowlist: the srt CLI refuses "*" — the gateway's embedded bridge runs open`),s.length&&r==="darwin"&&(e.sockets=s,delete e.socketsDropped),e);function I(){return G&&!W?{bin:process.execPath,argv:[G]}:d==="srt-cli"||q()?{bin:"srt",argv:[]}:null}function Oe(){const e=Array.isArray(t.exactHosts)?t.exactHosts:t.mode==="open"?["*"]:t.mode==="none"?[]:[...new Set([...Object.values(we).flatMap(o=>o.hosts),...fe,...t.extraHosts])],n={id:`session:${t.mode}`,network:{mode:t.mode,allowedDomains:e},filesystem:{allowWrite:[M.tmpdir(),...Ue,...t.extraWrite],denyRead:[...Me,...t.extraDenyRead]}},s=ue(n,{loopback:S,home:r==="linux"?y:"",platform:r});return r==="darwin"&&Array.isArray(t.exactSockets)&&t.exactSockets.length&&(s.network.allowUnixSockets=t.exactSockets),g?{...s,windows:{srtWin:{path:g.exe}}}:s}async function re(){return U||(U=a.SandboxManager.initialize(Oe()).then(()=>{try{a.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(e=>{for(const n of e||[]){const s=ge(n?.line);if(!s||!n?.encodedCommand)continue;let o="";try{o=Buffer.from(n.encodedCommand,"base64").toString("utf8")}catch{continue}const i=`${o}|${s.host}|${n.timestamp instanceof Date?n.timestamp.getTime():String(n.timestamp)}`;H.has(i)||(H.add(i),ye({commandId:o,...s,at:n.timestamp instanceof Date?n.timestamp.getTime():Date.now()}))}})}catch(e){L(`sandbox: violations not subscribed (${e.message})`)}})),U}function $e(e){const n=$.join(M.tmpdir(),"chatpanel-srt");ce(n,{recursive:!0,mode:448});const s=$.join(n,`host-${_e(8).toString("hex")}.json`);return ae(s,JSON.stringify(e),{mode:384}),s}function Le(e,n){const s=(l,u)=>a.expandWindowsFsPaths(l,{mode:u}).filter(h=>!T.has(`${u}:${h.toLowerCase()}`)),o=s(e,"grant"),i=s(n,"grant");if(!(!o.length&&!i.length)){a.grantWindowsAcl({sandboxUserSid:R,read:o,write:i,srtWin:g});for(const l of o)T.add(`grant:${l.toLowerCase()}`);for(const l of i)T.add(`grant:${l.toLowerCase()}`);ee||(ee=!0,Se(()=>{try{a.revokeWindowsAcl({sandboxUserSid:R,srtWin:g})}catch{}}))}}async function Re(e,n,s,{engine:o,workdir:i,kit:l,settings:u,commandId:h,record:C,caBundle:m=""}){await re();const D=w=>typeof w=="string"&&/^[a-z]:\\/i.test(w),{read:P,write:k}=He({kit:l,files:[e,...D(n[0])?[n[0]]:[],...xe].filter(Boolean),home:y});Le(P,k);const f=he(e,n,{platform:"win32"}),E=await a.SandboxManager.wrapWithSandboxArgv(f,void 0,{filesystem:{denyRead:u.filesystem.denyRead,denyWrite:u.filesystem.denyWrite}},void 0,i,{commandId:h,commandText:f}),p=s?.env||process.env,v={...Pe({engine:o,home:y,env:p,base:process.env}),...V({},{platform:r,caBundle:m})},_=je(E.argv,v),b={};for(const[w,N]of Object.entries(E.env||{}))process.env[w]!==N&&(b[w]=N);return{bin:_[0],argv:_.slice(1),opts:{...s,env:{...p,...b},shell:!1},record:C,commandId:h}}return Ie({id:"srt",label:"Anthropic sandbox-runtime",async detect(){return await ke(),{ok:!!d,runtime:d,reason:c,ownSessions:!!(d&&(d==="srt-lib"&&(B??K(W))||r!=="win32"&&I())),...r==="win32"&&A!==null?{provisioned:A,...A?{}:{install:z}}:{}}},async wrap({kit:e,grant:n,bin:s,argv:o,opts:i,engine:l,workdir:u,commandId:h,caBundle:C=""}){const m=ue(e,{loopback:S,home:r==="linux"?y:"",platform:r}),D=he(s,o),P=Array.isArray(t.exactHosts),k=t.mode==="allowlist"&&n.hosts.length>0&&!P,f=m.network.allowUnixSockets||[],E=f.length>0&&!P;delete m.network.allowUnixSockets;const p=(k||E)&&d==="srt-lib"?B??K(W):"",v=k&&!p&&r!=="win32"?I():null,_=!!(p||v),b=Ne({layer:"process",runtime:p?"srt-host":v?"srt-cli":d,kitId:e.id,mode:e.network.mode,hosts:_||!k?n.hosts:[]});k&&!_&&(b.hostsDropped=n.hosts,te||(te=!0,L(`sandbox: hosts granted to ${l} (${n.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`))),E&&!p?b.socketsDropped=f:E&&(b.sockets=f);try{if(p){const x=me(h),O={bin:s,argv:o,cwd:i?.cwd||null,engine:l,workdir:u,grant:n,commandId:h,config:{enabled:!0,mode:t.mode,extraHosts:[],extraWrite:t.extraWrite,extraDenyRead:t.extraDenyRead,windows:t.windows,exactHosts:e.network.allowedDomains,exactSockets:f,required:t.required||!1},loopback:S,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:J?{url:J,token:x}:null},j={...i?.env||process.env};return{bin:process.execPath,argv:[p,$e(O)],opts:{...i,env:j,shell:!1},record:b,commandId:h}}if(v){const x={...i?.env||process.env};Object.assign(x,V(x,{platform:r,caBundle:C}));const O=ne(m,{hosts:n.hosts,sockets:f});return{bin:v.bin,argv:[...v.argv,"-s",pe(O.settings),"-c",D],opts:{...i,env:x,shell:!1},record:se(b,O,f),commandId:h}}if(d==="srt-lib"&&r==="win32")return{...await Re(s,o,i,{engine:l,workdir:u,kit:e,settings:m,commandId:h,record:b,caBundle:C})};if(d==="srt-lib"){await re();const x=await a.SandboxManager.wrapWithSandboxArgv(D,void 0,{filesystem:m.filesystem},void 0,u,{commandId:h,commandText:D}),O=i?.env||process.env,j={};for(const[oe,ie]of Object.entries(x.env||{}))process.env[oe]!==ie&&(j[oe]=ie);const F={...O,...j};return Object.assign(F,V(F,{platform:r,caBundle:C})),{bin:x.argv[0],argv:x.argv.slice(1),opts:{...i,env:F,shell:!1},record:b,commandId:h}}const w=I(),N=ne(m,{hosts:n.hosts,sockets:f});return{bin:w.bin,argv:[...w.argv,"-s",pe(N.settings),"-c",D],opts:{...i,shell:!1},record:se(b,N,f),commandId:h}}catch(w){return L(`sandbox: could not wrap ${s}: ${w.message}`),{passReason:w?.code==="SHAPE"?`the sandbox policy refused this run: ${w.message}`:`sandbox-runtime failed to wrap the command: ${w.message}`}}},violations(e){try{return a?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(e)||[]}catch{return[]}},close(){if(!(!R||!T.size)){try{a.revokeWindowsAcl({sandboxUserSid:R,srtWin:g})}catch(e){L(`sandbox: could not release the Windows grants: ${e.message}`)}T.clear()}}})}Fe("srt",t=>Je(t));export{Je as createSrtRuntime};
|
package/src/sandbox.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as de}from"node:child_process";import"node:fs";import{randomBytes as pe}from"node:crypto";import{AsyncLocalStorage as fe}from"node:async_hooks";import{fileURLToPath as he}from"node:url";import A from"node:os";import xe from"node:path";import{ensureCaBundle as we}from"./ca-bundle.js";import{kitFor as me,sandboxRecord as ge,normalizeGrant as E,mergePersonGrants as Se,signInHosts as be,writableRoots as Ae,NETWORK_MODES as z}from"./events/sandbox-policy.js";import{awsSignIn as ye}from"./aws-credentials.js";import{createSandboxRuntime as Ne,sandboxRuntimeIds as _e}from"./sandbox-runtime.js";import"./sandbox-srt.js";const q=new fe,Q=new Set(["codex","claude","antigravity","custom"]);function nt(e,t){let n;try{n=E(e)}catch{n=null}return q.run(n,t)}function st(e){const t=e&&typeof e=="object"?e:{};if(!t.reach||t.reach==="any"||!t.sandbox||typeof t.sandbox!="object"||!("outside"in t.sandbox))return t;const{outside:n,...s}=t.sandbox;return{...t,sandbox:s}}function rt(e,t,{config:n=B().config}={}){const s=t&&typeof t=="object"?t:{},o=n?.agents?.[String(e||"")];if(!o||s.reach&&s.reach!=="any")return s;let a;try{a=Se(s.sandbox,o)}catch{a=E(o)}return{...s,sandbox:a}}function Z(){return q.getStore()||null}function ot(e,{config:t=ae(),grant:n=Z(),home:s=A.homedir()}={}){try{return Ae({grant:n,extraWrite:t.extraWrite,cwd:e,home:s})}catch{return[]}}const Te=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function ee(e){const t=Te.exec(String(e||""));return t?{host:t[1].toLowerCase(),port:Number(t[2])||0,reason:t[3]||""}:null}const v=new Map,O=[],P=new Map,Ee=new Set,Oe=50;function te({commandId:e,host:t,port:n=0,reason:s="",at:o=Date.now()}){if(!e||!t)return;let a=v.get(e);for(a||(a=new Map,v.set(e,a)),a.set(t,{at:o,reason:s,port:n}),O.push({id:e,engine:P.get(e)||String(e).split(":")[0],host:t,at:o});O.length>Oe;)O.shift()}function Re(e){const t=v.get(e);return t?[...t.entries()].sort((n,s)=>s[1].at-n[1].at).map(([n])=>n):[]}function Le(e=20){return O.slice(-e).reverse()}function at(){v.clear(),O.length=0,P.clear(),Ee.clear()}const ne=new Map;function se(e){const t=pe(16).toString("hex");return ne.set(t,e),t}function it(e={}){const t=ne.get(String(e?.token||""));return!t||t!==e.commandId?!1:(te({commandId:t,host:String(e.host||"").toLowerCase().slice(0,253),port:Number(e.port)||0,reason:String(e.reason||"").slice(0,200)}),!0)}let De=0;const Ce=e=>`${e}:${(++De).toString(36)}${Date.now().toString(36).slice(-4)}`,$=new Map;function ve(e,t,{kind:n="agent",label:s=""}={}){if(!e||!t)return e;try{e.sandbox=t.record}catch{}if(typeof e.on!="function")return e;const o=t.commandId||"";$.set(e,{id:o,kind:n,engine:P.get(o)||String(o).split(":")[0]||"custom",command:t.label||"",label:s,pid:e.pid??null,since:Date.now(),sandbox:t.record});const a=()=>$.delete(e);return e.once("exit",a),e.once("error",a),e}function ut(){return[...$.values()].map(e=>({...e,refused:Re(e.id)}))}function ct(){$.clear()}function re(e){if(e)return"";try{return he(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}const oe="open",lt="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",Pe=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],H=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean),$e=["off","0","false"];function We(e,t){const n={};if(!e)return n;let s;try{s=JSON.parse(e)}catch{return t.push("CHATPANEL_SANDBOX_AGENTS is not JSON — no agent has settings of its own"),n}if(!s||typeof s!="object"||Array.isArray(s))return t.push("CHATPANEL_SANDBOX_AGENTS must be an object keyed by agent id — no agent has settings of its own"),n;for(const[o,a]of Object.entries(s))try{n[o]=E(a)}catch(p){t.push(`sandbox settings for agent "${o}" are not valid and were left out — ${p.message}`)}return n}function ae(e=process.env){const t=String(e.CHATPANEL_SANDBOX||oe).toLowerCase(),n=!$e.includes(t),s=z.includes(t)?t:oe,o=[];return n&&!z.includes(t)&&o.push(`CHATPANEL_SANDBOX="${t}" is not one of open, allowlist, off — the sandbox stays on, in "open" mode`),{enabled:n,mode:s,agents:We(e.CHATPANEL_SANDBOX_AGENTS,o),warnings:o,extraHosts:H(e.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:H(e.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:H(e.CHATPANEL_SANDBOX_DENY_READ),windows:e.CHATPANEL_SANDBOX_WINDOWS==="1",reads:e.CHATPANEL_SANDBOX_READS==="inverted"?"inverted":"enumerated"}}function He({config:e=ae(),loadSrt:t=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:n=void 0,cliEntry:s=void 0,onRefusal:o=x=>te(x),reportUrl:a=process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT?`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT}/sandbox/refused`:"http://127.0.0.1:4319/sandbox/refused",hostEntry:p=null,compiled:l=!1,platform:u=process.platform,home:g=A.homedir(),loopback:k=Pe(),selfFiles:X=[process.execPath,process.argv[1]||""],onExit:G=x=>process.on("exit",x),runtimeId:D=process.env.CHATPANEL_SANDBOX_RUNTIME||"srt",makeRuntime:F=null,signInAws:ie=ye,log:h=()=>{}}={}){let x=null,C=null,w={ok:!1,runtime:null,reason:null,ownSessions:!1};function y(){if(x||C)return x;try{x=F?F({config:e,platform:u,home:g,loopback:k,compiled:l,selfFiles:X,onExit:G,hostEntry:p,reportUrl:a,mintReportToken:se,onRefusal:o,parseRefusal:ee,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:re,log:h}):Ne(D,{config:e,platform:u,home:g,loopback:k,compiled:l,selfFiles:X,onExit:G,hostEntry:p,reportUrl:a,mintReportToken:se,onRefusal:o,parseRefusal:ee,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:re,log:h})}catch(r){C=r?.message||String(r),h(`sandbox: ${C}`)}return x}async function M(){if(!e.enabled)return w={ok:!1,runtime:null,reason:"sandboxing is off (CHATPANEL_SANDBOX=off)",ownSessions:!1},w;const r=y();if(!r)return w={ok:!1,runtime:null,reason:C,ownSessions:!1},w;try{w={...w,...await r.detect()}}catch(f){w={ok:!1,runtime:null,reason:`the ${r.id} sandbox could not be started: ${f.message}`,ownSessions:!1}}return w}return{config:e,async status(){const r=await M(),f=y();return{enabled:e.enabled,mode:e.mode,runtime:r.runtime,platform:u,layer:f?.id||D,layers:_e(),...r.reason?{reason:r.reason}:{},extras:{hosts:e.extraHosts,write:e.extraWrite,denyRead:e.extraDenyRead},...e.agents&&Object.keys(e.agents).length?{agents:e.agents}:{},...e.warnings?.length?{warnings:e.warnings}:{},...r.runtime==="srt-cli"&&e.mode==="open"?{narrowed:'This install runs agents through the `srt` command, which cannot allow every public host: each agent reaches its own service, the developer hosts, the hosts you add here and its sign-ins\' — nothing else. Installing the gateway with npm runs "open" as it says.'}:{},ownSessions:!!r.ownSessions,refused:Le(),...r.provisioned!==void 0?{provisioned:r.provisioned}:{},...r.install?{install:r.install}:{}}},close(){try{y()?.close()}catch(r){h(`sandbox: close failed: ${r.message}`)}},async wrap(r,f,N,{engine:d="custom",cwd:_=null,commandId:S=null,grant:j=Z(),readOnly:ue=!1,peers:ce=!0}={}){const U=await M();S=S||Ce(d),P.set(S,d);const J=_||N?.cwd||process.cwd(),K=xe.basename(String(r||"")),T=i=>({bin:r,argv:f,opts:N,record:ge({layer:"none",reason:i}),commandId:S,label:K});let V=!1;try{V=E(j).outside===!0}catch{}if(V&&Q.has(d))return T("you allowed this agent to run outside the ChatPanel sandbox (its own sandbox still applies)");if(!U.ok)return T(U.reason);const le=await we({home:A.homedir(),log:h}).catch(()=>"");let Y,c;try{if(c=E(j),c.signIn&&!Q.has(d)){const{signIn:i,...W}=c;c=W}c.signIn&&(c={...c,hosts:[...new Set([...c.hosts,...be(c)])]}),Y=me({engine:d,cwd:J,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[A.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead,grant:c,home:A.homedir(),reads:e.reads,readOnly:ue,peers:ce})}catch(i){return T(`kit: ${i.message}`)}let b;try{b=await y().wrap({kit:Y,grant:c,bin:r,argv:f,opts:N,engine:d,workdir:J,commandId:S,caBundle:le})}catch(i){return h(`sandbox: could not wrap ${r}: ${i.message}`),T(`the ${D} sandbox failed to wrap the command: ${i.message}`)}if(!b||b.passReason)return T(b?.passReason||`the ${D} sandbox returned nothing`);const m={...b,commandId:b.commandId||S,label:K};if(c.signIn&&(m.record.signIn=c.signIn,c.signIn.includes("aws"))){const i=await ie({env:m.opts?.env||process.env,engine:d,home:A.homedir()}).catch(W=>({failed:`AWS sign-in: ${W.message}`}));i?.env?(m.opts={...m.opts,env:{...m.opts?.env||process.env,...i.env}},i.expiresAt&&(m.expiresAt=i.expiresAt),h(`sandbox: ${d} is signed in to AWS with profile "${i.profile}" — its credential_process ran outside the sandbox${i.expiresAt?`, good until ${new Date(i.expiresAt).toISOString()}`:""}`)):i?.failed&&(m.record.signInNote=i.failed,h(`sandbox: ${i.failed}`))}return m},async wrapOwn(r,f,N,d={}){const _=await this.wrap(r,f(!1),N,d);return _.record.layer==="none"?{..._,argv:f(!0),inner:!0}:{..._,inner:!1}},violations(r){try{return y()?.violations(r)||[]}catch{return[]}}}}let R=null;function B(){if(!R){const{isCompiledBinary:e}=Be();R=He({compiled:e(),log:t=>console.error(`[bridge] ${t}`)});for(const t of R.config.warnings||[])console.error(`[bridge] sandbox: ${t}`)}return R}function dt(e){R=e}let I=null;function Be(){return I||(I={isCompiledBinary:()=>{const e=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}}),I}const L=new Set;function pt(e,t){if(!t||typeof e!="function"||(t.signInNote&&!L.has(t.signInNote)&&(L.add(t.signInNote),e({type:"status",text:t.signInNote})),t.layer!=="none"))return;const n=t.reason||"unknown";L.has(n)||(L.add(n),e({type:"status",text:`Running outside a sandbox — ${n}`}))}function ft(){L.clear()}const Ie=/sandbox_apply: Operation not permitted/;function ht(e,t="This agent"){return Ie.test(String(e||""))?`${t} tried to start a sandbox of its own inside the ChatPanel sandbox, and macOS does not allow one inside another — so that tool could not run. To let it, turn on "Run outside the ChatPanel sandbox" in this agent's settings.`:null}async function xt(e,t,n,s={},{spawnImpl:o=de,box:a=B(),kind:p="agent",label:l=""}={}){const u=await a.wrap(e,t,n,s);return ve(o(u.bin,u.argv,u.opts),u,{kind:p,label:l})}async function wt(e,{box:t=B(),platform:n=process.platform,loadSrt:s=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:o=console.log,err:a=console.error}={}){const p=e[0]||"status";if(p==="status")return o(JSON.stringify(await t.status(),null,2)),0;if(p!=="install")return a("usage: chatpanel-bridge sandbox [status|install]"),2;if(n!=="win32")return o("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let l;try{l=await s()}catch(u){return a(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${u.message})`),1}try{const u=l.resolveSrtWin({path:l.VENDORED_SRT_WIN_EXE}),g=await l.installWindowsSandboxAsync({srtWin:u});return g?.cancelled?(a("Cancelled at the administrator prompt — nothing was installed."),1):(o(`The sandbox account is installed${g?.user?.sid?` (${g.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(u){a(`install failed: ${u.message}`);try{a(l.windowsInstallInstructions())}catch{}return 1}}export{ct as _resetLiveForTest,ft as _resetNotedForTest,at as _resetRefusalsForTest,dt as _setSandboxForTest,it as acceptRefusalReport,He as createSandbox,Z as currentGrant,ot as grantedWriteRoots,ut as liveProcesses,ht as nestedSandboxLine,pt as noteSandbox,ee as parseRefusalLine,Le as recentRefusals,te as recordRefusal,Re as refusalsFor,wt as runSandboxCli,B as sandbox,ae as sandboxConfigFromEnv,xt as sandboxedSpawn,ve as track,rt as withAgentGrant,nt as withGrant,st as withoutOutsideWhenCapped};
|
|
1
|
+
import{spawn as me}from"node:child_process";import"node:fs";import{randomBytes as Ae}from"node:crypto";import{AsyncLocalStorage as we}from"node:async_hooks";import{fileURLToPath as Se}from"node:url";import N from"node:os";import ge from"node:path";import{ensureCaBundle as be}from"./ca-bundle.js";import{kitFor as Ne,validateKit as _e,sandboxRecord as Z,normalizeGrant as T,mergePersonGrants as ye,signInHosts as Ee,writableRoots as Te,NETWORK_MODES as ee}from"./events/sandbox-policy.js";import{awsSignIn as Oe}from"./aws-credentials.js";import{createSandboxRuntime as Re,sandboxRuntimeIds as Le}from"./sandbox-runtime.js";import{isCompiledBinary as De,hostFacts as Ce}from"./events/runtime-host.js";import"./sandbox-srt.js";import"./sandbox-command.js";const te=new we,ne=new Set(["codex","claude","antigravity","custom"]);function lt(e,t){let n;try{n=T(e)}catch{n=null}return te.run(n,t)}function pt(e){const t=e&&typeof e=="object"?e:{};if(!t.reach||t.reach==="any"||!t.sandbox||typeof t.sandbox!="object"||!("outside"in t.sandbox))return t;const{outside:n,...s}=t.sandbox;return{...t,sandbox:s}}function ft(e,t,{config:n=k().config}={}){const s=t&&typeof t=="object"?t:{},o=n?.agents?.[String(e||"")];if(!o||s.reach&&s.reach!=="any")return s;let a;try{a=ye(s.sandbox,o)}catch{a=T(o)}return{...s,sandbox:a}}function se(){return te.getStore()||null}function ht(e,{config:t=de(),grant:n=se(),home:s=N.homedir()}={}){try{return Te({grant:n,extraWrite:t.extraWrite,cwd:e,home:s})}catch{return[]}}const Pe=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function re(e){const t=Pe.exec(String(e||""));return t?{host:t[1].toLowerCase(),port:Number(t[2])||0,reason:t[3]||""}:null}const B=new Map,O=[],v=new Map,$e=new Set,He=50;function oe({commandId:e,host:t,port:n=0,reason:s="",at:o=Date.now()}){if(!e||!t)return;let a=B.get(e);for(a||(a=new Map,B.set(e,a)),a.set(t,{at:o,reason:s,port:n}),O.push({id:e,engine:v.get(e)||String(e).split(":")[0],host:t,at:o});O.length>He;)O.shift()}function Be(e){const t=B.get(e);return t?[...t.entries()].sort((n,s)=>s[1].at-n[1].at).map(([n])=>n):[]}function ve(e=20){return O.slice(-e).reverse()}function xt(){B.clear(),O.length=0,v.clear(),$e.clear()}const ae=new Map;function ie(e){const t=Ae(16).toString("hex");return ae.set(t,e),t}function mt(e={}){const t=ae.get(String(e?.token||""));return!t||t!==e.commandId?!1:(oe({commandId:t,host:String(e.host||"").toLowerCase().slice(0,253),port:Number(e.port)||0,reason:String(e.reason||"").slice(0,200)}),!0)}let Ie=0;const We=e=>`${e}:${(++Ie).toString(36)}${Date.now().toString(36).slice(-4)}`,I=new Map;function Xe(e,t,{kind:n="agent",label:s=""}={}){if(!e||!t)return e;try{e.sandbox=t.record}catch{}if(typeof e.on!="function")return e;const o=t.commandId||"";I.set(e,{id:o,kind:n,engine:v.get(o)||String(o).split(":")[0]||"custom",command:t.label||"",label:s,pid:e.pid??null,since:Date.now(),sandbox:t.record});const a=()=>I.delete(e);return e.once("exit",a),e.once("error",a),e}function At(){return[...I.values()].map(e=>({...e,refused:Be(e.id)}))}function wt(){I.clear()}function ue(e){if(e)return"--sandbox-host";try{return Se(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}const ce="open",St="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",ke=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],X=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean),Ge=["off","0","false"];function Me(e,t){const n={};if(!e)return n;let s;try{s=JSON.parse(e)}catch{return t.push("CHATPANEL_SANDBOX_AGENTS is not JSON — no agent has settings of its own"),n}if(!s||typeof s!="object"||Array.isArray(s))return t.push("CHATPANEL_SANDBOX_AGENTS must be an object keyed by agent id — no agent has settings of its own"),n;for(const[o,a]of Object.entries(s))try{n[o]=T(a)}catch(f){t.push(`sandbox settings for agent "${o}" are not valid and were left out — ${f.message}`)}return n}function de(e=process.env){const t=String(e.CHATPANEL_SANDBOX||ce).toLowerCase(),n=!Ge.includes(t),s=ee.includes(t)?t:ce,o=[];return n&&!ee.includes(t)&&o.push(`CHATPANEL_SANDBOX="${t}" is not one of open, allowlist, off — the sandbox stays on, in "open" mode`),{enabled:n,mode:s,agents:Me(e.CHATPANEL_SANDBOX_AGENTS,o),warnings:o,extraHosts:X(e.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:X(e.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:X(e.CHATPANEL_SANDBOX_DENY_READ),windows:e.CHATPANEL_SANDBOX_WINDOWS==="1",reads:e.CHATPANEL_SANDBOX_READS==="inverted"?"inverted":"enumerated",command:String(e.CHATPANEL_SANDBOX_COMMAND||""),image:String(e.CHATPANEL_SANDBOX_IMAGE||""),engine:["podman","docker"].includes(e.CHATPANEL_SANDBOX_ENGINE)?e.CHATPANEL_SANDBOX_ENGINE:"",required:["policy"].includes(String(e.CHATPANEL_SANDBOX_REQUIRED||"").toLowerCase())?"policy":["1","on","true","yes"].includes(String(e.CHATPANEL_SANDBOX_REQUIRED||"").toLowerCase())?"on":!1}}function Fe({config:e=de(),loadSrt:t=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:n=void 0,cliEntry:s=void 0,onRefusal:o=x=>oe(x),reportUrl:a=process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT?`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT}/sandbox/refused`:"http://127.0.0.1:4319/sandbox/refused",hostEntry:f=null,compiled:d=!1,platform:u=process.platform,home:S=N.homedir(),loopback:M=ke(),selfFiles:F=[process.execPath,process.argv[1]||""],onExit:j=x=>process.on("exit",x),runtimeId:D=process.env.CHATPANEL_SANDBOX_RUNTIME||"srt",makeRuntime:q=null,signInAws:le=Oe,srtOnDisk:C=void 0,now:P=void 0,log:h=()=>{}}={}){let x=null,$=null,m={ok:!1,runtime:null,reason:null,ownSessions:!1};function _(){if(x||$)return x;try{x=q?q({config:e,platform:u,home:S,loopback:M,compiled:d,selfFiles:F,onExit:j,hostEntry:f,reportUrl:a,mintReportToken:ie,onRefusal:o,parseRefusal:re,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:ue,...C?{onDisk:C}:{},...P?{now:P}:{},log:h}):Re(D,{config:e,platform:u,home:S,loopback:M,compiled:d,selfFiles:F,onExit:j,hostEntry:f,reportUrl:a,mintReportToken:ie,onRefusal:o,parseRefusal:re,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:ue,...C?{onDisk:C}:{},...P?{now:P}:{},log:h})}catch(r){$=r?.message||String(r),h(`sandbox: ${$}`)}return x}async function U(){if(!e.enabled)return m={ok:!1,runtime:null,reason:"sandboxing is off (CHATPANEL_SANDBOX=off)",ownSessions:!1},m;const r=_();if(!r)return m={ok:!1,runtime:null,reason:$,ownSessions:!1},m;try{m={...m,...await r.detect()}}catch(l){m={ok:!1,runtime:null,reason:`the ${r.id} sandbox could not be started: ${l.message}`,ownSessions:!1}}return m}return{config:e,async status(){const r=await U(),l=_();return{enabled:e.enabled,mode:e.mode,runtime:r.runtime,platform:u,...e.required?{required:e.required}:{},layer:l?.id||D,layers:Le(),...r.reason?{reason:r.reason}:{},extras:{hosts:e.extraHosts,write:e.extraWrite,denyRead:e.extraDenyRead},...e.agents&&Object.keys(e.agents).length?{agents:e.agents}:{},...e.warnings?.length?{warnings:e.warnings}:{},...r.runtime==="srt-cli"&&e.mode==="open"?{narrowed:'This install runs agents through the `srt` command, which cannot allow every public host: each agent reaches its own service, the developer hosts, the hosts you add here and its sign-ins\' — nothing else. Installing the gateway with npm runs "open" as it says.'}:{},ownSessions:!!r.ownSessions,refused:ve(),...r.provisioned!==void 0?{provisioned:r.provisioned}:{},...r.install?{install:r.install}:{}}},close(){try{_()?.close()}catch(r){h(`sandbox: close failed: ${r.message}`)}},async wrap(r,l,g,{engine:p="custom",cwd:y=null,commandId:w=null,grant:J=se(),readOnly:pe=!1,peers:fe=!0,kit:K=null}={}){const Y=await U();w=w||We(p),v.set(w,p);const Q=y||g?.cwd||process.cwd(),E=ge.basename(String(r||"")),H=i=>{if(e.required)throw Object.assign(new Error(`The sandbox is required on this computer and could not be applied to ${E||"this process"} — ${i}. Nothing was run.`),{code:"sandbox_required",reason:i});return{bin:r,argv:l,opts:g,record:Z({layer:"none",reason:i}),commandId:w,label:E}},he=i=>{if(e.required==="policy")throw Object.assign(new Error(`Your organisation requires the sandbox, so ${E||"this agent"} cannot run outside it. Nothing was run.`),{code:"sandbox_required",reason:i});return{bin:r,argv:l,opts:g,record:Z({layer:"none",reason:i}),commandId:w,label:E}};let V=!1;try{V=T(J).outside===!0}catch{}if(V&&ne.has(p))return he("you allowed this agent to run outside the ChatPanel sandbox (its own sandbox still applies)");if(!Y.ok)return H(Y.reason);const xe=await be({home:N.homedir(),log:h}).catch(()=>"");let z,c;try{if(c=T(J),c.signIn&&!ne.has(p)){const{signIn:i,...W}=c;c=W}c.signIn&&(c={...c,hosts:[...new Set([...c.hosts,...Ee(c)])]}),z=K?_e(K):Ne({engine:p,cwd:Q,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[N.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead,grant:c,home:N.homedir(),reads:e.reads,readOnly:pe,peers:fe})}catch(i){return H(`kit: ${i.message}`)}let b;try{b=await _().wrap({kit:z,grant:c,bin:r,argv:l,opts:g,engine:p,workdir:Q,commandId:w,caBundle:xe})}catch(i){return h(`sandbox: could not wrap ${r}: ${i.message}`),H(`the ${D} sandbox failed to wrap the command: ${i.message}`)}if(!b||b.passReason)return H(b?.passReason||`the ${D} sandbox returned nothing`);const A={...b,commandId:b.commandId||w,label:E};if(c.signIn&&(A.record.signIn=c.signIn,c.signIn.includes("aws"))){const i=await le({env:A.opts?.env||process.env,engine:p,home:N.homedir()}).catch(W=>({failed:`AWS sign-in: ${W.message}`}));i?.env?(A.opts={...A.opts,env:{...A.opts?.env||process.env,...i.env}},i.expiresAt&&(A.expiresAt=i.expiresAt),h(`sandbox: ${p} is signed in to AWS with profile "${i.profile}" — its credential_process ran outside the sandbox${i.expiresAt?`, good until ${new Date(i.expiresAt).toISOString()}`:""}`)):i?.failed&&(A.record.signInNote=i.failed,h(`sandbox: ${i.failed}`))}return A},async wrapOwn(r,l,g,p={}){const y=await this.wrap(r,l(!1),g,p);return y.record.layer==="none"?{...y,argv:l(!0),inner:!0}:{...y,inner:!1}},violations(r){try{return _()?.violations(r)||[]}catch{return[]}}}}let R=null;function k(){if(!R){const{isCompiledBinary:e}=je();R=Fe({compiled:e(),log:t=>console.error(`[bridge] ${t}`)});for(const t of R.config.warnings||[])console.error(`[bridge] sandbox: ${t}`)}return R}function gt(e){R=e}let G=null;function je(){return G||(G={isCompiledBinary:()=>De(Ce())}),G}const L=new Set;function bt(e,t){if(!t||typeof e!="function"||(t.signInNote&&!L.has(t.signInNote)&&(L.add(t.signInNote),e({type:"status",text:t.signInNote})),t.layer!=="none"))return;const n=t.reason||"unknown";L.has(n)||(L.add(n),e({type:"status",text:`Running outside a sandbox — ${n}`}))}function Nt(){L.clear()}const qe=/sandbox_apply: Operation not permitted/;function _t(e,t="This agent"){return qe.test(String(e||""))?`${t} tried to start a sandbox of its own inside the ChatPanel sandbox, and macOS does not allow one inside another — so that tool could not run. To let it, turn on "Run outside the ChatPanel sandbox" in this agent's settings.`:null}async function yt(e,t,n,s={},{spawnImpl:o=me,box:a=k(),kind:f="agent",label:d=""}={}){const u=await a.wrap(e,t,n,s);return Xe(o(u.bin,u.argv,u.opts),u,{kind:f,label:d})}async function Et(e,{box:t=k(),platform:n=process.platform,loadSrt:s=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:o=console.log,err:a=console.error}={}){const f=e[0]||"status";if(f==="status")return o(JSON.stringify(await t.status(),null,2)),0;if(f!=="install")return a("usage: chatpanel-bridge sandbox [status|install]"),2;if(n!=="win32")return o("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let d;try{d=await s()}catch(u){return a(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${u.message})`),1}try{const u=d.resolveSrtWin({path:d.VENDORED_SRT_WIN_EXE}),S=await d.installWindowsSandboxAsync({srtWin:u});return S?.cancelled?(a("Cancelled at the administrator prompt — nothing was installed."),1):(o(`The sandbox account is installed${S?.user?.sid?` (${S.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(u){a(`install failed: ${u.message}`);try{a(d.windowsInstallInstructions())}catch{}return 1}}export{wt as _resetLiveForTest,Nt as _resetNotedForTest,xt as _resetRefusalsForTest,gt as _setSandboxForTest,mt as acceptRefusalReport,Fe as createSandbox,se as currentGrant,ht as grantedWriteRoots,At as liveProcesses,_t as nestedSandboxLine,bt as noteSandbox,re as parseRefusalLine,ve as recentRefusals,oe as recordRefusal,Be as refusalsFor,Et as runSandboxCli,k as sandbox,de as sandboxConfigFromEnv,yt as sandboxedSpawn,Xe as track,ft as withAgentGrant,lt as withGrant,pt as withoutOutsideWhenCapped};
|
package/src/server.js
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as
|
|
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
|
|
2
|
+
import{createServer as Be}from"node:http";import O from"node:os";import{randomBytes as Ge,randomInt as Ue,timingSafeEqual as Le}from"node:crypto";import{mkdirSync as We,writeFileSync as je,readFileSync as oe,existsSync as Fe}from"node:fs";import{join as H}from"node:path";import*as Je from"./engines/claude.js";import*as Xe from"./engines/codex.js";import*as Ke from"./engines/antigravity.js";import{pi as ze,opencode as Ye,kiro as Ve,copilot as Qe,deepseek as Ze,hermes as qe}from"./engines/cli-agents.js";import{connectorsFor as et}from"./connectors.js";import*as tt from"./engines/custom.js";import{installService as nt,uninstallService as ot,serviceStatus as rt,restartService as re}from"./service.js";import{skillIndex as F,listRecords as at,readRecord as it,readPackageFile as st,skillsHealth as ct,quarantinedSkills as lt,clearSkillCache as J}from"./skills.js";import{writeSkillPackage as dt,writeSkillFile as ut,deleteSkillPackage as ht,SkillWriteError as pt}from"./skill-write.js";import{agentDefRoots as ft,scanAgentDefs as mt,listAgentDefs as gt,readAgentDef as wt,planAgentExport as yt,exportAgentDef as bt,agentDefsHealth as St,AgentDefError as kt}from"./agent-defs.js";import{capabilityToolSpecs as Tt,runCapabilityTool as xt}from"./mcp-capabilities.js";import{createSession as Et,deleteSession as ae,getSession as ie,activeSession as vt,relayToolCall as At}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Ot,isDefaultWorkdir as Ct,resolveWorkdir as Pt,writeScopeNote as $t}from"./workdir.js";import{sandbox as X,runSandboxCli as Rt,withGrant as se,withAgentGrant as It,withoutOutsideWhenCapped as Nt,grantedWriteRoots as ce,acceptRefusalReport as Dt,liveProcesses as _t,sandboxConfigFromEnv as Ht}from"./sandbox.js";import{createAccessGate as Mt,chatKeyOf as Bt,chatFolders as Gt}from"./access-gate.js";import{signInDenial as Ut}from"./events/sandbox-policy.js";import{gitState as Lt,gitDelta as Wt}from"./scm.js";import{listConnections as jt,putConnection as Ft,removeConnection as Jt,runEnvFor as Xt,testConnection as Kt,secretBackend as le}from"./connections.js";import{worktreeFor as de,listWorktrees as zt,removeWorktree as Yt,withHook as Vt,WORKTREE_ROOT as ue}from"./worktree.js";import{AGENT_CLIS as Qt,agentAvailable as Zt,agentInstallDirs as qt,enrichPath as en,enrichAgentEnv as tn,findAgentBin as nn,forgetMisses as on,primeAgentLookups as rn,resolveCommand as he,isCompiledBinary as an}from"./env.js";import"./sanitize.js";import{checkForUpdate as sn,selfUpdate as pe,isEmbedded as fe}from"./update.js";import{callLocalMcp as cn,localMcpStatus as ln,signInLocalMcp as dn,signInStatusLocalMcp as un}from"./mcp-local.js";import{assertPublicHttpUrl as me,assertPublicWebUrl as ge}from"./ssrf.js";import{startRun as we,endRun as K,cancelRun as hn,cancelAll as pn}from"./runs.js";import{closeWarmPools as fn,warmStatus as mn}from"./warm.js";import{SESSION_AGENTS as ye,listSessions as gn,readSession as wn,adoptSession as yn,catchUp as bn}from"./agent-sessions.js";import{agentContext as Sn}from"./agent-context.js";import{normalizeThread as be}from"./events/agent-thread.js";import{portClashPlan as kn,serviceManagerOf as Tn,STANDBY_POLL_MS as xn}from"./events/service-standby.js";import{holdThread as Se}from"./threads.js";import{createSnapshot as En}from"./health-snapshot.js";import{CompatError as P,anthropicError as z,anthropicStream as vn,chatCompletionStream as An,completionStream as On,createAnthropicMessage as Cn,createChatCompletion as Pn,createCompletion as $n,createResponse as Rn,openAIError as k,parseAnthropicMessage as In,parseChatCompletion as Nn,parseCompletion as Dn,parseResponse as _n,responseStream as Hn}from"./api-compat.js";import{callerTrust as Mn,isPaired as I,parseExtensionIds as Bn,capRunOptions as Gn,engineHonoursReach as Un,createPairingStore as Ln,formatPairingCode as Wn}from"./pii/trust.js";const b="0.46.0",x=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",T=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:Je,label:"Claude Code"},codex:{engine:Xe,label:"Codex"},antigravity:{engine:Ke,label:"Antigravity",tools:!1},pi:{engine:ze,label:"Pi"},opencode:{engine:Ye,label:"OpenCode"},hermes:{engine:qe,label:"Hermes"},kiro:{engine:Ve,label:"Kiro"},copilot:{engine:Qe,label:"GitHub Copilot"},deepseek:{engine:Ze,label:"DeepSeek Harness"},custom:{engine:tt,label:"Custom",hidden:!0}};function ke(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=Bn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Mn({origin:n.headers.origin||"",hasToken:ve(n),extensionIds:jn})),n.chatpanelTrust}function Fn(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 Jn(n,e){const t=n.headers.origin||"",o=ke(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 Y=new Set(["127.0.0.1","localhost","::1"]);function Xn(n){if(!Y.has(x))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return Y.has(t)}const D=H(O.homedir(),".chatpanel","bridge-token");let v="";function Kn(){try{Fe(D)&&(v=oe(D,"utf8").trim()),v||(v=Ge(32).toString("hex"),We(H(O.homedir(),".chatpanel"),{recursive:!0}),je(D,v,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const Te=Ln({random:()=>Ue(0,1e6)/1e6});function zn(n){if(!v)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=Te.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 Yn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=Te.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 Vn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:b})}let M=null;async function xe(){if(M)return M;const{createChannelService:n}=await import("./channels/service.js");return M=n({home:H(O.homedir(),".chatpanel"),dataDir:H(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${T}`,token:v},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),M}async function Ee(n,e,t){try{const o=await xe(),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 ve(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&&Le(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"]),Zn=new Set(["/debug"]),qn=n=>Zn.has(n),eo=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function to(n,e){if(!Xn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!ke(t))return"forbidden origin";const o=n.method==="POST"&&Qn.has(e)||n.method==="GET"&&qn(e)||eo(n.method,e);return o&&!(Fn(t)||ve(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!oo.has(e)?no:null}const Ae=()=>fe()?"chatpanel-gateway pair":"chatpanel-bridge pair",no=`forbidden: this client is not paired with the bridge — run \`${Ae()}\` and enter the code in ChatPanel Settings`,oo=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function V(n,e,t){const o=N(n),r=It(e,Nt(Gn(t,o)));if(!Un(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 (${Ae()})`} 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 Oe(n,e,t){const o=e?.message||String(e);try{const r=await X().status(),a=!!(r.enabled&&r.runtime)&&t?.outside!==!0,s=Ut(`${o}
|
|
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 Ce=En({compute:ro});async function ro(){await rn();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(y=>({ok:!1,reason:String(y?.message||y)})),p=await et(a).catch(()=>[]);return{id:a,label:c,available:l.ok,reason:l.reason,connectors:p,...d===!1?{tools:!1}:{}}})),e=fe()?{current:b,updateAvailable:!1,embedded:"gateway"}:await sn(b).catch(()=>({current:b,updateAvailable:!1})),t=await ct().catch(()=>null),o=await St().catch(()=>null),r=await X().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function ao(n,{fresh:e=!1}={}){e&&on();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await Ce.get({fresh:e});i(n,200,{ok:!0,version:b,agents:o,update:r,checkedAt:t,workspace:Ot,sandbox:c,localMcp:ln(),processes:_t(),worktrees:ue,secretBackend:le(),warm:mn(),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 io(n,e,t){const{index:o,problems:r}=await F({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:at(o),problems:r})}async function so(n,e,t){i(n,200,{ok:!0,quarantined:await lt(e,t)})}async function co(n,e,t,o){const{index:r}=await F({extraDirs:t,workdir:o}),a=it(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function lo(n,e,t,o,r){const{index:a}=await F({extraDirs:o,workdir:r}),s=await st(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 uo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await dt({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return J(),i(e,200,o)}catch(o){return i(e,Q(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function ho(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 ut({name:t,path:o,text:r?.text??""});return J(),i(e,200,a)}catch(a){return i(e,Q(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function po(n,e){try{const t=await ht({name:e});return J(),i(n,200,t)}catch(t){return i(n,Q(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function Q(n){return n instanceof pt?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Pe(n,e){return mt({roots:ft(process.env,O.homedir(),n,e)})}async function fo(n,e,t){const{index:o,quarantined:r,problems:a}=await Pe(e,t);i(n,200,{ok:!0,agents:gt(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 mo(n,e,t,o){const{index:r}=await Pe(t,o),a=wt(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function go(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 yt({agent:t?.agent,to:t?.to})})}catch(o){return i(e,$e(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function wo(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 bt({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,$e(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function $e(n){if(n instanceof kt){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function yo(){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 Re(n,e=""){const t=await yo();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,k(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function bo(n){try{const e=await pe(b);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>re(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function So(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=V(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
|
-
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,d=
|
|
5
|
+
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,d=we(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 y=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 de({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),K(c),e.writableEnded||e.end();return}}const _=f?f.path:Pt(t.options?.workingDir),L=Bt(t.agent,t.options),q=L?Gt(L):[];q.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...q])]}});let C=null;{const h=_,g=!!f||!Ct(t.options?.workingDir),w=$t(t.agent,t.options?.permissionMode,h,ce(h,{grant:t.options?.sandbox}));a({type:"workdir",path:h,isDefault:!g,writeScope:w||void 0}),a({type:"status",text:`Working in ${h}${g?"":" (default)"}`}),w&&a({type:"status",text:w}),C=await Lt(h),C&&a({type:"scm",phase:"before",...C})}let W=null;if(C||f){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:g,connection:w}=Xt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});W=Vt(g),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...w?{connection:w}:{}}),w&&a({type:"status",text:`Git credential: ${w.kind} · ${w.host}${w.hasSecret?"":" (no token stored)"} · push: ${g.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:g.CHATPANEL_SCM_PUSH}`})}const j=t.approvals===!0,S={...t.options||{},...f?{workingDir:f.path}:{},...W?{runEnv:W}:{},approvals:j};let R=null;(t.pageTools?.specs?.length||j)&&(R=Et(y,t.pageTools?.specs||[]),S.permissionSession=R,t.pageTools?.specs?.length&&(S.mcp={url:`http://${x}:${T}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const He=Ht();let ee=S.sandbox||null;j&&He.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&S.sandbox?.outside!==!0&&(S.accessGate=Mt({agent:t.agent,label:E[t.agent]?.label||t.agent,key:L,cwd:_,roots:()=>ce(_,{grant:ee})}));try{const h=(g,w)=>se(g.sandbox,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:w,options:g,images:Array.isArray(t.images)?t.images:[]},y,{signal:l.signal}));await Se(t.agent,S,l.signal,async()=>{await h(S,t.system||"");let g=S;for(let w=0;w<2&&S.accessGate?.restart().length&&!l.signal.aborted;w++){const te=S.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...te])]}},ee=g.sandbox;const ne=te.map(Me=>S.accessGate.short(Me)).join(", ");y({type:"status",text:`Restarted with write access to ${ne} — carrying on`}),await h(g,`${t.system||""}
|
|
6
6
|
|
|
7
|
-
`)}function
|
|
7
|
+
[ChatPanel] The person has just allowed writing in ${ne}, and you were restarted with that access. Carry on with their request: do the step that was blocked. Do not ask again.`.trim())}})}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),h?.detail&&u("error",`${t.agent} said: ${h.detail}`),a({type:"error",error:await Oe(t.agent,h,S.sandbox)})}finally{if(!s){const h=await Wt(_,C).catch(()=>null);h&&y({type:"scm",phase:"after",...h})}K(c),R&&ae(R.id),e.writableEnded||e.end()}}async function ko(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:jt(),secretBackend:le()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:Ft(o.connection||o,{token:o.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const r=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return r?r[2]==="delete"?i(e,200,{ok:Jt(r[1])}):i(e,200,Kt(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function To(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ue,worktrees:await zt()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/worktrees"){const r=await de({repo:o.repo,projectId:o.projectId,jobId:o.jobId,base:o.base||null});return i(e,r.error?400:200,r.error?{error:r.error}:{ok:!0,...r})}if(t==="/worktrees/remove"){const r=await Yt({projectId:o.projectId,jobId:o.jobId,force:!!o.force});return i(e,r.ok?200:400,r)}return i(e,404,{error:"Not found"})}async function A(n,e,t){const o=E[n.agent];if(!o||o.hidden)throw new P(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const r=await o.engine.available().catch(l=>({ok:!1,reason:l?.message||String(l)}));if(!r.ok)throw new P(r.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,s=we(a),c=()=>s.cancel("disconnected");t.on("close",c);let d="";try{return await se(n.options?.sandbox,()=>Se(n.agent,n.options,s.signal,()=>o.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},l=>{l?.type==="delta"&&l.text?(d+=l.text,e(l.text)):l?.type==="done"&&l.text&&!d&&(d=l.text,e(l.text))},{signal:s.signal}))),d}catch(l){throw l instanceof Error&&!(l instanceof P)&&(l.message=await Oe(n.agent,l,n.options?.sandbox)),l}finally{t.off("close",c),K(a)}}function B(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function $(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
8
|
+
|
|
9
|
+
`)}function G(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
8
10
|
data: ${JSON.stringify(t)}
|
|
9
11
|
|
|
10
|
-
`)}async function U(n,e,t,o){try{const r=t(await m(n)),a=z(n,r.agent,r.options||{});if(a.error)throw new P(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${r.message}`):r)),null}}async function lo(n,e){const t=await U(n,e,bn,S);if(!t)return;if(!t.stream)try{const r=await v(t,()=>{},e);return i(e,200,gn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=pn(t.requestedModel,r=>$(e,r));try{await v(t,r=>o.delta(r),e),o.done()}catch(r){$(e,S(r))}$(e,"[DONE]"),e.end()}async function uo(n,e){const t=await U(n,e,kn,S);if(!t)return;if(!t.stream)try{const r=await v(t,()=>{},e);return i(e,200,yn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=fn(t.requestedModel,r=>$(e,r));try{await v(t,r=>o.delta(r),e),o.done()}catch(r){$(e,S(r))}$(e,"[DONE]"),e.end()}async function ho(n,e){const t=await U(n,e,Tn,S);if(!t)return;if(!t.stream)try{const r=await v(t,()=>{},e);return i(e,200,wn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=En(t.requestedModel,r=>B(e,r.type,r));try{await v(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...S(r)};B(e,"error",a)}e.end()}async function po(n,e){const t=await U(n,e,Sn,J);if(!t)return;if(!t.stream)try{const r=await v(t,()=>{},e);return i(e,200,mn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,J(r))}M(e);const o=hn(t.requestedModel,(r,a)=>B(e,r,a));try{await v(t,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",J(r))}e.end()}async function fo(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?Zt(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Ae(n,e,t){let o;try{o=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?te(t):gt(),a=d=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:d})},s=(d,l)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:d,message:l}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return a({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:g}});const c=pt();if(o.method==="tools/list"){const d=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...d]})}if(o.method==="tools/call"){const d=await ft(o.params?.name,o.params?.arguments||{});if(d)return a(d);if(!r)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await yt(r,o.params?.name,o.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function mo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await Kt({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox},r);return r.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function go(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{};if(!o.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const r={key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox};try{return i(e,200,t.status?Qt(r):await Vt(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function yo(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const{url:o,headers:r,message:a}=t||{};if(!o||!a)return i(e,400,{error:"need url and message"});let s;try{s=le(o)}catch(h){return i(e,400,{error:String(h?.message||h)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[h,y]of Object.entries(r)){const f=h.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[h]=String(y))}const d=new AbortController,l=setTimeout(()=>d.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:d.signal});try{h.url&&le(h.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const y=await h.text().catch(()=>"");return i(e,200,{status:h.status,sessionId:h.headers.get("Mcp-Session-Id")||null,contentType:h.headers.get("Content-Type")||"",authenticate:h.headers.get("WWW-Authenticate")||"",body:y})}catch(h){const y=h?.name==="AbortError"?"timed out":String(h?.message||h);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const Ce=256*1024,wo=5,So=8e3;async function bo(n){let e=de(n);const t=new AbortController,o=setTimeout(()=>t.abort(),So);try{for(let r=0;r<=wo;r++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${g} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=de(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:Eo(await ko(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function ko(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ce);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=Ce))break}}finally{try{await e.cancel()}catch{}}return o}function To(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function Eo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?To(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function vo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await bo(o);return i(e,200,{title:r.title||null,url:r.url||o})}catch(r){const a=r?.name==="AbortError"?"timed out":String(r?.message||r);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Oo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=te(t.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Ao(n,e){let t;try{t=await m(n)}catch(d){return i(e,400,{error:"Bad JSON: "+d.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=z(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const c=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let d="";return typeof o.engine.complete=="function"?d=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},l=>{l.type==="delta"?d+=l.text||"":l.type==="done"&&l.text&&(d+=l.text)}),i(e,200,{text:(d||"").trim()})}catch(d){return i(e,502,{error:d?.message||String(d)})}}async function Co(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function xo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(t.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=ie(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function Po(n,e,t){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(o?.agent||"");if(!he.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${he.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await nn(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await on(r,String(o.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=pe({id:o.thread?.id??o.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const s=await rn(r,String(o.id||""),a.id);return s?i(e,200,{session:s}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=pe({id:o.thread?.id??o.thread});return a?i(e,200,await an(r,a.id,Array.isArray(o.messages)?o.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const Y=Pe(async(n,e)=>{if(In(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const o=Gn(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return Xn(e,{fresh:t.searchParams.get("fresh")==="1"});const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return zn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-context"){const s=await m(n).catch(()=>({})),c=s?.options&&typeof s.options=="object"?s.options:{},d={...c.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof c.permissionMode=="string"?{permissionMode:c.permissionMode}:{},...typeof c.workingDir=="string"&&c.workingDir?{workingDir:c.workingDir}:{},...typeof c.model=="string"&&c.model?{model:c.model}:{}};return i(e,200,await sn({agent:typeof s?.agent=="string"?s.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Kn(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return eo(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return no(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return oo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return to(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return Qn(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?n.method==="DELETE"?qn(e,decodeURIComponent(s)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):Zn(n,e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?Yn(e,decodeURIComponent(s),r,a):Vn(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return so(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return co(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return Oe(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return Oe(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:g,agents:Object.fromEntries(Ut.map(c=>[c,s?Ft(c)||ie(c)?.kind||null:Wt(c)])),...s?{home:O.homedir(),path:process.env.PATH,installDirs:Lt(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Po(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return io(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Hn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return _n(e);if(n.method==="POST"&&t.pathname==="/whoami")return Mn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return lo(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return uo(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return ho(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return po(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Ae(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return Ae(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return ee(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return we(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return we(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return fo(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=At(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return mo(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return go(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return yo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return vo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Ao(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Co(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return xo(n,e);if(n.method==="POST"&&t.pathname==="/update")return ao(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function $o(n){let e="";const t=[];let o=!1,r=!1;const a=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const c=t.shift();let d;try{d=JSON.parse(c)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(d.id==null)continue;const h=(await l.text()).trim();h&&process.stdout.write(h+`
|
|
12
|
+
`)}async function U(n,e,t,o){try{const r=t(await m(n)),a=V(n,r.agent,r.options||{});if(a.error)throw new P(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${r.message}`):r)),null}}async function xo(n,e){const t=await U(n,e,Nn,k);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Pn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,k(r))}B(e);const o=An(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,k(r))}$(e,"[DONE]"),e.end()}async function Eo(n,e){const t=await U(n,e,Dn,k);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,$n(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,k(r))}B(e);const o=On(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,k(r))}$(e,"[DONE]"),e.end()}async function vo(n,e){const t=await U(n,e,_n,k);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Rn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,k(r))}B(e);const o=Hn(t.requestedModel,r=>G(e,r.type,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...k(r)};G(e,"error",a)}e.end()}async function Ao(n,e){const t=await U(n,e,In,z);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Cn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,z(r))}B(e);const o=vn(t.requestedModel,(r,a)=>G(e,r,a));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){G(e,"error",z(r))}e.end()}async function Oo(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?hn(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Ie(n,e,t){let o;try{o=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?ie(t):vt(),a=d=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:d})},s=(d,l)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:d,message:l}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return a({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:b}});const c=Tt();if(o.method==="tools/list"){const d=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...d]})}if(o.method==="tools/call"){const d=await xt(o.params?.name,o.params?.arguments||{});if(d)return a(d);if(!r)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await At(r,o.params?.name,o.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function Co(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await cn({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox},r);return r.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Po(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{};if(!o.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const r={key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox};try{return i(e,200,t.status?un(r):await dn(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function $o(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:o,headers:r,message:a}=t||{};if(!o||!a)return i(e,400,{error:"need url and message"});let s;try{s=me(o)}catch(p){return i(e,400,{error:String(p?.message||p)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[p,y]of Object.entries(r)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[p]=String(y))}const d=new AbortController,l=setTimeout(()=>d.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:d.signal});try{p.url&&me(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const y=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:y})}catch(p){const y=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${y}`})}finally{clearTimeout(l)}}const Ne=256*1024,Ro=5,Io=8e3;async function No(n){let e=ge(n);const t=new AbortController,o=setTimeout(()=>t.abort(),Io);try{for(let r=0;r<=Ro;r++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${b} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=ge(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:Ho(await Do(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function Do(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ne);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=Ne))break}}finally{try{await e.cancel()}catch{}}return o}function _o(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function Ho(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?_o(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Mo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await No(o);return i(e,200,{title:r.title||null,url:r.url||o})}catch(r){const a=r?.name==="AbortError"?"timed out":String(r?.message||r);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Bo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=ie(t.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Go(n,e){let t;try{t=await m(n)}catch(d){return i(e,400,{error:"Bad JSON: "+d.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=V(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const c=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let d="";return typeof o.engine.complete=="function"?d=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},l=>{l.type==="delta"?d+=l.text||"":l.type==="done"&&l.text&&(d+=l.text)}),i(e,200,{text:(d||"").trim()})}catch(d){return i(e,502,{error:d?.message||String(d)})}}async function Uo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function Lo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(t.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=he(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function Wo(n,e,t){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(o?.agent||"");if(!ye.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${ye.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await gn(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await wn(r,String(o.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=be({id:o.thread?.id??o.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const s=await yn(r,String(o.id||""),a.id);return s?i(e,200,{session:s}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=be({id:o.thread?.id??o.thread});return a?i(e,200,await bn(r,a.id,Array.isArray(o.messages)?o.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const Z=Be(async(n,e)=>{if(Jn(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const o=to(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return ao(e,{fresh:t.searchParams.get("fresh")==="1"});const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return io(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-context"){const s=await m(n).catch(()=>({})),c=s?.options&&typeof s.options=="object"?s.options:{},d={...c.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof c.permissionMode=="string"?{permissionMode:c.permissionMode}:{},...typeof c.workingDir=="string"&&c.workingDir?{workingDir:c.workingDir}:{},...typeof c.model=="string"&&c.model?{model:c.model}:{}};return i(e,200,await Sn({agent:typeof s?.agent=="string"?s.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return so(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return fo(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return go(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return wo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return mo(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return uo(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?n.method==="DELETE"?po(e,decodeURIComponent(s)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):ho(n,e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?co(e,decodeURIComponent(s),r,a):lo(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return ko(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return To(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return Re(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return Re(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:b,agents:Object.fromEntries(Qt.map(c=>[c,s?nn(c)||he(c)?.kind||null:Zt(c)])),...s?{home:O.homedir(),path:process.env.PATH,installDirs:qt(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Wo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return So(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Yn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return zn(e);if(n.method==="POST"&&t.pathname==="/whoami")return Vn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return xo(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Eo(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return vo(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Ao(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Ie(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return Ie(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return ae(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return Ee(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return Ee(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Bo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=Dt(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return Co(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Po(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return $o(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Mo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Go(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Uo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Lo(n,e);if(n.method==="POST"&&t.pathname==="/update")return bo(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function jo(n){let e="";const t=[];let o=!1,r=!1;const a=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const c=t.shift();let d;try{d=JSON.parse(c)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(d.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
|
|
11
13
|
`)}catch(l){d.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:d.id,error:{code:-32e3,message:String(l?.message||l)}})+`
|
|
12
14
|
`)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",c=>{e+=c;let d;for(;(d=e.indexOf(`
|
|
13
|
-
`))>=0;){const l=e.slice(0,d).trim();e=e.slice(d+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function
|
|
15
|
+
`))>=0;){const l=e.slice(0,d).trim();e=e.slice(d+1),l&&t.push(l)}s()}),process.stdin.on("end",()=>{r=!0,a()}),process.stdin.resume()}function Fo(){en(),tn(),Kn();let n=!1;Z.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${T}/health`,{signal:AbortSignal.timeout(1500)}).then(t=>t.ok?t.json():null).catch(()=>null).then(t=>{const o=!!(t?.version&&Array.isArray(t.agents)),r=kn({name:"bridge",self:b,holder:o?{ours:o,version:t.version}:null,managedBy:Tn(process.env),port:T});if(r.action==="standby"||n&&!t){if(!n)for(const a of r.lines)u("info",a);n=!0,setTimeout(()=>Z.listen(T,x),xn);return}if(o)for(const a of r.lines)u("error",a);else u("error",`Port ${T} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings.");process.exit(1)});return}u("error",`bridge server error: ${e?.message||e}`),process.exit(1)});for(const e of["SIGINT","SIGTERM"])process.on(e,()=>{const t=pn("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const o=fn("shutdown");o&&u("info",`shutdown: closed ${o} warm agent process${o===1?"":"es"}`),X().close(),setTimeout(()=>process.exit(0),t||o?300:0).unref?.(),!t&&!o&&process.exit(0)});Z.listen(T,x,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${x}:${T}`),Ce.warm(),Y.has(x)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${x}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:e,label:t,hidden:o}]of Object.entries(E)){if(o)continue;const r=await e.available().catch(()=>({ok:!1}));u("info",` ${r.ok?"✓":"✕"} ${t}${r.ok?"":" — "+(r.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),xe().then(e=>e.startIfConfigured()).then(e=>{e?.skipped||(e?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${e?.error||"unknown error"}`))}).catch(e=>u("error",`channels: ${e?.message||e}`))})}function Jo(){console.log(`ChatPanel Bridge v${b}
|
|
14
16
|
|
|
15
17
|
Usage:
|
|
16
|
-
chatpanel-bridge start the bridge (foreground) on ${
|
|
18
|
+
chatpanel-bridge start the bridge (foreground) on ${x}:${T}
|
|
17
19
|
chatpanel-bridge --install run automatically at login, in the background
|
|
18
20
|
chatpanel-bridge --uninstall remove the login auto-start
|
|
19
21
|
chatpanel-bridge --status show whether auto-start is set up
|
|
@@ -22,4 +24,4 @@ Usage:
|
|
|
22
24
|
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
23
25
|
chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
|
|
24
26
|
|
|
25
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function
|
|
27
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function Xo(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return Jo(),!0;if(e("--version","-v"))return console.log(b),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=oe(D,"utf8").trim()}catch{}const o=`http://${x}:${T}`;try{if(!t)throw new Error(`no token at ${D} — is the bridge running?`);const r=await fetch(`${o}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await r.json().catch(()=>({}));if(!r.ok)throw new Error(a.error||`HTTP ${r.status}`);console.log(`Pairing code: ${Wn(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(r){u("error",`could not get a pairing code from the bridge at ${o}: ${r?.message||r}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return Rt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{nt(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){u("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{ot(),u("info","Removed the login auto-start.")}catch(t){u("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=rt()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const De=process.argv.indexOf("--mcp-stdio"),_e=process.argv.indexOf("--sandbox-host");if(_e>=0){const{runSandboxHost:n}=await import("./sandbox-host.js");await n(process.argv[_e+1],{compiled:an()})}else if(De>=0){const n=process.argv[De+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),jo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await pe(b);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),re()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():Xo()||Fo();
|