@chatpanel/bridge 0.32.2 → 0.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/scripts/sync-events.mjs +2 -2
- package/src/agent-sessions.js +16 -0
- package/src/channels/adapters/telegram.js +3 -3
- package/src/engines/claude-warm.js +3 -3
- package/src/engines/claude.js +8 -8
- package/src/engines/codex-appserver.js +11 -11
- package/src/engines/codex.js +6 -6
- package/src/engines/prompt.js +8 -6
- package/src/events/agent-permission.js +2 -2
- package/src/events/agent-thread.js +5 -0
- package/src/events/compaction.js +11 -0
- package/src/events/context-window.js +1 -0
- package/src/events/dialect-a2a.js +1 -1
- package/src/events/dialect-claude.js +1 -1
- package/src/events/harness-cards.js +1 -1
- package/src/events/sandbox-policy.js +1 -1
- package/src/events/service-standby.js +1 -0
- package/src/events/skill-scan.js +3 -3
- package/src/pii/pipeline.js +1 -1
- package/src/sandbox-srt.js +1 -1
- package/src/sandbox.js +1 -1
- package/src/server.js +9 -9
- package/src/service.js +10 -5
- package/src/threads.js +1 -0
- package/src/warm-pool.js +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
2
|
-
`);let
|
|
1
|
+
const $="permission_request",p=Object.freeze({ALLOW:"allow",ALLOW_CHAT:"allow_chat",DENY:"deny"}),W=600*1e3,_="permission_prompt";function N(){return{name:_,description:"Chap-internal: the person answers the agent's permission prompt. Not for the model.",parameters:{type:"object",properties:{tool:{type:"string"},input:{type:"object"},description:{type:"string"},path:{type:"string"},rules:{type:"array"}}}}}const T=t=>t===_,u=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),a=t=>typeof t=="string"?t:t==null?"":String(t);function k(t={}){const e=u(t)?t:{},o=a(e.tool_name||e.toolName||e.tool),n=[];for(const s of Array.isArray(e.permission_suggestions)?e.permission_suggestions:[])if(!(!u(s)||s.type!=="addRules"||s.behavior==="deny"))for(const r of Array.isArray(s.rules)?s.rules:[]){if(!u(r))continue;const c=a(r.toolName||o),i=a(r.ruleContent);c&&!n.some(f=>f.tool===c&&f.content===i)&&n.push({tool:c,content:i})}return{tool:o,displayName:a(e.display_name||e.displayName)||o,input:u(e.input)?e.input:{},description:a(e.description),path:a(e.blocked_path||e.path)||null,rules:n,toolUseId:a(e.tool_use_id||e.toolUseId)||null}}function g(t={}){const e=Array.isArray(t.rules)?t.rules.filter(o=>o&&o.tool):[];return e.length?e.map(o=>o.content?`${o.tool}(${o.content})`:o.tool):t.tool?[String(t.tool)]:[]}function L(t={}){const e=a(t.tool),o=u(t.input)?t.input:{},n=(l,d=240)=>l.length>d?`${l.slice(0,d-1)}…`:l;let s,r;if(e==="Bash")s="Run a command",r=n(a(o.command).trim()||a(t.description)||"a shell command");else if(e==="Edit"||e==="MultiEdit"||e==="NotebookEdit")s="Edit a file",r=a(o.file_path||o.notebook_path||t.path)||"a file";else if(e==="Write"){s="Write a file";const l=a(o.file_path||t.path)||"a file",d=a(o.content).length;r=d?`${l} (${d.toLocaleString()} chars)`:l}else if(/^mcp__/.test(e))s="Use a connected server",r=e.replace(/^mcp__/,"").replace(/__/," › ");else{s=`Use ${t.displayName||e||"a tool"}`;let l="";try{l=JSON.stringify(o)}catch{l=""}r=a(t.description)||(l&&l!=="{}"?n(l,200):e)}const c=g(t),i=Array.isArray(t.rules)?t.rules.filter(l=>l?.content):[],f=i.length&&i.some(l=>l.content!==r)?i.map(l=>l.content).join(", "):c.length&&!i.length?`every ${e} call`:null;return{title:s,detail:r,scope:f,description:a(t.description)||null}}function h(t,e=""){return t===p.ALLOW?{behavior:"allow",scope:"once"}:t===p.ALLOW_CHAT?{behavior:"allow",scope:"chat"}:{behavior:"deny",scope:"once",...e?{message:String(e)}:{}}}function w(t){return u(t)&&t.behavior==="allow"}function E(t,e){const o=new Set(Array.isArray(t)?t:[]);for(const n of g(e))o.add(n);return[...o].sort()}const b="*";function O(t,e){const o=new Set(Array.isArray(t)?t:[]);if(o.has(b))return h(p.ALLOW);const n=g(e);return n.length&&n.every(s=>o.has(s))?h(p.ALLOW):null}function R(t,e,o={}){const n=u(o)?o:{},s=w(e);let r;if(s){if(r={behavior:"allow",updatedInput:u(n.input)?n.input:{}},e.scope==="chat"){const c=(Array.isArray(n.permission_suggestions)?n.permission_suggestions:[]).filter(i=>u(i)&&i.type==="addRules"&&i.behavior!=="deny"&&Array.isArray(i.rules)&&i.rules.length).map(i=>({type:"addRules",rules:i.rules,behavior:"allow",destination:"session"}));c.length&&(r.updatedPermissions=c)}}else r={behavior:"deny",message:a(e?.message)||"The user declined this action in Chap. Continue without it, or explain what it was for and ask."};return{type:"control_response",response:{subtype:"success",request_id:String(t),response:r}}}function C(t,e){const{detail:o}=L(t),n=w(e),s=n&&e.scope==="chat"?" for this chat":"";return`${n?"Allowed":"Declined"}${s}: ${o}`}function x(t){return t==="Bash"?"code":/^(Edit|MultiEdit|NotebookEdit)$/.test(String(t))?"pencil":t==="Write"?"file":/^mcp__/.test(String(t))?"plug":"bot"}function P({memory:t=new Map}={}){const e=t;async function o(n,{convId:s=null,confirm:r,agentName:c="The agent"}={}){const i=O(await e.get(s)||[],n);if(i)return i;const{title:f,detail:l,scope:d,description:y}=L(n),S=[l,y&&y!==l?y:"",d?`“Allow for this chat” also covers: ${d}`:""].filter(Boolean).join(`
|
|
2
|
+
`);let m;try{if(typeof r!="function")throw new Error("no card");m=await r(S,{title:`${c} asks — ${f.toLowerCase()}?`,iconName:x(n.tool),scopeLabel:"Allow for this chat",allLabel:"Allow all in this chat"})}catch(A){return h(p.DENY,`Chap could not show the permission card (${A?.message||A}).`)}return m==="all"?(await e.set(s,[b]),h(p.ALLOW_CHAT)):m==="site"||m==="always"?(await e.set(s,E(await e.get(s)||[],n)),h(p.ALLOW_CHAT)):h(m==="allow"?p.ALLOW:p.DENY)}return{ask:o,forget(n){e.delete(n)},standing(n){return e.get(n)||[]},provider({convId:n=null,confirm:s,agentName:r="The agent"}={}){return{id:"permission",specs:[N()],execute:async(c,i)=>JSON.stringify(await o(i&&typeof i=="object"?i:{},{convId:n,confirm:s,agentName:r}))}}}}export{b as ALLOW_ALL,p as PERMISSION_ANSWERS,$ as PERMISSION_EVENT,W as PERMISSION_TIMEOUT_MS,_ as PERMISSION_TOOL_NAME,R as claudePermissionResponse,P as createPermissionDesk,L as describePermission,T as isPermissionTool,w as permissionAllowed,h as permissionAnswer,x as permissionIcon,g as permissionKeys,C as permissionLine,k as permissionRequestFromClaude,N as permissionToolSpec,O as recallPermission,E as rememberPermission};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{EventError as p}from"./event.js";const y=(t,r)=>{if(!t)throw new p("SHAPE",r)},m=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function I(t){if(!t||typeof t!="object")return null;const r=String(t.id??"").trim().replace(/^chat:/,"");if(!m.test(r))return null;const n=String(t.title??"").replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim().slice(0,120);return{id:r,...n?{title:n}:{}}}function E(t){return t?[`chat:${t}`]:[]}function x(t=[]){const n=(Array.isArray(t)?t:[]).slice(0,-1);return{users:n.filter(e=>e?.role==="user").map(e=>l(e.content).trim()),answers:n.filter(e=>e?.role==="assistant").length}}function A(t=[],{answered:r=!0}={}){const n=Array.isArray(t)?t:[];return{users:n.filter(e=>e?.role==="user").map(e=>l(e.content).trim()),answers:n.filter(e=>e?.role==="assistant").length+(r?1:0)}}const g=8;function h(t,r=g){const n=String(t??"").trim(),e=[n];let s=n;for(let i=0;i<r;i++){const o=s.lastIndexOf(`
|
|
2
|
+
|
|
3
|
+
`);if(o<0)break;s=s.slice(0,o).trim(),s&&e.push(s)}return[...new Set(e)]}function w(t,r){const n=String(r??"").trim();return h(t).includes(n)}function b(t=[],{answered:r=!0}={}){const n=A(t,{answered:r});return{users:n.users.slice(0,-1),answers:n.answers,last:h(n.users.at(-1)??"")}}function P(t=[]){const r=x(t);return{users:r.users.slice(0,-1),answers:r.answers,last:r.users.at(-1)??null}}function T(t=[],{n:r,answers:n}={}){const e=Array.isArray(t)?t:[];if(!Number.isInteger(r)||r<0||!Number.isInteger(n)||n<0)return null;const s=[];let i=0,o=-1;for(let f=0;f<e.length;f++){const c=e[f];if(c?.role==="user"){if(s.length===r){o=f;break}s.push(l(c.content).trim())}else c?.role==="assistant"&&i++}if(o<0)return null;const u=n-i;if(u!==0&&u!==1)return null;let a=o+1;if(u===1){for(;a<e.length&&e[a]?.role!=="assistant";){if(e[a]?.role==="user")return null;a++}if(a>=e.length)return null;a++}const d=e.slice(a);return d.at(-1)?.role!=="user"?null:{prefix:{users:s,answers:n},last:l(e[o].content).trim(),tail:d,answered:u===1}}function D(t=[],r=()=>!1,{answered:n=!0}={}){const e=Array.isArray(t)?t:[];for(let s=e.length-1;s>=0;s--){if(e[s]?.role!=="user"||!r(l(e[s].content).trim()))continue;let i=s+1;n&&e[i]?.role==="assistant"&&i++;const o=e.slice(i).filter(u=>u?.role==="user"||u?.role==="assistant");return o.at(-1)?.role==="user"&&o.pop(),o}return[]}function _(t=[],r=[]){let n=Array.isArray(t)?t:[];for(const e of Array.isArray(r)?r:[]){if(e?.role!=="user")continue;const s=n.findIndex(i=>i?.role==="user"&&w(l(i.content),l(e.content)));s>=0&&(n=[...n.slice(0,s),...n.slice(s+1)])}return n}function z(t=[]){const r=Array.isArray(t)?t:[],n=r.filter(e=>e?.role==="user").map(e=>l(e.content).trim());return{users:n.slice(0,-1),answers:r.filter(e=>e?.role==="assistant").length,last:h(n.at(-1)??"")}}function l(t){return typeof t=="string"?t:Array.isArray(t)?t.map(r=>typeof r=="string"?r:r?.text||"").filter(Boolean).join(`
|
|
4
|
+
|
|
5
|
+
`):String(t??"")}function N({link:t=null,digest:r="",cwd:n="",hasHistory:e=!1}={}){return y(typeof r=="string","threadPlan: digest must be a string"),!t||!t.sessionId?{mode:"start",sessionId:null,seed:!!e,why:"no session holds this thread yet"}:String(t.cwd||"")!==String(n||"")?{mode:"start",sessionId:null,seed:!!e,why:"the thread moved to another folder"}:!r||t.digest!==r?{mode:"start",sessionId:null,seed:!!e,why:"the history differs from what the session saw (edited or regenerated)"}:{mode:"resume",sessionId:String(t.sessionId),seed:!1,why:"the session has seen exactly this history"}}export{T as historyExtension,x as historyShape,P as historySplit,E as legacyThreadIds,A as nextShape,I as normalizeThread,_ as outsideBeyond,D as outsideTurns,z as seenOf,h as sentVariants,N as threadPlan,b as turnSeen,w as userTextMatches};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{keepRecentFor as m}from"./context-window.js";const g="You compress a conversation into a compact but COMPLETE summary for continuation. Preserve: the user’s goals, key facts, decisions made, current task/automation state, open questions, and specifics needed to keep going. Terse bullet points. No preamble.",f=4e3;function a(e=[]){return(Array.isArray(e)?e:[]).filter(t=>t&&!t.pending&&(t.role==="user"||t.role==="assistant")&&(t.content||t.attachments?.length))}function y({messages:e=[],keepRecent:t=4,budget:n=0,tokensOf:o=null}={}){const r=a(e);let i=Math.max(1,Math.floor(Number(t)||4));if(n>0&&typeof o=="function")for(;i>1&&r.slice(r.length-i).reduce((c,p)=>c+(o(p)||0),0)>n;)i-=1;if(r.length<=i+1)return null;const s=r.slice(0,r.length-i),l=r.slice(r.length-i),u=s.map(c=>`${c.role==="user"?"User":"Assistant"}: ${String(c.content||"").slice(0,f)}`).join(`
|
|
2
|
+
|
|
3
|
+
`);return{fold:s,keep:l,uptoId:s[s.length-1].id,transcript:u}}function x({transcript:e="",previousSummary:t=""}={}){return`${t?`Earlier summary to fold in:
|
|
4
|
+
${t}
|
|
5
|
+
|
|
6
|
+
`:""}Summarize the conversation so far:
|
|
7
|
+
|
|
8
|
+
${e}`}function S({summary:e,uptoId:t,now:n=Date.now()}={}){return{summary:String(e||"").trim(),uptoId:t,ts:n}}function A(e=[],t=null){const n=a(e);if(!t?.uptoId)return n;const o=n.findIndex(r=>r.id===t.uptoId);return o>=0?n.slice(o+1):n}function E(e="",t=null){const n=String(t?.summary||"").trim();return n?`${e?`${e}
|
|
9
|
+
|
|
10
|
+
`:""}[Summary of the earlier part of this conversation — continue seamlessly; do not mention this summary]
|
|
11
|
+
${n}`:e||""}const d=36e4;function k(e=[],{maxChars:t=d}={}){const n=Array.isArray(e)?e:[];let o=0,r=n.length;for(;r>0;){const i=String(n[r-1]?.content??"").length+16;if(o+i>t&&r<n.length)break;o+=i,r-=1}return{kept:n.slice(r),elided:r}}export{g as COMPACTION_SYSTEM,d as SEED_MAX_CHARS,a as compactable,x as compactionPrompt,S as compactionRecord,m as keepRecentFor,A as messagesAfter,y as planCompaction,k as seedWithin,E as systemWithSummary};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const d=[[/gpt-4\.1/,1e6],[/gpt-5|o3|o4|o1/,2e5],[/gpt-4o|gpt-4-turbo/,128e3],[/claude-(3|4|5|opus|sonnet|haiku|fable)/,2e5],[/gemini-(1\.5|2|2\.5|3)/,1e6],[/gemini/,1e6],[/deepseek/,128e3],[/mistral-large|mixtral|codestral/,128e3],[/grok/,128e3],[/llama-3\.[1-3]|llama-4/,128e3]];function x(t={},n=null){const e=String(t.id||""),i=String(t.model||t.id||"").toLowerCase(),u=n&&(n[l(t)]||n[i]||n[String(t.model||"")]||(t.gateway?0:n[e]));if(Number(u)>0)return Number(u);const r=Number(t.window||t.contextLength||t.contextWindow||0);if(r>0)return r;if(t.reach==="device"||t.kind==="webllm")return 0;for(const[o,c]of d)if(o.test(i))return c;return 0}function l(t={}){const n=String(t.id||""),e=String(t.model||"");return e?`${n}:${e}`:n}const s=.85,a=8192,f=t=>Number(t)>0&&Number(t)<=a,w=2;function p({promptTokens:t=0,floorTokens:n=0,window:e=0,reserve:i=1024,headroom:u=s}={}){const r=Number(e)||0;if(!r)return{status:"unknown",budget:0,over:0,window:0};const o=Math.max(0,Math.floor(r*u)-Math.max(0,Number(i)||0)),c=Math.max(0,Number(t)||0),m=Math.max(0,Number(n)||0);return c<=o?{status:"ok",budget:o,over:0,window:r}:m<=o?{status:"compact",budget:o,over:c-o,window:r}:{status:"too-big",budget:o,over:m-o,window:r}}function _(t=0){const n=Number(t)||0;return n?n<=8e3?2:n<=32768?4:n<=128e3?8:12:4}function b({floorTokens:t=0,reserve:n=1024,headroom:e=s}={}){const i=Math.max(0,Number(t)||0);return i?Math.ceil((i+Math.max(0,Number(n)||0))/e):0}function h(t){return/context.{0,8}(length|window|size)|context_length_exceeded|prompt is too long|too many tokens|maximum context|exceed.{0,20}context|reduce the (length|number|size)|input is too long|token limit|n_ctx|kv cache|longer than .{0,80}\bwindow\b|exceed.{0,30}\bwindow\b/i.test(String(t?.message||t||""))}export{s as FIT_HEADROOM,a as SMALL_WINDOW,w as SMALL_WINDOW_ROUNDS,p as fitFor,h as isContextLimitError,f as isSmallWindow,_ as keepRecentFor,b as minWindowFor,l as observedKey,x as windowOf};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{normalizeCard as s,cardToProfile as p,A2A_VERSION as u}from"./agent-card.js";import{defineAgentDialect as h}from"./agent-dialects.js";const a=t=>typeof t=="string"?t.trim():t==null?"":String(t).trim(),y=h({id:"a2a",label:"A2A agent card",filename:t=>`${t?.id||"agent"}.agent-card.json`,detect(t,{filename:r=""}={}){let n;try{n=JSON.parse(String(t??""))}catch{return 0}if(!n||typeof n!="object"||Array.isArray(n))return 0;const i=!!a(n.name)&&!!a(n.description),e=Array.isArray(n.supportedInterfaces)||!!a(n.url)||!!n.capabilities;return/agent-card\.json$/i.test(r)&&i?.99:i&&e&&Array.isArray(n.skills)?.9:i&&e?.6:0},parse(t,{name:r=""}={}){let n;try{n=JSON.parse(String(t??""))}catch{return{form:{},extras:{},warnings:["not JSON"]}}const i=s(n),e=[];return i.supportedInterfaces.length||e.push("this card names no endpoint, so there is nowhere to reach the agent"),e.push("a card advertises a remote agent: its engine is a placeholder until
|
|
1
|
+
import{normalizeCard as s,cardToProfile as p,A2A_VERSION as u}from"./agent-card.js";import{defineAgentDialect as h}from"./agent-dialects.js";const a=t=>typeof t=="string"?t.trim():t==null?"":String(t).trim(),y=h({id:"a2a",label:"A2A agent card",filename:t=>`${t?.id||"agent"}.agent-card.json`,detect(t,{filename:r=""}={}){let n;try{n=JSON.parse(String(t??""))}catch{return 0}if(!n||typeof n!="object"||Array.isArray(n))return 0;const i=!!a(n.name)&&!!a(n.description),e=Array.isArray(n.supportedInterfaces)||!!a(n.url)||!!n.capabilities;return/agent-card\.json$/i.test(r)&&i?.99:i&&e&&Array.isArray(n.skills)?.9:i&&e?.6:0},parse(t,{name:r=""}={}){let n;try{n=JSON.parse(String(t??""))}catch{return{form:{},extras:{},warnings:["not JSON"]}}const i=s(n),e=[];return i.supportedInterfaces.length||e.push("this card names no endpoint, so there is nowhere to reach the agent"),e.push("a card advertises a remote agent: its engine is a placeholder until Chap can call an A2A endpoint"),{form:{id:"",name:i.name||a(r),purpose:i.description,prompt:m(i),engine:{kind:"auto",policy:{prefer:"balanced"}},grants:["none"],skills:i.skills.map(o=>o.id)},extras:{card:i},warnings:e}},render(t){return`${JSON.stringify(g(t),null,2)}
|
|
2
2
|
`},carries:["id","name","purpose","skills","provider","version","iconUrl","documentationUrl","tags","examples","inputModes","outputModes"],notes:{prompt:"a card is served to strangers — an agent's own instructions are never published in one",engine:"a card says where to reach an agent, never what model is behind it",grants:"what a remote agent may touch is its own operator's business, not ours to declare",tools:"a card advertises skills, not the tools behind them",denyTools:"a card advertises skills, not the tools behind them",mcpServers:"an agent's own connections are not published",permissionMode:"no equivalent — authorization is expressed with security schemes",sandboxMode:"no equivalent — how a remote agent is contained is its operator's business",maxTurns:"no equivalent in a card",effort:"no equivalent in a card",isolation:"no equivalent in a card",color:"no equivalent in a card",background:"no equivalent in a card",hooks:"no equivalent in a card",memoryScope:"no equivalent in a card",workdir:"a local path has no meaning to whoever reads the card"}});function m(t){const r=s(t),n=[];if(r.description&&n.push(r.description),r.skills.length){n.push("","What it offers:");for(const e of r.skills)n.push(`- ${e.name||e.id}${e.description?` — ${e.description}`:""}`)}const i=r.supportedInterfaces[0];return i&&n.push("",`Reached over A2A at ${i.url} (${i.protocolBinding}).`),r.provider?.organization&&n.push(`Published by ${r.provider.organization}.`),n.join(`
|
|
3
3
|
`).trim()}function g(t,{interfaces:r=[],profile:n=u,skills:i=[]}={}){const e=t||{},o=e.dialectExtras?.a2a?.card,c=i.length?i:(e.skills||[]).map(l=>f(l,e)),d=s({...o||{},name:e.name||e.id||"",description:e.purpose||"",version:e.version||o?.version||"0.1.0",...e.provider?{provider:e.provider}:{},...e.iconUrl?{iconUrl:e.iconUrl}:{},...e.documentationUrl?{documentationUrl:e.documentationUrl}:{},supportedInterfaces:r.length?r:o?.supportedInterfaces||[],capabilities:{streaming:!0,pushNotifications:!1,...o?.capabilities||{}},defaultInputModes:e.inputModes?.length?e.inputModes:o?.defaultInputModes,defaultOutputModes:e.outputModes?.length?e.outputModes:o?.defaultOutputModes,skills:c});return delete d.signatures,p(d,n)}function f(t,r){const n=String(t||"").trim();return{id:n,name:n,description:`${n}, as performed by ${r?.name||r?.id||"this agent"}`,tags:r?.tags?.length?[...r.tags]:[]}}export{y as a2aDialect,m as briefFromCard,g as cardFromAgent};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{parseFrontmatter as p,renderFrontmatter as k}from"./frontmatter.js";import{defineAgentDialect as w,grantsFromTools as S,toolsFromGrants as b,toNameList as d}from"./agent-dialects.js";const T=Object.freeze(["name","description","tools","disallowedTools","model","permissionMode","maxTurns","skills","mcpServers","hooks","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental"]),x=Object.freeze(["tools","disallowedTools","model","permissionMode","maxTurns","isolation","color","hooks","initialPrompt"]),m=t=>typeof t=="string"?t.trim():t==null?"":String(t).trim(),A=w({id:"claude",label:"Claude Code",filename:t=>`${t?.id||"agent"}.md`,detect(t,{filename:o=""}={}){const{meta:e,body:n}=p(t);if(!e.name&&!e.description)return 0;const i=/(^|\/)agents\//.test(o)&&/\.md$/i.test(o),r=x.some(s=>e[s]!==void 0);return/(^|\/)SKILL\.md$/i.test(o)||!i&&/(^|\/)skills\//.test(o)?0:i&&r?.95:i?.8:r?.7:n.trim()?.35:.2},parse(t,{name:o=""}={}){const{meta:e,body:n}=p(t),i=[],r=d(e.tools),{grants:s,mcpServers:c,unmapped:u}=S(r);u.length&&i.push(`tools with no
|
|
1
|
+
import{parseFrontmatter as p,renderFrontmatter as k}from"./frontmatter.js";import{defineAgentDialect as w,grantsFromTools as S,toolsFromGrants as b,toNameList as d}from"./agent-dialects.js";const T=Object.freeze(["name","description","tools","disallowedTools","model","permissionMode","maxTurns","skills","mcpServers","hooks","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental"]),x=Object.freeze(["tools","disallowedTools","model","permissionMode","maxTurns","isolation","color","hooks","initialPrompt"]),m=t=>typeof t=="string"?t.trim():t==null?"":String(t).trim(),A=w({id:"claude",label:"Claude Code",filename:t=>`${t?.id||"agent"}.md`,detect(t,{filename:o=""}={}){const{meta:e,body:n}=p(t);if(!e.name&&!e.description)return 0;const i=/(^|\/)agents\//.test(o)&&/\.md$/i.test(o),r=x.some(s=>e[s]!==void 0);return/(^|\/)SKILL\.md$/i.test(o)||!i&&/(^|\/)skills\//.test(o)?0:i&&r?.95:i?.8:r?.7:n.trim()?.35:.2},parse(t,{name:o=""}={}){const{meta:e,body:n}=p(t),i=[],r=d(e.tools),{grants:s,mcpServers:c,unmapped:u}=S(r);u.length&&i.push(`tools with no Chap equivalent, left ungranted rather than guessed at: ${u.join(", ")}`);const f=d(e.mcpServers),h={id:"",name:m(e.name)||m(o),purpose:m(e.description),prompt:n.trim(),engine:y(e.model),grants:s.length?s:["none"],skills:d(e.skills)},a={raw:{}};for(const[l,g]of Object.entries(e))T.includes(l)||(a.raw[l]=g);Object.keys(a.raw).length||delete a.raw,r.length&&(a.tools=r),d(e.disallowedTools).length&&(a.disallowedTools=d(e.disallowedTools)),f.length&&(a.mcpServers=f);for(const l of["permissionMode","maxTurns","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental","hooks"])e[l]!==void 0&&(a[l]=e[l]);return m(e.model)&&(a.model=m(e.model)),{form:h,extras:a,warnings:i}},render(t){const o=t||{},e=o.dialectExtras?.claude||{},n={name:o.id||o.name||"agent",description:o.purpose||o.name||""},i=o.grants?.length?b(o.grants,{dialect:"claude"}):d(e.tools);i.length&&(n.tools=i),e.disallowedTools&&(n.disallowedTools=e.disallowedTools);const r=v(o,e);r&&(n.model=r),o.skills?.length&&(n.skills=[...o.skills]),e.mcpServers&&(n.mcpServers=e.mcpServers);for(const s of["permissionMode","maxTurns","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental","hooks"])e[s]!==void 0&&(n[s]=e[s]);for(const[s,c]of Object.entries(e.raw||{}))n[s]===void 0&&(n[s]=c);return k(n,`
|
|
2
2
|
${String(o.prompt||"").trim()}
|
|
3
3
|
`)},carries:["id","name","purpose","prompt","engine","grants","skills","mcpServers","tools","denyTools","permissionMode","maxTurns","effort","isolation","color","background","hooks"],notes:{sandboxMode:"Claude Code has no sandbox_mode; its equivalent is permissionMode plus the tools allowed",memoryScope:"Claude Code scopes memory to user, project or local — not to a named namespace",workdir:"a Claude Code agent runs wherever the session runs; a working directory is not part of its definition",provider:"a definition file describes an agent, not who publishes it — that is A2A card territory",version:"a definition file carries no version of its own",iconUrl:"no icon in the format",documentationUrl:"no documentation link in the format",tags:"no tags in the format",examples:'no examples in the format — the description is where the "use this when" goes',inputModes:"media types are an A2A idea",outputModes:"media types are an A2A idea"}});function y(t){const o=m(t);return!o||o==="inherit"?o==="inherit"?{kind:"assistant"}:{kind:"harness",harnessId:"claude"}:{kind:"harness",harnessId:"claude",model:o}}function v(t,o){const e=t?.engine;return e?.kind==="assistant"?"inherit":e?.kind==="harness"&&e.harnessId==="claude"&&e.model||e?.kind==="model"&&e.model&&/claude|sonnet|opus|haiku/i.test(String(e.model))?String(e.model):o.model?String(o.model):""}export{A as claudeDialect};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as
|
|
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=n=>String(n||"").toLowerCase().replace(/[^a-z]/g,""),d={claudecode:"claude",githubcopilot:"copilot",copilotcli:"copilot",deepseekharness:"deepseek",gemini:"antigravity",geminicli:"antigravity"};function s(n){const o=p(n);if(l[o])return{id:o,...l[o]};if(d[o])return{id:d[o],...l[d[o]]};const e=Object.entries(l).find(([i,t])=>o.includes(i)||o.includes(p(t.label)));return e?{id:e[0],...e[1]}:null}function m(n,{repointed:o=null}={}){const e=s(n);return e?o?{egress:"configurable",where:`a coding agent · model at ${o}`,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(n){if(n==null)return null;if(typeof n=="string")return u({flag:n,repeat:!0});if(typeof n!="object"||Array.isArray(n))throw new a("SHAPE","dirs: must be { flag, repeat } or { flag, separator }");const o=String(n.flag||"").trim();if(!/^--?[A-Za-z][\w-]*$/.test(o))throw new a("SHAPE",`dirs: not a flag: ${JSON.stringify(n.flag)}`);const e=n.separator==null?null:String(n.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:o,separator:e}:{flag:o,repeat:!0}}function h({harness:n,roots:o=[],dirs:e}={}){const i=(Array.isArray(o)?o:[]).map(r=>String(r||"").trim()).filter(Boolean);if(!i.length)return[];const t=u(e!==void 0?e:s(n)?.dirs??null);return t?t.separator?[t.flag,i.join(t.separator)]:i.flatMap(r=>[t.flag,r]):[]}function w(n,o){try{return!!u(o!==void 0?o:s(n)?.dirs??null)}catch{return!1}}const f=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function A({harness:n,mode:o,id:e="",name:i=""}={}){const t=s(n)?.session;if(!t)return[];if(o==="off")return Array.isArray(t.off)?[...t.off]:[];if(o==="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(o!=="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=n=>Array.isArray(s(n)?.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 L}from"./event.js";import{normalizeGrant as x}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as P,SECRET_DIR_PAIRS as N}from"./secret-names.js";const R=Object.freeze(["none","process","container","kubernetes"]),S=Object.freeze(["open","allowlist","none","gateway"]),E=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),g=e=>{let t=String(e||"").trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"));)t=t.slice(0,-1);return t},_=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),b=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},v=E.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function I(e,t=""){const n=m(g(_(g(e),t)));if(!n)return!1;for(const o of E)if(b(n,o)||t&&b(n,_(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return v.some(o=>{for(let s=0;s+o.length<=r.length;s+=1)if(o.every((c,l)=>c.toLowerCase()===r[s+l]))return!0;return!1})}const $=Object.freeze([...[...P].map(e=>`~/**/${e}`),...N.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 Z(e,{home:t="",globs:n=[...E,...$]}={}){const r=m(g(_(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),s=m(g(t));for(const c of n){const l=m(g(c));if(l){if(l.startsWith("~/**/")){if(s&&!b(r,s))continue;const a=l.slice(5).split("/").filter(Boolean).map(z);for(let i=0;i+a.length<=o.length;i+=1)if(a.every((f,p)=>f.test(o[i+p])))return c;continue}if(b(r,_(l,t)))return c}}return null}function z(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const W=".cache/chatpanel/ca-bundle.crt",J=".cache/chatpanel/ca-bundle.pem";function ee(e=""){const t=m(g(e));return t?`${t}/${W}`:`~/${W}`}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"]),D=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}),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\/?$/,k=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),O=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),d=(e,t)=>{if(!e)throw new L("SHAPE",t)},u=e=>[...new Set(e)];function j(e){d(h(e),"kit: must be an object"),d(typeof e.id=="string"&&e.id.length>0,"kit: id required"),d(h(e.network)&&S.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${S.join(", ")}`),d(O(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),d(O(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),d(h(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])d(O(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return d(O(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&d(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&d(Array.isArray(e.credentials)&&e.credentials.every(t=>h(t)&&typeof t.name=="string"&&typeof t.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:u(e.network.allowedDomains||[]),deniedDomains:u(e.network.deniedDomains||[])},filesystem:{allowWrite:u(e.filesystem.allowWrite),denyWrite:u(e.filesystem.denyWrite||[]),allowRead:u(e.filesystem.allowRead||[]),denyRead:u(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:h(e.limits)?{...e.limits}:{}}}import{normalizeGrant as ue,mergeGrants as pe,parseHostList as ge}from"./sandbox-grant.js";function te({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:s=[],grant:c=null,home:l="",reads:a="enumerated",readOnly:i=!1}={}){const f=C[e]||C.custom;d(typeof t=="string"&&t.length>0,"kit: cwd required");const p=x(c);return j({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:u([...f.hosts,...k,...r,...p.hosts]),deniedDomains:[]},filesystem:{allowWrite:u(i?[...D,...f.write]:[t,...D,...f.write,...[...o,...p.write].filter(A=>!I(A,l))]),denyWrite:[],allowRead:a==="inverted"?u([t,...H,...f.write,...f.keychain?[T]:[],...U({grant:p,extraWrite:o,cwd:t,home:l})]):[t],denyRead:u([...a==="inverted"?["~",...l?[l]:[]]:[],...[...E,...$].filter(A=>!(f.keychain&&K.test(A))),...s])}})}function Y(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 U({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 f=String(i||"").trim();for(;f.length>1&&(f.endsWith("/")||f.endsWith("\\"));)f=f.slice(0,-1);return f},c=(i,f)=>i===f||i.startsWith(`${f}/`)||i.startsWith(`${f}\\`),l=s(o(n)),a=[];for(const i of[...x(e).write,...Array.isArray(t)?t:[]]){const f=Y(s(o(s(i))));if(f&&!I(f,r)&&!(l&&c(f,l))&&!a.some(p=>c(f,p))){for(let p=a.length-1;p>=0;p--)c(a[p],f)&&a.splice(p,1);a.push(f)}}return a}function ne(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=j(e),s=l=>n&&l.startsWith("~")?n+l.slice(1):l,c=o.network.mode==="none"?[]:t.map(l=>`127.0.0.1:${l}`);return{network:{allowedDomains:u([...o.network.allowedDomains,...c]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&c.length>0},filesystem:{denyRead:o.filesystem.denyRead.map(s),allowRead:o.filesystem.allowRead.map(s),allowWrite:o.filesystem.allowWrite.map(s),denyWrite:o.filesystem.denyWrite.map(s)}}}function oe({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:s=null}={}){return d(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:u(s)}:{}}}function B(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){d(!/[\r\n]/.test(n),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=n;if(n===""||/[ \t\v"]/.test(n)){r='"';for(let o=0;o<n.length;o++){let 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 G=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function re(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of G)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 se(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>B(r,{platform:n})).join(" ")}const ie=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),M=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function y(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function q(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 ae({kit:e,files:t=[],home:n}){d(typeof n=="string"&&n.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?n+a.slice(1):a).replace(/\//g,"\\"),o=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(d(!M(i)&&w(i)!==w(n),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),y(i,n)&&o.push(i))}const s=(a,i)=>i.some(f=>w(a)===w(f)||y(a,f)),c=[];for(const a of t){const i=q(a);i&&y(i,n)&&c.push(i)}for(const a of e?.filesystem?.allowRead||[]){const i=r(a);y(i,n)&&c.push(i)}const l=u(c).filter(a=>!s(a,o));return{read:l.filter(a=>!l.some(i=>i!==a&&y(a,i))),write:u(o)}}const F=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 ce({engine:e="custom",home:t,env:n={},base:r={},carry:o=F}={}){d(typeof t=="string"&&t.length>0,"windows env: home required");const s=t.replace(/\//g,"\\"),c=/^[a-z]:/i.test(s)?s.slice(0,2):"",l={USERPROFILE:s,...c?{HOMEDRIVE:c,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(n))typeof i=="string"&&(r[a]!==i||o.includes(a))&&(l[a]=i);return e==="codex"&&!l.CODEX_HOME&&(l.CODEX_HOME=s+"\\.codex"),l}function le(e,t){d(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;d(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let c=n+1;c<r;c++)e[c]==="--env"&&typeof e[c+1]=="string"&&o.add(e[c+1].split("=")[0].toUpperCase());const s=[];for(const[c,l]of Object.entries(t||{}))d(/^[A-Za-z_][A-Za-z0-9_]*$/.test(c),`srt-win env: bad key ${c}`),d(!/[\r\n]/.test(l),`srt-win env: ${c} holds a newline`),o.has(c.toUpperCase())||s.push("--env",`${c}=${l}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{W as CA_BUNDLE_RELPATH,J as CA_BUNDLE_RELPATH_LEGACY,D as COMMON_WRITE,k as DEVELOPER_HOSTS,C as ENGINE_KITS,S as NETWORK_MODES,R as SANDBOX_LAYERS,E as SECRET_PATHS,$ as SECRET_READ_GLOBS,H as TOOLCHAIN_READ,F as WINDOWS_CARRY_KEYS,ee as caBundlePath,I as isSecretWritePath,te as kitFor,pe as mergeGrants,ue as normalizeGrant,ge as parseHostList,Z as readDenialFor,re as sandboxEnvOverlay,oe as sandboxRecord,se as shellJoin,B as shellQuote,ne as toSrtSettings,y as underWindowsHome,j as validateKit,ae as windowsGrantsFor,q as windowsInstallRoot,ce as windowsSandboxEnv,le as withSrtWinEnv,U as writableRoots};
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c=15e3,h=Object.freeze({CHATPANEL_SERVICE:"1"});function p(e={},{labels:s=["net.chatpanel.gateway","net.chatpanel.bridge"]}={}){return e.CHATPANEL_MANAGED_BY==="desktop"?"desktop":e.XPC_SERVICE_NAME&&s.includes(e.XPC_SERVICE_NAME)?"launchd":e.CHATPANEL_SERVICE==="1"?"service":null}function u({name:e,self:s,holder:n,managedBy:i,port:t}){const o=e==="bridge"?"Bridge":"Gateway";if(n?.ours&&i){const r=a(s,n.version);return{action:"standby",lines:[`ChatPanel ${o} v${n.version||"?"} already answers on ${t}; this copy (v${s}, started by ${i}) is standing by and takes over the moment the port is free.`,...r>0?[`This copy is newer. To switch now, stop the other one (\`chatpanel-${e} --status\` shows where it runs).`]:[]]}}if(n?.ours){const r=a(s,n.version);return{action:"exit",lines:[`ChatPanel ${o} v${n.version||"?"} is already running on ${t} — this one (v${s}) did not start.`,r>0?`To replace it with this version and keep it starting at login: chatpanel-${e} --install`:r<0?`The running one is NEWER. Nothing to do — this copy (v${s}) is the stale one; \`which -a chatpanel-${e}\` shows where it comes from.`:`It is this same version: nothing to do. \`chatpanel-${e} --status\` shows how it is started.`]}}return{action:"exit",lines:[]}}function a(e,s){const n=String(e||"").split(".").map(t=>parseInt(t,10)),i=String(s||"").split(".").map(t=>parseInt(t,10));if(n.length<3||i.length<3||n.some(Number.isNaN)||i.some(Number.isNaN))return 0;for(let t=0;t<3;t+=1)if(n[t]!==i[t])return n[t]>i[t]?1:-1;return 0}export{h as SERVICE_ENV,c as STANDBY_POLL_MS,a as compareVersions,u as portClashPlan,p as serviceManagerOf};
|
package/src/events/skill-scan.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
class
|
|
2
|
-
`).length,
|
|
1
|
+
class O extends Error{constructor(t,r){super(r),this.name="SkillScanError",this.code=t}}const g=2,I=Object.freeze(["clean","suspicious","dangerous"]),p={clean:0,suspicious:1,dangerous:2},f=/[----\u{e0000}-\u{e007f}]/u,w=[/\bignore\s+(?:all\s+|any\s+)?(?:previous|prior|earlier|above)\s+(?:instructions?|prompts?|rules?|directions?)\b/i,/\bdisregard\s+(?:all\s+|any\s+)?(?:previous|prior|the)\s+(?:instructions?|system\s+prompt|rules?)\b/i,/\b(?:forget|override)\s+(?:everything|all)\s+(?:you|above|previously)\b/i,/\byou\s+are\s+no\s+longer\s+(?:bound|restricted|required)\b/i,/<\/?(?:system|assistant)\b[^>]*>/i,/\bnew\s+system\s+prompt\s*:/i],y=[/\b(?:do\s+not|don't|never)\s+(?:tell|inform)\s+the\s+user\b(?!\s+to\s)/i,/\b(?:do\s+not|don't|never)\s+(?:mention|reveal|disclose)\s+(?:this|that|it|any(?:thing)?)?\s*to\s+the\s+user\b/i,/\bwithout\s+(?:telling|informing|notifying)\s+the\s+user\b/i,/\bhide\s+(?:this|that|it)\s+from\s+the\s+user\b/i],v=[/~\/\.ssh\/|\bid_rsa\b|\bid_ed25519\b/i,/~\/\.aws\/credentials|\bAWS_SECRET_ACCESS_KEY\b/i,/\.env\b(?!\w)|\bprintenv\b|\benv\s*\|/i,/~\/\.netrc|\.git-credentials|\bkeychain\s+dump\b/i,/\bGITHUB_TOKEN\b|\bNPM_TOKEN\b|\bOPENAI_API_KEY\b|\bANTHROPIC_API_KEY\b/,/~\/\.config\/(?:gh|gcloud)\/|\bgcloud\s+auth\s+print-access-token\b/i],E=[/\bcurl\b[^\n|]*(?:-d|--data|--data-binary|-F|--form|-T|--upload-file)\b/i,/\bwget\b[^\n|]*--post-(?:data|file)\b/i,/\b(?:nc|netcat|ncat)\b\s+[\w.-]+\s+\d+/i,/\bfetch\s*\([^)]*method\s*:\s*['"]POST/i,/\brequests\.post\s*\(/i,/\|\s*(?:curl|nc|netcat)\b/i,/\bscp\b\s+\S+\s+\S+@/i],S=[{re:/\brm\s+-[a-z]*[rR][a-z]*f[a-z]*\s+(?:--no-preserve-root\s+)?(?:\/|~|\$HOME)(?:\/\s|\/?[`'"\s]|$)/,why:"recursive delete of a root or home directory"},{re:/\bmkfs(?:\.\w+)?\b/,why:"filesystem format"},{re:/\bdd\s+[^\n]*\bof=\/dev\/(?:sd|nvme|disk)/,why:"raw write to a block device"},{re:/:\(\)\s*\{\s*:\|:&\s*\}\s*;\s*:/,why:"fork bomb"},{re:/\bchmod\s+-R\s+777\s+\//,why:"world-writable root"},{re:/\bhistory\s+-c\b|\bshred\b\s+[^\n]*\.(?:log|history)/,why:"covering tracks"}],x="(?![\\w.-])",N=["localhost","127\\.0\\.0\\.1","\\[::1\\]","schemas\\.android\\.com","schemas\\.(?:xmlsoap|microsoft|openxmlformats)\\.(?:org|com)","www\\.w3\\.org","purl\\.org","ns\\.adobe\\.com","(?:[\\w-]+\\.)*example(?:\\.(?:com|net|org))?","[\\w.-]+\\.(?:test|invalid|localhost)"].map(e=>e+x).concat(["(?:www\\.)?(?:apache|gnu)\\.org\\/licenses\\b","opensource\\.org\\/licenses\\b"]).join("|"),T=[{re:/\b(?:eval|exec)\s*\(\s*(?:atob|base64|Buffer\.from)/i,why:"executes decoded content"},{re:/\bbase64\s+-d\b[^\n]*\|\s*(?:sh|bash|zsh|python)/i,why:"pipes decoded content to a shell"},{re:/\bcurl\b[^\n]*\|\s*(?:sudo\s+)?(?:sh|bash|zsh)\b/i,why:"pipes a download straight into a shell"},{re:/[A-Za-z0-9+/]{280,}={0,2}/,why:"a large opaque base64 blob"},{re:new RegExp(`\\bhttp:\\/\\/(?!${N})[\\w.-]+`,"i"),why:"sends or fetches over plain HTTP"},{re:/\bsudo\s+(?:-S\s+)?[^\n]*<<</i,why:"feeds a password to sudo"}],_=(e,t)=>e.slice(0,t).split(`
|
|
2
|
+
`).length,k=(e,t,r=90)=>e.slice(Math.max(0,t-10),t+r).replace(/\s+/g," ").trim();function a(e,t){const r=t.exec(e);return r?{index:r.index,match:r[0]}:null}function R({name:e="",prompt:t="",files:r=[],extra:u=""}={}){const n=[String(t||""),String(u||"")].filter(Boolean).join(`
|
|
3
3
|
|
|
4
|
-
`),
|
|
4
|
+
`),l=[],c=(s,o,i,m)=>{l.push({rule:s,severity:o,why:m,line:i?_(n,i.index):0,excerpt:i?k(n,i.index):""})};f.test(n)&&c("hidden-text","dangerous",a(n,f),"contains characters that are invisible to a reader but not to the model");for(const s of w){const o=a(n,s);if(o){c("instruction-override","dangerous",o,"tries to override the instructions it is running under");break}}for(const s of y){const o=a(n,s);if(o){c("concealment","suspicious",o,"asks the model to keep something from the user");break}}const d=v.map(s=>a(n,s)).find(Boolean),h=E.map(s=>a(n,s)).find(Boolean);d&&h?c("credential-exfiltration","dangerous",d,`names a credential (${d.match.trim().slice(0,40)}) alongside a command that sends data off the machine`):d?c("credential-mention","suspicious",d,"refers to a credential file or secret variable"):h&&c("outbound-data","suspicious",h,"sends data to a remote host");for(const{re:s,why:o}of S){const i=a(n,s);i&&c("destructive-command","dangerous",i,o)}for(const{re:s,why:o}of T){const i=a(n,s);i&&c("suspicious-pattern","suspicious",i,o)}const b=(Array.isArray(r)?r:[]).filter(s=>String(s).startsWith("scripts/"));return b.length&&l.push({rule:"ships-executable",severity:"suspicious",why:`ships ${b.length} executable file${b.length===1?"":"s"} (${b.join(", ")}) — these run on your machine, not in the browser`,line:0,excerpt:""}),{verdict:l.reduce((s,o)=>p[o.severity]>p[s]?o.severity:s,"clean"),findings:l,scanner:g,name:String(e||"")}}function C(e){return e!=="dangerous"}function $(e){if(!e||e.verdict==="clean")return"";const t=(e.findings||[]).filter(n=>n.severity===e.verdict),r=t[0],u=t.length>1?` (+${t.length-1} more)`:"";return r?`${r.why}${u}`:e.verdict}export{g as SCANNER_VERSION,I as SCAN_VERDICTS,O as SkillScanError,C as admits,R as scanSkill,$ as scanSummary};
|
package/src/pii/pipeline.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{redactText as
|
|
1
|
+
import{redactText as f,restoreText as d,restoreWithAliases as R,redactResultShape as b}from"./pii-redact.js";function y(t){return!!(t&&t.mode&&t.mode!=="off")}function T(t,e){const r=t?.tier==="full"?"full":"basic";return r==="full"&&!e?"basic":r}const k=5;function I(t,e){const r=Array.isArray(t?.dictionary)?t.dictionary:[];return e?r:r.slice(0,k)}function x(t,e){const r=t?.scope||{};return e?r:{chat:r.chat!==!1,context:!1,history:!1,toolResults:!1}}function l(t,e,r){return{tier:T(t,e),entities:r||[],dictionary:I(t,e)}}function E({messages:t,system:e,vault:r,cfg:n,isPro:o=!1,entities:a=[]}){if(!y(n)||!r)return{messages:t,system:e};const u=l(n,o,a),p=x(n,o),A=i=>Array.isArray(i)?i.map(s=>s&&s.type==="text"&&typeof s.text=="string"?{...s,text:f(s.text,r,u)}:s):f(i,r,u),m=i=>{const s={...i};return p.chat!==!1&&i.content&&(s.content=A(i.content)),Array.isArray(i.attachments)&&(s.attachments=i.attachments.map(c=>c.kind==="image"||!c.text||(c.kind==="history-rag"?p.history===!1:p.context===!1)?c:{...c,text:f(c.text,r,u)})),s};return{messages:(t||[]).map(m),system:e&&f(e,r,u)}}function S(t,{vault:e,cfg:r,isPro:n=!1,entities:o=[]}={}){return!y(r)||!e||!x(r,n).toolResults||typeof t!="string"?t:f(t,e,l(r,n,o))}function j(t){let e="";return{push(r){if(!t)return r||"";e+=r||"";const n=e.lastIndexOf("[[");let o;return n!==-1&&!e.slice(n).includes("]]")?(o=e.slice(0,n),e=e.slice(n)):(o=e,e=""),d(o,t)},flush(){const r=t?d(e,t):e;return e="",r}}}function C(t,e){return e?d(t,e):t}function h(t,e){if(!e)return t;if(typeof t=="string")return R(t,e);if(Array.isArray(t))return t.map(r=>h(r,e));if(t&&typeof t=="object"){const r={};for(const n of Object.keys(t))r[n]=h(t[n],e);return r}return t}function H(t,e){const{vault:r,cfg:n,isPro:o=!1,entities:a=[]}=e||{};return!y(n)||!r||!x(n,o).toolResults?t:b(t,r,l(n,o,a))}export{k as FREE_DICT_LIMIT,T as effectiveTier,I as gatedDictionary,x as gatedScope,j as makeStreamRestorer,l as redactOpts,E as redactOutbound,H as redactResult,S as redactToolResult,y as redactionEnabled,C as restore,h as restoreDeep};
|
package/src/sandbox-srt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as
|
|
1
|
+
import{spawnSync as ke}from"node:child_process";import{writeFileSync as oe,mkdirSync as re,existsSync as De}from"node:fs";import{createHash as Ee,randomBytes as Oe}from"node:crypto";import{fileURLToPath as $e}from"node:url";import M from"node:os";import $ from"node:path";import{toSrtSettings as ie,sandboxRecord as Le,shellJoin as ae,sandboxEnvOverlay as F,windowsGrantsFor as Ce,windowsSandboxEnv as Re,withSrtWinEnv as Te,ENGINE_KITS as ce,DEVELOPER_HOSTS as de,SECRET_PATHS as Ne,COMMON_WRITE as He}from"./events/sandbox-policy.js";import{defineSandboxRuntime as _e,registerSandboxRuntime as Pe}from"./sandbox-runtime.js";function je(n=process.env.CHATPANEL_SRT_MODULE){if(!n)return"";try{const o=n.startsWith("file:")?$e(new URL("./cli.js",n)):$.join($.dirname(n),"cli.js");return De(o)?o:""}catch{return""}}const le=new Set;function ue(n,o=$.join(M.tmpdir(),"chatpanel-srt")){const y=JSON.stringify(n),p=$.join(o,`${Ee("sha256").update(y).digest("hex").slice(0,16)}.json`);return le.has(p)||(re(o,{recursive:!0,mode:448}),oe(p,y,{mode:384}),le.add(p)),p}function Me(){try{const n=ke(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return n.status===0&&String(n.stdout||"").trim().length>0}catch{return!1}}const z="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)";function Ue({config:n,platform:o=process.platform,home:y=M.homedir(),loopback:p=[],compiled:W=!1,selfFiles:he=[process.execPath,process.argv[1]||""],onExit:we=_=>process.on("exit",_),hostEntry:B=null,reportUrl:J="",mintReportToken:fe=()=>"",onRefusal:be=()=>{},parseRefusal:xe=()=>null,loadSrt:X=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:G=Me,cliEntry:K=je(),hostEntryFor:q=()=>"",log:L=()=>{}}={}){const _=new Set;let c=null,w=null,a=null,U=null,C=null,g=null,A=null;const R=new Set;let Q=!1;const me="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",pe="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function Se(){if(!n.windows){w=me;return}if(W){w=pe;return}try{a=await X()}catch(t){w=`sandbox-runtime is not installed — it ships with the gateway (${t.message})`;return}if(!a?.SandboxManager?.wrapWithSandboxArgv||typeof a.grantWindowsAcl!="function"||typeof a.getWindowsSandboxUserStatusAsync!="function"){w="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{g=a.resolveSrtWin({path:a.VENDORED_SRT_WIN_EXE})}catch(t){w=`Windows: srt-win.exe is not beside sandbox-runtime (${t.message})`;return}let e;try{e=await a.getWindowsSandboxUserStatusAsync({srtWin:g})}catch(t){A=!1,w=`Windows: srt-win could not be asked whether the sandbox account exists (${t.message}) — ${z}`;return}if(A=!!(e?.provisioned&&e.sid),!A){w=`Windows: the sandbox account is not installed — ${z}`;return}C=e.sid,c="srt-lib"}async function ye(){if(!(c||w)){if(!n.enabled){w="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(o==="win32")return Se();if(!W)try{if(a=await X(),a?.SandboxManager?.wrapWithSandboxArgv){c="srt-lib";return}}catch(e){L(`sandbox: library not available (${e.message})`)}if(G()){c="srt-cli";return}w=W?"srt is not on PATH — the compiled bridge cannot carry it: npm i -g @anthropic-ai/sandbox-runtime":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}}let Y=!1;function Z(e,{hosts:t=[],sockets:s=[]}={}){const r={...e.network};let i=!1;if((r.allowedDomains||[]).includes("*")){const d=r.allowedDomains.filter(l=>l.startsWith("127.0.0.1:"));r.allowedDomains=[...new Set([...Object.values(ce).flatMap(l=>l.hosts),...de,...n.extraHosts,...t,...d])],i=!0}return o==="darwin"&&s.length&&(r.allowUnixSockets=s),{settings:{...e,network:r},narrowed:i}}const ee=(e,{narrowed:t},s)=>(t&&(e.narrowed=`open → allowlist: the srt CLI refuses "*" — the gateway's embedded bridge runs open`),s.length&&o==="darwin"&&(e.sockets=s,delete e.socketsDropped),e);function I(){return K&&!W?{bin:process.execPath,argv:[K]}:c==="srt-cli"||G()?{bin:"srt",argv:[]}:null}function ge(){const e=Array.isArray(n.exactHosts)?n.exactHosts:n.mode==="open"?["*"]:n.mode==="none"?[]:[...new Set([...Object.values(ce).flatMap(r=>r.hosts),...de,...n.extraHosts])],t={id:`session:${n.mode}`,network:{mode:n.mode,allowedDomains:e},filesystem:{allowWrite:[M.tmpdir(),...He,...n.extraWrite],denyRead:[...Ne,...n.extraDenyRead]}},s=ie(t,{loopback:p,home:o==="linux"?y:"",platform:o});return o==="darwin"&&Array.isArray(n.exactSockets)&&n.exactSockets.length&&(s.network.allowUnixSockets=n.exactSockets),g?{...s,windows:{srtWin:{path:g.exe}}}:s}async function te(){return U||(U=a.SandboxManager.initialize(ge()).then(()=>{try{a.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(e=>{for(const t of e||[]){const s=xe(t?.line);if(!s||!t?.encodedCommand)continue;let r="";try{r=Buffer.from(t.encodedCommand,"base64").toString("utf8")}catch{continue}const i=`${r}|${s.host}|${t.timestamp instanceof Date?t.timestamp.getTime():String(t.timestamp)}`;_.has(i)||(_.add(i),be({commandId:r,...s,at:t.timestamp instanceof Date?t.timestamp.getTime():Date.now()}))}})}catch(e){L(`sandbox: violations not subscribed (${e.message})`)}})),U}function ve(e){const t=$.join(M.tmpdir(),"chatpanel-srt");re(t,{recursive:!0,mode:448});const s=$.join(t,`host-${Oe(8).toString("hex")}.json`);return oe(s,JSON.stringify(e),{mode:384}),s}function We(e,t){const s=(d,l)=>a.expandWindowsFsPaths(d,{mode:l}).filter(u=>!R.has(`${l}:${u.toLowerCase()}`)),r=s(e,"grant"),i=s(t,"grant");if(!(!r.length&&!i.length)){a.grantWindowsAcl({sandboxUserSid:C,read:r,write:i,srtWin:g});for(const d of r)R.add(`grant:${d.toLowerCase()}`);for(const d of i)R.add(`grant:${d.toLowerCase()}`);Q||(Q=!0,we(()=>{try{a.revokeWindowsAcl({sandboxUserSid:C,srtWin:g})}catch{}}))}}async function Ae(e,t,s,{engine:r,workdir:i,kit:d,settings:l,commandId:u,record:T,caBundle:S=""}){await te();const k=h=>typeof h=="string"&&/^[a-z]:\\/i.test(h),{read:P,write:D}=Ce({kit:d,files:[e,...k(t[0])?[t[0]]:[],...he].filter(Boolean),home:y});We(P,D);const f=ae(e,t,{platform:"win32"}),E=await a.SandboxManager.wrapWithSandboxArgv(f,void 0,{filesystem:{denyRead:l.filesystem.denyRead,denyWrite:l.filesystem.denyWrite}},void 0,i,{commandId:u,commandText:f}),x=s?.env||process.env,v={...Re({engine:r,home:y,env:x,base:process.env}),...F({},{platform:o,caBundle:S})},N=Te(E.argv,v),b={};for(const[h,H]of Object.entries(E.env||{}))process.env[h]!==H&&(b[h]=H);return{bin:N[0],argv:N.slice(1),opts:{...s,env:{...x,...b},shell:!1},record:T,commandId:u}}return _e({id:"srt",label:"Anthropic sandbox-runtime",async detect(){return await ye(),{ok:!!c,runtime:c,reason:w,ownSessions:!!(c&&(c==="srt-lib"&&(B??q(W))||o!=="win32"&&I())),...o==="win32"&&A!==null?{provisioned:A,...A?{}:{install:z}}:{}}},async wrap({kit:e,grant:t,bin:s,argv:r,opts:i,engine:d,workdir:l,commandId:u,caBundle:T=""}){const S=ie(e,{loopback:p,home:o==="linux"?y:"",platform:o}),k=ae(s,r),P=Array.isArray(n.exactHosts),D=n.mode==="allowlist"&&t.hosts.length>0&&!P,f=S.network.allowUnixSockets||[],E=f.length>0&&!P;delete S.network.allowUnixSockets;const x=(D||E)&&c==="srt-lib"?B??q(W):"",v=D&&!x&&o!=="win32"?I():null,N=!!(x||v),b=Le({layer:"process",runtime:x?"srt-host":v?"srt-cli":c,kitId:e.id,mode:e.network.mode,hosts:N||!D?t.hosts:[]});D&&!N&&(b.hostsDropped=t.hosts,Y||(Y=!0,L(`sandbox: hosts granted to ${d} (${t.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`))),E&&!x?b.socketsDropped=f:E&&(b.sockets=f);try{if(x){const m=fe(u),O={bin:s,argv:r,cwd:i?.cwd||null,engine:d,workdir:l,grant:t,commandId:u,config:{enabled:!0,mode:n.mode,extraHosts:[],extraWrite:n.extraWrite,extraDenyRead:n.extraDenyRead,windows:n.windows,exactHosts:e.network.allowedDomains,exactSockets:f},loopback:p,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:J?{url:J,token:m}:null},j={...i?.env||process.env};return{bin:process.execPath,argv:[x,ve(O)],opts:{...i,env:j,shell:!1},record:b,commandId:u}}if(v){const m={...i?.env||process.env};Object.assign(m,F(m,{platform:o,caBundle:T}));const O=Z(S,{hosts:t.hosts,sockets:f});return{bin:v.bin,argv:[...v.argv,"-s",ue(O.settings),"-c",k],opts:{...i,env:m,shell:!1},record:ee(b,O,f),commandId:u}}if(c==="srt-lib"&&o==="win32")return{...await Ae(s,r,i,{engine:d,workdir:l,kit:e,settings:S,commandId:u,record:b,caBundle:T})};if(c==="srt-lib"){await te();const m=await a.SandboxManager.wrapWithSandboxArgv(k,void 0,{filesystem:S.filesystem},void 0,l,{commandId:u,commandText:k}),O=i?.env||process.env,j={};for(const[ne,se]of Object.entries(m.env||{}))process.env[ne]!==se&&(j[ne]=se);const V={...O,...j};return Object.assign(V,F(V,{platform:o,caBundle:T})),{bin:m.argv[0],argv:m.argv.slice(1),opts:{...i,env:V,shell:!1},record:b,commandId:u}}const h=I(),H=Z(S,{hosts:t.hosts,sockets:f});return{bin:h.bin,argv:[...h.argv,"-s",ue(H.settings),"-c",k],opts:{...i,shell:!1},record:ee(b,H,f),commandId:u}}catch(h){return L(`sandbox: could not wrap ${s}: ${h.message}`),{passReason:h?.code==="SHAPE"?`the sandbox policy refused this run: ${h.message}`:`sandbox-runtime failed to wrap the command: ${h.message}`}}},violations(e){try{return a?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(e)||[]}catch{return[]}},close(){if(!(!C||!R.size)){try{a.revokeWindowsAcl({sandboxUserSid:C,srtWin:g})}catch(e){L(`sandbox: could not release the Windows grants: ${e.message}`)}R.clear()}}})}Pe("srt",n=>Ue(n));export{Ue as createSrtRuntime};
|
package/src/sandbox.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as
|
|
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};
|