@chatpanel/bridge 0.44.2 → 0.45.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/aws-credentials.js +4 -0
- package/src/cli-errors.js +6 -5
- package/src/engines/claude-warm.js +2 -2
- package/src/engines/codex-appserver.js +5 -5
- package/src/events/harness-cards.js +1 -1
- package/src/events/sandbox-grant.js +1 -1
- package/src/events/sandbox-policy.js +1 -1
- package/src/pii/pii-detect.js +2 -2
- package/src/pii/tool-harness.js +1 -1
- package/src/sandbox.js +1 -1
- package/src/server.js +8 -7
- package/src/warm-pool.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.45.2",
|
|
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": [
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{exec as C}from"node:child_process";import{readFileSync as O,writeFileSync as L,mkdirSync as P}from"node:fs";import{createHash as R}from"node:crypto";import N from"node:os";import E from"node:path";import{harnessCard as k}from"./events/harness-cards.js";const g="CHATPANEL_AWS_CRED_",T=5,W=10*6e4,K=5*6e4,$=3e4,j=(s,e)=>s==="~"||s.startsWith("~/")?e+s.slice(1):s;function b(s,{home:e=N.homedir(),read:t=r=>O(r,"utf8")}={}){const r={};for(const n of k(s)?.envFrom||[])try{const o=JSON.parse(t(j(n,e)))?.env;if(o&&typeof o=="object"&&!Array.isArray(o))for(const[a,i]of Object.entries(o))typeof i=="string"&&(r[a]=i)}catch{}return r}function M(s){const e=new Map;let t=null;return String(s||"").split(`
|
|
2
|
+
`).forEach((r,n)=>{const o=/^\s*\[\s*([^\]]+?)\s*\]\s*$/.exec(r);if(o){const l=/^(?:profile\s+(.+)|(default))$/.exec(o[1]);t=l?{props:{},lines:{}}:null,t&&e.set((l[1]||l[2]).trim(),t);return}if(!t||/^\s/.test(r)||/^[#;]/.test(r))return;const a=r.indexOf("=");if(a<=0)return;const i=r.slice(0,a).trim().toLowerCase();t.props[i]=r.slice(a+1).trim(),t.lines[i]=n}),e}function v(s,e){let t=e;for(let r=0;r<T;r++){const n=s.get(t);if(!n)return[];if(n.props.credential_process)return[{profile:t,command:n.props.credential_process,line:n.lines.credential_process}];if(!n.props.source_profile||n.props.source_profile===t)return[];t=n.props.source_profile}return[]}function H(s){let e;try{e=JSON.parse(String(s||""))}catch{throw new Error("it did not print JSON")}if(!e||typeof e!="object"||e.Version!==1)throw new Error("its output is not Version 1 of the credential_process format");if(typeof e.AccessKeyId!="string"||!e.AccessKeyId||typeof e.SecretAccessKey!="string"||!e.SecretAccessKey)throw new Error("its output has no AccessKeyId and SecretAccessKey");const t=typeof e.Expiration=="string"?Date.parse(e.Expiration):NaN;return{json:JSON.stringify({Version:1,AccessKeyId:e.AccessKeyId,SecretAccessKey:e.SecretAccessKey,...typeof e.SessionToken=="string"&&e.SessionToken?{SessionToken:e.SessionToken}:{},...Number.isFinite(t)?{Expiration:new Date(t).toISOString()}:{}}),expiresAt:Number.isFinite(t)?t:0}}const D=/^\s*(aws_access_key_id|aws_secret_access_key|aws_session_token)\s*=/i;function G(s,e){const t=String(s||"").split(`
|
|
3
|
+
`);return e.forEach((r,n)=>{t[r.line]=`credential_process = /bin/sh -c 'printf %s "$${g}${n}"'`}),t.filter(r=>!D.test(r)).join(`
|
|
4
|
+
`)}function J(s,e){return new Promise((t,r)=>{C(s,{env:e,timeout:$,windowsHide:!0,maxBuffer:256*1024},(n,o)=>{if(n)return r(new Error(n.killed?`it did not answer in ${$/1e3} s`:`it exited ${n.code??n.signal??"with an error"}`));t(o)})})}const m=new Map;function z(){m.clear()}async function Q({env:s=process.env,engine:e="custom",home:t=N.homedir(),base:r=process.env,platform:n=process.platform,read:o=p=>O(p,"utf8"),run:a=J,now:i=()=>Date.now(),write:l=(p,u)=>{P(E.dirname(p),{recursive:!0,mode:448}),L(p,u,{mode:384})}}={}){if(n==="win32"||s[`${g}0`])return null;const p=b(e,{home:t,read:o}),u=s.AWS_CONFIG_FILE||p.AWS_CONFIG_FILE||E.join(t,".aws","config");let h;try{h=o(u)}catch{return null}const x=s.AWS_PROFILE||p.AWS_PROFILE||s.AWS_DEFAULT_PROFILE||"default",A=v(M(h),x);if(!A.length)return null;const I={};let _=0;for(const[y,d]of A.entries()){const w=`${u}|${d.profile}|${d.command}`;let c=m.get(w);if(!c||i()>=c.until)try{const f=H(await a(d.command,{...r,AWS_PROFILE:d.profile,AWS_CONFIG_FILE:u}));if(f.expiresAt&&f.expiresAt<=i())throw new Error("the credentials it returned have already expired");c={...f,until:f.expiresAt?f.expiresAt-K:i()+W},m.set(w,c)}catch(f){return m.delete(w),{failed:`AWS sign-in: the credential_process of profile "${d.profile}" failed when ChatPanel ran it for this agent — ${f.message}. Run it in a terminal to see why; the agent will try on its own and may not be able to sign in.`}}I[`${g}${y}`]=c.json,c.expiresAt&&(!_||c.expiresAt<_)&&(_=c.expiresAt)}const F=G(h,A),S=E.join(t,".cache","chatpanel","aws",`config-${R("sha256").update(F).digest("hex").slice(0,16)}`);try{l(S,F)}catch(y){return{failed:`AWS sign-in: could not write ${S} (${y.message}) — the agent will try on its own.`}}return{env:{...I,AWS_CONFIG_FILE:S},expiresAt:_,profile:x}}export{z as _resetAwsCacheForTest,Q as awsSignIn,v as credentialProcessChain,b as harnessEnvFrom,M as parseAwsConfig,H as parseProcessOutput,G as shimConfig};
|
package/src/cli-errors.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import{loginRequired as
|
|
2
|
-
`).some(v),short:"it rejected the agent's token",say:e=>`${e} rejected the agent's token (401/invalid_token). Re-authenticate that server in the agent, then retry.`},{kind:"refused",test
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import{loginRequired as m,signInMessage as k}from"./sign-in.js";const p=[/^\s*$/,/^\s*at\s+/,/^\s*[.#]?[\w-]+\s*\{/,/^\s*[\w-]+:\s*[^;]+;$/,/^\s*<\//];function l(e){return String(e||"").replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<svg[\s\S]*?<\/svg>/gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/[ \t]+/g," ")}const b=[/(?:refresh OAuth tokens|refresh tools) for (?:MCP )?server ['"`]?([\w.-]+)['"`]?/i,/MCP server ['"`]([\w.-]+)['"`]/i,/server ['"]?([\w.-]+)['"]? (?:requires|failed) auth/i];function h(e){for(const t of b){const n=t.exec(String(e||""))?.[1];if(n)return n}return null}const f=/api error|authentication_error|invalid (?:x-)?api[- ]key|bearer token|anthropic|openai|x-api-key|\baws\b|bedrock|security token/i,v=e=>/\b401\b/.test(e)&&!f.test(e)&&(/\bmcp\b/i.test(e)||!!h(e)),x=e=>/HTTP 403|\b403\b/.test(e)&&!f.test(e),$=[{kind:"expired",test:/refresh token (?:does not exist|was rejected)|invalid_grant/i,short:"its saved login has expired",say:e=>`${e} needs re-authentication — its saved OAuth token has expired or been revoked. Re-login to that server in the agent's own config; ChatPanel can't refresh it.`},{kind:"unauthorized",test:e=>/invalid_token|AuthRequired|www-authenticate/i.test(e)||e.split(`
|
|
2
|
+
`).some(v),short:"it rejected the agent's token",say:e=>`${e} rejected the agent's token (401/invalid_token). Re-authenticate that server in the agent, then retry.`},{kind:"refused",test:e=>e.split(`
|
|
3
|
+
`).some(x),short:"it is refusing requests",say:e=>`${e} returned 403 and an error page — that server is refusing requests or is temporarily down. This is outside ChatPanel; retry when it recovers.`},{kind:"unreachable",requiresMcpContext:!0,test:/handshaking with MCP server failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|dns error|connection (?:refused|reset)|failed to start and is unavailable|network is unreachable/i,short:"it could not be reached",say:e=>`${e} could not be reached — it is offline, or needs a network (VPN) this machine is not on. ChatPanel can't reach it either; retry when it is available.`}];function w(e){const t=String(e||""),n=h(t),s=/\bmcp\b/i.test(t)||!!n;for(const i of $)if(!(i.requiresMcpContext&&!s)&&(typeof i.test=="function"?i.test(t):i.test.test(t)))return{server:n,kind:i.kind,short:i.short,say:i.say(n?`its MCP server "${n}"`:"one of its MCP servers")};return null}function y(e){const t=w(e);return t?t.say:/ENOENT|command not found/i.test(e)?"the command could not be found on PATH.":null}const A={"claude code":"claude",claude:"claude",codex:"codex","github copilot":"copilot",copilot:"copilot",opencode:"opencode",kiro:"kiro",hermes:"hermes",antigravity:"antigravity",pi:"pi"};function C(e,t,n,s="",{agentId:i=null}={}){const r=`${n||""}
|
|
4
|
+
${s||""}`;if(m(r))return k(e,i||A[String(e).toLowerCase()]||null);const o=y(r);if(o)return`${e} exited ${t}: ${o}`;const c=l(r).split(`
|
|
5
|
+
`).map(a=>a.trim()).filter(a=>a&&!p.some(g=>g.test(a))),u=c.filter(a=>/error|fail|fatal|panic|refused|denied|timeout/i.test(a)),d=(u.length?u:c).pop()||"failed";return`${e} exited ${t}: ${d.length>300?`${d.slice(0,300)}…`:d}`}const E=[[/(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1…"],[/\b(sk-|sk_|ghp_|gho_|xox[abpr]-|AKIA)[A-Za-z0-9_-]{6,}/g,"$1…"],[/\b[A-Za-z0-9_-]{24,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"…"],[/\b[A-Za-z0-9+/_-]{40,}={0,2}/g,"…"]];function _(e,t="",{lines:n=6,width:s=300}={}){return l(`${e||""}
|
|
5
6
|
${t||""}`).split(`
|
|
6
|
-
`).map(r=>r.trim()).filter(r=>r&&!p.some(o=>o.test(r))&&/error|fail|fatal|panic|refused|denied|timeout|unauthori[sz]ed|\b40[13]\b/i.test(r)).slice(-n).map(r=>
|
|
7
|
+
`).map(r=>r.trim()).filter(r=>r&&!p.some(o=>o.test(r))&&/error|fail|fatal|panic|refused|denied|timeout|unauthori[sz]ed|\b40[13]\b/i.test(r)).slice(-n).map(r=>E.reduce((o,[c,u])=>o.replace(c,u),r)).map(r=>r.length>s?`${r.slice(0,s)}…`:r).join(" ⏎ ")}function P(e,t,n,s="",i={}){return Object.assign(new Error(C(e,t,n,s,i)),{detail:_(n,s)})}export{P as cliError,_ as errorTail,w as mcpFailure,h as mcpServerName,l as stripMarkup,C as summarizeCliError};
|
|
@@ -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 W,deleteSession as P,rebindSession as ee,releaseSession as re,relayPermission as U}from"../mcp-sessions.js";import{resolveClaude as se,buildSpawnSpec as te}from"../env.js";import{loginRequired as B,signInMessage as H}from"../sign-in.js";import{pushExtraArgs as R,FORBIDDEN as q}from"./args.js";import{buildClaudeLaunch as F,claudePrompt as ae,handleMessage as ne,harnessChars as le,writeImages as oe,answerControlRequest as ie}from"./claude.js";const j=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,ue=5e3,
|
|
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 W,deleteSession as P,rebindSession as ee,releaseSession as re,relayPermission as U}from"../mcp-sessions.js";import{resolveClaude as se,buildSpawnSpec as te}from"../env.js";import{loginRequired as B,signInMessage as H}from"../sign-in.js";import{pushExtraArgs as R,FORBIDDEN as q}from"./args.js";import{buildClaudeLaunch as F,claudePrompt as ae,handleMessage as ne,harnessChars as le,writeImages as oe,answerControlRequest as ie}from"./claude.js";const j=Number(process.env.CHATPANEL_CLAUDE_TIMEOUT_MS)||18e4,ue=5e3,f=Z("claude",Y({log:n=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[claude] ${n}`)}}));function ce(n={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CLAUDE_WARM==="off"||n.warm===!1)}async function G({spec:n,args:x,cwd:r,env:b,spawnImpl:E,log:g=()=>{},ask:$=null,peers:w=!0}){const u=[...x,"--input-format","stream-json"],[p,c,A]=te(n,u,r,b),d=await X().wrap(p,c,A,{engine:"claude",cwd:r,peers:w});d.record.layer==="none"&&g(`sandbox: claude session runs outside a sandbox — ${d.record.reason}`);const[i,m,S]=[d.bin,d.argv,d.opts];let e=null;const v=new Set;let y="",T=0,k=0,l=null;const h=K(i,m,{spawnOpts:S,spawnImpl:(s,t,a)=>V((E||Q)(s,t,a),d,{kind:"warm"}),jsonrpc:!1,onStderr:s=>{y=(y+s).slice(-2e3),e&&e.touch()},onExit:s=>{if(g(`claude exited: ${s.signal||s.code}${y?` — ${y.trim().split(`
|
|
2
2
|
`).pop()}`:""}`),e){const t=e.apiError&&B(e.apiError)?H("Claude Code","claude"):e.apiError?`Claude Code reported an error: ${e.apiError}`:`Claude Code exited (${s.signal||s.code})${y?`: ${y.trim().split(`
|
|
3
|
-
`).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:t})}for(const t of
|
|
3
|
+
`).pop().slice(0,200)}`:""}`;e.finish({status:"died",error:t})}for(const t of v)try{t(s)}catch{}},onMessage:s=>{if(!e||(e.touch(),s.type==="control_response"))return;if(s.type==="control_request"){const a=e;a.asking++,a.touch(),ie(s,$,I=>{try{h.send(I)}catch{}}).catch(()=>{}).finally(()=>{a.asking--,e===a&&a.touch()});return}const t=ne(s,e.emit,e.streamedAny,r,e.flow);t.sessionId&&(l=t.sessionId),t.streamed&&(e.streamedAny=!0),t.result!=null&&(e.resultText=t.result),t.apiError&&(e.apiError=t.apiError),s.type==="result"&&(e.apiError&&B(e.apiError)?e.finish({status:"failed",error:H("Claude Code","claude")}):e.apiError?e.finish({status:"failed",error:`Claude Code reported an error: ${e.apiError}`}):e.finish({status:"completed",error:null}))}});return{get pid(){return h.pid},get alive(){return!h.exited},expiresAt:d.expiresAt||0,get sessionId(){return l},onExit(s){v.add(s)},close(){h.close()},async turn({prompt:s,emit:t,signal:a,harness:I=null}){if(h.exited)throw new Error("Claude Code process is gone");if(e)throw new Error("a turn is already running on this process");let _=null,C;const N=new Promise(M=>{C=M}),o={emit:t,flow:{sawText:!1,tail:"",boundary:!1,costUsdBefore:k,harnessChars:I},streamedAny:!1,resultText:"",apiError:null,asking:0,touch(){clearTimeout(_),!o.asking&&(_=setTimeout(()=>o.finish({status:"timeout",error:`Claude Code timed out — no output for ${Math.round(j/1e3)}s.`}),j))},finish(M){e===o&&(clearTimeout(_),e=null,C(M))}};e=o,o.touch();const O=()=>{if(e===o){o.interrupted=!0;try{h.send({type:"control_request",request_id:`stop_${++T}`,request:{subtype:"interrupt"}})}catch{}setTimeout(()=>{e===o&&(o.finish({status:"killed",error:null}),h.kill())},ue).unref?.()}};if(a?.aborted)return o.finish({status:"killed",error:null}),{streamedAny:!1,resultText:"",status:"killed"};a?.addEventListener("abort",O,{once:!0});try{h.send({type:"user",message:{role:"user",content:s}})}catch(M){o.finish({status:"failed",error:M.message})}const L=await N;o.flow.costUsdTotal!=null&&(k=o.flow.costUsdTotal),a?.removeEventListener("abort",O),L.status==="timeout"&&h.kill();const J=L.status==="killed"?"killed":o.interrupted?"interrupted":L.status;return{streamedAny:o.streamedAny,resultText:o.resultText,status:J,error:L.error,sessionId:l}}}}const D=new Set;async function de({key:n,spec:x,options:r,label:b,launch:E=G,log:g=()=>{},force:$=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!$||!n||!x||r?.ephemeral===!0||D.has(n)||f.peek({key:n,messages:[{role:"user",content:""}]}))return!1;D.add(n);const w=f.reserve({key:n,label:`${b} (spare)`,evict:!1});if(!w)return D.delete(n),!1;let u=null,p=null;try{let c=r.mcp;const A=r.mcp?.specs||[];(c?.url&&A.length||r.approvals===!0)&&(u=W(()=>{},A),c?.url&&A.length&&(c={...c,url:`${c.url.replace(/\/[^/]*$/,"")}/${u.id}`})),p=await F({system:"",options:{...r,mcp:c},tag:`spare-${Date.now()}-${Math.random().toString(36).slice(2)}`});const d=[...p.args];R(d,r.extraArgs,q.claude,()=>{});const i=u,m=await E({spec:x,args:d,cwd:p.cwd,env:p.runEnv,ask:p.approvals&&i?e=>U(i,e):null,peers:p.peers});m.mcpSession=u,m.systemSent="",f.attach(w,m);const S=p.cleanup;return m.onExit(()=>{u&&P(u.id),S()}),f.release(w,{user:null,answered:!1}),g(`warm ${b}: spare ready`),!0}catch(c){return u&&P(u.id),p?.cleanup?.(),f.drop(w,`spare launch failed: ${c.message}`),!1}finally{D.delete(n)}}async function ve({messages:n,system:x,options:r,images:b,thread:E=null},g,{signal:$,launch:w=G}={}){if(!ce(r))return{handled:!1,reason:"not eligible"};const u=se();if(!u)return{handled:!1,reason:"claude not resolvable"};const p=`${Date.now()}-${Math.random().toString(36).slice(2)}`,c=(r.mcp?.specs||[]).map(s=>s?.name).filter(Boolean),A=[];R(A,r.extraArgs,q.claude,()=>{});const d=JSON.stringify({agent:"claude",cwd:r.workingDir||"",mode:r.permissionMode||"default",model:r.model||"",local:r.useLocalConfig!==!1,reach:r.reach||"",tools:[...c].sort(),extra:A,approvals:r.approvals===!0,env:r.runEnv?Object.keys(r.runEnv).sort().map(s=>`${s}=${r.runEnv[s]}`):[],hosts:r.sandbox?.hosts?(Array.isArray(r.sandbox.hosts)?r.sandbox.hosts:String(r.sandbox.hosts).split(/[\s,;]+/)).map(s=>String(s).trim().toLowerCase()).filter(Boolean).sort():[],outside:r.sandbox?.outside===!0,...Array.isArray(r.sandbox?.signIn)&&r.sandbox.signIn.length?{signIn:[...r.sandbox.signIn].sort()}:{},ephemeral:r.ephemeral===!0});let i=f.acquire({key:d,messages:n}),m=!1;const S=!i&&E?.plan.mode==="resume"?E.plan.sessionId:null;if(!i){if(i=f.reserve({key:d,label:`claude ${r.workingDir||"home"}`,evict:r.ephemeral!==!0}),!i)return{handled:!1,reason:"all warm slots busy"};m=!0;let s=null,t=null;try{let a=r.mcp;(a?.url&&c.length||r.approvals===!0)&&(s=W(g,a?.specs||[]),a?.url&&c.length&&(a={...a,url:`${a.url.replace(/\/[^/]*$/,"")}/${s.id}`})),t=await F({system:x,options:{...r,mcp:a},tag:p,resume:S,name:E?.thread.title||""});const I=[...t.args];R(I,r.extraArgs,q.claude,g);const _=s,C=await w({spec:u,args:I,cwd:t.cwd,env:t.runEnv,ask:t.approvals&&_?o=>U(_,o):null,peers:t.peers});C.mcpSession=s,C.systemSent=String(x||""),f.attach(i,C),S&&f.holds(i,n);const N=t.cleanup;C.onExit(()=>{s&&P(s.id),N()})}catch(a){return s&&P(s.id),t?.cleanup(),f.drop(i,`launch failed: ${a.message}`),{handled:!1,reason:a.message}}}const e=i.session;e.mcpSession&&ee(e.mcpSession,g,r.mcp?.specs);const v=n[n.length-1],y=await oe(b,p),T=String(x||""),k=ae(m&&!S?n:S?E.plan.tail||[v]:[v],y,!m&&T!==e.systemSent?T:"");e.systemSent=T;let l;try{l=await e.turn({prompt:k,emit:g,signal:$,harness:le({prompt:k,system:m?T:"",specs:m?r.mcp?.specs:null})})}finally{y.forEach(s=>z(s).catch(()=>{})),e.mcpSession&&re(e.mcpSession)}if($?.aborted||l.status==="interrupted")return l.status==="interrupted"&&e.alive?f.release(i,{user:String(v?.content||""),answered:l.streamedAny}):f.drop(i,"stopped"),{handled:!0};if(l.status!=="completed"){if(f.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}`)}g({type:"done",text:l.streamedAny?"":l.resultText}),f.release(i,{user:String(v?.content||""),answered:!0});const h=l.sessionId||e.sessionId||null;return setTimeout(()=>{de({key:d,spec:u,options:r,label:`claude ${r.workingDir||"home"}`,launch:w}).catch(()=>{})},250).unref?.(),{handled:!0,completed:!0,sessionId:h}}export{ve as chatWarm,G as launchClaudeSession,f as pool,de as prewarmClaude,ce as warmEligible};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import Z from"node:os";import L from"node:path";import{unlink as ee}from"node:fs/promises";import{spawnRpcChild as te}from"../rpc-child.js";import{spawnGroupOpts as re}from"../proc.js";import{spawn as se}from"node:child_process";import{track as ne,sandbox as ae,nestedSandboxLine as oe,grantedWriteRoots as H}from"../sandbox.js";import{createWarmPool as ie}from"../warm-pool.js";import{createSession as W,deleteSession as M,rebindSession as le,releaseSession as de,relayPermission as ce}from"../mcp-sessions.js";import{buildCliPrompt as U}from"./prompt.js";import{codexMcpConfigArgs as B,codexDisableArgs as z,configuredMcpServers as ue,redundantChatpanelServers as fe,ensureIsolatedHome as pe,writeImages as me}from"./codex.js";import{disabledMcpServers as he}from"../mcp-quarantine.js";import{resolveWorkdir as ge}from"../workdir.js";import{registerWarmPool as ye}from"../warm.js";const F=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,X=process.env.CHATPANEL_CODEX_EFFORT??"low",xe=9e4,J=5e3,A=ye("codex",ie({log:e=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[codex] ${e}`)}}));let j=0;function Fe(){j=0}const we=e=>e&&typeof e=="object"?(Array.isArray(e.hosts)?e.hosts:String(e.hosts||"").split(/[\s,;]+/)).map(n=>String(n).trim().toLowerCase()).filter(Boolean).sort():[];function
|
|
1
|
+
import Z from"node:os";import L from"node:path";import{unlink as ee}from"node:fs/promises";import{spawnRpcChild as te}from"../rpc-child.js";import{spawnGroupOpts as re}from"../proc.js";import{spawn as se}from"node:child_process";import{track as ne,sandbox as ae,nestedSandboxLine as oe,grantedWriteRoots as H}from"../sandbox.js";import{createWarmPool as ie}from"../warm-pool.js";import{createSession as W,deleteSession as M,rebindSession as le,releaseSession as de,relayPermission as ce}from"../mcp-sessions.js";import{buildCliPrompt as U}from"./prompt.js";import{codexMcpConfigArgs as B,codexDisableArgs as z,configuredMcpServers as ue,redundantChatpanelServers as fe,ensureIsolatedHome as pe,writeImages as me}from"./codex.js";import{disabledMcpServers as he}from"../mcp-quarantine.js";import{resolveWorkdir as ge}from"../workdir.js";import{registerWarmPool as ye}from"../warm.js";const F=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,X=process.env.CHATPANEL_CODEX_EFFORT??"low",xe=9e4,J=5e3,A=ye("codex",ie({log:e=>{process.env.CHATPANEL_WARM_LOG&&console.error(`[codex] ${e}`)}}));let j=0;function Fe(){j=0}const we=e=>e&&typeof e=="object"?(Array.isArray(e.hosts)?e.hosts:String(e.hosts||"").split(/[\s,;]+/)).map(n=>String(n).trim().toLowerCase()).filter(Boolean).sort():[];function be({agent:e="codex",cwd:n,options:t={},mcpNames:c=[],runEnv:a=null,disabled:f=[],roots:g=[]}){return JSON.stringify({agent:e,cwd:n,mode:t.permissionMode||"default",model:t.model||"",local:t.useLocalConfig!==!1,tools:[...c].sort(),env:a?Object.keys(a).sort().map(l=>`${l}=${a[l]}`):[],disabled:[...f].sort(),hosts:we(t.sandbox),...Array.isArray(t.sandbox?.signIn)&&t.sandbox.signIn.length?{signIn:[...t.sandbox.signIn].sort()}:{},outside:t.sandbox?.outside===!0,ephemeral:t.ephemeral===!0,roots:[...g].sort()})}function Se(e={}){return!(process.env.CHATPANEL_WARM==="off"||process.env.CHATPANEL_CODEX_APPSERVER==="off"||e.warm===!1||e.extraArgs&&String(e.extraArgs).trim()||Date.now()<j)}function G(e){return e==="bypassPermissions"?"danger-full-access":e==="acceptEdits"?"workspace-write":"read-only"}function V(e){if(e==null)return"";if(typeof e=="string")return e;if(Array.isArray(e?.content))return e.content.map(n=>typeof n=="string"?n:n?.text||"").filter(Boolean).join(`
|
|
2
2
|
`);try{return JSON.stringify(e)}catch{return String(e)}}function Ae(e,n,t,c){const a=e?.type||"",f=e?.id||`i_${c.n++}`,g=(l,d)=>{c.started.has(f)||(c.started.add(f),t({type:"tool",name:l,phase:"start",callId:f,input:d}))};if(a==="agentMessage"){n&&e.text&&!c.deltaItems.has(f)&&!c.said.has(f)&&(c.said.add(f),t({type:"delta",text:`${c.saidAny?`
|
|
3
3
|
|
|
4
4
|
`:""}${e.text}`}),c.saidAny=!0);return}if(a==="commandExecution"){if(g("shell",{command:e.command||""}),n){const l=e.exitCode===0||e.exitCode==null;t({type:"tool",name:"shell",phase:"done",callId:f,status:l?"ok":`exit ${e.exitCode}`,result:String(e.aggregatedOutput||"").slice(0,4e3)})}return}if(a==="fileChange"){const l=Array.isArray(e.changes)?e.changes.map(d=>d?.path||d?.file).filter(Boolean):[];g("edit",{files:l}),n&&t({type:"tool",name:"edit",phase:"done",callId:f,status:e.status==="failed"?"error":"ok"});return}if(a==="webSearch"){const l=e.action&&typeof e.action=="object"?e.action:{},d=e.query||l.query||"",m=l.url||"";g("web_search",{query:d,...m?{url:m}:{}}),n&&t({type:"tool",name:"web_search",phase:"done",callId:f,status:"ok",result:m?`Opened ${m}`:d?`Searched the web for ${d}`:"Searched the web"});return}if(a==="mcpToolCall"){const l=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(g(l,e.arguments&&typeof e.arguments=="object"?e.arguments:{}),n){const d=e.status==="failed"||e.error!=null,m=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error;t({type:"tool",name:l,phase:"done",callId:f,status:d?`error: ${String(m||"failed").slice(0,80)}`:"ok",result:String(d?m||"":V(e.result)).slice(0,4e3)});const r=!c.saidNested&&oe(`${m||""}
|
|
5
5
|
${V(e.result)}`,"Codex");r&&(c.saidNested=!0,t({type:"status",text:r}))}return}if(a==="plan"&&n&&e.text&&c.lastPlan!==e.text){c.lastPlan=e.text,t({type:"status",text:`Plan:
|
|
6
6
|
${e.text}`});return}if(a==="reasoning"&&n){if(c.deltaItems.has(f))return;const l=(Array.isArray(e.summary)?e.summary:[]).map(d=>typeof d=="string"?d:d?.text||"").filter(Boolean).join(`
|
|
7
7
|
`);l&&!c.reasoned.has(f)&&(c.reasoned.add(f),t({type:"reasoning",text:`${l}
|
|
8
|
-
`}))}}const
|
|
9
|
-
`).pop()}`:""}`),r&&r.finish({status:"died",error:i.error?.message||`Codex exited (${i.signal||i.code})`});for(const s of P)try{s(i)}catch{}},onRequest:async(i,s)=>{const u=
|
|
8
|
+
`}))}}const Ie="mcpServer/elicitation/request",ve={"item/commandExecution/requestApproval":{kind:"command",legacy:!1},execCommandApproval:{kind:"command",legacy:!0},"item/fileChange/requestApproval":{kind:"files",legacy:!1},applyPatchApproval:{kind:"files",legacy:!0}};function Ce(e,n={}){const t=n&&typeof n=="object"?n:{};if(e==="command"){const a=w(Array.isArray(t.command)?t.command.join(" "):t.command);return{tool:"Bash",displayName:"Codex",input:{command:a},description:w(t.reason),path:null,rules:a?[{tool:"Bash",content:a}]:[],toolUseId:w(t.itemId||t.callId)||null}}const c=w(t.grantRoot);return{tool:"Edit",displayName:"Codex",input:c?{file_path:c}:{},description:w(t.reason)||"change files outside its working folder",path:c||null,rules:c?[{tool:"Edit",content:c}]:[],toolUseId:w(t.itemId)||null}}function ke(e,n=!1){const t=e?.behavior==="allow";return n?{decision:t?"approved":"denied"}:{decision:t?e.scope==="chat"?"acceptForSession":"accept":"decline"}}const w=e=>String(e??"").replace(/\s+/g," ").trim().slice(0,200);function Ee(e={}){const n=e&&typeof e=="object"?e:{},t=n._meta&&typeof n._meta=="object"?n._meta:{},c=n.requestedSchema?.properties,a=!c||typeof c=="object"&&!Object.keys(c).length;if(n.mode==="url"||!a||!w(n.message))return null;const f=w(t.tool_name)||`${w(n.serverName)||"plugin"}_elicitation`,g=t.tool_params&&typeof t.tool_params=="object"&&!Array.isArray(t.tool_params)?t.tool_params:{};let l=w(t.origin||g.origin);if(!l)try{l=JSON.stringify(g)}catch{l=""}return{tool:f,displayName:w(t.connector_name||t.tool_title)||f,input:g,description:w(n.message),path:null,rules:[{tool:f,content:l&&l!=="{}"?l:w(n.message)}],toolUseId:w(t.callId)||null}}function _e(e){return e?.behavior==="allow"?{action:"accept",content:{}}:{action:"decline"}}function $e(){return{n:0,started:new Set,said:new Set,reasoned:new Set,deltaItems:new Set,saidAny:!1,lastPlan:null}}async function K({bin:e="codex",cwd:n,env:t,configArgs:c=[],options:a={},spawnImpl:f,log:g=()=>{},resume:l=null}){const d=a.permissionMode||"default",m=d==="bypassPermissions";let r=null,_=!1;const P=new Set;let C="";const N=d!=="acceptEdits"&&d!=="bypassPermissions",k=await ae().wrap(e,["app-server",...c],{cwd:n||void 0,env:t,...re},{engine:"codex",cwd:n,readOnly:N}),b=k.record.layer==="none"?G(d):"danger-full-access";k.record.layer==="none"&&g(`sandbox: codex app-server runs outside a sandbox — ${k.record.reason}`);const y=te(k.bin,k.argv,{cwd:n,env:t,spawnImpl:(i,s,u)=>ne((f||se)(i,s,u),k,{kind:"warm"}),spawnOpts:k.opts,onStderr:i=>{C=(C+i).slice(-2e3)},onExit:i=>{g(`app-server exited: ${i.signal||i.code}${C?` — ${C.trim().split(`
|
|
9
|
+
`).pop()}`:""}`),r&&r.finish({status:"died",error:i.error?.message||`Codex exited (${i.signal||i.code})`});for(const s of P)try{s(i)}catch{}},onRequest:async(i,s)=>{const u=ve[i];if(u){if(m)return u.legacy?{decision:"approved"}:{decision:"accept"};const o=r,v=Ce(u.kind,s);if(o?.ask){o.hold();try{return ke(await o.ask(v),u.legacy)}finally{r===o&&o.touch()}}return o?.emit({type:"status",text:u.kind==="command"?"Codex asked to run a command outside its sandbox — declined (ChatPanel could not ask you here; set Permissions to full access to allow).":"Codex asked to change files outside its folders — declined (ChatPanel could not ask you here; add the folder under Settings › Runtime, or set Permissions to full access)."}),u.legacy?{decision:"denied"}:{decision:"decline"}}if(i===Ie){const o=r,v=Ee(s);if(v&&o?.ask){o.hold();try{return _e(await o.ask(v))}finally{r===o&&o.touch()}}return o?.emit({type:"status",text:`Codex asked: ${w(s?.message)||`a question from ${s?.serverName||"a plugin"}`} — declined (${v?"ChatPanel could not ask you here":"ChatPanel cannot answer this kind of question yet"}).`}),{action:"decline"}}r?.emit({type:"status",text:`Codex asked for ${w(i)} — declined (ChatPanel cannot answer it).`})},onMessage:i=>{if(!i.method||!r)return;const s=i.params||{};if(s.threadId&&s.threadId!==r.threadId)return;r.touch();const u=i.method;if(u==="item/agentMessage/delta"){if(!s.delta)return;r.state.deltaItems.add(s.itemId),r.state.said.has(s.itemId)||(r.state.said.add(s.itemId),r.state.saidAny&&r.emit({type:"delta",text:`
|
|
10
10
|
|
|
11
11
|
`})),r.state.saidAny=!0,r.streamed=!0,r.emit({type:"delta",text:s.delta})}else if(u==="item/reasoning/summaryTextDelta"||u==="item/reasoning/textDelta"){if(!s.delta)return;r.state.deltaItems.add(s.itemId),r.streamed=!0,r.emit({type:"reasoning",text:s.delta})}else if(u==="item/reasoning/summaryPartAdded")r.state.deltaItems.has(s.itemId)&&r.emit({type:"reasoning",text:`
|
|
12
|
-
`});else if(u==="item/started"||u==="item/completed"){const o=r.state.started.size+r.state.said.size;Ae(s.item,u==="item/completed",r.emit,r.state),r.state.started.size+r.state.said.size>o&&(r.streamed=!0)}else if(u==="thread/tokenUsage/updated"){const o=s.tokenUsage?.last||s.tokenUsage?.total;o&&(r.usage={type:"usage",provider:"bridge",inputTokens:o.inputTokens||0,outputTokens:o.outputTokens||0,cacheReadTokens:o.cachedInputTokens||0,cacheWriteTokens:o.cacheWriteInputTokens||0,costUsd:null})}else if(u==="error"){const o=s.error?.message||"error";s.willRetry?r.emit({type:"status",text:`Codex: ${o.slice(0,200)} — retrying`}):r.lastError=o}else if(u==="turn/completed"){const o=s.turn||{};if(r.turnId&&o.id&&o.id!==r.turnId)return;r.finish({status:o.status||"completed",error:o.error?.message||r.lastError||null})}}});let
|
|
13
|
-
`).filter(Boolean).pop()||"";throw new Error(s?`${i.message}: ${s.slice(-300)}`:i.message)}let
|
|
12
|
+
`});else if(u==="item/started"||u==="item/completed"){const o=r.state.started.size+r.state.said.size;Ae(s.item,u==="item/completed",r.emit,r.state),r.state.started.size+r.state.said.size>o&&(r.streamed=!0)}else if(u==="thread/tokenUsage/updated"){const o=s.tokenUsage?.last||s.tokenUsage?.total;o&&(r.usage={type:"usage",provider:"bridge",inputTokens:o.inputTokens||0,outputTokens:o.outputTokens||0,cacheReadTokens:o.cachedInputTokens||0,cacheWriteTokens:o.cacheWriteInputTokens||0,costUsd:null})}else if(u==="error"){const o=s.error?.message||"error";s.willRetry?r.emit({type:"status",text:`Codex: ${o.slice(0,200)} — retrying`}):r.lastError=o}else if(u==="turn/completed"){const o=s.turn||{};if(r.turnId&&o.id&&o.id!==r.turnId)return;r.finish({status:o.status||"completed",error:o.error?.message||r.lastError||null})}}});let S,$=!1;try{await y.request("initialize",{clientInfo:{name:"chatpanel-bridge",version:"1"},capabilities:{experimentalApi:!0}},{timeoutMs:2e4}),y.notify("initialized");const i=H(n),s=v=>y.request(l?"thread/resume":"thread/start",{...l?{threadId:l,excludeTurns:!0}:a.ephemeral===!0?{ephemeral:!0}:{},cwd:n||void 0,sandbox:v,approvalPolicy:"never",...a.model?{model:a.model}:{},...i.length?{config:{sandbox_workspace_write:{writable_roots:i}}}:{}},{timeoutMs:xe});let u=await s(b);const o=String(u?.sandbox?.type||"");if(b==="danger-full-access"&&o&&o!=="dangerFullAccess"&&(u=await s(G(d)),$=!0),S=u?.thread?.id,!S)throw new Error("Codex app-server started no thread")}catch(i){y.kill();const s=C.trim().split(`
|
|
13
|
+
`).filter(Boolean).pop()||"";throw new Error(s?`${i.message}: ${s.slice(-300)}`:i.message)}let I="";return{threadId:S,async setName(i){const s=String(i||"").trim();if(!(!s||s===I||y.exited)){I=s;try{await y.request("thread/name/set",{threadId:S,name:s},{timeoutMs:5e3})}catch{}}},get pid(){return y.pid},get alive(){return!y.exited},onExit(i){P.add(i)},close(){y.close()},async turn({prompt:i,imageFiles:s=[],emit:u,signal:o,ask:v=null}){if(y.exited)throw new Error("Codex process is gone");if(r)throw new Error("a turn is already running on this thread");const x=$e();let p=null,E;const O=new Promise(T=>{E=T}),h={threadId:S,turnId:null,emit:u,state:x,streamed:!1,usage:null,lastError:null,ask:v,hold(){clearTimeout(p)},touch(){clearTimeout(p),p=setTimeout(()=>h.finish({status:"timeout",error:`Codex timed out — no output for ${Math.round(F/1e3)}s.`}),F)},finish(T){r===h&&(clearTimeout(p),r=null,E(T))}};r=h,h.touch();const D=async()=>{if(r===h){try{await y.request("turn/interrupt",{threadId:S,turnId:h.turnId},{timeoutMs:J})}catch{}setTimeout(()=>{r===h&&(h.finish({status:"killed",error:null}),y.kill())},J).unref?.()}};if(o?.aborted)return h.finish({status:"killed",error:null}),{streamed:!1,said:!1,status:"killed",usage:null};o?.addEventListener("abort",D,{once:!0}),$&&!_&&(_=!0,u({type:"status",text:"Your organisation’s Codex policy does not let ChatPanel’s sandbox replace Codex’s own, and Codex’s cannot start inside ChatPanel’s — so Codex will ask you before each command. “Allow for this chat” stops it asking again for the same command."})),u({type:"status",text:"Codex working"});try{const T=[{type:"text",text:i},...s.map(Q=>({type:"localImage",path:Q}))],Y=await y.request("turn/start",{threadId:S,input:T,summary:"auto",...X?{effort:X}:{}},{timeoutMs:3e4});h.turnId=Y?.turn?.id||null}catch(T){h.finish({status:"failed",error:T.message})}const q=await O;return o?.removeEventListener("abort",D),q.status==="timeout"&&y.kill(),h.usage&&u(h.usage),{streamed:h.streamed,said:x.saidAny,status:q.status,error:q.error,usage:h.usage}}}}const R=new Set;async function Pe({key:e,cwd:n,env:t,configArgs:c,options:a,label:f,launch:g=K,force:l=!1}={}){if(process.env.CHATPANEL_WARM_SPARE==="off"&&!l||!e||R.has(e)||A.peek({key:e,messages:[{role:"user",content:""}]}))return!1;R.add(e);const d=A.reserve({key:e,label:`${f} (spare)`,evict:!1});if(!d)return R.delete(e),!1;let m=null;try{const r=[...c];if(a.mcp?.url&&(a.mcp?.specs||[]).length){m=W(()=>{},a.mcp.specs);const C=a.mcp.url.replace(/\/[^/]*$/,"");r.unshift(...B({url:`${C}/${m.id}`,serverName:a.mcp?.serverName||"chatpanel_browser",specs:a.mcp.specs}))}const _=await g({cwd:n,env:t,configArgs:r,options:a});_.mcpSession=m,_.systemSent="",A.attach(d,_);const P=m;return _.onExit(()=>{P&&M(P.id)}),A.release(d,{user:null,answered:!1}),!0}catch(r){return m&&M(m.id),A.drop(d,`spare launch failed: ${r.message}`),!1}finally{R.delete(e)}}async function Xe({messages:e,system:n,options:t,images:c,thread:a=null},f,{signal:g,launch:l=K}={}){if(!Se(t))return{handled:!1,reason:"not eligible"};const d=ge(t.workingDir),m={...process.env,...t.runEnv||{}};if(t.useLocalConfig===!1){const p=pe();p&&(m.CODEX_HOME=p)}const r=t.mcp?.serverName||"chatpanel_browser",_=m.CODEX_HOME||L.join(Z.homedir(),".codex"),P=ue(_),C=(t.mcp?.specs||[]).map(p=>p?.name).filter(Boolean),N=[...new Set([...he("codex",t,[r]),...C.length?fe(_):[]])].filter(p=>P.has(p)),k=be({cwd:d,options:t,mcpNames:C,runEnv:t.runEnv||null,disabled:N,roots:H(d)});let b=A.acquire({key:k,messages:e}),y=!1,S=null,$=!b&&a?.plan.mode==="resume"?a.plan.sessionId:null;if(!b){if(b=A.reserve({key:k,label:`codex ${L.basename(d||"")}`}),!b)return{handled:!1,reason:"all warm slots busy"};y=!0;try{const p=[];if(t.mcp?.url&&C.length){S=W(f,t.mcp.specs);const h=t.mcp.url.replace(/\/[^/]*$/,"");p.push(...B({url:`${h}/${S.id}`,serverName:r,specs:t.mcp.specs}))}p.push(...z(N));let E;try{E=await l({cwd:d,env:m,configArgs:p,options:t,resume:$})}catch(h){if(!$)throw h;a.forget(),a=a.restart(),$=null,E=await l({cwd:d,env:m,configArgs:p,options:t})}E.mcpSession=S,E.systemSent="",A.attach(b,E),$&&A.holds(b,e);const O=S;E.onExit(()=>{O&&M(O.id)})}catch(p){return S&&M(S.id),A.drop(b,`launch failed: ${p.message}`),/unknown|unrecognized|unexpected argument|app-server/i.test(p.message)&&(j=Date.now()+10*6e4),{handled:!1,reason:p.message}}}const I=b.session;I.mcpSession&&le(I.mcpSession,f,t.mcp?.specs);const i=e[e.length-1],s=String(n||""),u=y&&!$?U(e,s):U($?a.plan.tail||[i]:[i],s&&($||s!==I.systemSent)?s:""),o=`${Date.now()}-${Math.random().toString(36).slice(2)}`,v=await me(c,o);let x;try{const p=t.approvals===!0&&t.permissionSession?E=>ce(t.permissionSession,null,{request:E}):null;x=await I.turn({prompt:u,imageFiles:v,emit:f,signal:g,ask:p})}finally{v.forEach(p=>ee(p).catch(()=>{})),I.mcpSession&&de(I.mcpSession)}if(I.systemSent=s,g?.aborted||x.status==="interrupted")return x.status==="interrupted"&&I.alive?A.release(b,{user:String(i?.content||""),answered:x.streamed}):A.drop(b,"stopped"),{handled:!0};if(x.status!=="completed"){if(A.drop(b,x.error||x.status),!x.streamed)return{handled:!1,reason:x.error||x.status};throw new Error(x.error||`Codex ${x.status}`)}return x.said||f({type:"delta",text:"(no output)"}),f({type:"done",text:""}),a?.thread.title&&I.setName?.(a.thread.title).catch(()=>{}),A.release(b,{user:String(i?.content||""),answered:!0}),setTimeout(()=>{Pe({key:k,cwd:d,env:m,configArgs:z(N),options:t,label:`codex ${L.basename(d||"")}`,launch:l}).catch(()=>{})},250).unref?.(),{handled:!0,completed:!0,sessionId:I.threadId||null,thread:a}}export{Xe as chatWarm,Ce as codexApprovalRequest,ke as codexApprovalResponse,Ee as codexElicitationRequest,_e as codexElicitationResponse,Ae as forwardV2Item,K as launchCodexSession,$e as newTurnState,A as pool,Pe as prewarmCodex,Fe as resetSupport,Se as warmEligible,be as warmKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as a}from"./event.js";const l=Object.freeze({claude:{label:"Claude Code",vendor:"Anthropic",hosts:["api.anthropic.com"],repoint:"limited",how:"ANTHROPIC_BASE_URL (+ ANTHROPIC_AUTH_TOKEN) to an Anthropic-compatible endpoint — this gateway’s /v1/messages qualifies",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",session:{resume:["--resume","{id}"],off:["--no-session-persistence"],name:["--name","{name}"]}},codex:{label:"Codex",vendor:"OpenAI",hosts:["api.openai.com","chatgpt.com"],repoint:"limited",how:"OPENAI_BASE_URL, or a model_provider in ~/.codex/config.toml pointing at an OpenAI-compatible endpoint",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",ownSandbox:"computer use (controlling the browser and other apps)",session:{resume:["resume","{id}"],off:["--ephemeral"]}},antigravity:{label:"Antigravity",vendor:"Google",hosts:["*.googleapis.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},kiro:{label:"Kiro",vendor:"AWS",hosts:["*.amazonaws.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},copilot:{label:"GitHub Copilot",vendor:"GitHub",hosts:["api.githubcopilot.com","*.github.com"],repoint:"no",how:"",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",session:{resume:["--session-id","{id}"],off:null,name:["--name","{name}"]}},deepseek:{label:"DeepSeek Harness",vendor:"DeepSeek",hosts:["api.deepseek.com"],repoint:"limited",how:"its base URL setting, to an OpenAI-compatible endpoint",dirs:null,defaultModel:"cloud"},opencode:{label:"OpenCode",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, Ollama, LM Studio, or this gateway",dirs:null,defaultModel:"configurable",session:{resume:["--session","{id}"],off:null,name:["--title","{name}"]}},pi:{label:"Pi",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, or this gateway",dirs:null,defaultModel:"configurable"},hermes:{label:"Hermes",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — a local model is a first-class choice",dirs:null,defaultModel:"configurable"}}),p=
|
|
1
|
+
import{EventError as a}from"./event.js";const l=Object.freeze({claude:{label:"Claude Code",vendor:"Anthropic",hosts:["api.anthropic.com"],repoint:"limited",how:"ANTHROPIC_BASE_URL (+ ANTHROPIC_AUTH_TOKEN) to an Anthropic-compatible endpoint — this gateway’s /v1/messages qualifies",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",session:{resume:["--resume","{id}"],off:["--no-session-persistence"],name:["--name","{name}"]},envFrom:["~/.claude/settings.json","/etc/claude-code/managed-settings.json","/Library/Application Support/ClaudeCode/managed-settings.json"]},codex:{label:"Codex",vendor:"OpenAI",hosts:["api.openai.com","chatgpt.com"],repoint:"limited",how:"OPENAI_BASE_URL, or a model_provider in ~/.codex/config.toml pointing at an OpenAI-compatible endpoint",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",ownSandbox:"computer use (controlling the browser and other apps)",session:{resume:["resume","{id}"],off:["--ephemeral"]}},antigravity:{label:"Antigravity",vendor:"Google",hosts:["*.googleapis.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},kiro:{label:"Kiro",vendor:"AWS",hosts:["*.amazonaws.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},copilot:{label:"GitHub Copilot",vendor:"GitHub",hosts:["api.githubcopilot.com","*.github.com"],repoint:"no",how:"",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",session:{resume:["--session-id","{id}"],off:null,name:["--name","{name}"]}},deepseek:{label:"DeepSeek Harness",vendor:"DeepSeek",hosts:["api.deepseek.com"],repoint:"limited",how:"its base URL setting, to an OpenAI-compatible endpoint",dirs:null,defaultModel:"cloud"},opencode:{label:"OpenCode",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, Ollama, LM Studio, or this gateway",dirs:null,defaultModel:"configurable",session:{resume:["--session","{id}"],off:null,name:["--title","{name}"]}},pi:{label:"Pi",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, or this gateway",dirs:null,defaultModel:"configurable"},hermes:{label:"Hermes",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — a local model is a first-class choice",dirs:null,defaultModel:"configurable"}}),p=o=>String(o||"").toLowerCase().replace(/[^a-z]/g,""),d={claudecode:"claude",githubcopilot:"copilot",copilotcli:"copilot",deepseekharness:"deepseek",gemini:"antigravity",geminicli:"antigravity"};function s(o){const n=p(o);if(l[n])return{id:n,...l[n]};if(d[n])return{id:d[n],...l[d[n]]};const e=Object.entries(l).find(([i,t])=>n.includes(i)||n.includes(p(t.label)));return e?{id:e[0],...e[1]}:null}function m(o,{repointed:n=null}={}){const e=s(o);return e?n?{egress:"configurable",where:`a coding agent · model at ${n}`,note:`Re-pointed by you; ${e.how||"its own setting"}.`}:e.repoint==="yes"?{egress:"configurable",where:"a coding agent · model of your choosing",note:`Its model is a setting of its own — ${e.how}. Until you set one, whatever it defaults to.`}:e.repoint==="limited"?{egress:"internet",where:`a coding agent · model at ${e.vendor}`,note:`The conversation goes to ${e.vendor} with your own login. It can be re-pointed: ${e.how}.`}:{egress:"internet",where:`a coding agent · model at ${e.vendor}`,note:`The conversation goes to ${e.vendor} with your own login; this agent cannot be pointed elsewhere.`}:{egress:"internet",where:"a coding agent · its own model, elsewhere",note:"No card for this agent — assume its model is a vendor’s until you know otherwise."}}function u(o){if(o==null)return null;if(typeof o=="string")return u({flag:o,repeat:!0});if(typeof o!="object"||Array.isArray(o))throw new a("SHAPE","dirs: must be { flag, repeat } or { flag, separator }");const n=String(o.flag||"").trim();if(!/^--?[A-Za-z][\w-]*$/.test(n))throw new a("SHAPE",`dirs: not a flag: ${JSON.stringify(o.flag)}`);const e=o.separator==null?null:String(o.separator);if(e!=null&&(e.length===0||/\s/.test(e)))throw new a("SHAPE","dirs: separator must be a non-empty run of non-space characters");return e!=null?{flag:n,separator:e}:{flag:n,repeat:!0}}function h({harness:o,roots:n=[],dirs:e}={}){const i=(Array.isArray(n)?n:[]).map(r=>String(r||"").trim()).filter(Boolean);if(!i.length)return[];const t=u(e!==void 0?e:s(o)?.dirs??null);return t?t.separator?[t.flag,i.join(t.separator)]:i.flatMap(r=>[t.flag,r]):[]}function w(o,n){try{return!!u(n!==void 0?n:s(o)?.dirs??null)}catch{return!1}}const f=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function A({harness:o,mode:n,id:e="",name:i=""}={}){const t=s(o)?.session;if(!t)return[];if(n==="off")return Array.isArray(t.off)?[...t.off]:[];if(n==="name"){const r=String(i??"").replace(/\s+/g," ").trim().slice(0,120);return!r||r.startsWith("-")||!Array.isArray(t.name)?[]:t.name.map(c=>c==="{name}"?r:c)}if(n!=="resume"||!Array.isArray(t.resume))return[];if(!f.test(String(e)))throw new a("SHAPE",`harness session: ${JSON.stringify(String(e).slice(0,40))} is not a session id`);return t.resume.map(r=>r==="{id}"?String(e):r)}const y=o=>Array.isArray(s(o)?.session?.resume);export{l as HARNESS_CARDS,s as harnessCard,h as harnessDirArgs,m as harnessEgress,y as harnessResumes,A as harnessSessionArgs,w as harnessTakesDirs,u as normalizeDirsSpec};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as
|
|
1
|
+
import{EventError as p}from"./event.js";const c=t=>!!t&&typeof t=="object"&&!Array.isArray(t),n=t=>[...new Set(t)],i=(t,s)=>{if(!t)throw new p("SHAPE",s)},l=/^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d{1,5})?$/i,u=Object.freeze({aws:"AWS",oci:"Oracle Cloud",gcloud:"Google Cloud",azure:"Azure"}),a=Object.freeze(Object.keys(u));function y(t){return n(String(t||"").split(/[\s,;]+/).map(s=>s.trim().toLowerCase()).filter(Boolean))}function f(t){if(t==null)return{hosts:[],write:[]};i(c(t),"grant: must be an object");const s=Array.isArray(t.hosts)?t.hosts:typeof t.hosts=="string"?y(t.hosts):[],o=Array.isArray(t.write)?t.write:typeof t.write=="string"?t.write.split(/[\n,]+/).map(e=>e.trim()).filter(Boolean):[];for(const e of s)i(typeof e=="string"&&e!=="*"&&l.test(e),`grant: not a host pattern: ${JSON.stringify(e)}`);for(const e of o)i(typeof e=="string"&&e.length>0&&e.length<1024&&!e.includes("\0"),`grant: not a path: ${JSON.stringify(e)}`);const r=(Array.isArray(t.signIn)?t.signIn:typeof t.signIn=="string"?t.signIn.split(/[\s,;]+/):[]).map(e=>typeof e=="string"?e.trim().toLowerCase():e).filter(e=>e!=="");for(const e of r)i(a.includes(e),`grant: not a sign-in (${a.join(", ")}): ${JSON.stringify(e)}`);return{hosts:n(s.map(e=>e.toLowerCase())),write:n(o),...t.outside===!0?{outside:!0}:{},...r.length?{signIn:n(r)}:{}}}function h(...t){const s=t.map(f);return{hosts:n(s.flatMap(o=>o.hosts)),write:n(s.flatMap(o=>o.write))}}function w(...t){const s=t.map(f),o=n(s.flatMap(r=>r.signIn||[]));return{...h(...s),...s.some(r=>r.outside)?{outside:!0}:{},...o.length?{signIn:o}:{}}}export{u as SIGN_IN_LABELS,a as SIGN_IN_NAMES,h as mergeGrants,w as mergePersonGrants,f as normalizeGrant,y as parseHostList};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as L}from"./event.js";import{normalizeGrant as S}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as P,SECRET_DIR_PAIRS as v}from"./secret-names.js";const R=Object.freeze(["none","process","container","kubernetes"]),$=Object.freeze(["open","allowlist","none","gateway"]),_=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),g=e=>{let t=String(e||"").trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"));)t=t.slice(0,-1);return t},x=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),b=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},N=_.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function I(e,t=""){const n=m(g(x(g(e),t)));if(!n)return!1;for(const o of _)if(b(n,o)||t&&b(n,x(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return N.some(o=>{for(let s=0;s+o.length<=r.length;s+=1)if(o.every((a,l)=>a.toLowerCase()===r[s+l]))return!0;return!1})}const W=Object.freeze([...[...P].map(e=>`~/**/${e}`),...v.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 ee(e,{home:t="",globs:n=[..._,...W]}={}){const r=m(g(x(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),s=m(g(t));for(const a of n){const l=m(g(a));if(l){if(l.startsWith("~/**/")){if(s&&!b(r,s))continue;const c=l.slice(5).split("/").filter(Boolean).map(z);for(let i=0;i+c.length<=o.length;i+=1)if(c.every((d,u)=>d.test(o[i+u])))return a;continue}if(b(r,x(l,t)))return a}}return null}function z(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const D=".cache/chatpanel/ca-bundle.crt",te=".cache/chatpanel/ca-bundle.pem";function ne(e=""){const t=m(g(e));return t?`${t}/${D}`:`~/${D}`}const H=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"]),k=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),C=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:[]})}),T="~/Library/Keychains",K=/(^|\/)Keychains\/?$/,Y=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),h=e=>!!e&&typeof e=="object"&&!Array.isArray(e),y=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),f=(e,t)=>{if(!e)throw new L("SHAPE",t)},p=e=>[...new Set(e)];function j(e){f(h(e),"kit: must be an object"),f(typeof e.id=="string"&&e.id.length>0,"kit: id required"),f(h(e.network)&&$.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${$.join(", ")}`),f(y(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),f(y(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),f(h(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])f(y(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return f(y(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),f(y(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&&f(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&f(Array.isArray(e.credentials)&&e.credentials.every(t=>h(t)&&typeof t.name=="string"&&typeof t.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:p(e.network.allowedDomains||[]),deniedDomains:p(e.network.deniedDomains||[]),...(e.network.unixSockets||[]).length?{unixSockets:p(e.network.unixSockets)}:{}},filesystem:{allowWrite:p(e.filesystem.allowWrite),denyWrite:p(e.filesystem.denyWrite||[]),allowRead:p(e.filesystem.allowRead||[]),denyRead:p(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:h(e.limits)?{...e.limits}:{}}}import{normalizeGrant as ge,mergeGrants as me,parseHostList as we}from"./sandbox-grant.js";const U=e=>String(e).replace(/([\\/])\*$/,"$1**");function oe({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:s=[],grant:a=null,home:l="",reads:c="enumerated",readOnly:i=!1,peers:d=!0}={}){const u=C[e]||C.custom;f(typeof t=="string"&&t.length>0,"kit: cwd required");const O=S(a);return j({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:p([...u.hosts,...Y,...r,...O.hosts]),deniedDomains:[],unixSockets:d?[...u.sockets||[]]:[]},filesystem:{allowWrite:p(i?[...k,...u.write]:[t,...k,...u.write,...[...o,...O.write].filter(A=>!I(A,l)).map(U)]),denyWrite:[],allowRead:c==="inverted"?p([t,...H,...u.write,...u.keychain?[T]:[],...G({grant:O,extraWrite:o,cwd:t,home:l})]):[t],denyRead:p([...c==="inverted"?["~",...l?[l]:[]]:[],...[..._,...W].filter(A=>!(u.keychain&&K.test(A))),...s])}})}function B(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 G({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},a=(i,d)=>i===d||i.startsWith(`${d}/`)||i.startsWith(`${d}\\`),l=s(o(n)),c=[];for(const i of[...S(e).write,...Array.isArray(t)?t:[]]){const d=B(s(o(s(i))));if(d&&!I(d,r)&&!(l&&a(d,l))&&!c.some(u=>a(d,u))){for(let u=c.length-1;u>=0;u--)a(c[u],d)&&c.splice(u,1);c.push(d)}}return c}function re(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=j(e),s=l=>n&&l.startsWith("~")?n+l.slice(1):l,a=o.network.mode==="none"?[]:t.map(l=>`127.0.0.1:${l}`);return{network:{allowedDomains:p([...o.network.allowedDomains,...a]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&a.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 se({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:s=null}={}){return f(R.includes(e),`sandbox record: layer must be one of ${R.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(s)&&s.length?{hosts:p(s)}:{}}}function M(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){f(!/[\r\n]/.test(n),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=n;if(n===""||/[ \t\v"]/.test(n)){r='"';for(let o=0;o<n.length;o++){let 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 q=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function ie(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of q)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 ce(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>M(r,{platform:n})).join(" ")}const ae=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),F=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function E(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function X(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 le({kit:e,files:t=[],home:n}){f(typeof n=="string"&&n.length>0,"windows grants: home required");const r=c=>(c.startsWith("~")?n+c.slice(1):c).replace(/\//g,"\\"),o=[];for(const c of e?.filesystem?.allowWrite||[]){const i=r(c);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(f(!F(i)&&w(i)!==w(n),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),E(i,n)&&o.push(i))}const s=(c,i)=>i.some(d=>w(c)===w(d)||E(c,d)),a=[];for(const c of t){const i=X(c);i&&E(i,n)&&a.push(i)}for(const c of e?.filesystem?.allowRead||[]){const i=r(c);E(i,n)&&a.push(i)}const l=p(a).filter(c=>!s(c,o));return{read:l.filter(c=>!l.some(i=>i!==c&&E(c,i))),write:p(o)}}const V=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 de({engine:e="custom",home:t,env:n={},base:r={},carry:o=V}={}){f(typeof t=="string"&&t.length>0,"windows env: home required");const s=t.replace(/\//g,"\\"),a=/^[a-z]:/i.test(s)?s.slice(0,2):"",l={USERPROFILE:s,...a?{HOMEDRIVE:a,HOMEPATH:s.slice(2)}:{}};for(const[c,i]of Object.entries(n))typeof i=="string"&&(r[c]!==i||o.includes(c))&&(l[c]=i);return e==="codex"&&!l.CODEX_HOME&&(l.CODEX_HOME=s+"\\.codex"),l}function fe(e,t){f(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;f(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let a=n+1;a<r;a++)e[a]==="--env"&&typeof e[a+1]=="string"&&o.add(e[a+1].split("=")[0].toUpperCase());const s=[];for(const[a,l]of Object.entries(t||{}))f(/^[A-Za-z_][A-Za-z0-9_]*$/.test(a),`srt-win env: bad key ${a}`),f(!/[\r\n]/.test(l),`srt-win env: ${a} holds a newline`),o.has(a.toUpperCase())||s.push("--env",`${a}=${l}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{D as CA_BUNDLE_RELPATH,te as CA_BUNDLE_RELPATH_LEGACY,k as COMMON_WRITE,Y as DEVELOPER_HOSTS,C as ENGINE_KITS,$ as NETWORK_MODES,R as SANDBOX_LAYERS,_ as SECRET_PATHS,W as SECRET_READ_GLOBS,H as TOOLCHAIN_READ,V as WINDOWS_CARRY_KEYS,ne as caBundlePath,I as isSecretWritePath,oe as kitFor,me as mergeGrants,ge as normalizeGrant,we as parseHostList,ee as readDenialFor,ie as sandboxEnvOverlay,se as sandboxRecord,ce as shellJoin,M as shellQuote,re as toSrtSettings,E as underWindowsHome,j as validateKit,le as windowsGrantsFor,X as windowsInstallRoot,de as windowsSandboxEnv,fe as withSrtWinEnv,G 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 $=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};
|
package/src/pii/pii-detect.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{assertEndpointUrl as D}from"./net.js";const
|
|
1
|
+
import{assertEndpointUrl as D}from"./net.js";const N=new Map,p=300;function V(){N.clear()}function T(e,t){let o=5381;const s=`${t?.backend}|${t?.url}|${t?.model}|${t?.strictness||""}|${JSON.stringify(t?.types||null)}|${e}`;for(let n=0;n<s.length;n++)o=(o<<5)+o+s.charCodeAt(n)|0;return`${s.length}:${o}`}function y(e,t,o){return new Promise((s,n)=>{const i=setTimeout(()=>n(new Error("detect timeout")),Math.max(200,t||1500)),r=()=>{clearTimeout(i),n(new Error("aborted"))};o&&o.addEventListener?.("abort",r,{once:!0}),e.then(c=>{clearTimeout(i),s(c)},c=>{clearTimeout(i),n(c)})})}function w(e){const t=String(e||"ENTITY").toUpperCase().replace(/[^A-Z0-9]/g,"")||"ENTITY";return{PER:"PERSON",PERSON:"PERSON",PERSONNAME:"PERSON",PRIVATEPERSON:"PERSON",GIVENNAME:"PERSON",FIRSTNAME:"PERSON",MIDDLENAME:"PERSON",SURNAME:"PERSON",LASTNAME:"PERSON",FULLNAME:"PERSON",ORG:"ORG",ORGANIZATION:"ORG",COMPANYNAME:"ORG",COMPANY:"ORG",GPE:"LOCATION",LOC:"LOCATION",LOCATION:"LOCATION",CITY:"LOCATION",STATE:"LOCATION",COUNTY:"LOCATION",COUNTRY:"LOCATION",STREET:"ADDRESS",BUILDINGNUM:"ADDRESS",BUILDINGNUMBER:"ADDRESS",ZIPCODE:"ADDRESS",POSTCODE:"ADDRESS",SECADDRESS:"ADDRESS",ADDRESS:"ADDRESS",PRIVATEADDRESS:"ADDRESS",NORP:"GROUP",EMAIL:"EMAIL",EMAILADDRESS:"EMAIL",PRIVATEEMAIL:"EMAIL",PHONE:"PHONE",PHONENUMBER:"PHONE",TELEPHONENUM:"PHONE",PRIVATEPHONE:"PHONE",PHONEIMEI:"ID",SOCIALNUM:"SSN",USSSN:"SSN",SSN:"SSN",CREDITCARDNUMBER:"CREDITCARD",CREDITCARD:"CREDITCARD",IBAN:"IBAN",IBANCODE:"IBAN",ACCOUNTNUM:"ID",ACCOUNTNUMBER:"ID",TAXNUM:"ID",IDCARDNUM:"ID",DRIVERLICENSENUM:"ID",PASSPORTNUM:"ID",VEHICLEVRM:"ID",DATEOFBIRTH:"ID",DOB:"ID",PRIVATEDATE:"ID",PRIVATEURL:"ID",USERNAME:"ID",USERID:"ID",IP:"ID",IPADDRESS:"ID",MAC:"ID",PASSWORD:"SECRET",APIKEY:"SECRET",SECRET:"SECRET"}[t]||t}const C=new Set(["EMAIL","PHONE","SSN","CREDITCARD","IBAN","ID","SECRET"]),d=new Set(["LOCATION","FAC","ADDRESS","GROUP","NRP"]),P=/(?:^|[\s$€£])\$?\d+(?:[.,]\d+)?\s?(?:[kmb]n?|mm|million|billion|thousand|%)(?=[\s.,;:!?)]|$)/i,g=/(?:^|\s)\d{1,6}(?=\s|,|$)/;function L(e){const t=String(e||"").trim();return P.test(t)&&!g.test(t)}const j=Object.freeze(["balanced","strict"]),b=e=>e?.strictness==="strict"||e?.detection?.strictness==="strict"?"strict":"balanced",R=new Set(["chap","chatpanel"]),M=new Set(["by","hey"]);function U(e){const t=String(e||"").toLowerCase().match(new RegExp("\\p{L}[\\p{L}\\p{N}]*","gu"))||[];return t.some(o=>R.has(o))&&t.every(o=>R.has(o)||M.has(o))}function k(e,t,o,s="balanced"){const n=r=>!o||o[r]!==!1;return(t==="PERSON"||t==="ORG")&&U(e)||s!=="strict"&&t==="ADDRESS"&&L(e)?!1:C.has(t)?!0:t==="PERSON"?n("person"):t==="ORG"?n("org"):d.has(t)?n("location"):(String(e).match(/\d/g)||[]).length>=7?n("number"):!1}function f(e,t,{strictness:o="balanced"}={}){let s=[];Array.isArray(e)?s=e:e&&Array.isArray(e.entities)?s=e.entities:e&&Array.isArray(e.ents)?s=e.ents:e&&Array.isArray(e.results)&&(s=e.results);const n=[],i=new Set;for(const r of s){if(!r)continue;const c=String(r.value??r.text??r.entity??r.word??"").trim(),a=w(r.type??r.label??r.entity_group??r.entity_type??r.tag);if(!c||c.length>200||!k(c,a,t,o))continue;const l=`${a}:${c.toLowerCase()}`;i.has(l)||(i.add(l),n.push({value:c,type:a}))}return n}const x=new Set("a an the i am is are was were be been being to of in on at for and or but if so not no yes ok okay hi hello hey you your yours me my mine we us our ours they them their he him his she her it its this that these those what where when who whom why how which do does did done have has had having will would can could should may might must shall there here now then last next first time day days week month year today tomorrow yesterday see saw seen say said tell told go went gone come came get got give gave take took make made know knew think thought want need like just also very really with from into onto over under about after before between through during without within up down out off again still used use using live lived move moved work worked help please thanks thank sorry new old good bad more most some any all each because as than too so such only own same other another much many few both either neither every never always often".split(/\s+/));function K(e){const t=String(e||"");let o=!1;return{text:t.replace(new RegExp("(^|[^\\p{L}\\p{N}'’])(\\p{Ll})(\\p{L}*)","gu"),(n,i,r,c)=>{const a=r+c;if(x.has(a))return n;const l=r.toUpperCase();return l.length!==1||l===r?n:(o=!0,i+l+c)}),changed:o}}function $(e){if(!e)return null;const t=String(e).indexOf("{"),o=String(e).lastIndexOf("}");if(t<0||o<=t)return null;try{return JSON.parse(String(e).slice(t,o+1))}catch{return null}}const v="You extract sensitive entities from text for redaction. Copy each value exactly as it appears. Include people, organizations, locations, and account/ID numbers. No commentary, no code fences.",H='Return ONLY JSON: {"entities":[{"value":"<verbatim text>","type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. No commentary, no code fences.',I=Object.freeze({block:"",format:null,parse:null});async function B(e,t,o,s){const n=await s(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({text:e,...t.strictness==="strict"?{strict:!0}:{}}),signal:o});if(!n.ok)throw new Error(`detect HTTP ${n.status}`);return f(await n.json(),t.types,{strictness:t.strictness})}async function G(e,t,o,s,n=I){const i=String(t.url||"").replace(/\/$/,""),r=/\/chat\/completions$/.test(i)?i:/\/v\d+$/.test(i)?`${i}/chat/completions`:`${i}/v1/chat/completions`,c=`${v}
|
|
2
2
|
|
|
3
|
-
${n.block
|
|
3
|
+
${n.block||H}`,a=async S=>{const E=n.format?n.format(S):null,u=await s(r,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({model:t.model||"local",temperature:0,max_tokens:t.maxTokens||256,messages:[{role:"system",content:c},{role:"user",content:e}],...E||{}}),signal:o});if(!u.ok){const O=new Error(`detect HTTP ${u.status}`);throw O.status=u.status,O}return u.json()};let l=null;if(n.format)for(const S of["schema","object","none"])try{l=await a(S);break}catch(E){if(S==="none"||E.status!==400&&E.status!==422)throw E}else l=await a("none");const h=l?.choices?.[0]?.message?.content??l?.content??"",A=n.parse?n.parse(h):$(h);return f(A,t.types,{strictness:t.strictness})}function m(e,t,o,s,n,i){if(typeof e=="function")try{e({backend:t.backend||"",host:Y(t.url),chars:o.length,entities:n,ms:Date.now()-s,ok:!i,error:i?String(i.message||i).slice(0,200):""})}catch{}}const Y=e=>{try{return new URL(String(e)).host}catch{return""}};async function z(e,t,{signal:o,fetchImpl:s=globalThis.fetch,strict:n=!1,structured:i=I,onEgress:r=null,onError:c=null}={}){const a=t?.detection?{...t.detection,strictness:b(t)}:null;if(!a||!a.backend||a.backend==="off"||!a.url||typeof s!="function")return[];const l=a.transport==="in-process";if(l&&s===globalThis.fetch)throw new Error("detection.transport 'in-process' needs an injected fetch; refusing to treat a network call as in-process");const h=String(e||"").slice(0,a.maxChars||8e3);if(h.trim().length<8)return[];const A=T(h,a);if(!n&&N.has(A))return N.get(A);const S=a.backend==="endpoint"?B:G;let E=[];try{l||D(a.url);const u=Date.now();try{E=await y(S(h,a,o,s,i),a.timeoutMs||1500,o),l||m(r,a,h,u,E.length,null)}catch(O){throw l||m(r,a,h,u,0,O),O}}catch(u){if(n)throw u;try{c?.(u)}catch{}return[]}return N.size>=p&&N.clear(),n||N.set(A,E),E}export{v as EXTRACT_SYS,j as REDACTION_STRICTNESS,V as clearDetectCache,z as detectEntities,w as normType,f as normalizeEntities,U as ownName,$ as parseJsonLoose,L as quantityNotAddress,K as recaseForDetection,b as strictnessOf,y as withTimeout};
|
package/src/pii/tool-harness.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{restoreText as
|
|
1
|
+
import{restoreText as T,restoreWithAliases as N,redactResultShape as w}from"./pii-redact.js";import{narrowSpecs as S}from"./tool-rank.js";const R=e=>/^mcp[_-]/i.test(String(e||""));function h(e,o){if(!o)return e;if(typeof e=="string")return N(e,o);if(Array.isArray(e))return e.map(t=>h(t,o));if(e&&typeof e=="object"){const t={};for(const n of Object.keys(e))t[n]=h(e[n],o);return t}return e}function I({ownTools:e=!1}={}){return"PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], [[LOCATION_1]], [[ORG_1]] that stand in for the user's real private data. Treat each one as a CONCRETE, specific value you already have — not missing or unknown information. Do not ask what it stands for, do not say it is unresolved, and do not refuse on privacy grounds. Reason and write with the placeholder exactly as written; the real value is restored in your answer automatically."+(e?g:"")}const d="Any tool you bring yourself — your own web search, browser, shell, file or code tools — receives the placeholder text literally: it finds nothing, and it opens, types or saves the placeholder itself. ",L=" ONLY THE TOOLS LISTED IN THIS CONVERSATION restore placeholders. "+d+"So for ANYTHING that involves a placeholder — a lookup, a search, a page to open, text to type or save — call the listed tool (for example `find` with action `web_search` or `history_search`) rather than your own; if no listed tool can do it, say so instead of handing a placeholder to a tool of your own. Prefer the listed tools for lookups in general — the user sees those as steps — and keep your own tools for what the listed ones cannot do.",g=" That restoring happens in your ANSWER only. "+d+"So never hand a placeholder to a tool of your own: if the request needs the real value in a tool, say which part you could not do.";function _({toolData:e="real",ownTools:o=!1}={}){const t="PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], [[LOCATION_1]], [[ORG_1]] that stand in for the user's real private data. ",n=e==="redactRemote"?"When you call a LOCAL tool the placeholder is automatically replaced with the real value before the tool runs; REMOTE (MCP) tools deliberately receive the placeholder to keep private data off third-party servers. ":`When you call ${o?"a tool LISTED IN THIS CONVERSATION":"ANY tool"}, these placeholders are AUTOMATICALLY replaced with the real values before the tool executes — the tool receives the TRUE value and returns correct results. `,l="So: treat each placeholder as a CONCRETE, specific value you already have — it is enough to act on, NOT missing or unknown information. CALL THE TOOL using the placeholder exactly as written, as if it were the real value. If answering needs the real data behind a placeholder (e.g. which city [[LOCATION_1]] is, who [[PERSON_1]] is, what [[ORG_1]] does), do NOT reply that you lack information or cannot answer. Instead pick the most relevant available tool for that placeholder's TYPE — LOCATION → geography / place lookups, PERSON → people lookups, ORG → company/org lookups, dates/IDs → the matching lookup — and pass the placeholder straight through as the argument. The harness restores the true value before the tool runs, so the lookup returns correct results. Make your best-guess tool call FIRST; only conclude you lack data AFTER a tool has actually returned nothing useful. Do NOT ask the user to re-type the value and do NOT refuse on privacy grounds — the lookup will work. The real values are restored in your final answer automatically, so write your answer using the placeholders too.",i=o?L:"";return t+n+l+i}const E=new Set(["web_search","web_fetch","fetch_url"]);function k(e){return E.has(String(e||"").toLowerCase())}function f(e,o,t){const n=y(o);return!n||n===e?e:t instanceof Map&&t.get(n)===e?n:e}function y(e){let o=e;if(typeof o=="string")try{o=JSON.parse(o)}catch{return""}const t=o&&typeof o=="object"?o.action:null;return typeof t=="string"?t:""}function C({vault:e=null,toolData:o="real",redactOpts:t=null,redactResults:n=!0,remoteTools:l=null,hiddenVia:i=null}={}){const c=!!e,O=o==="redactRemote",u=typeof l=="function"?l:l instanceof Set?r=>l.has(r):R,p=(r,a)=>{if(u(r))return!0;const s=y(a);return!!s&&s!==r&&u(s)};return{enabled:c,isRemoteTool:p,realToolName:(r,a)=>f(r,a,i),selectTools(r,a,s={}){return S(r,a,s)},toTool(r,a){return!c||O&&p(r,a)?a:h(a,e)},toModelResult(r,a,s){return!c||!n||!t||k(f(r,s,i))?a:w(a,e,t)},toUser(r){return c?T(r,e):r}}}export{k as isPublicSourceTool,R as isRemoteToolName,C as makeToolHarness,I as placeholderNote,_ as placeholderToolNote,f as realToolName,h as restoreToolArgs};
|
package/src/sandbox.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as ae}from"node:child_process";import"node:fs";import{randomBytes as ie}from"node:crypto";import{AsyncLocalStorage as ue}from"node:async_hooks";import{fileURLToPath as ce}from"node:url";import N from"node:os";import le from"node:path";import{ensureCaBundle as de}from"./ca-bundle.js";import{kitFor as pe,sandboxRecord as fe,normalizeGrant as P,writableRoots as xe,NETWORK_MODES as me}from"./events/sandbox-policy.js";import{createSandboxRuntime as he,sandboxRuntimeIds as we}from"./sandbox-runtime.js";import"./sandbox-srt.js";const V=new ue,Se=new Set(["codex","claude","antigravity","custom"]);function Ve(e,t){let n;try{n=P(e)}catch{n=null}return V.run(n,t)}function Ye(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 Y(){return V.getStore()||null}function ze(e,{config:t=te(),grant:n=Y(),home:s=N.homedir()}={}){try{return xe({grant:n,extraWrite:t.extraWrite,cwd:e,home:s})}catch{return[]}}const be=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function z(e){const t=be.exec(String(e||""));return t?{host:t[1].toLowerCase(),port:Number(t[2])||0,reason:t[3]||""}:null}const g=new Map,R=[],O=new Map,Ae=new Set,ye=50;function J({commandId:e,host:t,port:n=0,reason:s="",at:a=Date.now()}){if(!e||!t)return;let o=g.get(e);for(o||(o=new Map,g.set(e,o)),o.set(t,{at:a,reason:s,port:n}),R.push({id:e,engine:O.get(e)||String(e).split(":")[0],host:t,at:a});R.length>ye;)R.shift()}function _e(e){const t=g.get(e);return t?[...t.entries()].sort((n,s)=>s[1].at-n[1].at).map(([n])=>n):[]}function Ne(e=20){return R.slice(-e).reverse()}function Je(){g.clear(),R.length=0,O.clear(),Ae.clear()}const q=new Map;function Q(e){const t=ie(16).toString("hex");return q.set(t,e),t}function qe(e={}){const t=q.get(String(e?.token||""));return!t||t!==e.commandId?!1:(J({commandId:t,host:String(e.host||"").toLowerCase().slice(0,253),port:Number(e.port)||0,reason:String(e.reason||"").slice(0,200)}),!0)}let Re=0;const Te=e=>`${e}:${(++Re).toString(36)}${Date.now().toString(36).slice(-4)}`,L=new Map;function Ee(e,t,{kind:n="agent",label:s=""}={}){if(!e||!t)return e;try{e.sandbox=t.record}catch{}if(typeof e.on!="function")return e;const a=t.commandId||"";L.set(e,{id:a,kind:n,engine:O.get(a)||String(a).split(":")[0]||"custom",command:t.label||"",label:s,pid:e.pid??null,since:Date.now(),sandbox:t.record});const o=()=>L.delete(e);return e.once("exit",o),e.once("error",o),e}function Qe(){return[...L.values()].map(e=>({...e,refused:_e(e.id)}))}function Ze(){L.clear()}function Z(e){if(e)return"";try{return ce(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}const ee="open",et="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",ge=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],W=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean);function te(e=process.env){const t=String(e.CHATPANEL_SANDBOX||ee).toLowerCase(),n=t!=="off"&&t!=="0"&&t!=="false",s=me.includes(t)?t:ee;return{enabled:n,mode:s,extraHosts:W(e.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:W(e.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:W(e.CHATPANEL_SANDBOX_DENY_READ),windows:e.CHATPANEL_SANDBOX_WINDOWS==="1",reads:e.CHATPANEL_SANDBOX_READS==="inverted"?"inverted":"enumerated"}}function Oe({config:e=te(),loadSrt:t=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:n=void 0,cliEntry:s=void 0,onRefusal:a=l=>J(l),reportUrl:o=process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT?`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT}/sandbox/refused`:"http://127.0.0.1:4319/sandbox/refused",hostEntry:p=null,compiled:u=!1,platform:i=process.platform,home:x=N.homedir(),loopback:$=ge(),selfFiles:B=[process.execPath,process.argv[1]||""],onExit:k=l=>process.on("exit",l),runtimeId:T=process.env.CHATPANEL_SANDBOX_RUNTIME||"srt",makeRuntime:M=null,log:m=()=>{}}={}){let l=null,E=null,d={ok:!1,runtime:null,reason:null,ownSessions:!1};function b(){if(l||E)return l;try{l=M?M({config:e,platform:i,home:x,loopback:$,compiled:u,selfFiles:B,onExit:k,hostEntry:p,reportUrl:o,mintReportToken:Q,onRefusal:a,parseRefusal:z,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:Z,log:m}):he(T,{config:e,platform:i,home:x,loopback:$,compiled:u,selfFiles:B,onExit:k,hostEntry:p,reportUrl:o,mintReportToken:Q,onRefusal:a,parseRefusal:z,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:Z,log:m})}catch(r){E=r?.message||String(r),m(`sandbox: ${E}`)}return l}async function X(){if(!e.enabled)return d={ok:!1,runtime:null,reason:"sandboxing is off (CHATPANEL_SANDBOX=off)",ownSessions:!1},d;const r=b();if(!r)return d={ok:!1,runtime:null,reason:E,ownSessions:!1},d;try{d={...d,...await r.detect()}}catch(c){d={ok:!1,runtime:null,reason:`the ${r.id} sandbox could not be started: ${c.message}`,ownSessions:!1}}return d}return{config:e,async status(){const r=await X(),c=b();return{enabled:e.enabled,mode:e.mode,runtime:r.runtime,platform:i,layer:c?.id||T,layers:we(),...r.reason?{reason:r.reason}:{},extras:{hosts:e.extraHosts,write:e.extraWrite,denyRead:e.extraDenyRead},ownSessions:!!r.ownSessions,refused:Ne(),...r.provisioned!==void 0?{provisioned:r.provisioned}:{},...r.install?{install:r.install}:{}}},close(){try{b()?.close()}catch(r){m(`sandbox: close failed: ${r.message}`)}},async wrap(r,c,A,{engine:f="custom",cwd:y=null,commandId:h=null,grant:F=Y(),readOnly:re=!1,peers:se=!0}={}){const G=await X();h=h||Te(f),O.set(h,f);const I=y||A?.cwd||process.cwd(),U=le.basename(String(r||"")),_=S=>({bin:r,argv:c,opts:A,record:fe({layer:"none",reason:S}),commandId:h,label:U});let j=!1;try{j=P(F).outside===!0}catch{}if(j&&Se.has(f))return _("you allowed this agent to run outside the ChatPanel sandbox (its own sandbox still applies)");if(!G.ok)return _(G.reason);const oe=await de({home:N.homedir(),log:m}).catch(()=>"");let K,D;try{D=P(F),K=pe({engine:f,cwd:I,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[N.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead,grant:D,home:N.homedir(),reads:e.reads,readOnly:re,peers:se})}catch(S){return _(`kit: ${S.message}`)}let w;try{w=await b().wrap({kit:K,grant:D,bin:r,argv:c,opts:A,engine:f,workdir:I,commandId:h,caBundle:oe})}catch(S){return m(`sandbox: could not wrap ${r}: ${S.message}`),_(`the ${T} sandbox failed to wrap the command: ${S.message}`)}return!w||w.passReason?_(w?.passReason||`the ${T} sandbox returned nothing`):{...w,commandId:w.commandId||h,label:U}},async wrapOwn(r,c,A,f={}){const y=await this.wrap(r,c(!1),A,f);return y.record.layer==="none"?{...y,argv:c(!0),inner:!0}:{...y,inner:!1}},violations(r){try{return b()?.violations(r)||[]}catch{return[]}}}}let C=null;function ne(){if(!C){const{isCompiledBinary:e}=Le();C=Oe({compiled:e(),log:t=>console.error(`[bridge] ${t}`)})}return C}function tt(e){C=e}let v=null;function Le(){return v||(v={isCompiledBinary:()=>{const e=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}}),v}const H=new Set;function nt(e,t){if(!t||t.layer!=="none"||typeof e!="function")return;const n=t.reason||"unknown";H.has(n)||(H.add(n),e({type:"status",text:`Running outside a sandbox — ${n}`}))}function rt(){H.clear()}const Ce=/sandbox_apply: Operation not permitted/;function st(e,t="This agent"){return Ce.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 ot(e,t,n,s={},{spawnImpl:a=ae,box:o=ne(),kind:p="agent",label:u=""}={}){const i=await o.wrap(e,t,n,s);return Ee(a(i.bin,i.argv,i.opts),i,{kind:p,label:u})}async function at(e,{box:t=ne(),platform:n=process.platform,loadSrt:s=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:a=console.log,err:o=console.error}={}){const p=e[0]||"status";if(p==="status")return a(JSON.stringify(await t.status(),null,2)),0;if(p!=="install")return o("usage: chatpanel-bridge sandbox [status|install]"),2;if(n!=="win32")return a("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let u;try{u=await s()}catch(i){return o(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${i.message})`),1}try{const i=u.resolveSrtWin({path:u.VENDORED_SRT_WIN_EXE}),x=await u.installWindowsSandboxAsync({srtWin:i});return x?.cancelled?(o("Cancelled at the administrator prompt — nothing was installed."),1):(a(`The sandbox account is installed${x?.user?.sid?` (${x.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(i){o(`install failed: ${i.message}`);try{o(u.windowsInstallInstructions())}catch{}return 1}}export{Ze as _resetLiveForTest,rt as _resetNotedForTest,Je as _resetRefusalsForTest,tt as _setSandboxForTest,qe as acceptRefusalReport,Oe as createSandbox,Y as currentGrant,ze as grantedWriteRoots,Qe as liveProcesses,st as nestedSandboxLine,nt as noteSandbox,z as parseRefusalLine,Ne as recentRefusals,J as recordRefusal,_e as refusalsFor,at as runSandboxCli,ne as sandbox,te as sandboxConfigFromEnv,ot as sandboxedSpawn,Ee as track,Ve as withGrant,Ye as withoutOutsideWhenCapped};
|
|
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};
|
package/src/server.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as xe}from"node:http";import v from"node:os";import{randomBytes as Pe,randomInt as $e,timingSafeEqual as Re}from"node:crypto";import{mkdirSync as Ie,writeFileSync as Ne,readFileSync as Q,existsSync as De}from"node:fs";import{join as _}from"node:path";import*as _e from"./engines/claude.js";import*as He from"./engines/codex.js";import*as Me from"./engines/antigravity.js";import{pi as Be,opencode as Ue,kiro as We,copilot as Le,deepseek as Ge,hermes as je}from"./engines/cli-agents.js";import{connectorsFor as Fe}from"./connectors.js";import*as Je from"./engines/custom.js";import{installService as Xe,uninstallService as ze,serviceStatus as Ke,restartService as Z}from"./service.js";import{skillIndex as L,listRecords as Ye,readRecord as Ve,readPackageFile as Qe,skillsHealth as Ze,quarantinedSkills as qe,clearSkillCache as G}from"./skills.js";import{writeSkillPackage as et,writeSkillFile as tt,deleteSkillPackage as nt,SkillWriteError as ot}from"./skill-write.js";import{agentDefRoots as rt,scanAgentDefs as at,listAgentDefs as it,readAgentDef as st,planAgentExport as ct,exportAgentDef as lt,agentDefsHealth as dt,AgentDefError as ut}from"./agent-defs.js";import{capabilityToolSpecs as ht,runCapabilityTool as pt}from"./mcp-capabilities.js";import{createSession as ft,deleteSession as q,getSession as ee,activeSession as mt,relayToolCall as gt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as yt,isDefaultWorkdir as wt,resolveWorkdir as St,writeScopeNote as bt}from"./workdir.js";import{sandbox as te,runSandboxCli as kt,withGrant as ne,withoutOutsideWhenCapped as Tt,grantedWriteRoots as Et,acceptRefusalReport as vt,liveProcesses as Ot}from"./sandbox.js";import{gitState as At,gitDelta as Ct}from"./scm.js";import{listConnections as xt,putConnection as Pt,removeConnection as $t,runEnvFor as Rt,testConnection as It,secretBackend as oe}from"./connections.js";import{worktreeFor as re,listWorktrees as Nt,removeWorktree as Dt,withHook as _t,WORKTREE_ROOT as ae}from"./worktree.js";import{AGENT_CLIS as Ht,agentAvailable as Mt,agentInstallDirs as Bt,enrichPath as Ut,enrichAgentEnv as Wt,findAgentBin as Lt,forgetMisses as Gt,primeAgentLookups as jt,resolveCommand as ie}from"./env.js";import"./sanitize.js";import{checkForUpdate as Ft,selfUpdate as se,isEmbedded as ce}from"./update.js";import{callLocalMcp as Jt,localMcpStatus as Xt,signInLocalMcp as zt,signInStatusLocalMcp as Kt}from"./mcp-local.js";import{assertPublicHttpUrl as le,assertPublicWebUrl as de}from"./ssrf.js";import{startRun as ue,endRun as j,cancelRun as Yt,cancelAll as Vt}from"./runs.js";import{closeWarmPools as Qt,warmStatus as Zt}from"./warm.js";import{SESSION_AGENTS as he,listSessions as qt,readSession as en,adoptSession as tn,catchUp as nn}from"./agent-sessions.js";import{agentContext as on}from"./agent-context.js";import{normalizeThread as pe}from"./events/agent-thread.js";import{portClashPlan as rn,serviceManagerOf as an,STANDBY_POLL_MS as sn}from"./events/service-standby.js";import{holdThread as fe}from"./threads.js";import{createSnapshot as cn}from"./health-snapshot.js";import{CompatError as R,anthropicError as F,anthropicStream as ln,chatCompletionStream as dn,completionStream as un,createAnthropicMessage as hn,createChatCompletion as pn,createCompletion as fn,createResponse as mn,openAIError as S,parseAnthropicMessage as gn,parseChatCompletion as yn,parseCompletion as wn,parseResponse as Sn,responseStream as bn}from"./api-compat.js";import{callerTrust as kn,isPaired as I,parseExtensionIds as Tn,capRunOptions as En,engineHonoursReach as vn,createPairingStore as On,formatPairingCode as An}from"./pii/trust.js";const g="0.44.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",b=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,O={claude:{engine:_e,label:"Claude Code"},codex:{engine:He,label:"Codex"},antigravity:{engine:Me,label:"Antigravity",tools:!1},pi:{engine:Be,label:"Pi"},opencode:{engine:Ue,label:"OpenCode"},hermes:{engine:je,label:"Hermes"},kiro:{engine:We,label:"Kiro"},copilot:{engine:Le,label:"GitHub Copilot"},deepseek:{engine:Ge,label:"DeepSeek Harness"},custom:{engine:Je,label:"Custom",hidden:!0}};function me(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 Cn=Tn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=kn({origin:n.headers.origin||"",hasToken:Se(n),extensionIds:Cn})),n.chatpanelTrust}function xn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Pn(n,e){const t=n.headers.origin||"",o=me(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 J=new Set(["127.0.0.1","localhost","::1"]);function $n(n){if(!J.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return J.has(t)}const D=_(v.homedir(),".chatpanel","bridge-token");let T="";function Rn(){try{De(D)&&(T=Q(D,"utf8").trim()),T||(T=Pe(32).toString("hex"),Ie(_(v.homedir(),".chatpanel"),{recursive:!0}),Ne(D,T,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const ge=On({random:()=>$e(0,1e6)/1e6});function In(n){if(!T)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ge.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 Nn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ge.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:T})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Dn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:g})}let H=null;async function ye(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(v.homedir(),".chatpanel"),dataDir:_(v.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${b}`,token:T},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function we(n,e,t){try{const o=await ye(),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 Se(n){if(!T)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(T);return o.length===r.length&&Re(o,r)}const _n=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"]),Hn=new Set(["/debug"]),Mn=n=>Hn.has(n),Bn=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Un(n,e){if(!$n(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!me(t))return"forbidden origin";const o=n.method==="POST"&&_n.has(e)||n.method==="GET"&&Mn(e)||Bn(n.method,e);return o&&!(xn(t)||Se(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!Ln.has(e)?Wn:null}const be=()=>ce()?"chatpanel-gateway pair":"chatpanel-bridge pair",Wn=`forbidden: this client is not paired with the bridge — run \`${be()}\` and enter the code in ChatPanel Settings`,Ln=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function X(n,e,t){const o=N(n),r=Tt(En(t,o));if(!vn(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 (${be()})`} 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}}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 ke=cn({compute:Gn});async function Gn(){await jt();const n=await Promise.all(Object.entries(O).filter(([,a])=>!a.hidden).map(async([a,{engine:s,label:c,tools:l}])=>{const d=await s.available().catch(y=>({ok:!1,reason:String(y?.message||y)})),h=await Fe(a).catch(()=>[]);return{id:a,label:c,available:d.ok,reason:d.reason,connectors:h,...l===!1?{tools:!1}:{}}})),e=ce()?{current:g,updateAvailable:!1,embedded:"gateway"}:await Ft(g).catch(()=>({current:g,updateAvailable:!1})),t=await Ze().catch(()=>null),o=await dt().catch(()=>null),r=await te().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function jn(n,{fresh:e=!1}={}){e&&Gt();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await ke.get({fresh:e});i(n,200,{ok:!0,version:g,agents:o,update:r,checkedAt:t,workspace:yt,sandbox:c,localMcp:Xt(),processes:Ot(),worktrees:ae,secretBackend:oe(),warm:Zt(),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 Fn(n,e,t){const{index:o,problems:r}=await L({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Ye(o),problems:r})}async function Jn(n,e,t){i(n,200,{ok:!0,quarantined:await qe(e,t)})}async function Xn(n,e,t,o){const{index:r}=await L({extraDirs:t,workdir:o}),a=Ve(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function zn(n,e,t,o,r){const{index:a}=await L({extraDirs:o,workdir:r}),s=await Qe(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 Kn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await et({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return G(),i(e,200,o)}catch(o){return i(e,z(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function Yn(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 tt({name:t,path:o,text:r?.text??""});return G(),i(e,200,a)}catch(a){return i(e,z(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function Vn(n,e){try{const t=await nt({name:e});return G(),i(n,200,t)}catch(t){return i(n,z(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function z(n){return n instanceof ot?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Te(n,e){return at({roots:rt(process.env,v.homedir(),n,e)})}async function Qn(n,e,t){const{index:o,quarantined:r,problems:a}=await Te(e,t);i(n,200,{ok:!0,agents:it(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 Zn(n,e,t,o){const{index:r}=await Te(t,o),a=st(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function qn(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 ct({agent:t?.agent,to:t?.to})})}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function eo(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 lt({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,Ee(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function Ee(n){if(n instanceof ut){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function to(){return(await Promise.all(Object.entries(O).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 ve(n,e=""){const t=await to();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new R(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function no(n){try{const e=await se(g);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>Z(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function oo(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const o=O[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=X(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=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
2
|
+
import{createServer as Pe}from"node:http";import O from"node:os";import{randomBytes as $e,randomInt as Re,timingSafeEqual as Ie}from"node:crypto";import{mkdirSync as Ne,writeFileSync as De,readFileSync as Z,existsSync as _e}from"node:fs";import{join as _}from"node:path";import*as He from"./engines/claude.js";import*as Me from"./engines/codex.js";import*as Be from"./engines/antigravity.js";import{pi as Ue,opencode as We,kiro as Le,copilot as Ge,deepseek as je,hermes as Fe}from"./engines/cli-agents.js";import{connectorsFor as Je}from"./connectors.js";import*as Xe from"./engines/custom.js";import{installService as ze,uninstallService as Ke,serviceStatus as Ye,restartService as q}from"./service.js";import{skillIndex as L,listRecords as Ve,readRecord as Qe,readPackageFile as Ze,skillsHealth as qe,quarantinedSkills as et,clearSkillCache as G}from"./skills.js";import{writeSkillPackage as tt,writeSkillFile as nt,deleteSkillPackage as ot,SkillWriteError as rt}from"./skill-write.js";import{agentDefRoots as at,scanAgentDefs as it,listAgentDefs as st,readAgentDef as ct,planAgentExport as lt,exportAgentDef as dt,agentDefsHealth as ut,AgentDefError as ht}from"./agent-defs.js";import{capabilityToolSpecs as pt,runCapabilityTool as ft}from"./mcp-capabilities.js";import{createSession as mt,deleteSession as ee,getSession as te,activeSession as gt,relayToolCall as yt}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as wt,isDefaultWorkdir as St,resolveWorkdir as bt,writeScopeNote as kt}from"./workdir.js";import{sandbox as j,runSandboxCli as Tt,withGrant as ne,withAgentGrant as Et,withoutOutsideWhenCapped as vt,grantedWriteRoots as Ot,acceptRefusalReport as At,liveProcesses as Ct}from"./sandbox.js";import{signInDenial as xt}from"./events/sandbox-policy.js";import{gitState as Pt,gitDelta as $t}from"./scm.js";import{listConnections as Rt,putConnection as It,removeConnection as Nt,runEnvFor as Dt,testConnection as _t,secretBackend as oe}from"./connections.js";import{worktreeFor as re,listWorktrees as Ht,removeWorktree as Mt,withHook as Bt,WORKTREE_ROOT as ae}from"./worktree.js";import{AGENT_CLIS as Ut,agentAvailable as Wt,agentInstallDirs as Lt,enrichPath as Gt,enrichAgentEnv as jt,findAgentBin as Ft,forgetMisses as Jt,primeAgentLookups as Xt,resolveCommand as ie}from"./env.js";import"./sanitize.js";import{checkForUpdate as zt,selfUpdate as se,isEmbedded as ce}from"./update.js";import{callLocalMcp as Kt,localMcpStatus as Yt,signInLocalMcp as Vt,signInStatusLocalMcp as Qt}from"./mcp-local.js";import{assertPublicHttpUrl as le,assertPublicWebUrl as de}from"./ssrf.js";import{startRun as ue,endRun as F,cancelRun as Zt,cancelAll as qt}from"./runs.js";import{closeWarmPools as en,warmStatus as tn}from"./warm.js";import{SESSION_AGENTS as he,listSessions as nn,readSession as on,adoptSession as rn,catchUp as an}from"./agent-sessions.js";import{agentContext as sn}from"./agent-context.js";import{normalizeThread as pe}from"./events/agent-thread.js";import{portClashPlan as cn,serviceManagerOf as ln,STANDBY_POLL_MS as dn}from"./events/service-standby.js";import{holdThread as fe}from"./threads.js";import{createSnapshot as un}from"./health-snapshot.js";import{CompatError as P,anthropicError as J,anthropicStream as hn,chatCompletionStream as pn,completionStream as fn,createAnthropicMessage as mn,createChatCompletion as gn,createCompletion as yn,createResponse as wn,openAIError as S,parseAnthropicMessage as Sn,parseChatCompletion as bn,parseCompletion as kn,parseResponse as Tn,responseStream as En}from"./api-compat.js";import{callerTrust as vn,isPaired as I,parseExtensionIds as On,capRunOptions as An,engineHonoursReach as Cn,createPairingStore as xn,formatPairingCode as Pn}from"./pii/trust.js";const g="0.45.2",k=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",b=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,E={claude:{engine:He,label:"Claude Code"},codex:{engine:Me,label:"Codex"},antigravity:{engine:Be,label:"Antigravity",tools:!1},pi:{engine:Ue,label:"Pi"},opencode:{engine:We,label:"OpenCode"},hermes:{engine:Fe,label:"Hermes"},kiro:{engine:Le,label:"Kiro"},copilot:{engine:Ge,label:"GitHub Copilot"},deepseek:{engine:je,label:"DeepSeek Harness"},custom:{engine:Xe,label:"Custom",hidden:!0}};function me(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 $n=On(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=vn({origin:n.headers.origin||"",hasToken:Se(n),extensionIds:$n})),n.chatpanelTrust}function Rn(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 In(n,e){const t=n.headers.origin||"",o=me(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 X=new Set(["127.0.0.1","localhost","::1"]);function Nn(n){if(!X.has(k))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return X.has(t)}const D=_(O.homedir(),".chatpanel","bridge-token");let T="";function Dn(){try{_e(D)&&(T=Z(D,"utf8").trim()),T||(T=$e(32).toString("hex"),Ne(_(O.homedir(),".chatpanel"),{recursive:!0}),De(D,T,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const ge=xn({random:()=>Re(0,1e6)/1e6});function _n(n){if(!T)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=ge.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 Hn(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=ge.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:T})):(u("info",`pairing refused (${o.reason}) from ${N(n)} caller`),i(e,403,{error:o.reason}))}function Mn(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:g})}let H=null;async function ye(){if(H)return H;const{createChannelService:n}=await import("./channels/service.js");return H=n({home:_(O.homedir(),".chatpanel"),dataDir:_(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${b}`,token:T},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),H}async function we(n,e,t){try{const o=await ye(),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 Se(n){if(!T)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(T);return o.length===r.length&&Ie(o,r)}const Bn=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"]),Un=new Set(["/debug"]),Wn=n=>Un.has(n),Ln=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function Gn(n,e){if(!Nn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!me(t))return"forbidden origin";const o=n.method==="POST"&&Bn.has(e)||n.method==="GET"&&Wn(e)||Ln(n.method,e);return o&&!(Rn(t)||Se(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":o&&!I(N(n))&&!Fn.has(e)?jn:null}const be=()=>ce()?"chatpanel-gateway pair":"chatpanel-bridge pair",jn=`forbidden: this client is not paired with the bridge — run \`${be()}\` and enter the code in ChatPanel Settings`,Fn=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function z(n,e,t){const o=N(n),r=Et(e,vt(An(t,o)));if(!Cn(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 (${be()})`} 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 ke(n,e,t){const o=e?.message||String(e);try{const r=await j().status(),a=!!(r.enabled&&r.runtime)&&t?.outside!==!0,s=xt(`${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 Te=un({compute:Jn});async function Jn(){await Xt();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)})),h=await Je(a).catch(()=>[]);return{id:a,label:c,available:l.ok,reason:l.reason,connectors:h,...d===!1?{tools:!1}:{}}})),e=ce()?{current:g,updateAvailable:!1,embedded:"gateway"}:await zt(g).catch(()=>({current:g,updateAvailable:!1})),t=await qe().catch(()=>null),o=await ut().catch(()=>null),r=await j().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:o,sandboxStatus:r}}async function Xn(n,{fresh:e=!1}={}){e&&Jt();const{at:t,value:{agents:o,update:r,skills:a,agentDefs:s,sandboxStatus:c}}=await Te.get({fresh:e});i(n,200,{ok:!0,version:g,agents:o,update:r,checkedAt:t,workspace:wt,sandbox:c,localMcp:Yt(),processes:Ct(),worktrees:ae,secretBackend:oe(),warm:tn(),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 zn(n,e,t){const{index:o,problems:r}=await L({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:Ve(o),problems:r})}async function Kn(n,e,t){i(n,200,{ok:!0,quarantined:await et(e,t)})}async function Yn(n,e,t,o){const{index:r}=await L({extraDirs:t,workdir:o}),a=Qe(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function Vn(n,e,t,o,r){const{index:a}=await L({extraDirs:o,workdir:r}),s=await Ze(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 Qn(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}try{const o=await tt({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return G(),i(e,200,o)}catch(o){return i(e,K(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function Zn(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 nt({name:t,path:o,text:r?.text??""});return G(),i(e,200,a)}catch(a){return i(e,K(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function qn(n,e){try{const t=await ot({name:e});return G(),i(n,200,t)}catch(t){return i(n,K(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function K(n){return n instanceof rt?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Ee(n,e){return it({roots:at(process.env,O.homedir(),n,e)})}async function eo(n,e,t){const{index:o,quarantined:r,problems:a}=await Ee(e,t);i(n,200,{ok:!0,agents:st(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 to(n,e,t,o){const{index:r}=await Ee(t,o),a=ct(r,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function no(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 lt({agent:t?.agent,to:t?.to})})}catch(o){return i(e,ve(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}async function oo(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 dt({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(o){return i(e,ve(o),{ok:!1,error:o.message,code:o.code||"ERROR"})}}function ve(n){if(n instanceof ht){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function ro(){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 Oe(n,e=""){const t=await ro();if(e){const o=t.find(r=>r.id===e);return o?i(n,200,o):i(n,404,S(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function ao(n){try{const e=await se(g);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>q(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function io(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=z(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=p=>{e.writableEnded||e.write(`data: ${JSON.stringify(p)}
|
|
3
4
|
|
|
4
|
-
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,
|
|
5
|
+
`)};let s=!1;const c=`run_${Math.random().toString(36).slice(2,10)}`,d=ue(c),l={signal:d.signal,abort:()=>d.cancel("client")},h=()=>{s=!0,d.cancel("disconnected")};n.on("close",h),e.on("close",h),e.on("error",h);const y=p=>{s||a(p)};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 p=t.options.workspace;if(f=await re({repo:p.repo,projectId:p.projectId,jobId:p.jobId,base:p.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),F(c),e.writableEnded||e.end();return}}const V=f?f.path:bt(t.options?.workingDir);let A=null;{const p=V,x=!!f||!St(t.options?.workingDir),w=kt(t.agent,t.options?.permissionMode,p,Ot(p,{grant:t.options?.sandbox}));a({type:"workdir",path:p,isDefault:!x,writeScope:w||void 0}),a({type:"status",text:`Working in ${p}${x?"":" (default)"}`}),w&&a({type:"status",text:w}),A=await Pt(p),A&&a({type:"scm",phase:"before",...A})}let W=null;if(A||f){const p=Array.isArray(t.options?.grants)?t.options.grants:[],{env:x,connection:w}=Dt({remote:A?.remote||null,grants:p,branch:f?.branch||null,connectionId:t.options?.connectionId||null});W=Bt(x),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: ${x.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:x.CHATPANEL_SCM_PUSH}`})}const Q=t.approvals===!0,C={...t.options||{},...f?{workingDir:f.path}:{},...W?{runEnv:W}:{},approvals:Q};let R=null;(t.pageTools?.specs?.length||Q)&&(R=mt(y,t.pageTools?.specs||[]),C.permissionSession=R,t.pageTools?.specs?.length&&(C.mcp={url:`http://${k}:${b}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));try{await ne(C.sandbox,()=>fe(t.agent,C,l.signal,()=>o.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:t.system||"",options:C,images:Array.isArray(t.images)?t.images:[]},y,{signal:l.signal})))}catch(p){u("error",`${t.agent} chat failed: ${p?.message||p}`),p?.detail&&u("error",`${t.agent} said: ${p.detail}`),a({type:"error",error:await ke(t.agent,p,C.sandbox)})}finally{if(!s){const p=await $t(V,A).catch(()=>null);p&&y({type:"scm",phase:"after",...p})}F(c),R&&ee(R.id),e.writableEnded||e.end()}}async function so(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:Rt(),secretBackend:oe()});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:It(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:Nt(r[1])}):i(e,200,_t(r[1],o.remote||"")):i(e,404,{error:"Not found"})}async function co(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:ae,worktrees:await Ht()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const o=await m(n);if(t==="/worktrees"){const r=await re({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 Mt({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 v(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=ue(a),c=()=>s.cancel("disconnected");t.on("close",c);let d="";try{return await ne(n.options?.sandbox,()=>fe(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 ke(n.agent,l,n.options?.sandbox)),l}finally{t.off("close",c),F(a)}}function M(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)}
|
|
5
6
|
|
|
6
7
|
`)}function B(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
7
8
|
data: ${JSON.stringify(t)}
|
|
8
9
|
|
|
9
|
-
`)}async function U(n,e,t,o){try{const r=t(await m(n)),a=X(n,r.agent,r.options||{});if(a.error)throw new R(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new R(`Bad JSON: ${r.message}`):r)),null}}async function io(n,e){const t=await U(n,e,yn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,pn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=dn(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function so(n,e){const t=await U(n,e,wn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,fn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=un(t.requestedModel,r=>x(e,r));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){x(e,S(r))}x(e,"[DONE]"),e.end()}async function co(n,e){const t=await U(n,e,Sn,S);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,mn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}M(e);const o=bn(t.requestedModel,r=>B(e,r.type,r));try{await E(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 lo(n,e){const t=await U(n,e,gn,F);if(!t)return;if(!t.stream)try{const r=await E(t,()=>{},e);return i(e,200,hn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,F(r))}M(e);const o=ln(t.requestedModel,(r,a)=>B(e,r,a));try{await E(t,r=>o.delta(r),e),o.done()}catch(r){B(e,"error",F(r))}e.end()}async function uo(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?Yt(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Oe(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?ee(t):mt(),a=l=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:l})},s=(l,d)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:l,message:d}});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=ht();if(o.method==="tools/list"){const l=r?r.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...l]})}if(o.method==="tools/call"){const l=await pt(o.params?.name,o.params?.arguments||{});if(l)return a(l);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 gt(r,o.params?.name,o.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function ho(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 Jt({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?Kt(r):await zt(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function fo(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 l=new AbortController,d=setTimeout(()=>l.abort(),3e4);try{const h=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:l.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(d)}}const Ae=256*1024,mo=5,go=8e3;async function yo(n){let e=de(n);const t=new AbortController,o=setTimeout(()=>t.abort(),go);try{for(let r=0;r<=mo;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:bo(await wo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function wo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,Ae);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>=Ae))break}}finally{try{await e.cancel()}catch{}}return o}function So(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 bo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?So(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function ko(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 yo(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 To(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=ee(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 Eo(n,e){let t;try{t=await m(n)}catch(l){return i(e,400,{error:"Bad JSON: "+l.message})}const o=O[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=X(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 l="";return typeof o.engine.complete=="function"?l=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},d=>{d.type==="delta"?l+=d.text||"":d.type==="done"&&d.text&&(l+=d.text)}),i(e,200,{text:(l||"").trim()})}catch(l){return i(e,502,{error:l?.message||String(l)})}}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=O[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 Oo(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 Ao(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 qt(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await en(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 tn(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 nn(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 K=xe(async(n,e)=>{if(Pn(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=Un(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return jn(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 Fn(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:{},l={...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 on({agent:typeof s?.agent=="string"?s.agent:"claude",options:l}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return Jn(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return Qn(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return qn(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return eo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return Zn(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return Kn(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"?Vn(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"}):Yn(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?Xn(e,decodeURIComponent(s),r,a):zn(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return ro(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return ao(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return ve(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return ve(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(Ht.map(c=>[c,s?Lt(c)||ie(c)?.kind||null:Mt(c)])),...s?{home:v.homedir(),path:process.env.PATH,installDirs:Bt(v.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Ao(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return oo(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Nn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return In(e);if(n.method==="POST"&&t.pathname==="/whoami")return Dn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return io(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return so(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return co(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return lo(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Oe(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 Oe(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return q(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 uo(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return To(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=vt(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return po(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return fo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return ko(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Eo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return vo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/update")return no(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 Co(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 l;try{l=JSON.parse(c)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(l.id==null)continue;const h=(await d.text()).trim();h&&process.stdout.write(h+`
|
|
10
|
-
`)}catch(
|
|
11
|
-
`)}}o=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",c=>{e+=c;let
|
|
12
|
-
`))>=0;){const
|
|
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+`
|
|
11
|
+
`)}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
|
+
`)}}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 Ro(){Gt(),jt(),Dn();let n=!1;Y.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${b}/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=cn({name:"bridge",self:g,holder:o?{ours:o,version:t.version}:null,managedBy:ln(process.env),port:b});if(r.action==="standby"||n&&!t){if(!n)for(const a of r.lines)u("info",a);n=!0,setTimeout(()=>Y.listen(b,k),dn);return}if(o)for(const a of r.lines)u("error",a);else u("error",`Port ${b} 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=qt("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const o=en("shutdown");o&&u("info",`shutdown: closed ${o} warm agent process${o===1?"":"es"}`),j().close(),setTimeout(()=>process.exit(0),t||o?300:0).unref?.(),!t&&!o&&process.exit(0)});Y.listen(b,k,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${k}:${b}`),Te.warm(),X.has(k)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${k}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine: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."),ye().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 Io(){console.log(`ChatPanel Bridge v${g}
|
|
13
14
|
|
|
14
15
|
Usage:
|
|
15
16
|
chatpanel-bridge start the bridge (foreground) on ${k}:${b}
|
|
@@ -21,4 +22,4 @@ Usage:
|
|
|
21
22
|
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
22
23
|
chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
|
|
23
24
|
|
|
24
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function
|
|
25
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function No(){const n=process.argv,e=(...t)=>t.some(o=>n.includes(o));if(e("--help","-h"))return Io(),!0;if(e("--version","-v"))return console.log(g),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=Z(D,"utf8").trim()}catch{}const o=`http://${k}:${b}`;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: ${Pn(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 Tt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{ze(),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{Ke(),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=Ye()}catch(o){u("error",String(o?.message||o))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const xe=process.argv.indexOf("--mcp-stdio");if(xe>=0){const n=process.argv[xe+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),$o(n)}else process.argv.includes("--update")?(async()=>{try{const n=await se(g);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),q()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():No()||Ro();
|
package/src/warm-pool.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{treeRssBytes as
|
|
1
|
+
import{treeRssBytes as L,totalMemoryBytes as B}from"./proc.js";import{historyShape as v,userTextMatches as D}from"./events/agent-thread.js";const d=1024**3,b=B(),k=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(b>=16*d?10*6e4:5*6e4),N=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(b*.2),3*d),S=400*1024**2;function z(n,o,a=S){const l=Math.floor(o/a),c=n>=48*d?4:n>=24*d?3:n>=12*d?2:1;return Math.max(1,Math.min(l,c))}const g=Number(process.env.CHATPANEL_WARM_MAX)||z(b,N),G=new Set;function U(n,o){if(n.answers!==o.answers||n.users.length!==o.users.length)return!1;const a=n.users.length;for(let l=0;l<a-1;l++)if(n.users[l]!==o.users[l])return!1;return a===0||D(n.users[a-1],o.users[a-1])}const W=2*6e4;function P({max:n=g,idleMs:o=k,budgetBytes:a=N,group:l=G,now:c=Date.now,measure:I=r=>L(r?.pid),log:h=()=>{}}={}){const r=new Set;let m=null;const M=()=>{let e=0;for(const s of l)e+=s.bytes;return e};let A=0;const f=e=>`${Math.round(e/1024**2)} MB`;function p(e,s="dropped"){if(r.has(e)){r.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}h(`warm ${e.label}: ${s} (${r.size} live)`),!r.size&&m&&(clearInterval(m),m=null)}}const w=e=>Number(e.session?.expiresAt)>0&&c()>=e.session.expiresAt-W;function E(){const e=c();for(const s of[...r])!s.busy&&e-s.lastUsed>o&&p(s,"idle")}function R(){m||!Number.isFinite(o)||o<=0||(m=setInterval(E,Math.min(o,6e4)),m.unref?.())}const x={get size(){return r.size},get bytes(){let e=0;for(const s of r)e+=s.bytes||0;return e},peek({key:e,messages:s}){const i=v(s);for(const t of r)if(!t.busy&&t.alive&&t.key===e&&!w(t)&&U(t.shape,i))return!0;return!1},acquire({key:e,messages:s}){const i=v(s);for(const t of r)if(!(t.busy||!t.alive||t.key!==e)){if(w(t)){p(t,"its sign-in is about to expire");continue}if(!U(t.shape,i)){h(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${i.users.length}u/${i.answers}a)`);continue}return t.busy=!0,t.lastUsed=c(),h(`warm ${t.label}: reused`),t}return null},reserve({key:e,label:s=e,evict:i=!0}){const t=()=>{let u=null;for(const $ of r)!$.busy&&(!u||$.lastUsed<u.lastUsed)&&(u=$);return u};if(r.size>=n){const u=i?t():null;if(!u)return null;p(u,"evicted")}const _=A||S;for(;M()+_>a;){const u=i?t():null;if(!u)return h(`warm ${s}: not kept — ${f(M())} warm + ~${f(_)} would pass the ${f(a)} budget`),null;p(u,`evicted for memory (${f(M())} warm)`)}const T={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:c(),bytes:_};return r.add(T),h(`warm ${s}: starting (${r.size} live, ~${f(M())} of ${f(a)})`),R(),T},holds(e,s){return e.shape=v(s),e},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&p(e,"process exited")}),e},release(e,{user:s,answered:i}){e.alive&&(typeof s=="string"&&(e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(i?1:0)}),e.busy=!1,e.lastUsed=c(),setImmediate(()=>{if(!e.alive)return;const t=I(e.session);t>0&&(e.bytes=t,A=t,h(`warm ${e.label}: ${f(t)} resident`))}))},drop:p,closeAll(e="shutdown"){for(const s of[...r])p(s,e)},keys(){return[...r].map(e=>e.key)},reap:E};return l.add(x),x}export{N as WARM_BUDGET_BYTES,P as createWarmPool,v as historyShape,z as warmMaxFor};
|